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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): nest layers in pass-through groups
Josh Corbettdde6315c59e4
diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdxindex 3678c8822e..b8b7c2daa7 100644--- a/docs/src/content/docs/development/Front End/project-files.mdx+++ b/docs/src/content/docs/development/Front End/project-files.mdx@@ -27,10 +27,10 @@ replaced. Project listings remain readable because they contain metadata, not andocument, and expose the minimum so clients can identify projects they cannot open.The floor is monotonic. A save may raise it, but cannot lower it, and SQLite commits the new-document, revision, project name, board name, and floor as one transaction. This is the activation-seam for a future canvas v3 document: the first v3 edit must send the v3 document and-`minimum_canvas_schema_version: 3` in the same optimistic-concurrency save. An older client then-defaults to a declared maximum of v2 and is refused before it can overwrite that document.+document, revision, project name, board name, and floor as one transaction. The hierarchical+canvas v3 document rides this seam: every save sends the document together with the+`minimum_canvas_schema_version` it requires (3 for any v3 canvas), so a client that still declares+a maximum of v2 is refused before it can overwrite that document.The frontend derives the requested floor from the highest declared version among the live canvasand every queued canvas snapshot. It also retains the server's monotonic floor in the offline sync@@ -54,9 +54,8 @@ revision keeps the server project under its id and turns the cached edit into aIf a response landed just before a crash, identical server and cache bytes simply clear the stalepending marker.-Requests that omit negotiation fields default to v2. That preserves compatibility during protocol-rollout while remaining safe for future documents: an undeclared older client is treated as v2,-not as unrestricted. The frontend's maximum lives in `canvasSchemaVersion.ts`; the canvas loader's+Requests that omit negotiation fields default to v2 on the server. That keeps an undeclared older+client from opening a v3 project: it is treated as v2, not as unrestricted. The frontend's maximum lives in `canvasSchemaVersion.ts`; the canvas loader'sforward-version gate and the project API adapter consume the same constant so advertised supportcannot drift from actual parsing support.@@ -177,11 +176,11 @@ 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 even when the visible document is currently v2. 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; 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.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.-Manifests parse through a zod discriminated union on `version`, so a version 1 archive is recognized and refused _as what it is_ — `InvkFormatError` carries a `reason` (`legacy-canvas-project`, `unsupported-version`, `not-a-project`, `damaged`, `too-large`) that `describeProjectFileError()` maps to a translated string. There is no translation layer from legacy canvas state to `CanvasStateContractV2`.+Manifests parse through a zod discriminated union on `version`, so a version 1 archive is recognized and refused _as what it is_ — `InvkFormatError` carries a `reason` (`legacy-canvas-project`, `unsupported-version`, `not-a-project`, `damaged`, `too-large`) that `describeProjectFileError()` maps to a translated string. There is no translation layer from legacy canvas state to `CanvasStateContractV3`.The legacy reader is the mirror image: it pins `version: 1` and refuses everything this app writes.diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 23f088f5d6..1c80ba2103 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -430,6 +430,7 @@"exporting": "Exporting \"{{name}}\"…","failedToLoad": "Failed to load your projects.","requiresNewerInvoke": "Requires a newer Invoke",+ "legacyFormat": "Older project format","file": {"bundlingProgress": "Bundling {{completed}} of {{total}} assets…","damaged": "This project file is damaged and cannot be opened.",@@ -470,6 +471,7 @@"load": {"invalid": "\"{{name}}\" contains canvas data this version of Invoke cannot read, and it was not opened.","multiple": "{{count}} saved projects were not opened because this version of Invoke cannot read them: {{names}}.",+ "legacyVersion": "\"{{name}}\" was saved by an older version of Invoke and cannot be opened here.","unsupportedVersion": "\"{{name}}\" was saved by a newer version of Invoke and cannot be opened here."},"newProject": "New project",diff --git a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.tsindex bbeba78c12..c3fabd952b 100644--- a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts+++ b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts@@ -19,6 +19,7 @@ afterAll(closeSourceAnalysis);/** Modules that may take part in stack order and selection repair: the reducer and the document seam. */const DOCUMENT_SEAM_OWNERS = [/^workbench\/canvasProjectMutations\.ts$/,+ /^workbench\/canvasMigration\.ts$/,/^workbench\/canvas-engine\/document\//,/^workbench\/canvas-engine\/document-model\//,];@@ -30,7 +31,7 @@ const SEAM_MODULES = [];/**- * Mutations that restructure the layer list. Controllers build some as forward/inverse pairs for+ * Mutations that restructure the stack forests. 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: '…'`.*/@@ -38,10 +39,9 @@ const STRUCTURAL_MUTATION_TYPES = ['addCanvasLayer','applyCanvasLayerStackMutation','convertCanvasLayer',- 'duplicateCanvasLayer','mergeCanvasLayersDown','removeCanvasLayers',- 'reorderCanvasLayerStacks',+ 'reorderCanvasSiblings','replaceCanvasDocument','replaceCanvasLayer','restoreCanvasSnapshot',@@ -51,8 +51,8 @@ const STRUCTURAL_MUTATION_TYPES = ['updateCanvasLayerSource',];/**- * 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.+ * The finite set of modules that construct structural mutations directly. Keeping this explicit+ * prevents new bypasses of the prepared-edit seam.*/const STRUCTURAL_MUTATION_OWNER_PATHS = new Set(['workbench/canvasProjectMutations.ts',@@ -70,7 +70,7 @@ const STRUCTURAL_MUTATION_OWNER_PATHS = new Set(['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-model/documentModel.ts','workbench/canvas-engine/document/bitmapStore.ts','workbench/canvas-engine/engine.ts','workbench/canvas-engine/mutationContracts.ts',@@ -83,7 +83,7 @@ const STRUCTURAL_MUTATION_OWNER_PATHS = new Set([]);const structuralLiteral = new RegExp(`type: '(?:${STRUCTURAL_MUTATION_TYPES.join('|')})'`, 'g');-const SEAM_ONLY_SYMBOLS = ['repairSelectedLayerId', 'moveLayersWithinStacks', 'reorderLayerStack'];+const SEAM_ONLY_SYMBOLS = ['repairSelectedLayerId', 'moveNodesWithinSiblings', 'reorderSiblings'];/** Production planners that consume the document model; dropping the import would reopen an ad-hoc path. */const MODEL_CONSUMERS = [@@ -101,7 +101,7 @@ const MODEL_CONSUMERS = ['workbench/canvas-operations/generationCompositePlan.ts',];-const MODEL_MODULE = 'workbench/canvas-engine/document-model/flatDocumentModel';+const MODEL_MODULE = 'workbench/canvas-engine/document-model/documentModel';describe('canvas document seam ownership', () => {it('keeps stack mutation and selection repair inside the reducer and the document seam', () => {@@ -127,7 +127,7 @@ describe('canvas document seam ownership', () => {expect(offenders).toEqual([]);}, 60_000);- it('keeps flat structural mutation construction in explicit owners', () => {+ it('keeps structural mutation construction in explicit owners', () => {const offenders: string[] = [];for (const [path, source] of productionSources) {if (STRUCTURAL_MUTATION_OWNER_PATHS.has(path)) {diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.tsindex 3cf2663774..6a60bac838 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts@@ -138,7 +138,7 @@ describe('dependency policy rules', () => {'@workbench/canvas-engine/document/sources','@workbench/canvas-engine/document/bitmapStore',])('keeps the pure document model free of engine, screen and framework imports: %s', (specifier) => {- expect(checkDependency('workbench/canvas-engine/document-model/flatDocumentModel.ts', specifier)).toContainEqual(+ expect(checkDependency('workbench/canvas-engine/document-model/documentModel.ts', specifier)).toContainEqual(expect.objectContaining({ rule: 'document-model-purity' }));});@@ -157,13 +157,13 @@ describe('dependency policy rules', () => {});it('permits the pure document model to read document facts, math and contracts', () => {- const source = 'workbench/canvas-engine/document-model/flatDocumentModel.ts';+ const source = 'workbench/canvas-engine/document-model/documentModel.ts';expect(checkDependency(source, './semanticLeaf')).toEqual([]);expect(checkDependency(source, '@workbench/canvas-engine/document/layerStacks')).toEqual([]);expect(checkDependency(source, '@workbench/canvas-engine/math/mat2d')).toEqual([]);expect(checkDependency(source, '@workbench/canvas-engine/contracts')).toEqual([]);expect(checkDependency(source, '@workbench/canvas-engine/mutationContracts')).toEqual([]);- expect(checkDependency('workbench/canvas-engine/document-model/flatDocumentModel.test.ts', 'vitest')).toEqual([]);+ expect(checkDependency('workbench/canvas-engine/document-model/documentModel.test.ts', 'vitest')).toEqual([]);});it('permits feature Core to depend on other pure Core and Platform State modules', () => {diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.tsindex df8e521703..f8af40478c 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts@@ -157,10 +157,19 @@ const isFeatureCoreForbiddenDependency = (specifier: string, target: string | nu/** The reducer shares the document seam's stack, anchor and repair helpers instead of the public API. */const CANVAS_REDUCER = 'workbench/canvasProjectMutations.ts';const REDUCER_DOCUMENT_MODULES = [+ 'workbench/canvas-engine/document/documentIndex',+ 'workbench/canvas-engine/document/documentTree','workbench/canvas-engine/document/insertionAnchors','workbench/canvas-engine/document/layerStacks','workbench/canvas-engine/document/selectionRepair',];+/** The loader repairs a persisted selection at ingress with the seam's own repair. */+const CANVAS_LOADER = 'workbench/canvasMigration.ts';+const LOADER_DOCUMENT_MODULES = ['workbench/canvas-engine/document/selectionRepair'];++const isSeamAllowance = (sourcePath: string, target: string): boolean =>+ (sourcePath === CANVAS_REDUCER && REDUCER_DOCUMENT_MODULES.includes(target)) ||+ (sourcePath === CANVAS_LOADER && LOADER_DOCUMENT_MODULES.includes(target));const DOCUMENT_MODEL_ROOT = 'workbench/canvas-engine/document-model/';const DOCUMENT_MODEL_DEPENDENCY_ROOTS = [DOCUMENT_MODEL_ROOT, 'workbench/canvas-engine/math/'];@@ -169,6 +178,8 @@ const DOCUMENT_MODEL_DEPENDENCY_MODULES = ['workbench/canvas-engine/types','workbench/canvas-engine/mutationContracts','workbench/canvas-engine/document/commandRefusal',+ 'workbench/canvas-engine/document/documentIndex',+ 'workbench/canvas-engine/document/documentTree','workbench/canvas-engine/document/insertionAnchors','workbench/canvas-engine/document/layerEligibility','workbench/canvas-engine/document/layerStacks',@@ -238,11 +249,7 @@ export const checkDependency = (source: string, specifier: string): DependencyViadd('feature-private-interface');}- if (- !isCanvasOwnedPath(sourcePath) &&- isCanvasPrivatePath(target) &&- !(sourcePath === CANVAS_REDUCER && REDUCER_DOCUMENT_MODULES.includes(target))- ) {+ if (!isCanvasOwnedPath(sourcePath) && isCanvasPrivatePath(target) && !isSeamAllowance(sourcePath, target)) {add('canvas-private-interface');}diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.tsindex 9b831134a9..8b1201f3bc 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasMode.test.ts@@ -46,7 +46,7 @@ describe('detectCanvasMode', () => {it('stays txt2img for a new canvas seeded with only an empty inpaint mask', () => {// A brand-new canvas carries one empty inpaint mask (see- // `createNewCanvasStateV2`). An empty mask contributes no raster content+ // `createNewCanvasState`). An empty mask contributes no raster content// (`contentBounds` stays null) and has no content (`hasActiveInpaintMask`// is false), so mode detection must NOT flip to inpaint.expect(detectCanvasMode(input({ contentBounds: null, hasActiveInpaintMask: false }))).toBe('txt2img');diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.tsindex a352e4749f..61716db19e 100644--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts@@ -95,7 +95,7 @@ describe('Canvas edit classification', () => {expect(isHighConfidenceCanvasEdit(mutation({- add: [{ anchor: {}, layers: [{}] }],+ add: [{ anchor: {}, nodes: [{}] }],enabledUpdates: [],selectedLayerId: 'new-layer',type: 'applyCanvasLayerStackMutation',diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.tsindex 206d5fbab1..9b7525e633 100644--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts@@ -118,10 +118,9 @@ const CANVAS_EDIT_CONFIDENCE = {deleteCanvasSnapshot: 'none',discardAllStagedImages: 'none',discardSelectedStagedImage: 'none',- duplicateCanvasLayer: 'high',mergeCanvasLayersDown: 'high',removeCanvasLayers: 'high',- reorderCanvasLayerStacks: 'high',+ reorderCanvasSiblings: 'high',replaceCanvasDocument: 'none',replaceCanvasLayer: 'high',resizeCanvasDocument: 'high',@@ -158,7 +157,8 @@ export const isHighConfidenceCanvasEdit = (mutation: CanvasProjectMutation): booif (mutation.type === 'applyCanvasLayerStackMutation') {return (- (mutation.add?.some((insertion) => insertion.layers.length > 0) ?? false) ||+ (mutation.add?.some((insertion) => insertion.nodes.length > 0) ?? false) ||+ (mutation.move?.length ?? 0) > 0 ||(mutation.removeIds?.length ?? 0) > 0 ||mutation.enabledUpdates.length > 0);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 562733e108..1aa8c66089 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -23,6 +23,16 @@ The port's `dispatch()` returns whether the named project's canvas identity chanPaint persistence clears a dirty result only after the intended layer accepts the bitmap reference. A rejected update retains dirty pixels for retry; deletion of the layer or project is terminal and discards obsolete persistence work. This applies equally to raster/control paint sources and paint-backed masks.+## Document contract and hierarchy++`CanvasDocumentContractV3` holds four stack forests, `document.stacks.{raster, control, regional_guidance, inpaint_mask}`. Each forest is a top-first tree of leaves (the unchanged v2 leaf contracts) and pass-through groups (`type: 'group'` with `id`, `name`, `isEnabled`, `isLocked`, optional overlay-only `isHidden`, and `children`). A node belongs to exactly one stack, ids are unique across the document, groups nest at most ten levels deep, and a document holds at most 10,000 nodes. `selectedLayerId` may name a leaf or a group; leaf-only tools refuse a group rather than guessing a descendant. Groups carry no opacity, blend mode, transform, or raster surface: they only organise leaves and gate their effective state. Older document versions are refused by the loader; nothing migrates them.++`document/documentIndex.ts` builds one index per `stacks` identity (parent, path, sibling index, document order, and ancestor-effective enabled/locked/hidden per node). The reducer preserves `stacks` identity across selection, bbox and geometry-only edits, so those changes cost no index. `document-model/documentModel.ts` compiles `SemanticLeaf`s from that index: a leaf's `contributionEnabled`, `effectiveLocked`, and `documentHidden` fold in every ancestor, and a leaf keeps its identity while its layer object, ancestor path, and ancestor-effective state are unchanged. Every consumer that decides visibility, contribution, editability, or export reads leaves (or `isLeaf*` predicates) rather than a layer's own flags.++Structural edits are prepared by the model (`insert`, `remove`, `duplicate`, `move`, `reorder`, `reparent`, `group`, `ungroup`, `patch*`, `set-*`, `translate`, `select`) and committed through `commitPrepared`. Restructuring lands as one `applyCanvasLayerStackMutation` that the reducer applies as `add`, then `move`, then `removeIds`, then flag and selection updates, refusing the whole mutation when any step is invalid or the result exceeds the limits. Insertion anchors are exact: before a surviving sibling under its current parent, after a surviving sibling, the top of the captured parent, the nearest surviving group on the captured path, then the stack top. Inverses restore removed or moved nodes as maximal sibling runs anchored to their unmoved neighbours, so undo reproduces the previous structure exactly.++The document mirror diffs forests by leaf identity and ancestor-effective state: a group flag flip reports every descendant leaf as changed (never source-changed), a group rename reports nothing, and a reparent that changes no leaf's effective state reports an order change only.+## Package and capability boundaries`canvas-engine/` is the rendering and editing core. It may import engine-internal modules and shared canvas contracts, mutations, and the project mutation port. It must not import React, widgets, application canvas operations, generation graphs, socket infrastructure, or backend networking. `importBoundaries.test.ts` enforces that rule.@@ -59,7 +69,7 @@ Controller-local tests instantiate these boundaries with fakes. Integration test## Immutable document and raster snapshots-`CanvasDocumentCapability.captureSnapshot()` returns a `CanvasDocumentSnapshot` or `null`. A snapshot contains a structured clone of the exact `CanvasStateContractV2` and the engine's `documentGeneration`. The engine privately associates it with the reducer canvas identity from which it was captured, so a caller cannot manufacture a current snapshot by copying fields.+`CanvasDocumentCapability.captureSnapshot()` returns a `CanvasDocumentSnapshot` or `null`. A snapshot contains a structured clone of the exact `CanvasStateContractV3` and the engine's `documentGeneration`. The engine privately associates it with the reducer canvas identity from which it was captured, so a caller cannot manufacture a current snapshot by copying fields.`CanvasExportCapability.captureRasterSnapshot(snapshot, layerIds, options)` requests exactly the required layer caches, temporarily pins them, reserves detached-surface capacity, and copies their pixels into independent surfaces. It returns a typed `ok`, `stale`, `aborted`, `not-ready`, or `over-budget` result. Freshness is checked before and after every asynchronous rasterization boundary and once after all copies are detached.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.tsindex 5b3900bfe2..593ede1aa3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts@@ -6,7 +6,7 @@ import type {LayerExportGuard,ReplaceSelectionFromImageResult,} from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasImageRef } from '@workbench/canvas-engine/contracts';import type {CommitRasterFilterOptions,CommitRasterFilterResult,@@ -50,7 +50,7 @@ export interface CanvasApplicationHost {| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }>;getCompositeExecutorDeps(): CanvasCompositeExecutorDeps;- getDocument(): CanvasDocumentContractV2 | null;+ getDocument(): CanvasDocumentContractV3 | null;isGuardCurrent(guard: LayerExportGuard): boolean;isInteractionLocked(): boolean;isSamToolActive(): boolean;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex db231c0004..ec2426094a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -1,19 +1,19 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,CanvasStagingCandidateContract,- CanvasStateContractV2,+ CanvasStateContractV3,} 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 { PreparedFlatEdit } from './document-model/flatDocumentCommands';-import type { FlatCanvasDocumentModel } from './document-model/flatDocumentModel';+import type { PreparedDocumentEdit } from './document-model/documentCommands';+import type { CanvasDocumentModel } from './document-model/documentModel';import type { CanvasCommandRefusal } from './document/commandRefusal';-import type { FlatLayerInsertionAnchor } from './document/insertionAnchors';+import type { CanvasNodeInsertionAnchor } from './document/insertionAnchors';import type { LayerStackKind } from './document/layerStacks';import type { CanvasTransactionOutcome, SubsetOf } from './editConcurrency';import type { CanvasEditGate } from './editGate';@@ -141,7 +141,7 @@ export interface CanvasSurfaceCapability {export interface CanvasDocumentCapability {captureSnapshot(): CanvasDocumentSnapshot | null;- getDocument(): CanvasDocumentContractV2 | null;+ getDocument(): CanvasDocumentContractV3 | null;/*** Counts every reducer document identity change, whatever its origin (user edits, previews,* selection, system syncs). Unlike `documentGeneration` (raster invalidation) and the persisted@@ -150,18 +150,18 @@ export interface CanvasDocumentCapability {*/getEditRevision(): number;/** Where a new `stack` layer lands: above `aboveId` when it belongs to the stack, else the stack top. */- captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor;- /** The anchor that restores `layerId` between its current same-stack neighbours; null when absent. */- captureRestoreAnchor(layerId: string): FlatLayerInsertionAnchor | null;+ captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): CanvasNodeInsertionAnchor;+ /** The anchor that restores `nodeId` between its current siblings; null when absent. */+ captureRestoreAnchor(nodeId: string): CanvasNodeInsertionAnchor | null;/** Swaps in a whole new document; the mirror treats it as a document swap and history clears. */- replaceDocument(document: CanvasDocumentContractV2): boolean;+ replaceDocument(document: CanvasDocumentContractV3): boolean;/** The pure model over the current document; the same instance until the document changes. */- model(): FlatCanvasDocumentModel | null;+ model(): CanvasDocumentModel | null;}/** Immutable reducer canvas state captured at one engine document generation. */export interface CanvasDocumentSnapshot {- readonly canvas: CanvasStateContractV2;+ readonly canvas: CanvasStateContractV3;readonly documentGeneration: number;}@@ -233,6 +233,7 @@ export type {CanvasMutationOrigin,CanvasProjectMutation,} from './mutationContracts';+export { GROUP_PATCH_KEYS } from './mutationContracts';export interface ExportLayerPixelsOptions {includeDisabled?: boolean;@@ -307,7 +308,7 @@ export interface StructuralCommitOptions {/** The edit revision the edit was prepared against; a mismatch refuses as `stale`. */expectedRevision?: number;/** An extra reducer postcondition beyond "the document changed". */- verify?: (document: CanvasDocumentContractV2) => boolean;+ verify?: (document: CanvasDocumentContractV3) => boolean;}/** The narrowest engine surface a structural edit needs. */@@ -333,7 +334,7 @@ export interface CanvasLayerCapability {options?: StructuralCommitOptions): StructuralCommitResult;/** Runs a prepared flat edit through the transaction: refusals, dispatch, verification and history. */- commitPrepared(label: string, edit: PreparedFlatEdit, options?: PreparedCommitOptions): StructuralCommitResult;+ commitPrepared(label: string, edit: PreparedDocumentEdit, options?: PreparedCommitOptions): StructuralCommitResult;invertMask(layerId: string): boolean;}@@ -484,7 +485,7 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {label: string,sourceLayerId: string,layer: CanvasLayerContract,- anchor: FlatLayerInsertionAnchor+ anchor: CanvasNodeInsertionAnchor): boolean;commitMaskImageResult(options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult>;commitOpenTextSession(): boolean;@@ -543,6 +544,7 @@ export interface CanvasEngine {// Public Canvas-owned value contracts. These remain serializable and contain// no engine implementation, mutable store, controller, or construction type.export type * from './contracts';+export { CANVAS_MAX_NODE_COUNT, CANVAS_MAX_NODE_DEPTH } from './contracts';export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';export interface StagedPreviewPlacement extends Rect {opacity: number;@@ -596,17 +598,39 @@ export { documentToExportLocalSamPoint } from './samCoordinates';export { bboxEquals, constrainBboxToRatio, roundBbox } from './tools/bboxHitTest';export { isEmpty, union } from './math/rect';export { ZOOM_PRESETS } from './math/snapping';-export { isLayerPixelEditEligible } from './editing/controlPixelEdit';+export { isLeafPixelEditEligible } from './editing/controlPixelEdit';export {- getStackOrder,- haveSameStackOrders,+ getSiblingOrder,+ haveSameStructure,+ isOverlayStack,LAYER_STACK_ORDER,LAYER_STACKS_TOP_FIRST,layerStackOf,type LayerStackKind,type LayerStackMoveKind,- type ReorderFlatStackCommand,+ type OverlayStackKind,+ type ReorderSiblingsCommand,} from './document/layerStacks';+export {+ childrenOf,+ collectSubtree,+ collectSubtreeLeaves,+ createEmptyStacks,+ isGroupNode,+ isLeafNode,+ subtreeDepth,+} from './document/documentTree';+export {+ getDocumentIndex,+ getDocumentLayer,+ getDocumentLeaves,+ getDocumentNode,+ hasDocumentNode,+ isSelfOrAncestor,+ outermostNodes,+ type CanvasDocumentIndex,+ type CanvasNodeEntry,+} from './document/documentIndex';export {type HideableLayer,isHideableLayer,@@ -616,34 +640,44 @@ export {isLayerPaintable,isMergeableRasterLayer,isLayerTransparencyLocked,+ isNodeHidden,isPixelBackedLayer,} from './document/layerEligibility';export {- type FlatDocumentCommand,- type FlatDocumentRefusal,+ type DocumentCommand,+ type DocumentRefusal,+ type InvalidTargetReason,type MergeDownEligibility,- type PreparedFlatEdit,- type PrepareFlatEditResult,-} from './document-model/flatDocumentCommands';+ type PreparedDocumentEdit,+ type PrepareEditResult,+} from './document-model/documentCommands';export {- createFlatDocumentModel,- type FlatCanvasDocumentModel,+ compileContributingLayers,+ compileDocumentLeaves,+ createDocumentModel,+ type CanvasDocumentModel,+ lookupDocumentLayer,+ lookupDocumentLeaf,+ lookupDocumentNode,lookupLayerBelow,mergeDownEligibility,-} from './document-model/flatDocumentModel';-export { checkFlatEditPostconditions, type FlatEditPostcondition } from './document-model/postconditions';+} from './document-model/documentModel';+export { checkEditPostconditions, type EditPostcondition } from './document-model/postconditions';export {+ isLeafIsolated,planScreenComposition,type CanvasScreenViewState,type ScreenCompositionPlan,} from './document-model/screenComposition';-export { type SemanticLeafV2 } from './document-model/semanticLeaf';+export { type SemanticLeaf } from './document-model/semanticLeaf';export {captureInsertionAnchor,captureRestoreAnchor,- resolveInsertionIndex,- type FlatLayerInsertion,- type FlatLayerInsertionAnchor,+ resolveInsertionTarget,+ type CanvasNodeInsertion,+ type CanvasNodeInsertionAnchor,+ type CanvasNodeMove,+ type InsertionAnchorCapture,} from './document/insertionAnchors';export { isExportableRasterLayer } from './layerExportGuards';export {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.tsindex a57d05f11b..61283e18d2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts@@ -52,21 +52,7 @@ export interface CanvasStagingCandidateContract extends GeneratedImageContract {sourceBackendItemId?: number;}-export interface CanvasRasterLayerContract extends GeneratedImageContract {- id: string;- acceptedAt: string;- label: string;- placement: CanvasPlacementContract;-}--export interface CanvasDocumentContract {- version: 1;- width: number;- height: number;- layers: CanvasRasterLayerContract[];-}--/** @deprecated legacy v1 shape, superseded by {@link CanvasStagingAreaContractV2}. Extracted so v1 and v2 canvas state can share its structure. */+/** The legacy-shaped staging area; v3 state extends it with `autoSwitchMode`. */export interface CanvasStagingAreaContract {sourceQueueItemId?: string;selectedLayerId?: string;@@ -77,25 +63,15 @@ export interface CanvasStagingAreaContract {areThumbnailsVisible: boolean;}-/** @deprecated legacy v1 shape, superseded by {@link CanvasStateContractV2}. Kept for migration input typing and the still-v1-shaped staging area. */-export interface CanvasStateContract {- version: 1;- document: CanvasDocumentContract;- stagingArea: CanvasStagingAreaContract;-}-// ----------------------------------------------------------------------------// Canvas v2 document contracts+// Canvas v3 document contracts//-// The canvas document is being rebuilt as a full photo editor: a layer stack-// supporting raster, control, regional-guidance, and inpaint-mask layers, each-// with its own transform/opacity/blend-mode. `CanvasStateContract` (v1) only-// ever produced single-image raster layers positioned by `placement`; v2-// layers are positioned by `transform` and reference bitmaps by `imageName`-// (via `CanvasImageRef`) rather than by resolved URLs, since URLs are-// ephemeral/backend-derived while the document is persisted. The staging-// area (pending queue results awaiting placement onto the canvas) keeps its-// v1 shape unchanged — only the accepted document evolves.+// A document holds four stack forests (raster, control, regional guidance and+// inpaint mask). Each forest is a top-first tree of leaves and pass-through+// groups. Leaves are positioned by `transform` and reference bitmaps by+// `imageName` (via `CanvasImageRef`) rather than by resolved URLs, since URLs+// are ephemeral. Groups organise leaves and gate their effective enabled,+// locked and hidden state; they carry no opacity, blend mode or transform.// ---------------------------------------------------------------------------export type CanvasBlendMode =@@ -293,14 +269,40 @@ export type CanvasLayerContract =| CanvasRegionalGuidanceLayerContract| CanvasInpaintMaskLayerContract;-export interface CanvasDocumentContractV2 {- version: 2;+export type CanvasLayerStackKind = CanvasLayerContract['type'];++/**+ * A pass-through group. It belongs to exactly one stack forest and may contain only that+ * stack's leaves and groups. `isHidden` is display-only and valid only in overlay stacks, with the+ * meaning the overlay leaves already give it; a raster group has no display-only hidden state.+ */+export interface CanvasGroupContract {+ id: string;+ type: 'group';+ name: string;+ isEnabled: boolean;+ isLocked: boolean;+ isHidden?: boolean;+ /** Index 0 is the top-most child. */+ children: CanvasNodeContract[];+}++export type CanvasNodeContract = CanvasLayerContract | CanvasGroupContract;++/** One top-first forest per stack; a node's stack is the forest it lives in. */+export type CanvasStackForests = Record<CanvasLayerStackKind, CanvasNodeContract[]>;++export const CANVAS_MAX_NODE_DEPTH = 10;+export const CANVAS_MAX_NODE_COUNT = 10_000;++export interface CanvasDocumentContractV3 {+ version: 3;width: number;height: number;background: 'transparent' | { color: string };- /** Index 0 is the top-most layer. */- layers: CanvasLayerContract[];+ stacks: CanvasStackForests;bbox: { x: number; y: number; width: number; height: number };+ /** A leaf or a group; leaf-only tools refuse a group rather than guessing a descendant. */selectedLayerId: string | null;}@@ -308,16 +310,16 @@ export interface CanvasSnapshotContract {id: string;name: string;createdAt: string;- document: CanvasDocumentContractV2;+ document: CanvasDocumentContractV3;}export interface CanvasStagingAreaContractV2 extends CanvasStagingAreaContract {autoSwitchMode: 'off' | 'latest' | 'progress';}-export interface CanvasStateContractV2 {- version: 2;- document: CanvasDocumentContractV2;+export interface CanvasStateContractV3 {+ version: 3;+ document: CanvasDocumentContractV3;/*** Monotonic counter bumped whenever the document is swapped wholesale* (snapshot restore, `replaceCanvasDocument`) rather than incrementallydiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.tsindex 19f2ee4722..d06541ed6f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts@@ -1,6 +1,6 @@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 { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';import type { History } from '@workbench/canvas-engine/history/history';@@ -9,7 +9,8 @@ import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/renimport type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import { isMergeableRasterLayer } from '@workbench/canvas-engine/document/layerEligibility';+import { lookupLayerBelow, mergeDownEligibility } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';@@ -23,14 +24,14 @@ export interface BooleanMergeControllerOptions {readonly concurrency: CanvasEditConcurrency;readonly backend: RasterBackend;readonly history: History;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;+ readonly getReducerDocument: () => CanvasDocumentContractV3 | null;readonly endBurst: () => void;- readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => boolean;+ readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;readonly dispatchPrepared: (action: CanvasProjectMutation,expectedReducer: () => boolean,@@ -63,15 +64,15 @@ export class BooleanMergeController {if (!document) {return 'missing';}- const upperIndex = document.layers.findIndex((layer) => layer.id === upperLayerId);- const upper = document.layers[upperIndex];- const below = document.layers[upperIndex + 1];- if (upperIndex < 0 || !upper || !below) {- return 'missing';- }- if (!isMergeableRasterLayer(upper) || !isMergeableRasterLayer(below)) {- return 'unsupported';+ const eligibility = mergeDownEligibility(document, upperLayerId);+ if (eligibility.status !== 'eligible') {+ return eligibility.status === 'missing' ||+ (eligibility.status === 'invalid-target' && eligibility.reason === 'no-layer-below')+ ? 'missing'+ : 'unsupported';}+ const upper = getDocumentLayer(document, eligibility.upperId)!;+ const below = getDocumentLayer(document, eligibility.lowerId)!;if (!this.deps.isCacheReady(upper, document) || !this.deps.isCacheReady(below, document)) {return 'not-ready';}@@ -120,8 +121,11 @@ export class BooleanMergeController {return this.deps.concurrency.isPermitCurrent(permit) ? 'not-ready' : 'busy';}const liveDocument = this.deps.getDocument();- const liveIndex = liveDocument?.layers.findIndex((layer) => layer.id === upperLayerId) ?? -1;- if (!liveDocument || liveDocument.layers[liveIndex] !== upper || liveDocument.layers[liveIndex + 1] !== below) {+ if (+ !liveDocument ||+ getDocumentLayer(liveDocument, upperLayerId) !== upper ||+ lookupLayerBelow(liveDocument, upperLayerId) !== below+ ) {return 'not-ready';}const resultRect = roundOut(union(upperPixels.rect, belowPixels.rect));@@ -164,13 +168,13 @@ export class BooleanMergeController {const disabled = original.map(({ id }) => ({ id, isEnabled: false }));const selectedLayerId = liveDocument.selectedLayerId;const anchor = this.deps.captureInsertionAnchor('raster', upper.id);- const hasState = (doc: CanvasDocumentContractV2 | null, updates: typeof original): boolean =>- updates.every((update) => doc?.layers.find((layer) => layer.id === update.id)?.isEnabled === update.isEnabled);+ const hasState = (doc: CanvasDocumentContractV3 | null, updates: typeof original): boolean =>+ updates.every((update) => getDocumentLayer(doc, update.id)?.isEnabled === update.isEnabled);const apply = (): void => {const prepared = this.deps.preparePixels(resultId, resultRect, pixels);this.deps.dispatchPrepared({- add: [{ anchor, layers: [resultLayer] }],+ add: [{ anchor, nodes: [resultLayer] }],enabledUpdates: disabled,selectedLayerId: resultId,type: 'applyCanvasLayerStackMutation',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.test.tsindex 93ef766569..408a923daa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.test.ts@@ -1,9 +1,11 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { createHistory } from '@workbench/canvas-engine/history/history';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';@@ -64,13 +66,13 @@ describe('PixelEditController', () => {type: 'control',withTransparencyEffect: false,};- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 8, width: 8, x: 0, y: 0 },height: 8,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: layer.id,- version: 2,+ version: 3,width: 8,};const history = createHistory();@@ -132,13 +134,13 @@ describe('PixelEditController', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',};- const document: CanvasDocumentContractV2 = {+ let document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 8, width: 8, x: 0, y: 0 },height: 8,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: layer.id,- version: 2,+ version: 3,width: 8,};const entry = layers.getOrCreate(layer.id, 1, 1);@@ -152,7 +154,7 @@ describe('PixelEditController', () => {canEdit: () => true,deleteDerived: vi.fn(),dispatchReplacement: (replacement) => {- document.layers = [replacement];+ document = { ...document, stacks: stacksFrom([replacement]) };},endBurst: vi.fn(),getActiveProjectId: () => 'project-1',@@ -184,7 +186,7 @@ describe('PixelEditController', () => {rect: { height: 1, width: 1, x: 0, y: 0 },})).toThrow('transform cleanup failed');- expect(document.layers[0]).toMatchObject({ source: { type: 'paint' }, type: 'raster' });+ expect(getDocumentLeaves(document)[0]).toMatchObject({ source: { type: 'paint' }, type: 'raster' });expect(history.canUndo()).toBe(true);expect(markLayerDirty).toHaveBeenCalledWith(layer.id);expect(release).toHaveBeenCalledOnce();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.tsindex 47085a1fdb..76278d9280 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts@@ -1,6 +1,6 @@/** Transactional pixel editing for controls and destructively edited raster images. */-import type { CanvasControlLayerContract, CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasControlLayerContract, CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { BitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';@@ -15,6 +15,8 @@ import type { PixelEditTransaction, PixelEditPatch, StrokeCommittedEvent } fromimport type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';import {bakePixelEditSurface,@@ -36,12 +38,12 @@ export interface PixelEditControllerOptions {readonly endBurst: () => void;readonly getActiveProjectId: () => string | null;readonly getAdjustedSurface: (layer: PixelEditableLayer, entry: LayerCacheEntry) => RasterSurface | null;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getTransformSession: () => unknown;readonly history: History;readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;readonly invalidate: (layerId: string, overlay?: boolean) => void;- readonly isCacheReady: (layer: PixelEditableLayer, document: CanvasDocumentContractV2) => boolean;+ readonly isCacheReady: (layer: PixelEditableLayer, document: CanvasDocumentContractV3) => boolean;readonly isOperationIdle: () => boolean;readonly layers: LayerCacheStore;readonly notifyPainted: (layerId: string) => void;@@ -99,7 +101,7 @@ export class PixelEditController {begin(layerId: string): PixelEditTransaction | null {const o = this.options;const document = o.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(document, layerId);if (!o.canEdit() ||!document ||@@ -112,8 +114,11 @@ export class PixelEditController {) {return null;}+ const leaf = lookupDocumentLeaf(document, layerId);const contentRect = getSourceContentRect(layer, document);const decision = decidePixelEdit({+ contributionEnabled: leaf?.contributionEnabled ?? false,+ effectiveLocked: leaf?.effectiveLocked ?? true,hasSourceContent: !isEmpty(contentRect),isCacheReady: o.isCacheReady(layer, document),layer,@@ -218,7 +223,7 @@ export class PixelEditController {!o.canEdit() ||!o.isOperationIdle() ||document?.selectedLayerId !== layerId ||- document.layers.find((candidate) => candidate.id === layerId) !== layer+ getDocumentLayer(document, layerId) !== layer) {cancel();return false;@@ -401,7 +406,7 @@ export class PixelEditController {!o.canEdit() ||!o.isOperationIdle() ||document?.selectedLayerId !== layerId ||- document.layers.find((candidate) => candidate.id === layerId) !== layer ||+ getDocumentLayer(document, layerId) !== layer ||!edited ||(event && event.layerId !== layerId)) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.tsindex c286f003c1..741f92cd46 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts@@ -1,6 +1,6 @@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 { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';import type { History } from '@workbench/canvas-engine/history/history';@@ -9,6 +9,8 @@ import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/renimport type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };@@ -16,13 +18,13 @@ type ExportResult =export interface CopyLayerControllerOptions {readonly concurrency: CanvasEditConcurrency;readonly history: History;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;+ readonly getReducerDocument: () => CanvasDocumentContractV3 | null;readonly endBurst: () => void;readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;readonly dispatchPrepared: (@@ -44,7 +46,7 @@ export class CopyLayerController {}this.deps.endBurst();const document = this.deps.getDocument();- const sourceLayer = document?.layers.find((candidate) => candidate.id === layerId);+ const sourceLayer = getDocumentLayer(document, layerId);if (!document || !sourceLayer) {return null;}@@ -64,7 +66,7 @@ export class CopyLayerController {return null;}const liveDocument = this.deps.getDocument();- if (!liveDocument || !liveDocument.layers.includes(sourceLayer)) {+ if (!liveDocument || getDocumentLayer(liveDocument, sourceLayer.id) !== sourceLayer) {return null;}const newId = this.deps.createLayerId();@@ -85,17 +87,17 @@ export class CopyLayerController {const prepared = this.deps.preparePixels(newId, baked.rect, baked.surface);this.deps.dispatchPrepared({- add: [{ anchor, layers: [layer] }],+ add: [{ anchor, nodes: [layer] }],enabledUpdates: [],selectedLayerId: newId,type: 'applyCanvasLayerStackMutation',},() =>this.deps.getReducerDocument()?.selectedLayerId === newId &&- this.deps.getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,+ getDocumentLayer(this.deps.getReducerDocument(), layer.id) === layer,() =>this.deps.getDocument()?.selectedLayerId === newId &&- this.deps.getDocument()?.layers.some((candidate) => candidate === layer) === true+ getDocumentLayer(this.deps.getDocument(), layer.id) === layer);this.deps.installPrepared(prepared);};@@ -113,10 +115,10 @@ export class CopyLayerController {{ enabledUpdates: [], removeIds: [newId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },() =>this.deps.getReducerDocument()?.selectedLayerId === selectedLayerId &&- this.deps.getReducerDocument()?.layers.some((candidate) => candidate.id === newId) === false,+ isNodeAbsent(this.deps.getReducerDocument(), newId),() =>this.deps.getDocument()?.selectedLayerId === selectedLayerId &&- this.deps.getDocument()?.layers.some((candidate) => candidate.id === newId) === false+ isNodeAbsent(this.deps.getDocument(), newId)),});return newId;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.tsindex 294365e205..a8be2ce994 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@ -1,6 +1,6 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';@@ -11,6 +11,7 @@ import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/renimport type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { intersect, isEmpty, roundOut } from '@workbench/canvas-engine/math/rect';@@ -32,15 +33,15 @@ export interface CropLayerControllerOptions {readonly concurrency: CanvasEditConcurrency;readonly backend: RasterBackend;readonly history: History;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;+ readonly getReducerDocument: () => CanvasDocumentContractV3 | null;readonly endBurst: () => void;readonly isSupportedSource: (source: CanvasLayerSourceContract) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;readonly captureCache: (layer: CanvasLayerContract,- document: CanvasDocumentContractV2+ document: CanvasDocumentContractV3) => PixelSnapshot | null | 'not-ready';readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;@@ -64,7 +65,7 @@ export class CropLayerController {}this.deps.endBurst();const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(document, layerId);if (!document || !layer) {return { status: 'missing' };}@@ -85,7 +86,7 @@ export class CropLayerController {return { status: 'busy' };}const liveDocument = this.deps.getDocument();- const liveLayer = liveDocument?.layers.find((candidate) => candidate.id === layerId);+ const liveLayer = getDocumentLayer(liveDocument, layerId);if (!liveDocument || !liveLayer) {return { status: 'missing' };}@@ -131,8 +132,8 @@ export class CropLayerController {const publish = (contract: CanvasLayerContract, prepared: PreparedLayerCacheReplacement): void => {this.deps.dispatchPrepared({ layer: contract, layerId, type: 'replaceCanvasLayer' },- () => this.deps.getReducerDocument()?.layers.find((candidate) => candidate.id === layerId) === contract,- () => this.deps.getDocument()?.layers.find((candidate) => candidate.id === layerId) === contract+ () => getDocumentLayer(this.deps.getReducerDocument(), layerId) === contract,+ () => getDocumentLayer(this.deps.getDocument(), layerId) === contract);try {this.deps.discardPersisted(layerId);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.tsindex 06d7cbfc2c..b5a80d2c62 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts@@ -1,8 +1,9 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { CanvasEditGate, CanvasEditGateController } from '@workbench/canvas-engine/editGate';import type { SelectionState, SelectionStateDeps } from '@workbench/canvas-engine/selection/selectionState';import type { Rect } from '@workbench/canvas-engine/types';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';import { getSourceBounds, isRenderableLayer } from '@workbench/canvas-engine/document/sources';import { createCanvasEditGate } from '@workbench/canvas-engine/editGate';import { roundOut, union } from '@workbench/canvas-engine/math/rect';@@ -16,7 +17,7 @@ import { TransformEditingController, type TransformEditingControllerOptions } frexport interface EditingControllerOptions {readonly selection: SelectionStateDeps;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly createSelectionState?: (deps: SelectionStateDeps) => SelectionState;readonly createEditGate?: () => CanvasEditGateController;readonly text: TextEditingControllerOptions;@@ -36,7 +37,7 @@ export class EditingController {readonly selectionImage: SelectionImageController;readonly floatingSelection: FloatingSelectionController;private readonly editGate: CanvasEditGateController;- private readonly getDocument: () => CanvasDocumentContractV2 | null;+ private readonly getDocument: () => CanvasDocumentContractV3 | null;private disposed = false;constructor(options: EditingControllerOptions) {@@ -69,9 +70,9 @@ export class EditingController {return null;}let bounds: Rect = { ...document.bbox };- for (const layer of document.layers) {- if (isRenderableLayer(layer)) {- bounds = union(bounds, getSourceBounds(layer, document));+ for (const leaf of compileDocumentLeaves(document)) {+ if (leaf.contributionEnabled && isRenderableLayer(leaf.layer)) {+ bounds = union(bounds, getSourceBounds(leaf.layer, document));}}return roundOut(bounds);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.tsindex 72ef1fe965..52e43c6c38 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts@@ -1,7 +1,7 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';import type { History } from '@workbench/canvas-engine/history/history';@@ -15,7 +15,9 @@ import type {import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { createEmptyStacks } from '@workbench/canvas-engine/document/documentTree';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';import { isEmpty } from '@workbench/canvas-engine/math/rect';import { compositeDocument } from '@workbench/canvas-engine/render/compositor';@@ -35,10 +37,10 @@ export interface ExtractMaskedAreaControllerOptions {readonly derived: DerivedSurfaceCache;readonly diagnostics: CanvasDiagnostics;readonly history: History;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;+ readonly getReducerDocument: () => CanvasDocumentContractV3 | null;readonly endBurst: () => void;- readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => boolean;+ readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;readonly hasExportableContent: (layerId: string) => boolean;readonly exportBaked: (layerId: string, includeDisabled?: boolean) => Promise<ExportResult>;readonly rasterize: (layerId: string) => Promise<ExportResult>;@@ -46,7 +48,7 @@ export interface ExtractMaskedAreaControllerOptions {readonly getAdjustedSurface: (layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null;readonly getMaskPattern: (style: string, color: string) => RasterSurface | null;readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;readonly dispatchPrepared: (@@ -57,6 +59,15 @@ export interface ExtractMaskedAreaControllerOptions {}/** Owns guarded extraction of raster content through an inpaint mask. */+/** Contributing raster leaves with content, top first, with ancestor state applied. */+const contributingRasters = (+ document: CanvasDocumentContractV3,+ hasContent: (layerId: string) => boolean+): CanvasLayerContract[] =>+ compileDocumentLeaves(document)+ .filter((leaf) => leaf.stack === 'raster' && leaf.contributionEnabled && hasContent(leaf.id))+ .map((leaf) => leaf.layer);+export class ExtractMaskedAreaController {private disposed = false;constructor(private readonly deps: ExtractMaskedAreaControllerOptions) {}@@ -71,8 +82,8 @@ export class ExtractMaskedAreaController {if (!document) {return { status: 'missing' };}- const maskIndex = document.layers.findIndex((layer) => layer.id === maskLayerId);- const mask = document.layers[maskIndex];+ const maskIndex = getDocumentLeaves(document).findIndex((layer) => layer.id === maskLayerId);+ const mask = getDocumentLeaves(document)[maskIndex];if (maskIndex < 0 || !mask) {return { status: 'missing' };}@@ -83,9 +94,7 @@ export class ExtractMaskedAreaController {if (isEmpty(getSourceContentRect(mask, document)) && (!liveMask || isEmpty(liveMask.rect))) {return { status: 'empty' };}- const contributors = document.layers.filter(- (layer) => isLayerContributing(layer) && layer.type === 'raster' && this.deps.hasExportableContent(layer.id)- );+ const contributors = contributingRasters(document, this.deps.hasExportableContent);if (contributors.length === 0) {return { status: 'empty' };}@@ -131,17 +140,16 @@ export class ExtractMaskedAreaController {return { status: 'not-ready' };}const liveDocument = this.deps.getDocument();- const liveMaskIndex = liveDocument?.layers.findIndex((layer) => layer.id === maskLayerId) ?? -1;- const currentMask = liveDocument?.layers[liveMaskIndex];+ const liveMaskIndex =+ getDocumentLeaves(liveDocument ?? null).findIndex((layer) => layer.id === maskLayerId) ?? -1;+ const currentMask = getDocumentLeaves(liveDocument ?? null)[liveMaskIndex];if (!liveDocument || !currentMask) {return { status: 'missing' };}if (currentMask !== mask) {return { status: currentMask.type === 'inpaint_mask' && currentMask.isLocked ? 'unsupported' : 'not-ready' };}- const liveContributors = liveDocument.layers.filter(- (layer) => isLayerContributing(layer) && layer.type === 'raster' && this.deps.hasExportableContent(layer.id)- );+ const liveContributors = contributingRasters(liveDocument, this.deps.hasExportableContent);if (liveMaskIndex !== maskIndex ||liveContributors.some((layer, index) => layer !== contributors[index]) ||@@ -169,7 +177,7 @@ export class ExtractMaskedAreaController {const pixels = this.deps.backend.createSurface(rect.width, rect.height);compositeDocument(pixels,- { ...document, layers: contributors },+ { ...document, stacks: { ...createEmptyStacks(), raster: contributors } },this.deps.layers,{ a: 1, b: 0, c: 0, d: 1, e: -rect.x, f: -rect.y },{@@ -202,17 +210,17 @@ export class ExtractMaskedAreaController {const prepared = this.deps.preparePixels(resultId, rect, pixels);this.deps.dispatchPrepared({- add: [{ anchor, layers: [layer] }],+ add: [{ anchor, nodes: [layer] }],enabledUpdates: [],selectedLayerId: resultId,type: 'applyCanvasLayerStackMutation',},() =>this.deps.getReducerDocument()?.selectedLayerId === resultId &&- this.deps.getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,+ getDocumentLayer(this.deps.getReducerDocument(), layer.id) === layer,() =>this.deps.getDocument()?.selectedLayerId === resultId &&- this.deps.getDocument()?.layers.some((candidate) => candidate === layer) === true+ getDocumentLayer(this.deps.getDocument(), layer.id) === layer);this.deps.installPrepared(prepared);};@@ -230,10 +238,10 @@ export class ExtractMaskedAreaController {{ enabledUpdates: [], removeIds: [resultId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },() =>this.deps.getReducerDocument()?.selectedLayerId === selectedLayerId &&- this.deps.getReducerDocument()?.layers.some((candidate) => candidate.id === resultId) === false,+ isNodeAbsent(this.deps.getReducerDocument(), resultId),() =>this.deps.getDocument()?.selectedLayerId === selectedLayerId &&- this.deps.getDocument()?.layers.some((candidate) => candidate.id === resultId) === false+ isNodeAbsent(this.deps.getDocument(), resultId)),});return { layerId: resultId, status: 'extracted' };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.tsindex 3882875cf7..6d3b5c582a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts@@ -1,7 +1,7 @@import type { CommitRasterFilterOptions, CommitRasterFilterResult } from '@workbench/canvas-engine/capabilities';import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,CanvasRasterLayerContractV2,@@ -12,6 +12,7 @@ import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/renimport type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';import { createControlLayer } from '@workbench/canvas-engine/document/layerFactories';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';@@ -25,7 +26,7 @@ export type {} from '@workbench/canvas-engine/capabilities';export interface FilterResultControllerOptions {- readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;+ readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => CapturedLayerCache;readonly ctx: CanvasMutationContext;readonly decodeImage: (image: CanvasImageRef,@@ -78,7 +79,7 @@ export class FilterResultController {}const pixels = decoded.surface;const document = o.ctx.getDocument();- const liveLayer = document?.layers.find((candidate) => candidate.id === options.guard.layerId);+ const liveLayer = getDocumentLayer(document, options.guard.layerId);if (!document || !liveLayer) {return { status: 'missing' };}@@ -122,8 +123,8 @@ export class FilterResultController {): void => {o.ctx.dispatchPrepared({ layer: contract, layerId: liveLayer.id, type: 'replaceCanvasLayer' },- () => o.ctx.getReducerDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract,- () => o.ctx.getDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract+ () => getDocumentLayer(o.ctx.getReducerDocument(), liveLayer.id) === contract,+ () => getDocumentLayer(o.ctx.getDocument(), liveLayer.id) === contract);if (publishOptions.discardPersistence) {try {@@ -201,8 +202,8 @@ export class FilterResultController {const prepared = o.ctx.preparePixels(layerId, rect, pixels);o.ctx.dispatchPrepared({ anchor, layer: copy, type: 'addCanvasLayer' },- () => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,- () => o.ctx.getDocument()?.layers.some((candidate) => candidate === copy) === true+ () => getDocumentLayer(o.ctx.getReducerDocument(), copy.id) === copy,+ () => getDocumentLayer(o.ctx.getDocument(), copy.id) === copy);o.ctx.installPrepared(prepared, false);};@@ -220,8 +221,8 @@ export class FilterResultController {);o.ctx.dispatchPrepared({ ids: [layerId], type: 'removeCanvasLayers' },- () => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,- () => o.ctx.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false+ () => isNodeAbsent(o.ctx.getReducerDocument(), layerId),+ () => isNodeAbsent(o.ctx.getDocument(), layerId));},});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.tsindex bd85ab9b3a..b0cf487784 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts@@ -1,7 +1,8 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createHistory } from '@workbench/canvas-engine/history/history';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';@@ -21,13 +22,13 @@ const paintLayer = (id: string, transform: Partial<CanvasLayerContract['transfortype: 'raster',});-const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: layers[0]?.id ?? null,- version: 2,+ version: 3,width: 100,});@@ -36,7 +37,7 @@ const createHarness = (options: { layer?: CanvasLayerContract; maskRect?: Rect;const layers = createLayerCacheStore(backend);const history = createHistory();const layer = options.layer ?? paintLayer('a');- let document: CanvasDocumentContractV2 | null = makeDoc([layer]);+ let document: CanvasDocumentContractV3 | null = makeDoc([layer]);const maskRect = options.maskRect ?? { height: 30, width: 30, x: 20, y: 20 };const maskSurface: PlacedSurface = {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.tsindex f22f6a3505..4c56fb4303 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -8,7 +8,9 @@ import type { SelectionState } from '@workbench/canvas-engine/selection/selectioimport type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';-import { isLayerPixelEditEligible } from '@workbench/canvas-engine/editing/controlPixelEdit';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafPixelEditEligible } from '@workbench/canvas-engine/editing/controlPixelEdit';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { renderLayerDisplayEffect } from '@workbench/canvas-engine/render/layerDisplayEffect';@@ -27,7 +29,7 @@ export interface FloatingSelectionControllerOptions {readonly selection: SelectionState;readonly history: History;readonly applyImagePatch: ImagePatchApply;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly canEdit: () => boolean;readonly endBurst: () => void;readonly notifyPainted: (layerId: string) => void;@@ -78,7 +80,7 @@ export class FloatingSelectionController {/** The float's layer, or `null` — resolved fresh so a deleted layer reads as absent. */private layerOf(float: FloatingSelection): CanvasLayerContract | null {const document = this.deps.getDocument();- return document?.layers.find((layer) => layer.id === float.layerId) ?? null;+ return getDocumentLayer(document, float.layerId) ?? null;}/**@@ -91,8 +93,9 @@ export class FloatingSelectionController {return false;}const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);- if (!document || !layer || !isLayerPixelEditEligible(layer)) {+ const leaf = lookupDocumentLeaf(document, layerId);+ const layer = leaf?.layer;+ if (!document || !layer || !isLeafPixelEditEligible(leaf)) {return false;}const mask = this.deps.selection.mask();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.tsindex 7e6c95d015..ab92770df8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts@@ -1,5 +1,5 @@import type { CommitGeneratedImageOptions, CommitGeneratedImageResult } from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CapturedLayerCache } from '@workbench/canvas-engine/controllers/layerMutationController';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';@@ -7,12 +7,13 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';+import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';import { createControlLayer, nextControlLayerName } from '@workbench/canvas-engine/document/layerFactories';import type { CanvasMutationContext } from './mutationContext';export interface GeneratedResultControllerOptions {- readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;+ readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => CapturedLayerCache;readonly clearPreview: (layerId: string) => void;readonly ctx: CanvasMutationContext;readonly decodeImage: (@@ -39,7 +40,7 @@ export class GeneratedResultController {return { status: 'aborted' };}const validate = ():- | { document: CanvasDocumentContractV2; liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }> }+ | { document: CanvasDocumentContractV3; liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }> }| { result: CommitGeneratedImageResult } => {if (!o.ctx.isPermitCurrent(permit)) {return { result: { status: 'busy' } };@@ -48,7 +49,7 @@ export class GeneratedResultController {if (!document) {return { result: { status: 'missing' } };}- const liveLayer = document.layers.find((layer) => layer.id === options.guard.layerId);+ const liveLayer = getDocumentLayer(document, options.guard.layerId);if (!liveLayer) {return { result: { status: 'missing' } };}@@ -91,8 +92,8 @@ export class GeneratedResultController {): void => {o.ctx.dispatchPrepared({ layer: contract, layerId: liveLayer.id, type: 'replaceCanvasLayer' },- () => o.ctx.getReducerDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract,- () => o.ctx.getDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract+ () => getDocumentLayer(o.ctx.getReducerDocument(), liveLayer.id) === contract,+ () => getDocumentLayer(o.ctx.getDocument(), liveLayer.id) === contract);if (publishOptions.discardPersistence) {try {@@ -160,7 +161,7 @@ export class GeneratedResultController {const mainBase = o.getMainModelBase();return {...createControlLayer(- options.copyLayerName ?? nextControlLayerName(document.layers.map((layer) => layer.name)),+ options.copyLayerName ?? nextControlLayerName(getDocumentLeaves(document).map((layer) => layer.name)),layerId,mainBase,o.getDefaultControlModel(mainBase)@@ -187,8 +188,8 @@ export class GeneratedResultController {const publishCopy = (prepared: PreparedLayerCacheReplacement): void => {o.ctx.dispatchPrepared({ anchor, layer: copy, type: 'addCanvasLayer' },- () => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,- () => o.ctx.getDocument()?.layers.some((candidate) => candidate === copy) === true+ () => getDocumentLayer(o.ctx.getReducerDocument(), copy.id) === copy,+ () => getDocumentLayer(o.ctx.getDocument(), copy.id) === copy);o.ctx.installPrepared(prepared, false);};@@ -219,8 +220,8 @@ export class GeneratedResultController {);o.ctx.dispatchPrepared({ ids: [layerId], type: 'removeCanvasLayers' },- () => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,- () => o.ctx.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false+ () => isNodeAbsent(o.ctx.getReducerDocument(), layerId),+ () => isNodeAbsent(o.ctx.getDocument(), layerId));},});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.tsindex c6f1b0915f..e793b22134 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts@@ -1,7 +1,7 @@import type { DuplicateLayersResult } from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterMemoryReservationResult } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';import type { History } from '@workbench/canvas-engine/history/history';@@ -10,8 +10,18 @@ import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/renimport type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import {+ getDocumentIndex,+ getDocumentLayer,+ hasDocumentNode,+ isNodeAbsent,+ outermostNodes,+ type CanvasNodeEntry,+} from '@workbench/canvas-engine/document/documentIndex';+import { cloneSubtree, collectSubtreeLeaves } from '@workbench/canvas-engine/document/documentTree';+import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';export type CapturedLayerCache = { pixels: RasterSurface; rect: Rect } | null | 'not-ready';@@ -33,8 +43,9 @@ type DuplicateRasterPreparationResult =export interface LayerMutationControllerOptions {readonly concurrency: CanvasEditConcurrency;- readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => CapturedLayerCache;+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;+ readonly captureRestoreAnchor: (nodeId: string) => CanvasNodeInsertionAnchor | null;readonly createLayerId: () => string;readonly discardPersisted: (layerId: string) => void;readonly dispatchPrepared: (@@ -45,12 +56,12 @@ export interface LayerMutationControllerOptions {readonly endBurst: () => void;readonly getDuplicateRasterPlan: (layer: CanvasLayerContract,- document: CanvasDocumentContractV2+ document: CanvasDocumentContractV3) => DuplicateLayerRasterPlan;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getEditRevision: () => number;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;- readonly getSelectedLayerIds: (document: CanvasDocumentContractV2) => readonly string[];+ readonly getReducerDocument: () => CanvasDocumentContractV3 | null;+ readonly getSelectedLayerIds: (document: CanvasDocumentContractV3) => readonly string[];readonly history: History;readonly hasPendingPixelWork: (layerId: string) => boolean;readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;@@ -61,10 +72,20 @@ export interface LayerMutationControllerOptions {readonly pinDuplicateRasterSources: (layerIds: readonly string[]) => { release(): void };readonly reserve: (bytes: number) => RasterMemoryReservationResult;readonly scheduleDuplicateRasterization: (layerIds: readonly string[]) => void;- readonly sameContract: (document: CanvasDocumentContractV2 | null, layer: CanvasLayerContract) => boolean;+ readonly sameContract: (document: CanvasDocumentContractV3 | null, layer: CanvasLayerContract) => boolean;readonly trackDetached: (bytes: number) => { release(): void };}+/** The outermost requested nodes in document order, or `null` when any id is absent or none is given. */+const duplicateRoots = (document: CanvasDocumentContractV3, ids: readonly string[]): CanvasNodeEntry[] | null => {+ const index = getDocumentIndex(document);+ const unique = [...new Set(ids)];+ if (unique.length === 0 || unique.some((id) => !index.byId.has(id))) {+ return null;+ }+ return outermostNodes(index, unique);+};+/** Owns failure-atomic copy and cross-type conversion mutations. */export class LayerMutationController {private duplicateInFlight = false;@@ -81,11 +102,11 @@ export class LayerMutationController {if (!document) {return { status: 'nothing' };}- const requested = new Set(layerIds);- const sources = document.layers.filter((layer) => requested.has(layer.id));- if (sources.length === 0 || sources.length !== requested.size) {+ const roots = duplicateRoots(document, layerIds);+ if (!roots) {return { status: 'nothing' };}+ const sources = roots.flatMap((entry) => collectSubtreeLeaves(entry.node));const plans = sources.map((source) => o.getDuplicateRasterPlan(source, document));const notReadySources = sources.filter((_source, index) => plans[index]?.type === 'not-ready');if (notReadySources.length === 0) {@@ -127,11 +148,11 @@ export class LayerMutationController {if (!document) {return { status: 'nothing' };}- const requested = new Set(layerIds);- const sources = document.layers.filter((layer) => requested.has(layer.id));- if (sources.length === 0 || sources.length !== requested.size) {+ const roots = duplicateRoots(document, layerIds);+ if (!roots) {return { status: 'nothing' };}+ const sources = roots.flatMap((entry) => collectSubtreeLeaves(entry.node));const plans = sources.map((source) => o.getDuplicateRasterPlan(source, document));let retainedBytes = 0;let reserveBytes = 0;@@ -167,50 +188,51 @@ export class LayerMutationController {if (captures.some((capture) => capture === 'not-ready')) {return { status: 'not-ready' };}- const existingIds = new Set(document.layers.map((layer) => layer.id));- const duplicates = sources.map((source) => {- const duplicate = structuredClone(source);- duplicate.id = o.createLayerId();- duplicate.name = `${source.name} copy`;- return duplicate;+ const existingIds = new Set(getDocumentIndex(document).byId.keys());+ const idMap = new Map<string, string>();+ const clones = roots.map((entry) => {+ const { node } = cloneSubtree(entry.node, o.createLayerId, idMap);+ return { ...node, name: `${entry.node.name} copy` };});- for (const [index, duplicate] of duplicates.entries()) {- if (plans[index]?.type !== 'empty') {- continue;- }- if (duplicate.type === 'raster' || duplicate.type === 'control') {- if (duplicate.source.type === 'paint') {- duplicate.source = { bitmap: null, type: 'paint' };+ const cloneLeaves = new Map(+ clones.flatMap((clone) => collectSubtreeLeaves(clone)).map((leaf) => [leaf.id, leaf])+ );+ // The cloned leaf for each pixel source, in source order; clones are fresh objects, so an+ // empty plan can strip their durable pixel reference in place before they enter the document.+ const duplicates = sources.map((source, index) => {+ const duplicate = cloneLeaves.get(idMap.get(source.id)!)!;+ if (plans[index]?.type === 'empty') {+ if (duplicate.type === 'raster' || duplicate.type === 'control') {+ if (duplicate.source.type === 'paint') {+ duplicate.source = { bitmap: null, type: 'paint' };+ }+ } else {+ duplicate.mask = { ...duplicate.mask, bitmap: null, offset: { x: 0, y: 0 } };}- } else if (duplicate.type === 'regional_guidance' || duplicate.type === 'inpaint_mask') {- duplicate.mask = { ...duplicate.mask, bitmap: null, offset: { x: 0, y: 0 } };}- }- if (- duplicates.some((layer) => existingIds.has(layer.id)) ||- new Set(duplicates.map((layer) => layer.id)).size !== duplicates.length- ) {+ return duplicate;+ });+ const createdIds = [...idMap.values()];+ if (createdIds.some((id) => existingIds.has(id)) || new Set(createdIds).size !== createdIds.length) {return { status: 'stale' };}- const duplicateBySource = new Map(sources.map((source, index) => [source.id, duplicates[index]!]));- const insertions = sources.map((source, index) => ({- anchor: o.captureInsertionAnchor(source.type, source.id),- layers: [duplicates[index]!],+ const insertions = roots.map((entry, index) => ({+ anchor: o.captureInsertionAnchor(entry.stack, entry.node.id),+ nodes: [clones[index]!],}));- const expectedLayers = insertions.reduce(- (layers, insertion) => insertLayersAtAnchor(layers, insertion.anchor, insertion.layers),- document.layers+ const expectedStacks = insertions.reduce(+ (stacks, insertion) => insertNodesAtAnchor(stacks, insertion.anchor, insertion.nodes),+ document.stacks);const selectedLayerId =- (document.selectedLayerId ? duplicateBySource.get(document.selectedLayerId)?.id : null) ?? duplicates[0]!.id;+ (document.selectedLayerId ? idMap.get(document.selectedLayerId) : undefined) ?? clones[0]!.id;const previousSelectedLayerId = document.selectedLayerId;const previousSelectedIds = [...o.getSelectedLayerIds(document)];- const duplicateIds = duplicates.map((layer) => layer.id);- const hasDuplicates = (candidate: CanvasDocumentContractV2 | null): boolean =>- candidate?.selectedLayerId === selectedLayerId && haveSameStackOrders(candidate.layers, expectedLayers);- const hasOriginals = (candidate: CanvasDocumentContractV2 | null): boolean =>- candidate?.selectedLayerId === previousSelectedLayerId &&- haveSameStackOrders(candidate.layers, document.layers);+ const duplicateIds = clones.map((clone) => clone.id);+ const hasDuplicates = (candidate: CanvasDocumentContractV3 | null): boolean =>+ candidate?.selectedLayerId === selectedLayerId && haveSameStructure(candidate.stacks, expectedStacks);+ const hasOriginals = (candidate: CanvasDocumentContractV3 | null): boolean =>+ candidate?.selectedLayerId === previousSelectedLayerId && haveSameStructure(candidate.stacks, document.stacks);const applyPrepared = (prepared: readonly { duplicate: CanvasLayerContract; replacement: PreparedLayerCacheReplacement }[]): void => {@@ -330,19 +352,19 @@ export class LayerMutationController {}}- copy(label: string, sourceLayerId: string, layer: CanvasLayerContract, anchor: FlatLayerInsertionAnchor): boolean {+ copy(label: string, sourceLayerId: string, layer: CanvasLayerContract, anchor: CanvasNodeInsertionAnchor): boolean {const o = this.options;if (!o.concurrency.canEdit() || o.concurrency.isGestureActive()) {return false;}o.endBurst();const document = o.getDocument();- const source = document?.layers.find((candidate) => candidate.id === sourceLayerId);+ const source = getDocumentLayer(document, sourceLayerId);if (!document ||!source ||anchor.capturedEditRevision !== o.getEditRevision() ||- document.layers.some((candidate) => candidate.id === layer.id)+ hasDocumentNode(document, layer.id)) {return false;}@@ -355,17 +377,15 @@ export class LayerMutationController {const prepared = captured ? o.preparePixels(layer.id, captured.rect, captured.pixels) : null;o.dispatchPrepared({- add: [{ anchor, layers: [layer] }],+ add: [{ anchor, nodes: [layer] }],enabledUpdates: [],selectedLayerId: layer.id,type: 'applyCanvasLayerStackMutation',},() =>o.getReducerDocument()?.selectedLayerId === layer.id &&- o.getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,- () =>- o.getDocument()?.selectedLayerId === layer.id &&- o.getDocument()?.layers.some((candidate) => candidate === layer) === true+ getDocumentLayer(o.getReducerDocument(), layer.id) === layer,+ () => o.getDocument()?.selectedLayerId === layer.id && getDocumentLayer(o.getDocument(), layer.id) === layer);if (prepared) {o.installPrepared(prepared, o.needsPixelPersistence(layer));@@ -382,10 +402,8 @@ export class LayerMutationController {{ enabledUpdates: [], removeIds: [layer.id], selectedLayerId, type: 'applyCanvasLayerStackMutation' },() =>o.getReducerDocument()?.selectedLayerId === selectedLayerId &&- o.getReducerDocument()?.layers.some((candidate) => candidate.id === layer.id) === false,- () =>- o.getDocument()?.selectedLayerId === selectedLayerId &&- o.getDocument()?.layers.some((candidate) => candidate.id === layer.id) === false+ isNodeAbsent(o.getReducerDocument(), layer.id),+ () => o.getDocument()?.selectedLayerId === selectedLayerId && isNodeAbsent(o.getDocument(), layer.id)),});return true;@@ -403,18 +421,26 @@ export class LayerMutationController {}o.endBurst();const document = o.getDocument();- const current = document?.layers.find((candidate) => candidate.id === expected.id);- if (!document || !current || current !== expected || current.isLocked || current.type !== expected.type) {+ const current = getDocumentLayer(document, expected.id);+ if (+ !document ||+ !current ||+ current !== expected ||+ current.type !== expected.type ||+ lookupDocumentLeaf(document, current.id)?.effectiveLocked !== false+ ) {return false;}const captured = o.captureCache(current, document);if (captured === 'not-ready') {return false;}- const apply = (layer: CanvasLayerContract): void => {+ // A conversion changes stacks, so undo carries the leaf back to its captured place.+ const restoreAnchor = o.captureRestoreAnchor(current.id) ?? undefined;+ const apply = (layer: CanvasLayerContract, anchor?: CanvasNodeInsertionAnchor): void => {const prepared = captured ? o.preparePixels(layer.id, captured.rect, captured.pixels) : null;o.dispatchPrepared(- { id: layer.id, layer, targetType: layer.type, type: 'convertCanvasLayer' },+ { anchor, id: layer.id, layer, targetType: layer.type, type: 'convertCanvasLayer' },() => o.sameContract(o.getReducerDocument(), layer),() => o.sameContract(o.getDocument(), layer));@@ -434,7 +460,7 @@ export class LayerMutationController {label,redo: () => apply(after),replayFailureAtomic: true,- undo: () => apply(before),+ undo: () => apply(before, restoreAnchor),});return true;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.tsindex 0fd08132b1..43b32ccef3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts@@ -1,11 +1,13 @@-import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { Rect } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { getSourceContentRect, isMaskLayer } from '@workbench/canvas-engine/document/sources';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';import { invert as invertMatrix } from '@workbench/canvas-engine/math/mat2d';@@ -16,10 +18,10 @@ export interface MaskLayerControllerOptions {readonly layers: LayerCacheStore;readonly history: History;readonly applyImagePatch: ImagePatchApply;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly canEdit: () => boolean;readonly isGestureActive: () => boolean;- readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => boolean;+ readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;readonly endBurst: () => void;readonly discardPersisted: (layerId: string) => void;readonly markDirty: (layerId: string) => void;@@ -40,7 +42,7 @@ export class MaskLayerController {return false;}const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(document, layerId);if (!document || !layer || !isMaskLayer(layer) || layer.isLocked) {return false;}@@ -91,8 +93,9 @@ export class MaskLayerController {return false;}const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);- if (!document || !layer || !isMaskLayer(layer) || !isLayerEditable(layer)) {+ const leaf = lookupDocumentLeaf(document, layerId);+ const layer = leaf?.layer;+ if (!document || !layer || !isMaskLayer(layer) || !isLeafEditable(leaf)) {return false;}if (!this.deps.isCacheReady(layer, document)) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.tsindex f8b29416fd..1ca27a74ad 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts@@ -3,13 +3,14 @@ import type {CommitMaskImageResultOptions,LayerExportGuard,} from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';import type { History } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';import {createInpaintMaskFromImage,createRegionalGuidanceFromImage,@@ -26,7 +27,7 @@ export type {} from '@workbench/canvas-engine/capabilities';export interface MaskResultControllerOptions {- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;readonly concurrency: CanvasEditConcurrency;readonly createLayerId: () => string;readonly dispatchPrepared: (@@ -35,8 +36,8 @@ export interface MaskResultControllerOptions {mirrorAccepted: () => boolean) => void;readonly endBurst: () => void;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;+ readonly getReducerDocument: () => CanvasDocumentContractV3 | null;readonly history: History;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;}@@ -57,7 +58,7 @@ export class MaskResultController {if (!document) {return Promise.resolve({ status: 'missing' });}- const liveLayer = document.layers.find((candidate) => candidate.id === options.guard.layerId);+ const liveLayer = getDocumentLayer(document, options.guard.layerId);if (!liveLayer) {return Promise.resolve({ status: 'missing' });}@@ -76,7 +77,7 @@ export class MaskResultController {if (options.signal?.aborted) {return Promise.resolve({ status: 'aborted' });}- const names = document.layers.map((layer) => layer.name);+ const names = getDocumentLeaves(document).map((layer) => layer.name);const layerId = o.createLayerId();const layer =options.target === 'inpaint_mask'@@ -90,7 +91,7 @@ export class MaskResultController {: createRegionalGuidanceFromImage({fill: {color: nextRegionalGuidanceFillColor(- document.layers.filter((candidate) => candidate.type === 'regional_guidance').length+ getDocumentLeaves(document).filter((candidate) => candidate.type === 'regional_guidance').length),style: 'solid',},@@ -104,8 +105,8 @@ export class MaskResultController {const apply = (): void =>o.dispatchPrepared({ anchor, layer, type: 'addCanvasLayer' },- () => o.getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,- () => o.getDocument()?.layers.some((candidate) => candidate === layer) === true+ () => getDocumentLayer(o.getReducerDocument(), layer.id) === layer,+ () => getDocumentLayer(o.getDocument(), layer.id) === layer);o.endBurst();apply();@@ -122,8 +123,8 @@ export class MaskResultController {);o.dispatchPrepared({ ids: [layerId], type: 'removeCanvasLayers' },- () => o.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,- () => o.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false+ () => isNodeAbsent(o.getReducerDocument(), layerId),+ () => isNodeAbsent(o.getDocument(), layerId));},});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex d959d71c11..f77ccdd55c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@ -1,13 +1,19 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterMemoryReservationResult } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import { lookupDocumentLayer, mergeDownEligibility } from '@workbench/canvas-engine/document-model/flatDocumentModel';-import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';+import {+ lookupDocumentLayer,+ mergeDownEligibility,+ compileDocumentLeaves,+} from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { removeNodes } from '@workbench/canvas-engine/document/documentTree';+import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';import { canMergeSelectedRasters, getMergeVisibleRasterLayers } from '@workbench/canvas-engine/document/mergeVisible';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';@@ -26,7 +32,7 @@ export interface MergeLayerControllerOptions {readonly ctx: CanvasMutationContext;readonly layers: LayerCacheStore;readonly canEdit: () => boolean;- readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => boolean;+ readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;readonly hasExportableContent: (layerId: string) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly notifyPainted: (layerId: string) => void;@@ -135,7 +141,7 @@ export class MergeLayerController {if (!document) {return 'nothing';}- const contributors = getMergeVisibleRasterLayers(document.layers, this.deps.hasExportableContent);+ const contributors = getMergeVisibleRasterLayers(compileDocumentLeaves(document), this.deps.hasExportableContent);if (contributors.length < 2) {return 'nothing';}@@ -182,7 +188,7 @@ export class MergeLayerController {const liveDocument = this.deps.ctx.getDocument();const liveContributors = liveDocument- ? getMergeVisibleRasterLayers(liveDocument.layers, this.deps.hasExportableContent)+ ? getMergeVisibleRasterLayers(compileDocumentLeaves(liveDocument), this.deps.hasExportableContent): [];if (!liveDocument ||@@ -229,13 +235,13 @@ export class MergeLayerController {};const selectedLayerId = liveDocument.selectedLayerId;const anchor = this.deps.ctx.captureInsertionAnchor('raster', null);- const hasResult = (doc: CanvasDocumentContractV2 | null): boolean =>- doc?.selectedLayerId === resultId && doc.layers.includes(resultLayer);+ const hasResult = (doc: CanvasDocumentContractV3 | null): boolean =>+ doc?.selectedLayerId === resultId && getDocumentLayer(doc, resultLayer.id) === resultLayer;const apply = (): void => {const prepared = this.deps.ctx.preparePixels(resultId, rect, pixels);this.deps.ctx.dispatchPrepared({- add: [{ anchor, layers: [resultLayer] }],+ add: [{ anchor, nodes: [resultLayer] }],enabledUpdates: [],selectedLayerId: resultId,type: 'applyCanvasLayerStackMutation',@@ -259,10 +265,10 @@ export class MergeLayerController {{ enabledUpdates: [], removeIds: [resultId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },() =>this.deps.ctx.getReducerDocument()?.selectedLayerId === selectedLayerId &&- this.deps.ctx.getReducerDocument()?.layers.some((layer) => layer.id === resultId) === false,+ isNodeAbsent(this.deps.ctx.getReducerDocument(), resultId),() =>this.deps.ctx.getDocument()?.selectedLayerId === selectedLayerId &&- this.deps.ctx.getDocument()?.layers.some((layer) => layer.id === resultId) === false+ isNodeAbsent(this.deps.ctx.getDocument(), resultId)),});return 'merged';@@ -284,8 +290,10 @@ export class MergeLayerController {return 'nothing';}const selectedIds = new Set(layerIds);- const contributors = document.layers.filter((layer) => selectedIds.has(layer.id));- if (!canMergeSelectedRasters(document.layers, selectedIds, this.deps.hasExportableContent)) {+ const contributors = getDocumentLeaves(document).filter((layer) => selectedIds.has(layer.id));+ if (+ !canMergeSelectedRasters(document, compileDocumentLeaves(document), selectedIds, this.deps.hasExportableContent)+ ) {return 'nothing';}const owned: Extract<ExportResult, { status: 'ok' }>[] = [];@@ -392,21 +400,19 @@ export class MergeLayerController {const anchor = this.deps.ctx.captureInsertionAnchor('raster', contributors[0]!.id);const restoreInsertions = contributors.map((layer) => ({anchor: this.deps.ctx.captureRestoreAnchor(layer.id)!,- layers: [layer],+ nodes: [layer],}));- const mergedLayers = insertLayersAtAnchor(document.layers, anchor, [resultLayer]).filter(- (layer) => !selectedIds.has(layer.id)- );+ const mergedStacks = removeNodes(insertNodesAtAnchor(document.stacks, anchor, [resultLayer]), selectedIds);const selectedLayerId = document.selectedLayerId;- const hasMerged = (candidate: CanvasDocumentContractV2 | null): boolean =>- candidate?.selectedLayerId === resultId && haveSameStackOrders(candidate.layers, mergedLayers);- const hasOriginals = (candidate: CanvasDocumentContractV2 | null): boolean =>- candidate?.selectedLayerId === selectedLayerId && haveSameStackOrders(candidate.layers, document.layers);+ const hasMerged = (candidate: CanvasDocumentContractV3 | null): boolean =>+ candidate?.selectedLayerId === resultId && haveSameStructure(candidate.stacks, mergedStacks);+ const hasOriginals = (candidate: CanvasDocumentContractV3 | null): boolean =>+ candidate?.selectedLayerId === selectedLayerId && haveSameStructure(candidate.stacks, document.stacks);const applyPrepared = (): void => {const prepared = this.deps.ctx.preparePixels(resultId, rect, pixels);this.deps.ctx.dispatchPrepared({- add: [{ anchor, layers: [resultLayer] }],+ add: [{ anchor, nodes: [resultLayer] }],enabledUpdates: [],removeIds: contributorIds,selectedLayerId: resultId,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.tsindex 821db0ad42..e9e702a26c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -341,7 +341,7 @@ describe('createCanvasMutationContext', () => {describe('edit revision', () => {it('advances once per reducer document identity and never on notification alone', () => {- let document = { layers: [] } as unknown as CanvasDocumentContractV2;+ let document = { layers: [] } as unknown as CanvasDocumentContractV3;const listeners: (() => void)[] = [];const { context } = createHarness({getReducerDocument: () => document,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.tsindex aaaa94d505..61176c6942 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts@@ -1,6 +1,6 @@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 { CanvasDocumentContractV3, CanvasStackForests } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeInsertionAnchor } 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';@@ -13,6 +13,7 @@ import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/renimport type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { EMPTY_STACKS } from '@workbench/canvas-engine/document/documentTree';import { captureInsertionAnchor, captureRestoreAnchor } from '@workbench/canvas-engine/document/insertionAnchors';/**@@ -23,12 +24,12 @@ import { captureInsertionAnchor, captureRestoreAnchor } from '@workbench/canvas-*/export interface CanvasMutationContext extends CanvasEditConcurrency {readonly history: History;- getDocument(): CanvasDocumentContractV2 | null;- getReducerDocument(): CanvasDocumentContractV2 | null;+ getDocument(): CanvasDocumentContractV3 | null;+ getReducerDocument(): CanvasDocumentContractV3 | null;/** Where a new `stack` layer lands: above `aboveId` when it belongs to the stack, else the stack top. */- captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor;+ captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): CanvasNodeInsertionAnchor;/** The anchor that restores `layerId` between its current same-stack neighbours; null when absent. */- captureRestoreAnchor(layerId: string): FlatLayerInsertionAnchor | null;+ captureRestoreAnchor(layerId: string): CanvasNodeInsertionAnchor | null;isGuardCurrent(guard: LayerExportGuard): boolean;dispatch(action: CanvasProjectMutation, origin?: CanvasMutationOrigin): boolean;dispatchPrepared(@@ -47,8 +48,8 @@ export interface CanvasMutationContext extends CanvasEditConcurrency {export interface CanvasMutationContextDeps {readonly projectId: string;readonly history: History;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;+ readonly getReducerDocument: () => CanvasDocumentContractV3 | null;readonly subscribeReducer: (listener: () => void) => () => void;readonly dispatch: (action: CanvasProjectMutation, origin?: CanvasMutationOrigin) => boolean;readonly commitEdit: (intent: CanvasEditIntent) => void;@@ -96,7 +97,7 @@ export const createCanvasMutationContext = (syncEditRevision();return editRevision;};- const currentLayers = (): readonly CanvasLayerContract[] => deps.getDocument()?.layers ?? [];+ const currentStacks = (): CanvasStackForests => deps.getDocument()?.stacks ?? EMPTY_STACKS;const canEdit = (owner?: symbol): boolean => owner === deps.editOwner || !deps.editingLocked.get();const capturePermit = (owner?: symbol): DocumentEditPermit | null =>canEdit(owner) ? { epoch: documentEditEpoch, owner } : null;@@ -174,7 +175,7 @@ export const createCanvasMutationContext = (return {canEdit,captureInsertionAnchor: (stack, aboveId) =>- captureInsertionAnchor(currentLayers(), {+ captureInsertionAnchor(currentStacks(), {aboveId,editRevision: getEditRevision(),projectId: deps.projectId,@@ -182,7 +183,7 @@ export const createCanvasMutationContext = (}),capturePermit,captureRestoreAnchor: (layerId) =>- captureRestoreAnchor(currentLayers(), layerId, deps.projectId, getEditRevision()),+ captureRestoreAnchor(currentStacks(), layerId, deps.projectId, getEditRevision()),createLayerId: () => deps.createLayerId(),dispatch: (action, origin) => deps.dispatch(action, origin),dispatchPrepared,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.tsindex ffc8dedf7a..987269ca3d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts@@ -1,5 +1,6 @@import type {- CanvasDocumentContractV2,+ CanvasStackForests,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';@@ -8,7 +9,10 @@ import type { SelectionState } from '@workbench/canvas-engine/selection/selectioimport type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { EMPTY_STACKS, removeNodes } from '@workbench/canvas-engine/document/documentTree';+import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createTestEditConcurrency } from '@workbench/canvas-engine/editConcurrency.testStub';import { createHistory } from '@workbench/canvas-engine/history/history';@@ -30,19 +34,19 @@ const paintLayer = (id: string, transform: Partial<CanvasLayerContract['transfortype: 'raster',});-const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV2 => ({+const makeDoc = (stacks: CanvasStackForests, selectedLayerId: string | null): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks,selectedLayerId,- version: 2,+ version: 3,width: 100,});/** The created layer, narrowed to the raster variant the controller always makes. */-const createdRaster = (document: CanvasDocumentContractV2 | null, id: string): CanvasRasterLayerContractV2 => {- const layer = document?.layers.find((candidate) => candidate.id === id);+const createdRaster = (document: CanvasDocumentContractV3 | null, id: string): CanvasRasterLayerContractV2 => {+ const layer = getDocumentLeaves(document).find((candidate) => candidate.id === id);if (!layer || layer.type !== 'raster') {throw new Error(`expected a raster layer ${id}`);}@@ -53,7 +57,7 @@ const imageData = (width: number, height: number): ImageData =>({ colorSpace: 'srgb', data: new Uint8ClampedArray(width * height * 4), height, width }) as ImageData;interface HarnessOptions {- layers?: CanvasLayerContract[];+ stacks?: CanvasStackForests;selectedLayerId?: string | null;maskRect?: Rect | null;cacheRect?: Rect;@@ -65,9 +69,10 @@ const createHarness = (options: HarnessOptions = {}) => {const backend = createTestStubRasterBackend();const layerCache = createLayerCacheStore(backend);const history = createHistory();- const layers = options.layers ?? [paintLayer('a')];- const selectedLayerId = options.selectedLayerId === undefined ? (layers[0]?.id ?? null) : options.selectedLayerId;- let document: CanvasDocumentContractV2 | null = makeDoc(layers, selectedLayerId);+ const stacks = options.stacks ?? stacksFrom([paintLayer('a')]);+ const selectedLayerId =+ options.selectedLayerId === undefined ? (stacks.raster[0]?.id ?? null) : options.selectedLayerId;+ let document: CanvasDocumentContractV3 | null = makeDoc(stacks, selectedLayerId);const maskRect = options.maskRect === undefined ? { height: 30, width: 30, x: 20, y: 20 } : options.maskRect;const mask: PlacedSurface | null = maskRect@@ -85,7 +90,7 @@ const createHarness = (options: HarnessOptions = {}) => {const controller = new NewRasterLayerController({backend,- captureInsertionAnchor: createTestInsertionAnchorCapture('p', () => document?.layers ?? []),+ captureInsertionAnchor: createTestInsertionAnchorCapture('p', () => document?.stacks ?? EMPTY_STACKS),concurrency: createTestEditConcurrency({capturePermit: () => (options.permit === undefined ? { epoch: 0 } : options.permit),isGestureActive: () => options.gestureActive === true,@@ -96,14 +101,14 @@ const createHarness = (options: HarnessOptions = {}) => {// Mirror the reducer: apply the stack mutation to the local document so// the controller's postconditions and later reads see the new layer.if (action.type === 'applyCanvasLayerStackMutation' && document) {- let next = document.layers;- if (action.removeIds) {- next = next.filter((layer) => !action.removeIds!.includes(layer.id));- }+ let next = document.stacks;for (const insertion of action.add ?? []) {- next = insertLayersAtAnchor(next, insertion.anchor, insertion.layers);+ next = insertNodesAtAnchor(next, insertion.anchor, insertion.nodes);}- document = { ...document, layers: next, selectedLayerId: action.selectedLayerId ?? null };+ if (action.removeIds) {+ next = removeNodes(next, new Set(action.removeIds));+ }+ document = { ...document, selectedLayerId: action.selectedLayerId ?? null, stacks: next };}},endBurst: vi.fn(),@@ -129,14 +134,17 @@ const createHarness = (options: HarnessOptions = {}) => {describe('NewRasterLayerController: insert', () => {it('inserts a paint layer above the active one and selects it', () => {- const h = createHarness({ layers: [paintLayer('top'), paintLayer('bottom')], selectedLayerId: 'bottom' });+ const h = createHarness({+ stacks: stacksFrom([paintLayer('top'), paintLayer('bottom')]),+ selectedLayerId: 'bottom',+ });const surface = h.backend.createSurface(10, 10);const result = h.controller.insert({ height: 10, width: 10, x: 5, y: 5 }, surface, 'New', 'Insert');expect(result).toEqual({ layerId: 'new-1', status: 'created' });// Index 0 is top-most, so "above bottom" is bottom's own index.- expect(h.document()!.layers.map((layer) => layer.id)).toEqual(['top', 'new-1', 'bottom']);+ expect(getDocumentLeaves(h.document()!).map((layer) => layer.id)).toEqual(['top', 'new-1', 'bottom']);expect(h.document()!.selectedLayerId).toBe('new-1');expect(h.installed).toHaveBeenCalledTimes(1);});@@ -153,14 +161,14 @@ describe('NewRasterLayerController: insert', () => {});it('undo removes the layer and restores the previous selection', () => {- const h = createHarness({ layers: [paintLayer('a')], selectedLayerId: 'a' });+ const h = createHarness({ stacks: stacksFrom([paintLayer('a')]), selectedLayerId: 'a' });const surface = h.backend.createSurface(10, 10);h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert');expect(h.history.canUndo()).toBe(true);h.history.undo();- expect(h.document()!.layers.map((layer) => layer.id)).toEqual(['a']);+ expect(getDocumentLeaves(h.document()!).map((layer) => layer.id)).toEqual(['a']);expect(h.document()!.selectedLayerId).toBe('a');});@@ -172,7 +180,7 @@ describe('NewRasterLayerController: insert', () => {h.history.undo();h.history.redo();- expect(h.document()!.layers.some((layer) => layer.id === 'new-1')).toBe(true);+ expect(getDocumentLeaves(h.document()!).some((layer) => layer.id === 'new-1')).toBe(true);expect(h.document()!.selectedLayerId).toBe('new-1');});@@ -258,7 +266,7 @@ describe('NewRasterLayerController: liftSelectionToLayer', () => {it('bakes the source layer transform into the new layer placement', () => {// The copy comes out layer-local; a new layer lives in document space, so a// translated source must shift where the pixels land.- const h = createHarness({ layers: [paintLayer('a', { x: 10, y: 5 })] });+ const h = createHarness({ stacks: stacksFrom([paintLayer('a', { x: 10, y: 5 })]) });h.controller.liftSelectionToLayer('Selection', 'Layer via copy');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.tsindex c56ce69de1..c0c1a7d2a1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts@@ -1,6 +1,6 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type {CanvasEditConcurrency,@@ -14,6 +14,7 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rendimport type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { Rect, Vec2 } from '@workbench/canvas-engine/types';+import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { liftSelectedPixels } from '@workbench/canvas-engine/selection/floatingSelection';import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';@@ -28,11 +29,11 @@ export interface NewRasterLayerControllerOptions {readonly layers: LayerCacheStore;readonly selection: SelectionState;readonly history: History;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;+ readonly getReducerDocument: () => CanvasDocumentContractV3 | null;readonly endBurst: () => void;readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;readonly dispatchPrepared: (@@ -103,17 +104,17 @@ export class NewRasterLayerController {const prepared = this.deps.preparePixels(layerId, rect, pixels);this.deps.dispatchPrepared({- add: [{ anchor, layers: [layer] }],+ add: [{ anchor, nodes: [layer] }],enabledUpdates: [],selectedLayerId: layerId,type: 'applyCanvasLayerStackMutation',},() =>this.deps.getReducerDocument()?.selectedLayerId === layerId &&- this.deps.getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,+ getDocumentLayer(this.deps.getReducerDocument(), layer.id) === layer,() =>this.deps.getDocument()?.selectedLayerId === layerId &&- this.deps.getDocument()?.layers.some((candidate) => candidate === layer) === true+ getDocumentLayer(this.deps.getDocument(), layer.id) === layer);this.deps.installPrepared(prepared);};@@ -137,10 +138,10 @@ export class NewRasterLayerController {},() =>this.deps.getReducerDocument()?.selectedLayerId === previousSelectedLayerId &&- this.deps.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,+ isNodeAbsent(this.deps.getReducerDocument(), layerId),() =>this.deps.getDocument()?.selectedLayerId === previousSelectedLayerId &&- this.deps.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false+ isNodeAbsent(this.deps.getDocument(), layerId)),});return { layerId, status: 'created' };@@ -152,7 +153,7 @@ export class NewRasterLayerController {*/liftSelectionToLayer(name: string, label: string): NewRasterLayerResult {const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === document.selectedLayerId);+ const layer = getDocumentLayer(document, document?.selectedLayerId);const mask = this.deps.selection.mask();const entry = layer ? this.deps.layers.get(layer.id) : undefined;if (!document || !layer || !mask || !entry || isEmpty(entry.rect)) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.tsindex 4817216523..1030ff4efb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts@@ -1,5 +1,5 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,CanvasLayerSourceContract,@@ -38,7 +38,7 @@ export interface RasterControllerOptions {readonly backend: RasterBackend;readonly diagnostics: CanvasDiagnostics;readonly onVersionChange?: (layerId: string) => void;- readonly getDocument?: () => CanvasDocumentContractV2 | null;+ readonly getDocument?: () => CanvasDocumentContractV3 | null;readonly getLayerImageName?: (layer: CanvasLayerContract) => string | null;readonly imageResolver?: (imageName: string, signal?: AbortSignal) => Promise<Blob>;}@@ -56,7 +56,7 @@ export class RasterController {private readonly thumbnailKeys = new Map<string, string>();private documentGeneration = 0;private disposed = false;- private readonly getDocument: () => CanvasDocumentContractV2 | null;+ private readonly getDocument: () => CanvasDocumentContractV3 | null;private readonly getLayerImageName: (layer: CanvasLayerContract) => string | null;private readonly backend: RasterBackend;private readonly imageResolver: ((imageName: string, signal?: AbortSignal) => Promise<Blob>) | null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.tsindex 0e33124738..11e808b2fc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts@@ -1,5 +1,6 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';@@ -24,13 +25,13 @@ describe('RasterExportController budget', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster' as const,};- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,};const reserve = vi.fn(() => ({ availableBytes: 0, requestedBytes: 40_000, status: 'over-budget' as const }));@@ -76,13 +77,13 @@ describe('RasterExportController budget', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster' as const,};- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,};const release = vi.fn();@@ -126,13 +127,13 @@ describe('RasterExportController budget', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster' as const,};- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,};const release = vi.fn();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.tsindex d3eef53118..f405fe47c7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts@@ -5,7 +5,7 @@ import type {LayerExportGuard,} from '@workbench/canvas-engine/capabilities';import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';@@ -13,8 +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 { lookupDocumentLayer, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';@@ -33,10 +32,10 @@ export type ExportLayerPixelsResult =export interface RasterExportControllerOptions {readonly backend: RasterBackend;readonly captureGuard: (layer: CanvasLayerContract, entry: LayerCacheEntry) => LayerExportGuard;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getOrStartRasterization: (layer: CanvasLayerContract,- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,signal?: AbortSignal) => Promise<'published' | 'stale' | 'error' | 'aborted'>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;@@ -117,7 +116,7 @@ export class RasterExportController {if (!layer || !source) {return { status: 'missing' };}- if (!options.includeDisabled && !isLayerContributing(layer)) {+ if (!options.includeDisabled && !lookupDocumentLeaf(document, layerId)?.contributionEnabled) {return { status: 'disabled' };}if (!this.options.isSupportedSource(source)) {@@ -166,7 +165,7 @@ export class RasterExportController {if (!currentSource) {return { status: 'missing' };}- if (!options.includeDisabled && !isLayerContributing(currentLayer)) {+ if (!options.includeDisabled && !lookupDocumentLeaf(currentDocument!, layerId)?.contributionEnabled) {return { status: 'disabled' };}if (!this.options.isSupportedSource(currentSource)) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.tsindex 8716e82845..2d9a1c4374 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts@@ -1,10 +1,11 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { rasterizeSource } from '@workbench/canvas-engine/render/rasterizers';@@ -14,8 +15,8 @@ export interface RasterizeLayerControllerOptions {readonly backend: RasterBackend;readonly layers: LayerCacheStore;readonly history: History;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly rasterizeDeps: (document: CanvasDocumentContractV2) => RasterizeDeps;+ readonly getDocument: () => CanvasDocumentContractV3 | null;+ readonly rasterizeDeps: (document: CanvasDocumentContractV3) => RasterizeDeps;readonly dispatch: (action: CanvasProjectMutation) => void;readonly canEdit: () => boolean;readonly isGestureActive: () => boolean;@@ -36,7 +37,7 @@ export class RasterizeLayerController {}this.deps.endBurst();const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(document, layerId);if (!document || !layer || layer.type !== 'raster' || layer.isLocked) {return false;}@@ -50,7 +51,7 @@ export class RasterizeLayerController {const parametricLayer: CanvasLayerContract = structuredClone(layer);const apply = (): void => {const liveDocument = this.deps.getDocument();- const liveLayer = liveDocument?.layers.find((candidate) => candidate.id === layerId);+ const liveLayer = getDocumentLayer(liveDocument, layerId);if (!liveDocument || !liveLayer || liveLayer.type !== 'raster') {return;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.tsindex b7f075d73d..8fe478f73a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts@@ -1,13 +1,15 @@import type { LayerExportGuard, ReplaceSelectionFromImageResult } from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { Rect } from '@workbench/canvas-engine/types';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+export interface SelectionImageControllerOptions {readonly concurrency: CanvasEditConcurrency;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly decodeImage: (image: CanvasImageRef,options: {@@ -52,7 +54,7 @@ export class SelectionImageController {if (!document) {return { status: 'missing' };}- const layer = document.layers.find((candidate) => candidate.id === guard.layerId);+ const layer = getDocumentLayer(document, guard.layerId);if (!layer) {return { status: 'missing' };}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.tsindex 52a615dfa1..a24cba5799 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts@@ -1,6 +1,7 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createHistory } from '@workbench/canvas-engine/history/history';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';@@ -21,17 +22,18 @@ describe('SelectionPixelController', () => {mask: () => ({ rect: { height: 2, width: 2, x: 0, y: 0 }, surface: mask }),} as unknown as SelectionState;const document = {- layers: [+ stacks: stacksFrom([{id: 'paint',isEnabled: true,isLocked: false,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },source: { type: 'paint' },type: 'raster',- },- ],+ } as unknown as CanvasLayerContract,+ ]),selectedLayerId: 'paint',- } as CanvasDocumentContractV2;+ } as CanvasDocumentContractV3;const history = createHistory();const markDirty = vi.fn();const notifyPainted = vi.fn();@@ -71,17 +73,18 @@ describe('SelectionPixelController', () => {mask: () => ({ rect: { height: 2, width: 2, x: 0, y: 0 }, surface: mask }),} as unknown as SelectionState;const document = {- layers: [+ stacks: stacksFrom([{id: 'paint',isEnabled: true,isLocked: false,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },source: { bitmap: { height: 2, imageName: 'durable', width: 2 }, type: 'paint' },type: 'raster',- },- ],+ } as unknown as CanvasLayerContract,+ ]),selectedLayerId: 'paint',- } as CanvasDocumentContractV2;+ } as CanvasDocumentContractV3;const markDirty = vi.fn();const requestRasterization = vi.fn();const history = createHistory();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.tsindex be97db4daf..5216966127 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -7,7 +7,9 @@ import type { SelectionState } from '@workbench/canvas-engine/selection/selectioimport type { PixelEditTransaction } from '@workbench/canvas-engine/tools/tool';import type { Rect } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { getSourceBounds } from '@workbench/canvas-engine/document/sources';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';import { intersect, isEmpty, roundOut } from '@workbench/canvas-engine/math/rect';@@ -23,7 +25,7 @@ export interface SelectionPixelControllerOptions {readonly layers: LayerCacheStore;readonly history: History;readonly applyImagePatch: ImagePatchApply;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly beginPixelEdit: (layerId: string) => PixelEditTransaction | null;readonly canEdit: () => boolean;readonly isGestureActive: () => boolean;@@ -31,10 +33,7 @@ export interface SelectionPixelControllerOptions {readonly endBurst: () => void;readonly deleteDerived: (layerId: string) => void;readonly invalidateLayer: (layerId: string) => void;- readonly isRasterCacheReady: (- layer: CanvasDocumentContractV2['layers'][number],- document: CanvasDocumentContractV2- ) => boolean;+ readonly isRasterCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;readonly notifyPainted: (layerId: string) => void;readonly requestRasterization: (layerId: string) => void;readonly markDirty: (layerId: string) => void;@@ -63,8 +62,9 @@ export class SelectionPixelController {if (!document?.selectedLayerId) {return null;}- const layer = document.layers.find((candidate) => candidate.id === document.selectedLayerId);- if (layer?.type === 'raster' && layer.source.type === 'paint' && isLayerEditable(layer)) {+ const leaf = lookupDocumentLeaf(document, document.selectedLayerId);+ const layer = leaf?.layer;+ if (leaf && layer?.type === 'raster' && layer.source.type === 'paint' && isLeafEditable(leaf)) {return { kind: 'raster', layerId: layer.id, transparencyLocked: layer.isTransparencyLocked === true };}if (layer?.type === 'control') {@@ -85,7 +85,7 @@ export class SelectionPixelController {return;}const selectionRect = roundOut(bounds);- const selectedLayer = document.layers.find((candidate) => candidate.id === document.selectedLayerId);+ const selectedLayer = getDocumentLayer(document, document.selectedLayerId);if (selectedLayer?.type === 'raster' &&selectedLayer.source.type === 'paint' &&diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.tsindex 5a8ee26339..b0d0767959 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts@@ -2,6 +2,7 @@ import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/coimport type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';@@ -74,7 +75,8 @@ describe('staged result project-port integration', () => {const result = engine.layers.commitStagedImage({ candidate: selected, selectedImageIndex: 1 });expect(result.status).toBe('committed');- expect(store.getState().projects[0]?.canvas.document.layers[0]?.transform.x).toBe(90);+ const accepted = store.getState().projects[0]?.canvas.document.stacks.raster[0];+ expect(accepted?.type === 'raster' ? accepted.transform.x : null).toBe(90);engine.lifecycle.dispose();});@@ -99,7 +101,7 @@ describe('staged result project-port integration', () => {throw new Error('expected commit');}const projectAfterSave = store.getState().projects[0]!;- const savedLayer = projectAfterSave.canvas.document.layers[0]!;+ const savedLayer = projectAfterSave.canvas.document.stacks.raster[0]!;expect(savedLayer).toMatchObject({ id: result.layerId, isEnabled: false, type: 'raster' });expect(projectAfterSave.canvas.document.selectedLayerId).toBe(currentLayerId);expect(projectAfterSave.canvas.stagingArea).toBe(stagedBefore);@@ -107,11 +109,11 @@ describe('staged result project-port integration', () => {expect(projectAfterSave.canvas.stagingArea.isVisible).toBe(true);engine.history.undo();- expect(store.getState().projects[0]!.canvas.document.layers).not.toContain(savedLayer);+ expect(getDocumentLeaves(store.getState().projects[0]!.canvas.document)).not.toContain(savedLayer);expect(store.getState().projects[0]!.canvas.stagingArea).toBe(stagedBefore);engine.history.redo();- expect(store.getState().projects[0]!.canvas.document.layers[0]).toBe(savedLayer);+ expect(store.getState().projects[0]!.canvas.document.stacks.raster[0]).toBe(savedLayer);expect(store.getState().projects[0]!.canvas.document.selectedLayerId).toBe(currentLayerId);expect(store.getState().projects[0]!.canvas.stagingArea).toBe(stagedBefore);engine.lifecycle.dispose();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.tsindex 849208a0c3..4429e3fcca 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts@@ -1,7 +1,10 @@-import type { CanvasStagingCandidateContract, CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasStagingCandidateContract, CanvasStateContractV3 } from '@workbench/canvas-engine/contracts';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { removeNodes } from '@workbench/canvas-engine/document/documentTree';+import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createTestEditConcurrency } from '@workbench/canvas-engine/editConcurrency.testStub';import { createHistory } from '@workbench/canvas-engine/history/history';@@ -21,14 +24,14 @@ const candidate: CanvasStagingCandidateContract = {};const selection = { candidate, selectedImageIndex: 0 } as const;-const makeCanvas = (): CanvasStateContractV2 => ({+const makeCanvas = (): CanvasStateContractV3 => ({document: {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,},documentRevision: 0,@@ -41,7 +44,7 @@ const makeCanvas = (): CanvasStateContractV2 => ({pendingImages: [candidate],selectedImageIndex: 0,},- version: 2,+ version: 3,});describe('StagedResultController', () => {@@ -56,14 +59,12 @@ describe('StagedResultController', () => {...reducerCanvas,document: {...reducerCanvas.document,- layers: mutation.removeIds- ? reducerCanvas.document.layers.filter((layer) => !mutation.removeIds?.includes(layer.id))- : mutation.add- ? mutation.add.reduce(- (layers, insertion) => insertLayersAtAnchor(layers, insertion.anchor, insertion.layers),- reducerCanvas.document.layers- )- : reducerCanvas.document.layers,+ stacks: mutation.removeIds+ ? removeNodes(reducerCanvas.document.stacks, new Set(mutation.removeIds))+ : (mutation.add ?? []).reduce(+ (stacks, insertion) => insertNodesAtAnchor(stacks, insertion.anchor, insertion.nodes),+ reducerCanvas.document.stacks+ ),selectedLayerId:mutation.selectedLayerId === undefined? reducerCanvas.document.selectedLayerId@@ -83,7 +84,7 @@ describe('StagedResultController', () => {const layer = mutation.layer;reducerCanvas = {...reducerCanvas,- document: { ...reducerCanvas.document, layers: [layer], selectedLayerId: layer.id },+ document: { ...reducerCanvas.document, stacks: stacksFrom([layer]), selectedLayerId: layer.id },stagingArea: { ...reducerCanvas.stagingArea, isVisible: false, pendingImageIds: [], pendingImages: [] },};mirrorDocument = reducerCanvas.document;@@ -105,7 +106,7 @@ describe('StagedResultController', () => {});expect(controller.commit(selection)).toEqual({ status: 'committed', layerId: 'layer-1' });- expect(reducerCanvas.document.layers[0]).toMatchObject({+ expect(getDocumentLeaves(reducerCanvas.document)[0]).toMatchObject({id: 'layer-1',opacity: 0.5,source: { image: { imageName: 'result.png' }, type: 'image' },@@ -115,13 +116,13 @@ describe('StagedResultController', () => {expect(history.canUndo()).toBe(true);history.undo();- expect(reducerCanvas.document.layers).toEqual([]);+ expect(getDocumentLeaves(reducerCanvas.document)).toEqual([]);expect(reducerCanvas.document.selectedLayerId).toBeNull();expect(reducerCanvas.stagingArea.pendingImages).toEqual([]);history.redo();- expect(reducerCanvas.document.layers[0]).toBe(reducerCanvas.document.layers[0]);- expect(reducerCanvas.document.layers[0]?.id).toBe('layer-1');+ expect(getDocumentLeaves(reducerCanvas.document)[0]).toBe(getDocumentLeaves(reducerCanvas.document)[0]);+ expect(getDocumentLeaves(reducerCanvas.document)[0]?.id).toBe('layer-1');expect(reducerCanvas.stagingArea.pendingImages).toEqual([]);});@@ -144,7 +145,7 @@ describe('StagedResultController', () => {});expect(controller.commit(selection)).toEqual({ status: 'stale' });- expect(canvas.document.layers).toEqual([]);+ expect(getDocumentLeaves(canvas.document)).toEqual([]);expect(canvas.stagingArea.pendingImages).toEqual([candidate]);expect(history.canUndo()).toBe(false);});@@ -222,7 +223,7 @@ describe('StagedResultController', () => {...reducerCanvas,document: {...reducerCanvas.document,- layers: [mutation.layer],+ stacks: stacksFrom([mutation.layer]),selectedLayerId: mutation.layer.id,},stagingArea: {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.tsindex 918b476c39..d7af69c7c0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts@@ -1,24 +1,25 @@import type { CommitStagedImageOptions, CommitStagedImageResult } from '@workbench/canvas-engine/capabilities';import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasRasterLayerContractV2,CanvasStagingCandidateContract,- CanvasStateContractV2,+ CanvasStateContractV3,} from '@workbench/canvas-engine/contracts';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';import type { History } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { ProjectEvent } from '@workbench/projectContracts';-import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';+import { getDocumentLayer, getDocumentLeaves, hasDocumentNode } from '@workbench/canvas-engine/document/documentIndex';+import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';import { getCanvasStagingCandidateFingerprint } from '@workbench/canvasStagingView';export interface StagedResultControllerOptions {readonly concurrency: CanvasEditConcurrency;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;readonly createEventId: () => string;readonly createLayerId: () => string;readonly dispatchPrepared: (@@ -28,8 +29,8 @@ export interface StagedResultControllerOptions {origin?: 'system' | 'user') => void;readonly endBurst: () => void;- readonly getCanvasState: () => CanvasStateContractV2 | null;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getCanvasState: () => CanvasStateContractV3 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly history: History;readonly now: () => string;}@@ -95,7 +96,7 @@ export class StagedResultController {const continueStaging = options.continueStaging === true;const layer = {- ...createLayer(o.createLayerId(), `Layer ${canvas.document.layers.length + 1}`, options.candidate),+ ...createLayer(o.createLayerId(), `Layer ${getDocumentLeaves(canvas.document).length + 1}`, options.candidate),isEnabled: !continueStaging,};const event: ProjectEvent = {@@ -107,22 +108,22 @@ export class StagedResultController {type: 'canvas-layer-accepted',};const previousSelectedLayerId = canvas.document.selectedLayerId;- const previousLayers = canvas.document.layers;+ const previousStacks = canvas.document.stacks;const anchor = o.captureInsertionAnchor('raster', null);- const acceptedLayers = insertLayersAtAnchor(previousLayers, anchor, [layer]);+ const acceptedStacks = insertNodesAtAnchor(previousStacks, anchor, [layer]);const previousStagingArea = canvas.stagingArea;const acceptedSelectedLayerId = continueStaging ? previousSelectedLayerId : layer.id;- const hasPreviousLayerStack = (document: CanvasDocumentContractV2 | null): boolean =>+ const hasPreviousLayerStack = (document: CanvasDocumentContractV3 | null): boolean =>document?.selectedLayerId === previousSelectedLayerId &&- !document.layers.some((current) => current.id === layer.id) &&- haveSameStackOrders(document.layers, previousLayers);- const hasAcceptedLayerStack = (document: CanvasDocumentContractV2 | null): boolean =>+ !hasDocumentNode(document, layer.id) &&+ haveSameStructure(document.stacks, previousStacks);+ const hasAcceptedLayerStack = (document: CanvasDocumentContractV3 | null): boolean =>document?.selectedLayerId === acceptedSelectedLayerId &&- document.layers.includes(layer) &&- haveSameStackOrders(document.layers, acceptedLayers);- const isCommitted = (next: CanvasStateContractV2 | null): boolean =>+ getDocumentLayer(document, layer.id) === layer &&+ haveSameStructure(document.stacks, acceptedStacks);+ const isCommitted = (next: CanvasStateContractV3 | null): boolean =>next?.document.selectedLayerId === acceptedSelectedLayerId &&- next.document.layers.some((current) => current === layer) &&+ getDocumentLayer(next.document, layer.id) === layer &&(continueStaging? next.stagingArea === previousStagingArea: next.stagingArea.pendingImages.length === 0 &&@@ -131,7 +132,7 @@ export class StagedResultController {!next.stagingArea.isVisible);const isMirrored = (): boolean =>o.getDocument()?.selectedLayerId === acceptedSelectedLayerId &&- o.getDocument()?.layers.some((current) => current === layer) === true;+ getDocumentLayer(o.getDocument(), layer.id) === layer;try {o.endBurst();@@ -187,7 +188,7 @@ export class StagedResultController {}};const addAcceptedLayer: Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }> = {- add: [{ anchor, layers: [layer] }],+ add: [{ anchor, nodes: [layer] }],enabledUpdates: [],selectedLayerId: acceptedSelectedLayerId,type: 'applyCanvasLayerStackMutation',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.tsindex a54f538fb3..99cf0c7f49 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts@@ -1,11 +1,9 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { Project } from '@workbench/projectContracts';-import {- createFlatDocumentModel,- type FlatCanvasDocumentModel,-} from '@workbench/canvas-engine/document-model/flatDocumentModel';+import { createDocumentModel, type CanvasDocumentModel } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createHistory } from '@workbench/canvas-engine/history/history';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -94,8 +92,8 @@ const rename = (id: string, name: string): CanvasProjectMutation => ({patch: { name },type: 'updateCanvasLayer',});-const layerName = (document: CanvasDocumentContractV2, id = 'layer'): string | undefined =>- document.layers.find((layer) => layer.id === id)?.name;+const layerName = (document: CanvasDocumentContractV3, id = 'layer'): string | undefined =>+ getDocumentLeaves(document).find((layer) => layer.id === id)?.name;describe('StructuralLayerController', () => {it('commits through the guarded dispatch and records one failure-atomic history entry', () => {@@ -213,7 +211,7 @@ describe('StructuralLayerController', () => {});describe('commitPrepared', () => {- const prepareRename = (model: FlatCanvasDocumentModel, name: string) => {+ const prepareRename = (model: CanvasDocumentModel, name: string) => {const result = model.prepare({ id: 'layer', patch: { name }, type: 'patch' });if (result.status !== 'prepared') {throw new Error(`expected a prepared edit, got ${result.status}`);@@ -223,7 +221,7 @@ describe('StructuralLayerController', () => {it('applies a prepared edit, verifies its postconditions and records one entry', () => {const { controller, ctx, document, history, projectId } = createHarness();- const model = createFlatDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId });+ const model = createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId });expect(controller.commitPrepared('Rename', prepareRename(model, 'Renamed'))).toEqual({ status: 'committed' });expect(layerName(document())).toBe('Renamed');@@ -235,14 +233,14 @@ describe('StructuralLayerController', () => {it('refuses an edit prepared against an older revision or another project', () => {const { controller, ctx, document, history, projectId } = createHarness();const stale = prepareRename(- createFlatDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId }),+ createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId }),'A');ctx.dispatch(rename('layer', 'Elsewhere'), 'system');expect(controller.commitPrepared('Rename', stale)).toMatchObject({ status: 'stale' });const foreign = prepareRename(- createFlatDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId: 'other' }),+ createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId: 'other' }),'B');expect(controller.commitPrepared('Rename', foreign)).toEqual({ status: 'dispatch-rejected' });@@ -252,7 +250,7 @@ describe('StructuralLayerController', () => {it('skips history for an edit whose policy is none', () => {const { controller, ctx, document, history, projectId } = createHarness();- const model = createFlatDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId });+ const model = createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId });const result = model.prepare({ id: null, type: 'select' });if (result.status !== 'prepared') {throw new Error('expected a prepared selection change');@@ -281,7 +279,7 @@ describe('StructuralLayerController', () => {expectedRevision: anchor.capturedEditRevision,status: 'stale',});- expect(document().layers.some((layer) => layer.id === 'added')).toBe(false);+ expect(getDocumentLeaves(document()).some((layer) => layer.id === 'added')).toBe(false);expect(anchor.projectId).toBe(projectId);});@@ -310,10 +308,10 @@ describe('StructuralLayerController', () => {expect(controller.nudge(1, 0)).toEqual({ status: 'committed' });now = 100;expect(controller.nudge(1, 0)).toEqual({ status: 'committed' });- expect(document().layers[0]?.transform.x).toBe(2);+ expect(getDocumentLayer(document(), 'layer')?.transform.x).toBe(2);history.undo();- expect(document().layers[0]?.transform.x).toBe(0);+ expect(getDocumentLayer(document(), 'layer')?.transform.x).toBe(0);expect(history.canUndo()).toBe(false);controller.commit(diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.tsindex 5ff4e07b0d..2987541a4f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts@@ -3,12 +3,12 @@ import type {StructuralCommitOptions,StructuralCommitResult,} from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';-import type { PreparedFlatEdit } from '@workbench/canvas-engine/document-model/flatDocumentCommands';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import type { PreparedDocumentEdit } from '@workbench/canvas-engine/document-model/documentCommands';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';+import { createDocumentModel } from '@workbench/canvas-engine/document-model/documentModel';+import { checkEditPostconditions } from '@workbench/canvas-engine/document-model/postconditions';import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';import type { CanvasMutationContext } from './mutationContext';@@ -47,7 +47,7 @@ export type StructuralFailureReport =export interface StructuralLayerControllerOptions {readonly ctx: StructuralMutationContext;- readonly getSelectedLayerIds?: (document: CanvasDocumentContractV2) => readonly string[];+ readonly getSelectedLayerIds?: (document: CanvasDocumentContractV3) => readonly string[];readonly report?: (message: StructuralFailureReport, label: string, error: unknown) => void;readonly now?: () => number;}@@ -60,14 +60,12 @@ interface NudgeBurst {const NUDGE_COALESCE_MS = 500;-const positionMutation = (positions: readonly { id: string; x: number; y: number }[]): CanvasProjectMutation =>- positions.length === 1- ? {- id: positions[0]!.id,- patch: { transform: { x: positions[0]!.x, y: positions[0]!.y } },- type: 'updateCanvasLayer',- }- : { type: 'setCanvasLayerPositions', updates: [...positions] };+const positionMutation = (positions: readonly { id: string; x: number; y: number }[]): CanvasProjectMutation => ({+ type: 'setCanvasLayerPositions',+ updates: [...positions],+});++const unique = (ids: readonly string[]): string[] => [...new Set(ids)];/** Owns guarded, failure-atomic structural document edits and nudge coalescing. */export class StructuralLayerController {@@ -110,7 +108,11 @@ export class StructuralLayerController {}/** A prepared flat edit: refused as `stale` unless its revision and project still match, verified by its postconditions. */- commitPrepared(label: string, edit: PreparedFlatEdit, options: PreparedCommitOptions = {}): StructuralCommitResult {+ commitPrepared(+ label: string,+ edit: PreparedDocumentEdit,+ options: PreparedCommitOptions = {}+ ): StructuralCommitResult {const refusal = this.refuse({ expectedRevision: edit.expectedRevision });if (refusal) {return refusal;@@ -123,7 +125,7 @@ export class StructuralLayerController {label,edit.forward,edit.inverse,- (document) => checkFlatEditPostconditions(document, edit.postconditions),+ (document) => checkEditPostconditions(document, edit.postconditions),options.origin);if (applied.status === 'committed' && edit.history === 'record') {@@ -150,28 +152,29 @@ export class StructuralLayerController {if (!document?.selectedLayerId) {return { status: 'dispatch-rejected' };}- const requested = new Set(this.deps.getSelectedLayerIds?.(document) ?? [document.selectedLayerId]);- const layers = document.layers.filter((layer) => requested.has(layer.id));- if (- layers.length === 0 ||- layers.length !== requested.size ||- !requested.has(document.selectedLayerId) ||- layers.some((layer) => !isLayerEditable(layer))- ) {+ const ids = unique([document.selectedLayerId, ...(this.deps.getSelectedLayerIds?.(document) ?? [])]);+ const model = createDocumentModel(document, { editRevision: ctx.getEditRevision(), projectId: ctx.projectId });+ const prepared = model.prepare({ dx, dy, ids, type: 'translate' });+ if (prepared.status !== 'prepared' || prepared.edit.forward.type !== 'setCanvasLayerPositions') {return { status: 'dispatch-rejected' };}- const selectionKey = layers.map((layer) => layer.id).join('\0');+ const leaves = model.compileLeaves();+ if (prepared.edit.touchedIds.some((id) => !leaves.find((leaf) => leaf.id === id)?.contributionEnabled)) {+ return { status: 'dispatch-rejected' };+ }+ const selectionKey = prepared.edit.touchedIds.join('\0');const now = this.now();const coalesce = !!this.burst && this.burst.selectionKey === selectionKey && now < this.burst.expiresAt;const origins =coalesce && this.burst? this.burst.origins- : layers.map((layer) => ({ id: layer.id, x: layer.transform.x, y: layer.transform.y }));- const next = layers.map((layer) => ({ id: layer.id, x: layer.transform.x + dx, y: layer.transform.y + dy }));+ : (prepared.edit.inverse as Extract<CanvasProjectMutation, { type: 'setCanvasLayerPositions' }>).updates;const label = 'Nudge layer';- const forward = positionMutation(next);+ const forward = prepared.edit.forward;const inverse = positionMutation(origins);- const applied = this.apply(label, forward, inverse);+ const applied = this.apply(label, forward, inverse, (next) =>+ checkEditPostconditions(next, prepared.edit.postconditions)+ );if (applied.status !== 'committed') {this.burst = null;return applied;@@ -217,7 +220,7 @@ export class StructuralLayerController {label: string,forward: CanvasProjectMutation,inverse: CanvasProjectMutation,- verify: (document: CanvasDocumentContractV2) => boolean = () => true,+ verify: (document: CanvasDocumentContractV3) => boolean = () => true,origin?: CanvasMutationOrigin): StructuralCommitResult {const { ctx } = this.deps;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.tsindex d20c5526a2..0fc968fa7c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts@@ -1,14 +1,16 @@import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { TextEditSession } from '@workbench/canvas-engine/engineStores';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { EMPTY_STACKS } from '@workbench/canvas-engine/document/documentTree';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { DEFAULT_TEXT_OPTIONS } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';import { TextEditingController } from './textEditingController';-const createHarness = (document: CanvasDocumentContractV2) => {+const createHarness = (document: CanvasDocumentContractV3) => {let session: TextEditSession | null = null;const commitStructural = vi.fn<(label: string, forward: unknown, inverse: unknown) => StructuralCommitResult>(() => ({status: 'committed',@@ -16,7 +18,7 @@ const createHarness = (document: CanvasDocumentContractV2) => {const invalidate = vi.fn();const controller = new TextEditingController({canEdit: () => true,- captureInsertionAnchor: createTestInsertionAnchorCapture('p', () => document?.layers ?? []),+ captureInsertionAnchor: createTestInsertionAnchorCapture('p', () => document?.stacks ?? EMPTY_STACKS),commitStructural,createLayerId: () => 'text-new',getDocument: () => document,@@ -33,7 +35,12 @@ const createHarness = (document: CanvasDocumentContractV2) => {describe('TextEditingController', () => {it('owns create session state and commits one structural layer addition', () => {- const h = createHarness({ bbox: { height: 1, width: 1, x: 0, y: 0 }, height: 1, layers: [], width: 1 } as never);+ const h = createHarness({+ bbox: { height: 1, width: 1, x: 0, y: 0 },+ height: 1,+ stacks: stacksFrom([]),+ width: 1,+ } as never);h.controller.openCreate({ x: 10.4, y: 20.6 });expect(h.getSession()?.transform).toMatchObject({ x: 10, y: 21 });@@ -44,7 +51,12 @@ describe('TextEditingController', () => {});it('uses the registered content reader and cancels empty creates', () => {- const h = createHarness({ bbox: { height: 1, width: 1, x: 0, y: 0 }, height: 1, layers: [], width: 1 } as never);+ const h = createHarness({+ bbox: { height: 1, width: 1, x: 0, y: 0 },+ height: 1,+ stacks: stacksFrom([]),+ width: 1,+ } as never);h.controller.openCreate({ x: 0, y: 0 });h.controller.setContentReader(() => ' ');@@ -57,7 +69,12 @@ describe('TextEditingController', () => {describe('TextEditingController refusals', () => {it('keeps the session for a transient refusal and drops it when the target is gone', () => {- const h = createHarness({ bbox: { height: 1, width: 1, x: 0, y: 0 }, height: 1, layers: [], width: 1 } as never);+ const h = createHarness({+ bbox: { height: 1, width: 1, x: 0, y: 0 },+ height: 1,+ stacks: stacksFrom([]),+ width: 1,+ } as never);h.commitStructural.mockReturnValueOnce({ status: 'busy' as const });h.controller.openCreate({ x: 0, y: 0 });@@ -70,7 +87,12 @@ describe('TextEditingController refusals', () => {});it('reports nothing to commit for an empty creation', () => {- const h = createHarness({ bbox: { height: 1, width: 1, x: 0, y: 0 }, height: 1, layers: [], width: 1 } as never);+ const h = createHarness({+ bbox: { height: 1, width: 1, x: 0, y: 0 },+ height: 1,+ stacks: stacksFrom([]),+ width: 1,+ } as never);h.controller.openCreate({ x: 0, y: 0 });expect(h.controller.commit(' ')).toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.tsindex cc4fea7f05..44fb7e00f1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts@@ -1,12 +1,14 @@import type { StructuralCommitResult } 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 { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { TextEditSession, TextSource, TextToolOptions } from '@workbench/canvas-engine/engineStores';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { Vec2 } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';export interface TextEditingControllerOptions {readonly session: {@@ -14,11 +16,11 @@ export interface TextEditingControllerOptions {set(value: TextEditSession | null): void;};readonly options: { get(): TextToolOptions };- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly canEdit: () => boolean;readonly isGestureActive: () => boolean;readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;readonly commitStructural: (label: string,forward: CanvasProjectMutation,@@ -82,8 +84,9 @@ export class TextEditingController {return;}const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);- if (!document || !layer || layer.type !== 'raster' || layer.source.type !== 'text' || !isLayerEditable(layer)) {+ const leaf = lookupDocumentLeaf(document, layerId);+ const layer = leaf?.layer;+ if (!document || !layer || layer.type !== 'raster' || layer.source.type !== 'text' || !isLeafEditable(leaf)) {return;}this.deps.session.set({@@ -140,7 +143,7 @@ export class TextEditingController {id: layerId,isEnabled: true,isLocked: false,- name: `Text ${(this.deps.getDocument()?.layers.length ?? 0) + 1}`,+ name: `Text ${(getDocumentLeaves(this.deps.getDocument() ?? null).length ?? 0) + 1}`,opacity: 1,source: finalSource,transform: session.transform,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.test.tsindex 17166a9efd..50c8ebbef3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.test.ts@@ -1,5 +1,6 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';@@ -18,13 +19,13 @@ describe('ThumbnailController budget', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster' as const,};- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,};const rasterize = vi.fn();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.tsindex f19e7958f0..fb3a598848 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts@@ -1,13 +1,13 @@import type { LayerThumbnailRequestResult } from '@workbench/canvas-engine/capabilities';import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';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 { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/documentModel';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';@@ -17,7 +17,7 @@ import { fitThumbnailSize } from '@workbench/canvas-engine/render/thumbnail';export interface ThumbnailControllerOptions {readonly backend: RasterBackend;readonly projectId: string;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getActiveProjectId: () => string | null;readonly getEntry: (layerId: string) => LayerCacheEntry | undefined;readonly getCheckerboard: () => RasterSurface;@@ -26,7 +26,7 @@ export interface ThumbnailControllerOptions {readonly isSupportedSource: (source: CanvasLayerSourceContract) => boolean;readonly rasterize: (layer: CanvasLayerContract,- document: CanvasDocumentContractV2+ document: CanvasDocumentContractV3) => Promise<'published' | 'stale' | 'error'>;readonly setStatus: (layerId: string, status: 'loading' | 'ready' | 'error' | null) => void;readonly reportError: (layerId: string, error: unknown) => void;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.tsindex c5c4ff43c2..263029bf14 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts@@ -1,6 +1,7 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { TransformSession } from '@workbench/canvas-engine/engineStores';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';@@ -9,7 +10,7 @@ import { TransformEditingController } from './transformEditingController';const document = {bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [+ stacks: stacksFrom([{blendMode: 'normal',id: 'shape',@@ -21,9 +22,9 @@ const document = {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',},- ],+ ]),width: 100,-} as CanvasDocumentContractV2;+} as CanvasDocumentContractV3;describe('TransformEditingController', () => {it('owns preview state and commits parametric transforms through declared ports', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.tsindex 83e9b1910c..ef73364cdd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { TransformSession } from '@workbench/canvas-engine/engineStores';import type { HistoryEntry } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';@@ -7,7 +7,9 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rendimport type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { isRenderableLayer } from '@workbench/canvas-engine/document/sources';import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';@@ -17,7 +19,7 @@ import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';export interface TransformEditingControllerOptions {readonly session: { get(): TransformSession | null; set(value: TransformSession | null): void };readonly backend: RasterBackend;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getCache: (layerId: string) => LayerCacheEntry | null;readonly setOverride: (layerId: string, transform: LayerTransform | null) => void;readonly replaceCache: (layerId: string, rect: Rect, surface: RasterSurface) => void;@@ -55,8 +57,9 @@ export class TransformEditingController {return;}const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);- if (!document || !layer || !isLayerEditable(layer) || !hittableLayerSize(layer, document)) {+ const leaf = lookupDocumentLeaf(document, layerId);+ const layer = leaf?.layer;+ if (!document || !layer || !isLeafEditable(leaf) || !hittableLayerSize(layer, document)) {return;}this.clearOverride();@@ -118,14 +121,14 @@ export class TransformEditingController {return;}const document = this.deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === session.layerId);+ const layer = getDocumentLayer(document, session.layerId);const size = document && layer ? hittableLayerSize(layer, document) : null;if (!document ||!layer ||!size ||!isRenderableLayer(layer) ||- layer.isLocked ||+ !isLeafEditable(lookupDocumentLeaf(document, session.layerId)) ||unchanged(session.transform, session.startTransform)) {this.cancel();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentCommands.tssimilarity index 51%rename from invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.tsrename to invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentCommands.tsindex 6aa6a1af24..6ae85164fd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentCommands.ts@@ -1,8 +1,12 @@-import type { CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';+import type {+ CanvasLayerContract,+ CanvasLayerSourceContract,+ CanvasNodeContract,+} from '@workbench/canvas-engine/contracts';import type {LayerStackKind,LayerStackMoveKind,- ReorderFlatStackCommand,+ ReorderSiblingsCommand,} from '@workbench/canvas-engine/document/layerStacks';import type {CanvasLayerBasePatch,@@ -10,21 +14,34 @@ import type {CanvasProjectMutation,} from '@workbench/canvas-engine/mutationContracts';-import type { FlatEditPostcondition } from './postconditions';+import type { EditPostcondition } from './postconditions';-export type FlatDocumentCommand =+export type DocumentCommand =| {readonly type: 'insert';- readonly layers: readonly CanvasLayerContract[];- /** Land above this layer when it belongs to the inserted layer's stack; otherwise at the stack top. */+ readonly nodes: readonly CanvasNodeContract[];+ /** Land above this node when it belongs to the inserted node's stack; otherwise at the stack top. */readonly aboveId: string | null;- /** The primary selection afterwards; defaults to the last inserted layer. */+ /** Land at the top of this group instead, when it belongs to the inserted node's stack. */+ readonly insideId?: string | null;+ /** The primary selection afterwards; defaults to the last inserted node. */readonly selectId?: string | null;+ /** The stack an empty group joins; leaves and non-empty groups carry their own. */+ readonly stack?: LayerStackKind;}| { readonly type: 'remove'; readonly ids: readonly string[] }- | { readonly type: 'duplicate'; readonly sourceId: string; readonly newId: string }+ | { readonly type: 'duplicate'; readonly ids: readonly string[]; readonly createId: () => string }| { readonly type: 'move'; readonly ids: readonly string[]; readonly kind: LayerStackMoveKind }- | { readonly type: 'reorder'; readonly stacks: readonly ReorderFlatStackCommand[] }+ | { readonly type: 'reorder'; readonly orders: readonly ReorderSiblingsCommand[] }+ | {+ /** Moves subtrees under `parentId` (`null` for the stack root) directly above `beforeId`, or to the bottom. */+ readonly type: 'reparent';+ readonly ids: readonly string[];+ readonly parentId: string | null;+ readonly beforeId: string | null;+ }+ | { readonly type: 'group'; readonly ids: readonly string[]; readonly groupId: string; readonly name: string }+ | { readonly type: 'ungroup'; readonly ids: readonly string[] }| {readonly type: 'patch';readonly id: string;@@ -42,51 +59,58 @@ export type FlatDocumentCommand =| { readonly type: 'set-enabled'; readonly updates: readonly { id: string; isEnabled: boolean }[] }| { readonly type: 'set-hidden'; readonly updates: readonly { id: string; isHidden: boolean }[] }| { readonly type: 'set-locked'; readonly updates: readonly { id: string; isLocked: boolean }[] }+ | { readonly type: 'translate'; readonly ids: readonly string[]; readonly dx: number; readonly dy: number }| { readonly type: 'select'; readonly id: string | null };-export type FlatDocumentRefusal =+export type DocumentRefusal =| { readonly status: 'missing'; readonly ids: readonly string[] }| { readonly status: 'locked'; readonly ids: readonly string[] }| {readonly status: 'wrong-type';- readonly expected: readonly CanvasLayerContract['type'][];+ readonly expected: readonly (CanvasLayerContract['type'] | 'group')[];readonly actual: string;}- | { readonly status: 'invalid-target'; readonly targetId: string; readonly reason: FlatInvalidTargetReason }+ | { readonly status: 'invalid-target'; readonly targetId: string; readonly reason: InvalidTargetReason }| { readonly status: 'unsupported'; readonly operation: string };-export type FlatInvalidTargetReason =+export type InvalidTargetReason =| 'id-exists'| 'foreign-stack'- | 'not-stack-members'+ | 'not-siblings'+ | 'not-a-group'+ | 'cycle'+ | 'depth-exceeded'+ | 'node-limit'| 'no-layer-below'| 'not-mergeable';-export type FlatEditHistoryPolicy = 'record' | 'none';+export type EditHistoryPolicy = 'record' | 'none';-/** A flat edit ready for the transaction module: what to dispatch, what must hold afterwards, how to record it. */-export interface PreparedFlatEdit {+/** A document edit ready for the transaction module: what to dispatch, what must hold afterwards, how to record it. */+export interface PreparedDocumentEdit {readonly forward: CanvasProjectMutation;readonly inverse: CanvasProjectMutation;readonly projectId: string;readonly expectedRevision: number;readonly selectionBefore: string | null;readonly selectionAfter: string | null;- /** Layers the edit changes, including neighbours whose stack position it displaces. */+ /** Nodes the edit changes, including neighbours whose position it displaces. */readonly touchedIds: readonly string[];+ /** Ids the edit brings into the document. */+ readonly createdIds: readonly string[];readonly touchedStacks: readonly LayerStackKind[];- readonly postconditions: readonly FlatEditPostcondition[];- /** Flat commands never need prepared pixels; pixel-bearing edits keep their own controllers. */+ readonly postconditions: readonly EditPostcondition[];+ /** Document commands never need prepared pixels; pixel-bearing edits keep their own controllers. */readonly rasterWork: null;- readonly history: FlatEditHistoryPolicy;+ readonly history: EditHistoryPolicy;}-export type PrepareFlatEditResult =- | { readonly status: 'prepared'; readonly edit: PreparedFlatEdit }+export type PrepareEditResult =+ | { readonly status: 'prepared'; readonly edit: PreparedDocumentEdit }/** The command describes the document as it already is; there is nothing to dispatch. */| { readonly status: 'unchanged' }- | FlatDocumentRefusal;+ | DocumentRefusal;export type MergeDownEligibility =| { readonly status: 'eligible'; readonly upperId: string; readonly lowerId: string }- | FlatDocumentRefusal;+ | DocumentRefusal;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.tsindex d0425d6bc0..1a615fbfb9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts@@ -1,6 +1,13 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type {+ CanvasDocumentContractV3,+ CanvasGroupContract,+ CanvasLayerContract,+ CanvasNodeContract,+ CanvasStackForests,+} from '@workbench/canvas-engine/contracts';-import { LAYER_STACK_ORDER } from '@workbench/canvas-engine/document/layerStacks';+import { createEmptyStacks } from '@workbench/canvas-engine/document/documentTree';+import { LAYER_STACK_ORDER, layerStackOf } from '@workbench/canvas-engine/document/layerStacks';const base = (id: string) => ({blendMode: 'normal' as const,@@ -49,27 +56,106 @@ export const layerContract = (return { ...contract, ...overrides } as CanvasLayerContract;};-export const flatDocument = (- layers: readonly CanvasLayerContract[],+export const groupContract = (+ id: string,+ children: readonly CanvasNodeContract[] = [],+ overrides: Partial<Omit<CanvasGroupContract, 'type' | 'children'>> = {}+): CanvasGroupContract => ({+ children: [...children],+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ type: 'group',+ ...overrides,+});++const stackOfNode = (node: CanvasNodeContract): CanvasLayerContract['type'] | null => {+ if (node.type !== 'group') {+ return layerStackOf(node);+ }+ for (const child of node.children) {+ const stack = stackOfNode(child);+ if (stack) {+ return stack;+ }+ }+ return null;+};++/** Partitions top-level nodes into forests by the stack of their first leaf; leafless groups go to raster. */+export const stacksFrom = (nodes: readonly CanvasNodeContract[]): CanvasStackForests => {+ const stacks = createEmptyStacks();+ for (const node of nodes) {+ stacks[stackOfNode(node) ?? 'raster'].push(node);+ }+ return stacks;+};++export const documentFrom = (+ stacks: Partial<CanvasStackForests> | readonly CanvasNodeContract[],selectedLayerId: string | null = null-): CanvasDocumentContractV2 => ({+): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 512, width: 512, x: 0, y: 0 },height: 512,- layers: [...layers],selectedLayerId,- version: 2,+ stacks: Array.isArray(stacks)+ ? stacksFrom(stacks)+ : { ...createEmptyStacks(), ...(stacks as Partial<CanvasStackForests>) },+ version: 3,width: 512,});-/** `count` layers cycling through every stack in flat order, ids `l0` (top) … `l{count-1}`. */+/** A document from a flat top-first node list, partitioned into stacks in order. */+export const flatDocument = documentFrom;++/** `count` leaves cycling through every stack, ids `l0` … `l{count-1}`, at the root of each forest. */export const createLargeFlatDocument = (count: number,selectedLayerId: string | null = 'l0'-): CanvasDocumentContractV2 =>- flatDocument(+): CanvasDocumentContractV3 =>+ documentFrom(Array.from({ length: count }, (_, index) =>layerContract(`l${index}`, LAYER_STACK_ORDER[index % LAYER_STACK_ORDER.length]!)),selectedLayerId);++/**+ * `count` nodes cycling through every stack: every `fanout` leaves are wrapped in a group, and every+ * `fanout` groups in another, so the tree exercises depth and ancestor-effective state.+ */+export const createLargeTreeDocument = (+ count: number,+ fanout = 8,+ selectedLayerId: string | null = 'l0'+): CanvasDocumentContractV3 => {+ const stacks = createEmptyStacks();+ let created = 0;+ let leaves = 0;+ let groups = 0;+ const build = (stack: CanvasLayerContract['type'], budget: number, depth: number): CanvasNodeContract[] => {+ const nodes: CanvasNodeContract[] = [];+ while (budget > 0 && created < count) {+ if (depth < 3 && budget > fanout) {+ const before = created;+ const id = `g${groups++}`;+ created += 1;+ const children = build(stack, Math.min(budget - 1, fanout * fanout), depth + 1);+ nodes.push(groupContract(id, children));+ budget -= created - before;+ } else {+ nodes.push(layerContract(`l${leaves++}`, stack));+ created += 1;+ budget -= 1;+ }+ }+ return nodes;+ };+ const perStack = Math.ceil(count / LAYER_STACK_ORDER.length);+ for (const stack of LAYER_STACK_ORDER) {+ stacks[stack].push(...build(stack, perStack, 0));+ }+ return documentFrom(stacks, selectedLayerId);+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.tsnew file mode 100644index 0000000000..fadd4ed117--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts@@ -0,0 +1,202 @@+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';++import {+ getDocumentIndex,+ getDocumentIndexBuildCount,+ resetDocumentIndexBuildCount,+} from '@workbench/canvas-engine/document/documentIndex';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { beforeEach, describe, expect, it } from 'vitest';++import type { DocumentCommand, PreparedDocumentEdit } from './documentCommands';++import { createLargeFlatDocument, createLargeTreeDocument } from './documentFixtures.testStub';+import {+ compileDocumentLeaves,+ createDocumentModel,+ getDocumentModelDiagnostics,+ resetDocumentModelDiagnostics,+} from './documentModel';+import { ALL_OVERLAY_STACKS_SHOWN, planScreenComposition } from './screenComposition';++const NODE_COUNT = 2_000;+const context = { editRevision: 0, projectId: 'budget' };++const resetCounters = (): void => {+ resetDocumentModelDiagnostics();+ resetDocumentIndexBuildCount();+};++const counters = () => ({ ...getDocumentModelDiagnostics(), indexBuilds: getDocumentIndexBuildCount() });++/** Runs the reducer over a fixture so the next document is the one production consumers see. */+const reduce = (document: CanvasDocumentContractV3, command: DocumentCommand) => {+ const initial = createInitialWorkbenchState().projects[0]!;+ const project = applyCanvasProjectMutation(initial, { document, type: 'replaceCanvasDocument' });+ const accepted = project.canvas.document;+ const model = createDocumentModel(accepted, { editRevision: 0, projectId: project.id });+ const result = model.prepare(command);+ if (result.status !== 'prepared') {+ throw new Error(`expected a prepared edit, got ${result.status}`);+ }+ return { edit: result.edit, model, next: applyCanvasProjectMutation(project, result.edit.forward).canvas.document };+};++type Annotate = (message: string) => unknown;++/** Timing is informational: it is annotated on the test, never asserted. */+const timed = <T>(annotate: Annotate, label: string, run: () => T): T => {+ const start = performance.now();+ const value = run();+ annotate(`${label}: ${(performance.now() - start).toFixed(2)}ms`);+ return value;+};++describe(`document model budgets over ${NODE_COUNT} nodes`, () => {+ beforeEach(resetCounters);++ it('builds one index per forest identity and none for selection-only changes', ({ annotate }) => {+ const fixture = createLargeFlatDocument(NODE_COUNT);+ resetCounters();+ const project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {+ document: fixture,+ type: 'replaceCanvasDocument',+ });+ const document = project.canvas.document;+ expect(counters().indexBuilds).toBe(1);+ const model = timed(annotate, 'model construction', () => createDocumentModel(document, context));+ createDocumentModel(document, context);+ model.getLayer('l1999');+ model.getStack('control');+ expect(model.prepare({ id: 'l7', type: 'select' }).status).toBe('prepared');+ expect(model.prepare({ id: 'l0', type: 'select' })).toEqual({ status: 'unchanged' });+ const leaves = compileDocumentLeaves(document);++ const reselected = applyCanvasProjectMutation(project, { id: 'l7', type: 'setCanvasSelectedLayer' }).canvas+ .document;+ expect(reselected).not.toBe(document);+ expect(reselected.stacks).toBe(document.stacks);+ expect(createDocumentModel(reselected, context).compileLeaves()).toBe(leaves);+ expect(counters()).toMatchObject({ indexBuilds: 1, leafCompilations: 1 });+ });++ it('compiles leaves once per forest and plans the screen from them', ({ annotate }) => {+ const document = createLargeTreeDocument(NODE_COUNT);+ const leafCount = getDocumentIndex(document).leaves.length;+ const leaves = timed(annotate, 'leaf compilation', () => compileDocumentLeaves(document));+ expect(compileDocumentLeaves(document)).toBe(leaves);+ expect(createDocumentModel(document, context).compileLeaves()).toBe(leaves);+ expect(counters()).toMatchObject({ indexBuilds: 1, leafCompilations: 1, leavesCompiled: leafCount });++ const plan = timed(annotate, 'screen plan', () =>+ planScreenComposition(leaves, { isolationLayerId: null, showOverlayStacks: ALL_OVERLAY_STACKS_SHOWN })+ );+ expect(plan.leaves).toHaveLength(leafCount);+ expect(plan.leaves.at(-1)?.stack).toBe('inpaint_mask');+ });++ it('recompiles only the patched leaf after a reducer edit inside a group', ({ annotate }) => {+ const { model, next } = reduce(createLargeTreeDocument(NODE_COUNT), {+ id: 'l5',+ patch: { opacity: 0.5 },+ type: 'patch',+ });+ const before = model.compileLeaves();+ resetCounters();+ const after = timed(annotate, 'representative edit recompile', () => compileDocumentLeaves(next));+ expect(counters()).toMatchObject({ indexBuilds: 1, leafCompilations: 1, leavesCompiled: 1 });+ after.forEach((leaf, index) => {+ if (leaf.id === 'l5') {+ expect(leaf).not.toBe(before[index]);+ expect(leaf.layer.opacity).toBe(0.5);+ } else {+ expect(leaf).toBe(before[index]);+ }+ });+ });++ it('recompiles zero leaves for a group rename and exactly the descendants for a group flag', () => {+ const renamed = reduce(createLargeTreeDocument(NODE_COUNT), { id: 'g0', patch: { name: 'Folder' }, type: 'patch' });+ const before = renamed.model.compileLeaves();+ resetCounters();+ expect(compileDocumentLeaves(renamed.next)).toEqual(before);+ expect(counters()).toMatchObject({ indexBuilds: 1, leavesCompiled: 0 });++ const gated = reduce(createLargeTreeDocument(NODE_COUNT), {+ type: 'set-enabled',+ updates: [{ id: 'g0', isEnabled: false }],+ });+ const descendants = getDocumentIndex(gated.next).leaves.filter((leaf) =>+ getDocumentIndex(gated.next).byId.get(leaf.id)!.path.includes('g0')+ );+ gated.model.compileLeaves();+ resetCounters();+ const after = compileDocumentLeaves(gated.next);+ expect(counters().leavesCompiled).toBe(descendants.length);+ expect(after.filter((leaf) => !leaf.contributionEnabled).map((leaf) => leaf.id)).toEqual(+ descendants.map((leaf) => leaf.id)+ );+ });++ it('preserves every leaf identity across a sibling reorder and a reparent', () => {+ const moved = reduce(createLargeTreeDocument(NODE_COUNT), { ids: ['l0'], kind: 'back', type: 'move' });+ const before = moved.model.compileLeaves();+ resetCounters();+ const reordered = compileDocumentLeaves(moved.next);+ expect(reordered).toHaveLength(before.length);+ expect(reordered.every((leaf) => before.includes(leaf)) && before.every((leaf) => reordered.includes(leaf))).toBe(+ true+ );+ expect(reordered.map((leaf) => leaf.id)).not.toEqual(before.map((leaf) => leaf.id));+ expect(counters().leavesCompiled).toBe(0);++ const tree = createLargeTreeDocument(NODE_COUNT);+ const entries = getDocumentIndex(tree).nodes.filter((entry) => entry.stack === 'raster');+ const targetGroup = entries.find((entry) => entry.node.type === 'group')!.node.id;+ const rootLeaf = entries.find((entry) => entry.node.type !== 'group' && !entry.path.includes(targetGroup))!.node.id;+ const reparented = reduce(tree, { beforeId: null, ids: [rootLeaf], parentId: targetGroup, type: 'reparent' });+ const untouched = reparented.model.compileLeaves();+ resetCounters();+ const after = compileDocumentLeaves(reparented.next);+ expect(counters().leavesCompiled).toBe(1);+ expect(after).toHaveLength(untouched.length);+ expect(after.filter((leaf) => leaf.id !== rootLeaf).every((leaf) => untouched.includes(leaf))).toBe(true);+ expect(after.find((leaf) => leaf.id === rootLeaf)).not.toBe(untouched.find((leaf) => leaf.id === rootLeaf));+ });++ it.each<[string, DocumentCommand, { ids: number; stacks: number; builds: number }]>([+ ['select', { id: 'l9', type: 'select' }, { builds: 1, ids: 0, stacks: 0 }],+ ['lock', { type: 'set-locked', updates: [{ id: 'l1', isLocked: true }] }, { builds: 1, ids: 1, stacks: 1 }],+ [+ 'enable',+ {+ type: 'set-enabled',+ updates: Array.from({ length: 10 }, (_, index) => ({ id: `l${index}`, isEnabled: false })),+ },+ { builds: 1, ids: 10, stacks: 4 },+ ],+ ['hide', { type: 'set-hidden', updates: [{ id: 'l1', isHidden: true }] }, { builds: 1, ids: 1, stacks: 1 }],+ ['move', { ids: ['l8', 'l12', 'l16'], kind: 'forward', type: 'move' }, { builds: 1, ids: 4, stacks: 1 }],+ // Removal repairs the selection over the projected forest, which costs one more index.+ ['remove', { ids: ['l1', 'l2'], type: 'remove' }, { builds: 2, ids: 2, stacks: 2 }],+ ])('prepares a %s edit with exact touched ids and stacks and no leaf compilation', (_label, command, expected) => {+ const model = createDocumentModel(createLargeFlatDocument(NODE_COUNT), context);+ const result = model.prepare(command);+ expect(result.status).toBe('prepared');+ const edit = (result as { edit: PreparedDocumentEdit }).edit;+ expect(edit.touchedIds).toHaveLength(expected.ids);+ expect(edit.touchedStacks).toHaveLength(expected.stacks);+ expect(edit.rasterWork).toBeNull();+ expect(counters()).toMatchObject({ indexBuilds: expected.builds, leafCompilations: 0 });+ });++ it('prepares group, ungroup and reparent edits on the tree without compiling leaves', () => {+ const model = createDocumentModel(createLargeTreeDocument(NODE_COUNT), context);+ // l0 sits inside g0, so the selection folds into its ancestor and groups as one node.+ expect(model.prepare({ groupId: 'new', ids: ['g0', 'l0'], name: 'x', type: 'group' }).status).toBe('prepared');+ expect(model.prepare({ ids: ['g0'], type: 'ungroup' }).status).toBe('prepared');+ expect(model.prepare({ beforeId: null, ids: ['l0'], parentId: 'g0', type: 'reparent' }).status).toBe('prepared');+ expect(counters()).toMatchObject({ indexBuilds: 1, leafCompilations: 0 });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.tsnew file mode 100644index 0000000000..85d3be6e63--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts@@ -0,0 +1,1110 @@+import type { CanvasDocumentContractV3, CanvasNodeContract } from '@workbench/canvas-engine/contracts';+import type { Project } from '@workbench/projectContracts';++import { CANVAS_MAX_NODE_COUNT } from '@workbench/canvas-engine/contracts';+import { getDocumentIndex, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';+import { isHideableLayer } from '@workbench/canvas-engine/document/layerEligibility';+import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { describe, expect, it } from 'vitest';++import type { DocumentCommand, PreparedDocumentEdit, PrepareEditResult } from './documentCommands';++import { createLargeFlatDocument, groupContract, layerContract, stacksFrom } from './documentFixtures.testStub';+import {+ compileDocumentLeaves,+ createDocumentModel,+ getDocumentModelDiagnostics,+ lookupDocumentLayer,+ lookupDocumentLeaf,+ lookupLayerBelow,+ mergeDownEligibility,+} from './documentModel';+import { checkEditPostconditions } from './postconditions';++const layer = layerContract;+const group = groupContract;++/** inpaint: i1 · regional: g1 · control: c1 · raster: r1, r2, r3 */+const flat = (): CanvasNodeContract[] => [+ layer('i1', 'inpaint_mask'),+ layer('r1'),+ layer('c1', 'control'),+ layer('r2'),+ layer('g1', 'regional_guidance'),+ layer('r3'),+];++/** inpaint: i1 · control: c1 · raster: r1, G[r2, H[r3], r4], r5 */+const tree = (): CanvasNodeContract[] => [+ layer('i1', 'inpaint_mask'),+ layer('c1', 'control'),+ layer('r1'),+ group('G', [layer('r2'), group('H', [layer('r3')]), layer('r4')]),+ layer('r5'),+];++const projectWith = (nodes: CanvasNodeContract[], selectedLayerId: string | null): Project => {+ const initial = createInitialWorkbenchState().projects[0]!;+ const project = applyCanvasProjectMutation(initial, {+ document: { ...createEmptyCanvasDocument(), selectedLayerId, stacks: stacksFrom(nodes) },+ type: 'replaceCanvasDocument',+ });+ if (+ project.canvas.document.stacks.raster.length + project.canvas.document.stacks.control.length === 0 &&+ nodes.length > 0+ ) {+ throw new Error('fixture document was not accepted by the reducer');+ }+ return project;+};++const context = (project: Project) => ({ editRevision: 0, projectId: project.id });+const modelOf = (project: Project) => createDocumentModel(project.canvas.document, context(project));++/** Every node id, stacks top first, each in preorder with indentation for depth. */+const outline = (document: CanvasDocumentContractV3): string[] =>+ getDocumentIndex(document).nodes.map((entry) => `${' '.repeat(entry.path.length)}${entry.node.id}`);++/** The reducer writes an explicit `isHidden: false` on undo where the original node had no key. */+const withExplicitHidden = (node: CanvasNodeContract): CanvasNodeContract =>+ isGroupNode(node)+ ? { ...node, children: node.children.map(withExplicitHidden), isHidden: node.isHidden === true }+ : isHideableLayer(node)+ ? { ...node, isHidden: node.isHidden === true }+ : node;+const normalized = (document: CanvasDocumentContractV3) => ({+ ...document,+ stacks: Object.fromEntries(+ Object.entries(document.stacks).map(([stack, nodes]) => [stack, nodes.map(withExplicitHidden)])+ ),+});++const roundTrip = (project: Project, command: DocumentCommand): { after: Project; edit: PreparedDocumentEdit } => {+ const result = modelOf(project).prepare(command);+ if (result.status !== 'prepared') {+ throw new Error(`expected a prepared edit, got ${JSON.stringify(result)}`);+ }+ const after = applyCanvasProjectMutation(project, result.edit.forward);+ expect(after.canvas.document).not.toBe(project.canvas.document);+ expect(checkEditPostconditions(after.canvas.document, result.edit.postconditions)).toBe(true);+ expect(after.canvas.document.selectedLayerId).toBe(result.edit.selectionAfter);+ const restored = applyCanvasProjectMutation(after, result.edit.inverse).canvas.document;+ const original = project.canvas.document;+ expect(haveSameStructure(restored.stacks, original.stacks)).toBe(true);+ expect(normalized(restored)).toEqual(normalized(original));+ return { after, edit: result.edit };+};++describe('createDocumentModel', () => {+ it('indexes lookup, entries and stack roots once per forest identity', () => {+ const project = projectWith(tree(), 'r2');+ const model = modelOf(project);+ const again = modelOf(project);++ expect(model.getLayer('r3')?.id).toBe('r3');+ expect(model.getLayer('G')).toBeNull();+ expect(model.getNode('G')?.type).toBe('group');+ expect(model.getLayer('ghost')).toBeNull();+ expect(model.getEntry('r3')).toMatchObject({ parentId: 'H', path: ['G', 'H'], siblingIndex: 0 });+ expect(model.getStack('raster').map((entry) => entry.id)).toEqual(['r1', 'G', 'r5']);+ expect(again.getStack('raster')).toBe(model.getStack('raster'));+ });++ it('compiles semantic leaves in document order with ancestor state applied', () => {+ const project = projectWith(+ [+ layer('i1', 'inpaint_mask', { isHidden: true } as never),+ group('hidden', [layer('c1', 'control')], { isHidden: true }),+ group('off', [group('locked', [layer('r1', 'raster', { isLocked: true })], { isLocked: true }), layer('r2')], {+ isEnabled: false,+ }),+ layer('r3'),+ ],+ 'r1'+ );+ const leaves = modelOf(project).compileLeaves();++ expect(leaves.map((leaf) => [leaf.id, leaf.stack, leaf.parentIds])).toEqual([+ ['i1', 'inpaint_mask', []],+ ['c1', 'control', ['hidden']],+ ['r1', 'raster', ['off', 'locked']],+ ['r2', 'raster', ['off']],+ ['r3', 'raster', []],+ ]);+ expect(leaves[0]).toMatchObject({+ contributionEnabled: true,+ documentHidden: true,+ effectiveLocked: false,+ locked: false,+ });+ expect(leaves[1]).toMatchObject({ contributionEnabled: true, documentHidden: true });+ expect(leaves[2]).toMatchObject({ contributionEnabled: false, effectiveLocked: true, locked: true });+ expect(leaves[3]).toMatchObject({ contributionEnabled: false, effectiveLocked: false, locked: false });+ expect(leaves[4]).toMatchObject({ contributionEnabled: true, documentHidden: false, effectiveLocked: false });+ expect(leaves[4]!.worldTransform).toEqual({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });+ });++ it('keeps leaf identity across edits that leave a leaf and its ancestors alone', () => {+ const project = projectWith(tree(), 'r2');+ const leaves = modelOf(project).compileLeaves();+ const before = getDocumentModelDiagnostics();++ const selected = applyCanvasProjectMutation(project, { id: 'r1', type: 'setCanvasSelectedLayer' });+ expect(createDocumentModel(selected.canvas.document, context(project)).compileLeaves()).toBe(leaves);+ expect(getDocumentModelDiagnostics().leafCompilations).toBe(before.leafCompilations);++ const renamed = applyCanvasProjectMutation(selected, {+ id: 'r3',+ patch: { name: 'Renamed' },+ type: 'updateCanvasLayer',+ });+ const next = createDocumentModel(renamed.canvas.document, context(project)).compileLeaves();+ expect(getDocumentModelDiagnostics().leavesCompiled).toBe(before.leavesCompiled + 1);+ expect(next.filter((leaf, index) => leaf === leaves[index]).map((leaf) => leaf.id)).toEqual([+ 'i1',+ 'c1',+ 'r1',+ 'r2',+ 'r4',+ 'r5',+ ]);++ const groupRenamed = applyCanvasProjectMutation(renamed, {+ id: 'G',+ patch: { name: 'Folder' },+ type: 'updateCanvasLayer',+ });+ expect(createDocumentModel(groupRenamed.canvas.document, context(project)).compileLeaves()).toEqual(next);+ expect(getDocumentModelDiagnostics().leavesCompiled).toBe(before.leavesCompiled + 1);++ const gated = applyCanvasProjectMutation(groupRenamed, {+ type: 'setCanvasLayersEnabled',+ updates: [{ id: 'H', isEnabled: false }],+ });+ const afterGate = createDocumentModel(gated.canvas.document, context(project)).compileLeaves();+ expect(getDocumentModelDiagnostics().leavesCompiled).toBe(before.leavesCompiled + 2);+ expect(afterGate.find((leaf) => leaf.id === 'r3')).toMatchObject({ contributionEnabled: false });+ expect(afterGate.filter((leaf) => leaf.id !== 'r3').every((leaf) => next.includes(leaf))).toBe(true);++ const reordered = applyCanvasProjectMutation(gated, {+ orders: [{ orderedIds: ['r5', 'G', 'r1'], parentId: null, stack: 'raster' }],+ type: 'reorderCanvasSiblings',+ });+ expect(+ createDocumentModel(reordered.canvas.document, context(project))+ .compileLeaves()+ .every((leaf) => afterGate.includes(leaf))+ ).toBe(true);+ });++ describe('prepare', () => {+ it('inserts above a node under its parent and restores the previous selection on undo', () => {+ const project = projectWith(tree(), 'r3');+ const { after, edit } = roundTrip(project, { aboveId: 'r3', nodes: [layer('n1')], type: 'insert' });++ expect(outline(after.canvas.document)).toEqual([+ 'i1',+ 'c1',+ 'r1',+ 'G',+ ' r2',+ ' H',+ ' n1',+ ' r3',+ ' r4',+ 'r5',+ ]);+ expect(edit).toMatchObject({+ createdIds: ['n1'],+ history: 'record',+ postconditions: [+ { kind: 'sibling-order', orderedIds: ['n1', 'r3'], parentId: 'H', stack: 'raster' },+ { id: 'n1', kind: 'selection' },+ ],+ selectionAfter: 'n1',+ touchedIds: ['n1'],+ touchedStacks: ['raster'],+ });+ });++ it('inserts inside a group, at a foreign stack top, and honours an explicit selection', () => {+ const project = projectWith(tree(), 'r3');+ const inside = roundTrip(project, { aboveId: null, insideId: 'G', nodes: [layer('n1')], type: 'insert' });+ expect(outline(inside.after.canvas.document).slice(3, 6)).toEqual(['G', ' n1', ' r2']);++ const foreign = roundTrip(project, {+ aboveId: 'r3',+ nodes: [layer('m2', 'inpaint_mask')],+ selectId: null,+ type: 'insert',+ });+ expect(outline(foreign.after.canvas.document).slice(0, 2)).toEqual(['m2', 'i1']);+ expect(foreign.after.canvas.document.selectedLayerId).toBeNull();+ });++ it('inserts a whole subtree and refuses one that mixes stacks or nests too deep', () => {+ const project = projectWith(tree(), 'r1');+ const subtree = group('S', [layer('s1'), group('S2', [layer('s2')])]);+ const { after, edit } = roundTrip(project, { aboveId: 'r5', nodes: [subtree], type: 'insert' });+ expect(outline(after.canvas.document).slice(-5)).toEqual(['S', ' s1', ' S2', ' s2', 'r5']);+ expect(edit.createdIds).toEqual(['S', 's1', 'S2', 's2']);++ expect(+ modelOf(project).prepare({+ aboveId: null,+ nodes: [group('bad', [layer('x'), layer('y', 'control')])],+ type: 'insert',+ })+ ).toEqual({+ reason: 'foreign-stack',+ status: 'invalid-target',+ targetId: 'bad',+ });+ const deep = (depth: number): CanvasNodeContract =>+ depth === 0 ? layer(`d${depth}`) : group(`d${depth}`, [deep(depth - 1)]);+ expect(modelOf(project).prepare({ aboveId: 'r3', nodes: [deep(9)], type: 'insert' })).toEqual({+ reason: 'depth-exceeded',+ status: 'invalid-target',+ targetId: 'd9',+ });+ expect(modelOf(project).prepare({ aboveId: null, nodes: [deep(9)], type: 'insert' }).status).toBe('prepared');+ });++ it('removes nodes, repairs the selection to a sibling, and restores runs between their neighbours', () => {+ const project = projectWith(tree(), 'r2');+ const { after, edit } = roundTrip(project, { ids: ['r2', 'i1', 'r4'], type: 'remove' });++ expect(outline(after.canvas.document)).toEqual(['c1', 'r1', 'G', ' H', ' r3', 'r5']);+ expect(edit).toMatchObject({+ selectionAfter: 'H',+ touchedIds: ['i1', 'r2', 'r4'],+ touchedStacks: ['inpaint_mask', 'raster'],+ });+ });++ it('removes a group with its descendants, once, even when descendants are listed too', () => {+ const project = projectWith(tree(), 'r3');+ const { after, edit } = roundTrip(project, { ids: ['G', 'r3'], type: 'remove' });++ expect(outline(after.canvas.document)).toEqual(['i1', 'c1', 'r1', 'r5']);+ expect(edit.forward).toEqual({ ids: ['G'], type: 'removeCanvasLayers' });+ expect(edit.touchedIds).toEqual(['G', 'r2', 'H', 'r3', 'r4']);+ expect(edit.selectionAfter).toBe('r5');+ });++ it('refuses to remove a node with a locked ancestor or descendant', () => {+ const project = projectWith(+ [group('G', [layer('r1'), group('H', [layer('r2', 'raster', { isLocked: true })])], { isLocked: true })],+ 'r1'+ );+ expect(modelOf(project).prepare({ ids: ['r1'], type: 'remove' })).toEqual({ ids: ['G'], status: 'locked' });+ expect(modelOf(project).prepare({ ids: ['G'], type: 'remove' })).toEqual({ ids: ['G', 'r2'], status: 'locked' });+ });++ it('duplicates leaves and subtrees above their sources with fresh ids', () => {+ let next = 0;+ const project = projectWith(tree(), 'r1');+ const { after, edit } = roundTrip(project, {+ createId: () => `d${next++}`,+ ids: ['G', 'r3', 'r5'],+ type: 'duplicate',+ });++ expect(outline(after.canvas.document)).toEqual([+ 'i1',+ 'c1',+ 'r1',+ 'd0',+ ' d1',+ ' d2',+ ' d3',+ ' d4',+ 'G',+ ' r2',+ ' H',+ ' r3',+ ' r4',+ 'd5',+ 'r5',+ ]);+ expect(edit).toMatchObject({ createdIds: ['d0', 'd1', 'd2', 'd3', 'd4', 'd5'], selectionAfter: 'd5' });+ expect(after.canvas.document.stacks.raster[1]).toMatchObject({ name: 'G copy', type: 'group' });+ });++ it('moves within sibling lists, keeping a selected group and its descendants together', () => {+ const project = projectWith(tree(), 'r3');+ const moved = roundTrip(project, { ids: ['G', 'r3'], kind: 'front', type: 'move' });+ expect(outline(moved.after.canvas.document)).toEqual([+ 'i1',+ 'c1',+ 'G',+ ' r2',+ ' H',+ ' r3',+ ' r4',+ 'r1',+ 'r5',+ ]);+ expect(moved.edit.touchedIds).toEqual(['G', 'r1']);++ const reordered = roundTrip(project, {+ orders: [+ { orderedIds: ['r4', 'r2', 'H'], parentId: 'G', stack: 'raster' },+ { orderedIds: ['c1'], parentId: null, stack: 'control' },+ ],+ type: 'reorder',+ });+ expect(outline(reordered.after.canvas.document)).toEqual([+ 'i1',+ 'c1',+ 'r1',+ 'G',+ ' r4',+ ' r2',+ ' H',+ ' r3',+ 'r5',+ ]);+ expect(reordered.edit).toMatchObject({ touchedIds: ['r4', 'r2', 'H'], touchedStacks: ['control', 'raster'] });+ });++ it('reparents nodes from several parents into a group before a sibling, and back exactly on undo', () => {+ const project = projectWith(tree(), 'r1');+ const { after, edit } = roundTrip(project, {+ beforeId: 'r3',+ ids: ['r1', 'r4', 'r5'],+ parentId: 'H',+ type: 'reparent',+ });++ expect(outline(after.canvas.document)).toEqual([+ 'i1',+ 'c1',+ 'G',+ ' r2',+ ' H',+ ' r1',+ ' r4',+ ' r5',+ ' r3',+ ]);+ expect(edit.forward).toMatchObject({+ move: [{ anchor: { beforeId: 'r3', parentPath: ['G', 'H'] }, ids: ['r1', 'r4', 'r5'] }],+ });+ expect(edit.inverse).toMatchObject({+ move: [+ { anchor: { afterId: null, beforeId: 'G', parentPath: [] }, ids: ['r1'] },+ { anchor: { afterId: 'G', beforeId: null, parentPath: [] }, ids: ['r5'] },+ { anchor: { afterId: 'H', beforeId: null, parentPath: ['G'] }, ids: ['r4'] },+ ],+ });+ expect(edit.selectionAfter).toBe('r1');+ });++ it('reparents to the bottom of the root and reports an unchanged placement', () => {+ const project = projectWith(tree(), 'r1');+ const { after } = roundTrip(project, { beforeId: null, ids: ['r3'], parentId: null, type: 'reparent' });+ expect(outline(after.canvas.document)).toEqual(['i1', 'c1', 'r1', 'G', ' r2', ' H', ' r4', 'r5', 'r3']);+ expect(modelOf(project).prepare({ beforeId: 'r5', ids: ['G'], parentId: null, type: 'reparent' })).toEqual({+ status: 'unchanged',+ });+ expect(modelOf(project).prepare({ beforeId: null, ids: ['r5'], parentId: null, type: 'reparent' })).toEqual({+ status: 'unchanged',+ });+ });++ it.each<[string, DocumentCommand, PrepareEditResult]>([+ [+ 'a cycle',+ { beforeId: null, ids: ['G'], parentId: 'H', type: 'reparent' },+ { reason: 'cycle', status: 'invalid-target', targetId: 'H' },+ ],+ [+ 'a leaf parent',+ { beforeId: null, ids: ['r5'], parentId: 'r1', type: 'reparent' },+ { reason: 'not-a-group', status: 'invalid-target', targetId: 'r1' },+ ],+ [+ 'a foreign parent',+ { beforeId: null, ids: ['c1'], parentId: 'G', type: 'reparent' },+ { reason: 'foreign-stack', status: 'invalid-target', targetId: 'G' },+ ],+ [+ 'mixed stacks',+ { beforeId: null, ids: ['c1', 'r5'], parentId: null, type: 'reparent' },+ { reason: 'foreign-stack', status: 'invalid-target', targetId: 'r5' },+ ],+ [+ 'a beforeId outside the target',+ { beforeId: 'r2', ids: ['r5'], parentId: null, type: 'reparent' },+ { reason: 'not-siblings', status: 'invalid-target', targetId: 'r2' },+ ],+ [+ 'a moving beforeId',+ { beforeId: 'r5', ids: ['r5', 'r1'], parentId: null, type: 'reparent' },+ { reason: 'not-siblings', status: 'invalid-target', targetId: 'r5' },+ ],+ [+ 'a missing parent',+ { beforeId: null, ids: ['r5'], parentId: 'ghost', type: 'reparent' },+ { ids: ['ghost'], status: 'missing' },+ ],+ ])('refuses reparenting with %s', (_label, command, refusal) => {+ expect(modelOf(projectWith(tree(), 'r1')).prepare(command)).toEqual(refusal);+ });++ it('refuses to reparent into a locked group, out of one, or past the depth limit', () => {+ const locked = projectWith([group('L', [layer('r1')], { isLocked: true }), layer('r2')], 'r2');+ expect(modelOf(locked).prepare({ beforeId: null, ids: ['r2'], parentId: 'L', type: 'reparent' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ expect(modelOf(locked).prepare({ beforeId: null, ids: ['r1'], parentId: null, type: 'reparent' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });++ const nest = (depth: number): CanvasNodeContract =>+ depth === 0 ? layer('leaf') : group(`n${depth}`, [nest(depth - 1)]);+ const deep = projectWith([nest(10), group('S', [layer('s')])], 'leaf');+ expect(modelOf(deep).prepare({ beforeId: null, ids: ['S'], parentId: 'n1', type: 'reparent' })).toEqual({+ reason: 'depth-exceeded',+ status: 'invalid-target',+ targetId: 'n1',+ });+ expect(modelOf(deep).prepare({ beforeId: null, ids: ['s'], parentId: 'n1', type: 'reparent' }).status).toBe(+ 'prepared'+ );+ });++ it('groups selected siblings at the topmost one, in order, and dissolves the group exactly on undo', () => {+ const project = projectWith(tree(), 'r5');+ const { after, edit } = roundTrip(project, { groupId: 'N', ids: ['r5', 'r1'], name: 'Group 1', type: 'group' });++ expect(outline(after.canvas.document)).toEqual([+ 'i1',+ 'c1',+ 'N',+ ' r1',+ ' r5',+ 'G',+ ' r2',+ ' H',+ ' r3',+ ' r4',+ ]);+ expect(after.canvas.document.stacks.raster[0]).toMatchObject({+ isEnabled: true,+ isLocked: false,+ name: 'Group 1',+ type: 'group',+ });+ expect(edit).toMatchObject({+ createdIds: ['N'],+ selectionAfter: 'N',+ touchedIds: ['N', 'r1', 'r5'],+ touchedStacks: ['raster'],+ });+ });++ it('groups nested siblings and refuses non-siblings, a locked parent, or a taken id', () => {+ const project = projectWith(tree(), 'r2');+ const { after } = roundTrip(project, { groupId: 'N', ids: ['r4', 'H'], name: 'Inner', type: 'group' });+ expect(outline(after.canvas.document)).toEqual([+ 'i1',+ 'c1',+ 'r1',+ 'G',+ ' r2',+ ' N',+ ' H',+ ' r3',+ ' r4',+ 'r5',+ ]);++ expect(modelOf(project).prepare({ groupId: 'N', ids: ['r1', 'r2'], name: 'x', type: 'group' })).toEqual({+ reason: 'not-siblings',+ status: 'invalid-target',+ targetId: 'r2',+ });+ expect(modelOf(project).prepare({ groupId: 'G', ids: ['r1'], name: 'x', type: 'group' })).toEqual({+ reason: 'id-exists',+ status: 'invalid-target',+ targetId: 'G',+ });+ const locked = projectWith([group('L', [layer('a'), layer('b')], { isLocked: true })], 'a');+ expect(modelOf(locked).prepare({ groupId: 'N', ids: ['a', 'b'], name: 'x', type: 'group' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ });++ it('ungroups in place, selecting the first child when the group was selected, and regroups on undo', () => {+ const project = projectWith(tree(), 'G');+ const { after, edit } = roundTrip(project, { ids: ['G'], type: 'ungroup' });++ expect(outline(after.canvas.document)).toEqual(['i1', 'c1', 'r1', 'r2', 'H', ' r3', 'r4', 'r5']);+ expect(edit).toMatchObject({ selectionAfter: 'r2', touchedIds: ['G', 'r2', 'H', 'r4'] });++ // Naming a group and one nested inside it dissolves both; nothing half-applies.+ const nested = roundTrip(projectWith(tree(), 'H'), { ids: ['H', 'G'], type: 'ungroup' });+ expect(outline(nested.after.canvas.document)).toEqual(['i1', 'c1', 'r1', 'r2', 'r3', 'r4', 'r5']);+ expect(nested.edit.selectionAfter).toBe('r3');+ expect(modelOf(project).prepare({ ids: ['r1'], type: 'ungroup' })).toEqual({+ actual: 'raster',+ expected: ['group'],+ status: 'wrong-type',+ });+ });++ it('translates leaves and groups by one delta and refuses any locked node in the set', () => {+ const project = projectWith(tree(), 'r1');+ const { after, edit } = roundTrip(project, { dx: 5, dy: -2, ids: ['G', 'r1'], type: 'translate' });+ const moved = getDocumentLeaves(after.canvas.document).filter((leaf) =>+ ['r1', 'r2', 'r3', 'r4'].includes(leaf.id)+ );+ expect(moved.map((leaf) => [leaf.transform.x, leaf.transform.y])).toEqual([+ [5, -2],+ [5, -2],+ [5, -2],+ [5, -2],+ ]);+ expect(lookupDocumentLayer(after.canvas.document, 'r5')?.transform).toMatchObject({ x: 0, y: 0 });+ expect(edit.touchedIds).toEqual(['r1', 'r2', 'r3', 'r4']);++ expect(modelOf(project).prepare({ dx: 0, dy: 0, ids: ['G'], type: 'translate' })).toEqual({+ status: 'unchanged',+ });+ const locked = projectWith([group('G', [layer('a'), layer('b', 'raster', { isLocked: true })])], 'a');+ expect(modelOf(locked).prepare({ dx: 1, dy: 0, ids: ['G'], type: 'translate' })).toEqual({+ ids: ['b'],+ status: 'locked',+ });+ expect(modelOf(locked).prepare({ dx: 1, dy: 0, ids: ['a', 'b'], type: 'translate' })).toEqual({+ ids: ['b'],+ status: 'locked',+ });+ });++ it('patches base fields and transforms with an exact inverse', () => {+ const project = projectWith(flat(), 'r1');+ const { after, edit } = roundTrip(project, {+ id: 'r1',+ patch: { name: 'Renamed', opacity: 0.5, transform: { x: 12 } },+ type: 'patch',+ });++ expect(lookupDocumentLayer(after.canvas.document, 'r1')).toMatchObject({+ name: 'Renamed',+ opacity: 0.5,+ transform: { x: 12, y: 0 },+ });+ expect(edit.inverse).toEqual({+ id: 'r1',+ patch: { name: 'r1', opacity: 1, transform: { x: 0 } },+ type: 'updateCanvasLayer',+ });+ expect(edit.postconditions).toEqual([+ { id: 'r1', kind: 'patched', patch: { name: 'Renamed', opacity: 0.5, transform: { x: 12 } } },+ ]);+ });++ it('patches a group name, enabled and locked state, and refuses leaf-only fields on a group', () => {+ const project = projectWith(tree(), 'G');+ const { after, edit } = roundTrip(project, {+ id: 'G',+ patch: { isEnabled: false, name: 'Folder' },+ type: 'patch',+ });+ expect(after.canvas.document.stacks.raster[1]).toMatchObject({ isEnabled: false, name: 'Folder' });+ expect(edit.inverse).toEqual({ id: 'G', patch: { isEnabled: true, name: 'G' }, type: 'updateCanvasLayer' });+ expect(modelOf(project).prepare({ id: 'G', patch: { opacity: 0.5 }, type: 'patch' })).toMatchObject({+ actual: 'group',+ status: 'wrong-type',+ });+ expect(modelOf(project).prepare({ id: 'G', patch: { transform: { x: 1 } }, type: 'patch' })).toMatchObject({+ status: 'wrong-type',+ });+ });++ it('takes a pre-gesture baseline so a previewed patch still records a real inverse', () => {+ const previewed = applyCanvasProjectMutation(projectWith(flat(), 'r1'), {+ id: 'r1',+ patch: { opacity: 0.4 },+ type: 'updateCanvasLayer',+ });+ const model = modelOf(previewed);+ expect(model.prepare({ id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })).toEqual({ status: 'unchanged' });+ expect(model.prepare({ before: { opacity: 1 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })).toMatchObject(+ {+ edit: { inverse: { id: 'r1', patch: { opacity: 1 }, type: 'updateCanvasLayer' } },+ status: 'prepared',+ }+ );+ expect(model.prepare({ before: { opacity: 0.4 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })).toEqual({+ status: 'unchanged',+ });+ expect(+ model.prepare({ before: { name: 'r1', opacity: 1 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })+ ).toEqual({+ operation: 'patch baseline names other fields',+ status: 'unsupported',+ });+ expect(+ model.prepare({+ before: { transform: { x: 0 } },+ id: 'r1',+ patch: { transform: { x: 1, y: 2 } },+ type: 'patch',+ })+ ).toEqual({ operation: 'patch baseline names other fields', status: 'unsupported' });+ expect(+ model.prepare({+ before: { layerType: 'inpaint_mask', mask: { fill: { color: '#000000', style: 'solid' } } },+ config: { layerType: 'inpaint_mask', mask: { offset: { x: 4, y: 4 } } },+ id: 'i1',+ type: 'patch-config',+ })+ ).toEqual({ operation: 'config baseline names other fields', status: 'unsupported' });+ expect(+ model.prepare({+ before: { isTransparencyLocked: false, layerType: 'control' } as never,+ config: { isTransparencyLocked: true, layerType: 'raster' },+ id: 'r1',+ type: 'patch-config',+ })+ ).toEqual({ operation: 'config baseline names another layer type', status: 'unsupported' });++ const fillBefore = { color: '#e07575', style: 'diagonal' as const };+ const fillNext = { color: '#00ff00', style: 'diagonal' as const };+ const previewedFill = applyCanvasProjectMutation(projectWith(flat(), 'i1'), {+ config: { layerType: 'inpaint_mask', mask: { fill: fillNext } },+ id: 'i1',+ type: 'updateCanvasLayerConfig',+ });+ expect(+ modelOf(previewedFill).prepare({+ before: { layerType: 'inpaint_mask', mask: { fill: fillBefore } },+ config: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },+ id: 'i1',+ type: 'patch-config',+ })+ ).toMatchObject({+ edit: { inverse: { config: { layerType: 'inpaint_mask', mask: { fill: fillBefore } }, id: 'i1' } },+ status: 'prepared',+ });+ expect(+ modelOf(previewedFill).prepare({+ config: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },+ id: 'i1',+ type: 'patch-config',+ })+ ).toEqual({ status: 'unchanged' });+ });++ it('round-trips config, source and flag commands through the reducer, groups included', () => {+ const project = projectWith(tree(), 'r1');+ const control = roundTrip(project, {+ config: { adapter: { weight: 0.5 }, layerType: 'control', withTransparencyEffect: true },+ id: 'c1',+ type: 'patch-config',+ });+ expect(lookupDocumentLayer(control.after.canvas.document, 'c1')).toMatchObject({+ adapter: { weight: 0.5 },+ withTransparencyEffect: true,+ });+ expect(control.edit.inverse).toEqual({+ config: { adapter: { weight: 1 }, layerType: 'control', withTransparencyEffect: false },+ id: 'c1',+ type: 'updateCanvasLayerConfig',+ });++ const source = { bitmap: null, offset: { x: 3, y: 4 }, type: 'paint' as const };+ const patched = roundTrip(project, { id: 'r3', source, type: 'patch-source' });+ expect((lookupDocumentLayer(patched.after.canvas.document, 'r3') as { source: unknown }).source).toBe(source);++ const enabled = roundTrip(project, {+ type: 'set-enabled',+ updates: [+ { id: 'G', isEnabled: false },+ { id: 'c1', isEnabled: true },+ ],+ });+ expect(enabled.edit).toMatchObject({ touchedIds: ['G'], touchedStacks: ['raster'] });+ expect(+ compileDocumentLeaves(enabled.after.canvas.document).find((leaf) => leaf.id === 'r3')?.contributionEnabled+ ).toBe(false);++ const hidden = roundTrip(projectWith([group('O', [layer('c2', 'control')])], 'c2'), {+ type: 'set-hidden',+ updates: [{ id: 'O', isHidden: true }],+ });+ expect(hidden.after.canvas.document.stacks.control[0]).toMatchObject({ isHidden: true });++ const locked = roundTrip(project, { type: 'set-locked', updates: [{ id: 'H', isLocked: true }] });+ expect(compileDocumentLeaves(locked.after.canvas.document).find((leaf) => leaf.id === 'r3')).toMatchObject({+ effectiveLocked: true,+ locked: false,+ });+ });++ it.each<[string, DocumentCommand, PrepareEditResult]>([+ [+ 'hiding a raster layer',+ { type: 'set-hidden', updates: [{ id: 'r1', isHidden: true }] },+ { actual: 'raster', expected: ['control', 'inpaint_mask', 'regional_guidance'], status: 'wrong-type' },+ ],+ [+ 'hiding a raster group',+ { type: 'set-hidden', updates: [{ id: 'G', isHidden: true }] },+ { actual: 'group', expected: ['control', 'inpaint_mask', 'regional_guidance'], status: 'wrong-type' },+ ],+ [+ 'a config patch for another layer type',+ { config: { layerType: 'control', withTransparencyEffect: true }, id: 'r1', type: 'patch-config' },+ { actual: 'raster', expected: ['control'], status: 'wrong-type' },+ ],+ [+ 'a config patch on a group',+ { config: { layerType: 'raster', isTransparencyLocked: true }, id: 'G', type: 'patch-config' },+ { actual: 'group', expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask'], status: 'wrong-type' },+ ],+ [+ 'a source patch on a mask',+ { id: 'i1', source: { bitmap: null, type: 'paint' }, type: 'patch-source' },+ { actual: 'inpaint_mask', expected: ['raster', 'control'], status: 'wrong-type' },+ ],+ [+ 'an empty flag update',+ { type: 'set-locked', updates: [] },+ { operation: 'set-locked nothing', status: 'unsupported' },+ ],+ [+ 'flags that already hold',+ { type: 'set-enabled', updates: [{ id: 'r1', isEnabled: true }] },+ { status: 'unchanged' },+ ],+ ])('answers %s', (_label, command, result) => {+ expect(modelOf(projectWith(tree(), 'r1')).prepare(command)).toEqual(result);+ });++ it('selects any node without recording history and reports the current selection as unchanged', () => {+ const project = projectWith(tree(), 'r1');+ const { edit } = roundTrip(project, { id: 'G', type: 'select' });+ expect(edit).toMatchObject({ history: 'none', selectionAfter: 'G', selectionBefore: 'r1', touchedIds: [] });+ expect(modelOf(project).prepare({ id: 'r1', type: 'select' })).toEqual({ status: 'unchanged' });+ });++ it.each<[string, DocumentCommand, PrepareEditResult]>([+ ['a move already at the boundary', { ids: ['r1'], kind: 'front', type: 'move' }, { status: 'unchanged' }],+ [+ 'a reorder that keeps the order',+ { orders: [{ orderedIds: ['r1', 'G', 'r5'], parentId: null, stack: 'raster' }], type: 'reorder' },+ { status: 'unchanged' },+ ],+ ])('reports %s as unchanged', (_label, command, result) => {+ expect(modelOf(projectWith(tree(), 'r1')).prepare(command)).toEqual(result);+ });++ it.each<[string, DocumentCommand, PrepareEditResult]>([+ ['a missing removal', { ids: ['ghost', 'r1'], type: 'remove' }, { ids: ['ghost'], status: 'missing' }],+ ['a locked removal', { ids: ['locked'], type: 'remove' }, { ids: ['locked'], status: 'locked' }],+ ['an empty removal', { ids: [], type: 'remove' }, { operation: 'remove nothing', status: 'unsupported' }],+ [+ 'a clashing insert',+ { aboveId: null, nodes: [layer('r1')], type: 'insert' },+ { reason: 'id-exists', status: 'invalid-target', targetId: 'r1' },+ ],+ [+ 'an insert clashing with a group id',+ { aboveId: null, nodes: [layer('G')], type: 'insert' },+ { reason: 'id-exists', status: 'invalid-target', targetId: 'G' },+ ],+ [+ 'an empty insert',+ { aboveId: null, nodes: [], type: 'insert' },+ { operation: 'insert nothing', status: 'unsupported' },+ ],+ [+ 'a missing duplicate source',+ { createId: () => 'x', ids: ['ghost'], type: 'duplicate' },+ { ids: ['ghost'], status: 'missing' },+ ],+ [+ 'a duplicate onto an existing id',+ { createId: () => 'r1', ids: ['r5'], type: 'duplicate' },+ { reason: 'id-exists', status: 'invalid-target', targetId: 'r1' },+ ],+ ['an empty move', { ids: [], kind: 'front', type: 'move' }, { operation: 'move nothing', status: 'unsupported' }],+ [+ 'a reorder missing a member',+ { orders: [{ orderedIds: ['r1'], parentId: null, stack: 'raster' }], type: 'reorder' },+ { reason: 'not-siblings', status: 'invalid-target', targetId: 'r1' },+ ],+ [+ 'a reorder naming a node of another list',+ { orders: [{ orderedIds: ['r1', 'G', 'r5', 'r2'], parentId: null, stack: 'raster' }], type: 'reorder' },+ { reason: 'not-siblings', status: 'invalid-target', targetId: 'r2' },+ ],+ [+ 'a reorder naming an unknown id',+ { orders: [{ orderedIds: ['r1', 'G', 'ghost'], parentId: null, stack: 'raster' }], type: 'reorder' },+ { ids: ['ghost'], status: 'missing' },+ ],+ [+ 'a reorder under a leaf',+ { orders: [{ orderedIds: [], parentId: 'r1', stack: 'raster' }], type: 'reorder' },+ { reason: 'not-a-group', status: 'invalid-target', targetId: 'r1' },+ ],+ [+ 'a reorder of one list twice',+ {+ orders: [+ { orderedIds: ['G', 'r1', 'r5'], parentId: null, stack: 'raster' },+ { orderedIds: ['r1', 'G', 'r5'], parentId: null, stack: 'raster' },+ ],+ type: 'reorder',+ },+ { operation: 'reorder one sibling list twice', status: 'unsupported' },+ ],+ [+ 'a patch of nothing',+ { id: 'r1', patch: {}, type: 'patch' },+ { operation: 'patch nothing', status: 'unsupported' },+ ],+ ['a selection of a missing node', { id: 'ghost', type: 'select' }, { ids: ['ghost'], status: 'missing' }],+ ['an ungroup of a missing node', { ids: ['ghost'], type: 'ungroup' }, { ids: ['ghost'], status: 'missing' }],+ [+ 'a translate of a missing node',+ { dx: 1, dy: 1, ids: ['ghost'], type: 'translate' },+ { ids: ['ghost'], status: 'missing' },+ ],+ ])('refuses %s', (_label, command, refusal) => {+ const project = projectWith([...tree(), layer('locked', 'raster', { isLocked: true })], 'r1');+ expect(modelOf(project).prepare(command)).toEqual(refusal);+ });++ it('stamps every prepared edit with the project id and edit revision it was built against', () => {+ const project = projectWith(tree(), 'r1');+ const result = createDocumentModel(project.canvas.document, { editRevision: 7, projectId: project.id }).prepare({+ ids: ['r1'],+ type: 'remove',+ });+ expect(result).toMatchObject({ edit: { expectedRevision: 7, projectId: project.id }, status: 'prepared' });+ });+ });++ describe('canMergeDown', () => {+ it('targets the raster sibling directly below under the same parent', () => {+ const project = projectWith([layer('a'), layer('b'), group('G', [layer('c'), layer('d')]), layer('e')], 'a');+ const model = modelOf(project);+ expect(model.canMergeDown('a')).toEqual({ lowerId: 'b', status: 'eligible', upperId: 'a' });+ expect(model.canMergeDown('b')).toEqual({ reason: 'no-layer-below', status: 'invalid-target', targetId: 'b' });+ expect(model.canMergeDown('c')).toEqual({ lowerId: 'd', status: 'eligible', upperId: 'c' });+ expect(model.canMergeDown('d')).toEqual({ reason: 'no-layer-below', status: 'invalid-target', targetId: 'd' });+ expect(model.canMergeDown('G')).toEqual({ actual: 'group', expected: ['raster'], status: 'wrong-type' });+ });++ it('reports a locked ancestor and a disabled ancestor', () => {+ const locked = projectWith([group('G', [layer('a'), layer('b')], { isLocked: true })], null);+ expect(modelOf(locked).canMergeDown('a')).toEqual({ ids: ['G'], status: 'locked' });+ const off = projectWith([group('G', [layer('a'), layer('b')], { isEnabled: false })], null);+ expect(modelOf(off).canMergeDown('a')).toEqual({+ reason: 'not-mergeable',+ status: 'invalid-target',+ targetId: 'a',+ });+ });++ it.each<[string, CanvasNodeContract[], string, object]>([+ ['the bottom layer', flat(), 'r3', { reason: 'no-layer-below', status: 'invalid-target', targetId: 'r3' }],+ ['a mask', flat(), 'i1', { actual: 'inpaint_mask', expected: ['raster'], status: 'wrong-type' }],+ ['a missing id', flat(), 'ghost', { ids: ['ghost'], status: 'missing' }],+ [+ 'a locked lower layer',+ [layer('a'), layer('b', 'raster', { isLocked: true })],+ 'a',+ { ids: ['b'], status: 'locked' },+ ],+ [+ 'a disabled upper layer',+ [layer('a', 'raster', { isEnabled: false }), layer('b')],+ 'a',+ { reason: 'not-mergeable', status: 'invalid-target', targetId: 'a' },+ ],+ ])('refuses %s', (_label, nodes, upperId, refusal) => {+ expect(modelOf(projectWith(nodes, null)).canMergeDown(upperId)).toEqual(refusal);+ });+ });+});++describe('document-level seam', () => {+ it('looks nodes, layers and leaves up through the same index the model uses', () => {+ const document = projectWith(tree(), 'r1').canvas.document;+ expect(lookupDocumentLayer(document, 'r3')).toBe(getDocumentLeaves(document).find((layer) => layer.id === 'r3'));+ expect(lookupDocumentLayer(document, 'G')).toBeNull();+ expect(lookupDocumentLeaf(document, 'r3')).toBe(compileDocumentLeaves(document).find((leaf) => leaf.id === 'r3'));+ expect(lookupDocumentLeaf(document, 'G')).toBeNull();+ expect(lookupDocumentLeaf(document, 'nope')).toBeNull();+ });++ it('finds the leaf sibling directly below, never crossing a parent or a group', () => {+ const document = projectWith(tree(), 'r1').canvas.document;+ expect(lookupLayerBelow(document, 'r2')).toBeNull();+ expect(lookupLayerBelow(document, 'r1')).toBeNull();+ expect(lookupLayerBelow(document, 'H')?.id).toBe('r4');+ expect(lookupLayerBelow(document, 'r4')).toBeNull();+ expect(lookupLayerBelow(projectWith([layer('a'), layer('b')], null).canvas.document, 'a')?.id).toBe('b');+ });++ it('shares the merge-down rule with the model', () => {+ const project = projectWith(tree(), 'r1');+ const model = modelOf(project);+ for (const entry of getDocumentIndex(project.canvas.document).nodes) {+ expect(mergeDownEligibility(project.canvas.document, entry.node.id)).toEqual(model.canMergeDown(entry.node.id));+ }+ });+});++describe('checkEditPostconditions', () => {+ const document = projectWith(tree(), 'r2').canvas.document;++ it.each([+ ['present ids', { ids: ['r1', 'G', 'r3'], kind: 'present' as const }, true],+ ['a missing present id', { ids: ['r1', 'ghost'], kind: 'present' as const }, false],+ ['absent ids', { ids: ['ghost'], kind: 'absent' as const }, true],+ ['a present absent id', { ids: ['r1'], kind: 'absent' as const }, false],+ [+ 'the exact root order',+ { kind: 'sibling-order' as const, orderedIds: ['r1', 'G', 'r5'], parentId: null, stack: 'raster' as const },+ true,+ ],+ [+ 'the exact group order',+ { kind: 'sibling-order' as const, orderedIds: ['r2', 'H', 'r4'], parentId: 'G', stack: 'raster' as const },+ true,+ ],+ [+ 'a shorter order',+ { kind: 'sibling-order' as const, orderedIds: ['r1', 'G'], parentId: null, stack: 'raster' as const },+ false,+ ],+ [+ 'a permuted order',+ { kind: 'sibling-order' as const, orderedIds: ['G', 'r1', 'r5'], parentId: null, stack: 'raster' as const },+ false,+ ],+ ['the selection', { id: 'r2', kind: 'selection' as const }, true],+ ['another selection', { id: 'r1', kind: 'selection' as const }, false],+ ['an applied patch', { id: 'r1', kind: 'patched' as const, patch: { name: 'r1', transform: { x: 0 } } }, true],+ ['an applied group patch', { id: 'G', kind: 'patched' as const, patch: { isEnabled: true, name: 'G' } }, true],+ ['an unapplied patch', { id: 'r1', kind: 'patched' as const, patch: { name: 'r1', transform: { x: 3 } } }, false],+ ['a leaf-only field on a group', { id: 'G', kind: 'patched' as const, patch: { opacity: 1 } }, false],+ ['a patch of a missing node', { id: 'ghost', kind: 'patched' as const, patch: { name: 'x' } }, false],+ ])('checks %s', (_label, postcondition, expected) => {+ expect(checkEditPostconditions(document, [postcondition])).toBe(expected);+ });+});++describe('lock coherence and limits', () => {+ /** raster: r1, L(locked)[r2, M[r3]], r4(locked) */+ const lockedTree = (): CanvasNodeContract[] => [+ layer('r1'),+ group('L', [layer('r2'), group('M', [layer('r3')])], { isLocked: true }),+ layer('r4', 'raster', { isLocked: true }),+ ];++ it('refuses content edits inside a locked group while name, enablement and lock flips stay open', () => {+ const model = modelOf(projectWith(lockedTree(), 'r2'));+ expect(model.prepare({ id: 'r2', patch: { transform: { x: 10 } }, type: 'patch' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ expect(model.prepare({ id: 'r3', patch: { opacity: 0.5 }, type: 'patch' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ expect(model.prepare({ id: 'r4', patch: { opacity: 0.5 }, type: 'patch' })).toEqual({+ ids: ['r4'],+ status: 'locked',+ });+ expect(model.prepare({ id: 'r2', source: { bitmap: null, type: 'paint' }, type: 'patch-source' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ expect(model.prepare({ id: 'r2', patch: { name: 'renamed' }, type: 'patch' }).status).toBe('prepared');+ expect(model.prepare({ id: 'r3', patch: { isEnabled: false }, type: 'patch' }).status).toBe('prepared');+ expect(model.prepare({ id: 'L', patch: { isLocked: false }, type: 'patch' }).status).toBe('prepared');+ });++ it('refuses inserting into or reordering inside a locked group, but moves a locked node among free siblings', () => {+ const model = modelOf(projectWith(lockedTree(), 'r2'));+ expect(model.prepare({ aboveId: 'r2', nodes: [layer('new')], type: 'insert' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ expect(model.prepare({ aboveId: null, insideId: 'M', nodes: [layer('new')], type: 'insert' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ expect(model.prepare({ ids: ['r2'], kind: 'back', type: 'move' })).toEqual({ ids: ['L'], status: 'locked' });+ expect(model.prepare({ ids: ['r4'], kind: 'front', type: 'move' }).status).toBe('prepared');+ expect(model.prepare({ aboveId: 'r1', nodes: [layer('new')], type: 'insert' }).status).toBe('prepared');+ });++ it('counts every node of a multi-stack insert and a multi-root duplicate against the node limit', () => {+ const document = createLargeFlatDocument(CANVAS_MAX_NODE_COUNT - 1);+ const model = createDocumentModel(document, { editRevision: 0, projectId: 'project' });+ expect(model.prepare({ aboveId: null, nodes: [layer('x'), layer('y', 'control')], type: 'insert' })).toMatchObject({+ reason: 'node-limit',+ status: 'invalid-target',+ });+ expect(model.prepare({ aboveId: null, nodes: [layer('x')], type: 'insert' }).status).toBe('prepared');+ let created = 0;+ const createId = () => `dup${created++}`;+ expect(model.prepare({ createId, ids: ['l0', 'l1'], type: 'duplicate' })).toMatchObject({ reason: 'node-limit' });+ expect(model.prepare({ createId, ids: ['l0'], type: 'duplicate' }).status).toBe('prepared');+ });++ it('inserts an empty group into the stack it names and refuses one without a stack', () => {+ expect(+ modelOf(projectWith(tree(), 'c1')).prepare({ aboveId: 'c1', nodes: [group('E')], type: 'insert' })+ ).toMatchObject({+ status: 'unsupported',+ });+ const { after } = roundTrip(projectWith(tree(), 'c1'), {+ aboveId: 'c1',+ nodes: [group('E')],+ stack: 'control',+ type: 'insert',+ });+ expect(after.canvas.document.stacks.control.map((node) => node.id)).toEqual(['E', 'c1']);+ });++ it('reparents leaves from different parents in one edit and restores each run on undo', () => {+ const { after } = roundTrip(projectWith(tree(), 'r1'), {+ beforeId: null,+ ids: ['r1', 'r3', 'r5'],+ parentId: 'G',+ type: 'reparent',+ });+ expect(outline(after.canvas.document)).toEqual(['i1', 'c1', 'G', ' r2', ' H', ' r4', ' r1', ' r3', ' r5']);+ });++ it('dissolves sibling groups in one edit', () => {+ const { after, edit } = roundTrip(+ projectWith([group('A', [layer('r1'), layer('r2')]), group('B', [layer('r3')])], 'r3'),+ {+ ids: ['A', 'B'],+ type: 'ungroup',+ }+ );+ expect(outline(after.canvas.document)).toEqual(['r1', 'r2', 'r3']);+ expect(edit.selectionAfter).toBe('r3');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.tsnew file mode 100644index 0000000000..d123a061f3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts@@ -0,0 +1,1321 @@+import type {+ CanvasDocumentContractV3,+ CanvasGroupContract,+ CanvasLayerContract,+ CanvasNodeContract,+} from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentIndex, CanvasNodeEntry } from '@workbench/canvas-engine/document/documentIndex';+import type {+ CanvasNodeInsertion,+ CanvasNodeInsertionAnchor,+ CanvasNodeMove,+} from '@workbench/canvas-engine/document/insertionAnchors';+import type { LayerStackKind, ReorderSiblingsCommand } from '@workbench/canvas-engine/document/layerStacks';+import type {+ CanvasLayerBasePatch,+ CanvasLayerConfigPatch,+ CanvasProjectMutation,+} from '@workbench/canvas-engine/mutationContracts';++import { CANVAS_MAX_NODE_COUNT, CANVAS_MAX_NODE_DEPTH } from '@workbench/canvas-engine/contracts';+import { childrenAt, getDocumentIndex, outermostNodes } from '@workbench/canvas-engine/document/documentIndex';+import {+ cloneSubtree,+ collectSubtree,+ collectSubtreeLeaves,+ isGroupNode,+ subtreeDepth,+} from '@workbench/canvas-engine/document/documentTree';+import { captureInsertionAnchor, insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import {+ isHideableLayer,+ isLayerContributing,+ isNodeHidden,+ isPixelBackedLayer,+} from '@workbench/canvas-engine/document/layerEligibility';+import {+ getSiblingOrder,+ isOverlayStack,+ LAYER_STACKS_TOP_FIRST,+ layerStackOf,+ moveNodesWithinSiblings,+ reorderSiblings,+} from '@workbench/canvas-engine/document/layerStacks';+import { repairSelectedLayerId } from '@workbench/canvas-engine/document/selectionRepair';+import { GROUP_PATCH_KEYS } from '@workbench/canvas-engine/mutationContracts';++import type {+ DocumentCommand,+ DocumentRefusal,+ MergeDownEligibility,+ PreparedDocumentEdit,+ PrepareEditResult,+} from './documentCommands';+import type { EditPostcondition } from './postconditions';+import type { SemanticLeaf } from './semanticLeaf';++import { isConfigApplied, isPatchApplied, sameValue } from './postconditions';+import { compileSemanticLeaf, isSemanticLeafCurrent } from './semanticLeaf';++export interface DocumentModelContext {+ readonly projectId: string;+ readonly editRevision: number;+}++/**+ * The pure document seam over a v3 canvas document: lookup, tree facts, semantic leaves and+ * prepared edits, with no knowledge of the engine, the screen or the panel. The index is built once+ * per forest identity; a leaf keeps its identity while its layer object and ancestor-effective+ * state are unchanged. Ordering belongs to the returned sequences.+ */+export interface CanvasDocumentModel {+ readonly document: CanvasDocumentContractV3;+ getNode(id: string): CanvasNodeContract | null;+ /** The leaf with `id`; `null` for a group or an absent id. */+ getLayer(id: string): CanvasLayerContract | null;+ getEntry(id: string): CanvasNodeEntry | null;+ getStack(kind: LayerStackKind): readonly CanvasNodeContract[];+ compileLeaves(): readonly SemanticLeaf[];+ canMergeDown(upperId: string): MergeDownEligibility;+ prepare(command: DocumentCommand): PrepareEditResult;+}++export interface DocumentModelDiagnostics {+ readonly leafCompilations: number;+ readonly leavesCompiled: number;+}++const diagnostics = { leafCompilations: 0, leavesCompiled: 0 };++/** Immutable snapshot for deterministic budget tests and diagnostics. */+export const getDocumentModelDiagnostics = (): DocumentModelDiagnostics => ({ ...diagnostics });++export const resetDocumentModelDiagnostics = (): void => {+ diagnostics.leafCompilations = 0;+ diagnostics.leavesCompiled = 0;+};++const leavesByIndex = new WeakMap<CanvasDocumentIndex, readonly SemanticLeaf[]>();+const leavesByLayer = new WeakMap<CanvasLayerContract, SemanticLeaf>();+const leafByIdByIndex = new WeakMap<CanvasDocumentIndex, ReadonlyMap<string, SemanticLeaf>>();+const contributingByIndex = new WeakMap<CanvasDocumentIndex, readonly CanvasLayerContract[]>();++const compileLeaves = (index: CanvasDocumentIndex): readonly SemanticLeaf[] => {+ const cached = leavesByIndex.get(index);+ if (cached) {+ return cached;+ }+ diagnostics.leafCompilations += 1;+ const leaves: SemanticLeaf[] = [];+ for (const entry of index.nodes) {+ if (isGroupNode(entry.node)) {+ continue;+ }+ const previous = leavesByLayer.get(entry.node);+ if (previous && isSemanticLeafCurrent(previous, entry.node, entry)) {+ leaves.push(previous);+ continue;+ }+ diagnostics.leavesCompiled += 1;+ const leaf = compileSemanticLeaf(entry.node, entry);+ leavesByLayer.set(entry.node, leaf);+ leaves.push(leaf);+ }+ leavesByIndex.set(index, leaves);+ return leaves;+};++const missing = (ids: readonly string[]): DocumentRefusal => ({ ids, status: 'missing' });++type DocumentView = CanvasDocumentContractV3 | null | undefined;++export const lookupDocumentNode = (document: DocumentView, id: string): CanvasNodeContract | null =>+ document ? (getDocumentIndex(document).byId.get(id)?.node ?? null) : null;++/** The leaf with `id`; `null` for a group or an absent id. */+export const lookupDocumentLayer = (document: DocumentView, id: string): CanvasLayerContract | null => {+ const node = lookupDocumentNode(document, id);+ return node && !isGroupNode(node) ? node : null;+};++/** The document's semantic leaves, stacks top first, each in preorder. */+export const compileDocumentLeaves = (document: CanvasDocumentContractV3): readonly SemanticLeaf[] =>+ compileLeaves(getDocumentIndex(document));++/** The layers of every contributing leaf, in leaf order; the same array while the forests are unchanged. */+export const compileContributingLayers = (document: CanvasDocumentContractV3): readonly CanvasLayerContract[] => {+ const index = getDocumentIndex(document);+ const cached = contributingByIndex.get(index);+ if (cached) {+ return cached;+ }+ const layers = compileLeaves(index)+ .filter((leaf) => leaf.contributionEnabled)+ .map((leaf) => leaf.layer);+ contributingByIndex.set(index, layers);+ return layers;+};++/** The leaf for `id`, or `null` when the document has no such leaf. */+export const lookupDocumentLeaf = (document: DocumentView, id: string): SemanticLeaf | null => {+ if (!document) {+ return null;+ }+ const index = getDocumentIndex(document);+ let byId = leafByIdByIndex.get(index);+ if (!byId) {+ byId = new Map(compileLeaves(index).map((leaf) => [leaf.id, leaf]));+ leafByIdByIndex.set(index, byId);+ }+ return byId.get(id) ?? null;+};++/** The sibling directly below `id` when it is a leaf; `null` at the bottom, below a group, or when absent. */+export const lookupLayerBelow = (document: DocumentView, id: string): CanvasLayerContract | null => {+ const entry = document ? getDocumentIndex(document).byId.get(id) : undefined;+ if (!document || !entry) {+ return null;+ }+ const below = childrenAt(getDocumentIndex(document), entry.stack, entry.parentId)?.[entry.siblingIndex + 1];+ return below && !isGroupNode(below) ? below : null;+};++/** Merge-down joins a raster leaf with the raster leaf directly below it under the same parent. */+export const mergeDownEligibility = (document: CanvasDocumentContractV3, upperId: string): MergeDownEligibility => {+ const index = getDocumentIndex(document);+ const upper = index.byId.get(upperId);+ if (!upper) {+ return missing([upperId]);+ }+ if (isGroupNode(upper.node) || upper.stack !== 'raster') {+ return { actual: upper.node.type, expected: ['raster'], status: 'wrong-type' };+ }+ const lower = lookupLayerBelow(document, upperId);+ if (!lower) {+ return { reason: 'no-layer-below', status: 'invalid-target', targetId: upperId };+ }+ const pair = [upper.node, lower];+ const unmergeable = pair.find((layer) => layer.type !== 'raster' || !isPixelBackedLayer(layer));+ if (unmergeable) {+ return { reason: 'not-mergeable', status: 'invalid-target', targetId: unmergeable.id };+ }+ const locked = pair.filter((layer) => layer.isLocked).map((layer) => layer.id);+ if (upper.ancestorsLocked) {+ locked.push(...upper.path.filter((id) => index.byId.get(id)!.node.isLocked));+ }+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ const disabled = pair.find((layer) => !isLayerContributing(layer));+ if (disabled || !upper.ancestorsEnabled) {+ return { reason: 'not-mergeable', status: 'invalid-target', targetId: disabled?.id ?? upperId };+ }+ return { lowerId: lower.id, status: 'eligible', upperId };+};++const unique = <T>(values: readonly T[]): T[] => [...new Set(values)];++/**+ * Whether two patches name the same fields, descending only into the partial containers listed in+ * `containers` as dotted paths; every other value is compared as a whole.+ */+const sameKeys = (+ left: Record<string, unknown>,+ right: Record<string, unknown>,+ containers: readonly string[],+ path = ''+): boolean => {+ const leftKeys = Object.keys(left).sort();+ const rightKeys = Object.keys(right).sort();+ return (+ leftKeys.length === rightKeys.length &&+ leftKeys.every((key, position) => key === rightKeys[position]) &&+ leftKeys.every((key) => {+ const keyPath = path ? `${path}.${key}` : key;+ if (!containers.includes(keyPath)) {+ return true;+ }+ const a = left[key];+ const b = right[key];+ return typeof a === 'object' && a !== null && typeof b === 'object' && b !== null+ ? sameKeys(a as Record<string, unknown>, b as Record<string, unknown>, containers, keyPath)+ : a === undefined && b === undefined;+ })+ );+};++const PATCH_CONTAINERS = ['transform'] as const;+const CONFIG_CONTAINERS = ['adapter', 'mask', 'mask.fill'] as const;++const stacksTopFirst = (stacks: readonly LayerStackKind[]): LayerStackKind[] =>+ LAYER_STACKS_TOP_FIRST.filter((stack) => stacks.includes(stack));++const patchInverse = (node: CanvasNodeContract, patch: CanvasLayerBasePatch): CanvasLayerBasePatch => {+ const inverse: Record<string, unknown> = {};+ for (const key of Object.keys(patch) as (keyof CanvasLayerBasePatch)[]) {+ if (key === 'transform') {+ if (isGroupNode(node)) {+ continue;+ }+ const transform: Record<string, number> = {};+ for (const axis of Object.keys(patch.transform ?? {}) as (keyof CanvasLayerContract['transform'])[]) {+ transform[axis] = node.transform[axis];+ }+ inverse.transform = transform;+ } else {+ inverse[key] = (node as unknown as Record<string, unknown>)[key];+ }+ }+ return inverse as CanvasLayerBasePatch;+};++const stackOf = (node: CanvasNodeContract, index: CanvasDocumentIndex): LayerStackKind | null =>+ isGroupNode(node) ? (index.byId.get(node.id)?.stack ?? null) : layerStackOf(node);++/** Levels a node's child lists reach below it: a group always opens one, even while empty. */+const levelsBelow = (node: CanvasNodeContract): number => (isGroupNode(node) ? Math.max(1, subtreeDepth(node)) : 0);++/** Ids of locked nodes along `path`, root first. */+const lockedAlong = (index: CanvasDocumentIndex, path: readonly string[]): string[] =>+ path.filter((id) => index.byId.get(id)!.node.isLocked);++/** Ids of locked nodes among `entry`'s ancestors, itself, and its subtree. */+const lockedWithin = (index: CanvasDocumentIndex, entry: CanvasNodeEntry): string[] => [+ ...lockedAlong(index, entry.path),+ ...collectSubtree(entry.node)+ .filter((node) => node.isLocked)+ .map((node) => node.id),+];++/** Ids of locked nodes among `entry`'s ancestors and itself: the ones that freeze its content. */+const frozenBy = (index: CanvasDocumentIndex, entry: CanvasNodeEntry): string[] =>+ lockedAlong(index, [...entry.path, entry.node.id]);++/** A contiguous run of outermost nodes under one parent, anchored to its unmoved neighbours. */+interface SiblingRun {+ readonly ids: string[];+ readonly anchor: CanvasNodeInsertionAnchor;+}++/**+ * Splits `entries` (outermost, document order) into maximal runs of adjacent siblings, each anchored+ * to the nearest siblings that are not among `entries`. Applying the runs top first puts every+ * node back exactly where it was, whether they are being restored after a removal or a move.+ */+const captureRestoreRuns = (+ index: CanvasDocumentIndex,+ entries: readonly CanvasNodeEntry[],+ context: DocumentModelContext+): SiblingRun[] => {+ const moving = new Set(entries.map((entry) => entry.node.id));+ const runs: SiblingRun[] = [];+ const seenParents = new Set<string>();+ for (const entry of entries) {+ const parentKey = `${entry.stack}\0${entry.parentId ?? ''}`;+ if (seenParents.has(parentKey)) {+ continue;+ }+ seenParents.add(parentKey);+ const siblings = childrenAt(index, entry.stack, entry.parentId) ?? [];+ let run: string[] = [];+ let afterId: string | null = null;+ const flush = (beforeId: string | null): void => {+ if (run.length > 0) {+ runs.push({+ anchor: {+ afterId,+ beforeId,+ capturedEditRevision: context.editRevision,+ parentPath: entry.path,+ projectId: context.projectId,+ stack: entry.stack,+ },+ ids: run,+ });+ run = [];+ }+ };+ for (const sibling of siblings) {+ if (moving.has(sibling.id)) {+ run.push(sibling.id);+ } else {+ flush(sibling.id);+ afterId = sibling.id;+ }+ }+ flush(null);+ }+ return runs;+};++export const createDocumentModel = (+ document: CanvasDocumentContractV3,+ context: DocumentModelContext+): CanvasDocumentModel => {+ const index = getDocumentIndex(document);+ const { stacks, selectedLayerId } = document;++ const lookup = (ids: readonly string[]): { entries: CanvasNodeEntry[] } | DocumentRefusal => {+ const absent = ids.filter((id) => !index.byId.has(id));+ return absent.length > 0 ? missing(absent) : { entries: ids.map((id) => index.byId.get(id)!) };+ };++ const prepared = (+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation,+ detail: Partial<Pick<PreparedDocumentEdit, 'createdIds' | 'history'>> &+ Pick<PreparedDocumentEdit, 'postconditions' | 'selectionAfter' | 'touchedIds' | 'touchedStacks'>+ ): PrepareEditResult => ({+ edit: {+ createdIds: [],+ history: 'record',+ ...detail,+ expectedRevision: context.editRevision,+ forward,+ inverse,+ projectId: context.projectId,+ rasterWork: null,+ selectionBefore: selectedLayerId,+ },+ status: 'prepared',+ });++ const structural = (+ mutation: Omit<Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }>, 'type' | 'enabledUpdates'>+ ): CanvasProjectMutation => ({ enabledUpdates: [], type: 'applyCanvasLayerStackMutation', ...mutation });++ const limits = (+ added: readonly CanvasNodeContract[],+ parentDepth: number,+ alreadyAdded: number+ ): DocumentRefusal | null => {+ const addedNodes = added.flatMap((node) => collectSubtree(node));+ if (index.nodes.length + alreadyAdded + addedNodes.length > CANVAS_MAX_NODE_COUNT) {+ return { reason: 'node-limit', status: 'invalid-target', targetId: added[0]?.id ?? '' };+ }+ const deepest = added.reduce((depth, node) => Math.max(depth, levelsBelow(node)), 0);+ if (parentDepth + 1 + deepest > CANVAS_MAX_NODE_DEPTH + 1) {+ return { reason: 'depth-exceeded', status: 'invalid-target', targetId: added[0]?.id ?? '' };+ }+ return null;+ };++ const siblingOrderOf = (stack: LayerStackKind, parentId: string | null): ReorderSiblingsCommand => ({+ orderedIds: (childrenAt(index, stack, parentId) ?? []).map((node) => node.id),+ parentId,+ stack,+ });++ const siblingOrderAfter = (+ next: CanvasDocumentContractV3['stacks'],+ stack: LayerStackKind,+ parentId: string | null+ ): EditPostcondition => ({ kind: 'sibling-order', ...getSiblingOrder(next, stack, parentId) });++ const prepareInsert = (command: Extract<DocumentCommand, { type: 'insert' }>): PrepareEditResult => {+ if (command.nodes.length === 0) {+ return { operation: 'insert nothing', status: 'unsupported' };+ }+ const ids = command.nodes.flatMap((node) => collectSubtree(node).map((entry) => entry.id));+ const clash = ids.find((id, at) => index.byId.has(id) || ids.indexOf(id) !== at);+ if (clash !== undefined) {+ return { reason: 'id-exists', status: 'invalid-target', targetId: clash };+ }+ const rootIds = command.nodes.map((node) => node.id);+ const selectionAfter = command.selectId === undefined ? rootIds.at(-1)! : command.selectId;+ if (selectionAfter !== null && !ids.includes(selectionAfter) && !index.byId.has(selectionAfter)) {+ return missing([selectionAfter]);+ }+ const stackFor = (node: CanvasNodeContract): LayerStackKind | null =>+ isGroupNode(node)+ ? collectSubtreeLeaves(node)[0]+ ? layerStackOf(collectSubtreeLeaves(node)[0]!)+ : (command.stack ?? null)+ : layerStackOf(node);+ const byStack = new Map<LayerStackKind, CanvasNodeContract[]>();+ for (const node of command.nodes) {+ const stack = stackFor(node);+ if (stack === null) {+ return { operation: 'insert an empty group without a stack', status: 'unsupported' };+ }+ if (isGroupNode(node) && collectSubtreeLeaves(node).some((leaf) => layerStackOf(leaf) !== stack)) {+ return { reason: 'foreign-stack', status: 'invalid-target', targetId: node.id };+ }+ if (+ stack === 'raster' &&+ collectSubtree(node).some((member) => isGroupNode(member) && member.isHidden !== undefined)+ ) {+ return { operation: 'insert a display-hidden group into the raster stack', status: 'unsupported' };+ }+ byStack.set(stack, [...(byStack.get(stack) ?? []), node]);+ }+ const touchedStacks = stacksTopFirst([...byStack.keys()]);+ const add: CanvasNodeInsertion[] = [];+ let expected = stacks;+ let added = 0;+ for (const stack of touchedStacks) {+ const nodes = byStack.get(stack)!;+ const anchor = captureInsertionAnchor(stacks, {+ aboveId: command.aboveId,+ editRevision: context.editRevision,+ insideId: command.insideId,+ projectId: context.projectId,+ stack,+ });+ const locked = lockedAlong(index, anchor.parentPath);+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ const refusal = limits(nodes, anchor.parentPath.length, added);+ if (refusal) {+ return refusal;+ }+ added += nodes.reduce((count, node) => count + collectSubtree(node).length, 0);+ add.push({ anchor, nodes });+ expected = insertNodesAtAnchor(expected, anchor, nodes);+ }+ const expectedIndex = getDocumentIndex({ stacks: expected });+ return prepared(+ structural({ add, selectedLayerId: selectionAfter }),+ structural({ removeIds: rootIds, selectedLayerId }),+ {+ createdIds: ids,+ postconditions: [+ ...add.map((insertion) => {+ const entry = expectedIndex.byId.get(insertion.nodes[0]!.id)!;+ return siblingOrderAfter(expected, entry.stack, entry.parentId);+ }),+ { id: selectionAfter, kind: 'selection' },+ ],+ selectionAfter,+ touchedIds: ids,+ touchedStacks,+ }+ );+ };++ const prepareRemove = (command: Extract<DocumentCommand, { type: 'remove' }>): PrepareEditResult => {+ const ids = unique(command.ids);+ if (ids.length === 0) {+ return { operation: 'remove nothing', status: 'unsupported' };+ }+ const found = lookup(ids);+ if ('status' in found) {+ return found;+ }+ const outer = outermostNodes(index, ids);+ const locked = unique(outer.flatMap((entry) => lockedWithin(index, entry)));+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ const removedIds = outer.flatMap((entry) => collectSubtree(entry.node).map((node) => node.id));+ const removedSet = new Set(removedIds);+ const remaining = { ...stacks };+ for (const stack of new Set(outer.map((entry) => entry.stack))) {+ remaining[stack] = stacks[stack]+ .filter((node) => !removedSet.has(node.id))+ .map((node) => stripRemoved(node, removedSet));+ }+ const selectionAfter = repairSelectedLayerId(remaining, selectedLayerId, stacks);+ const touchedStacks = stacksTopFirst(outer.map((entry) => entry.stack));+ const add: CanvasNodeInsertion[] = captureRestoreRuns(index, outer, context).map((run) => ({+ anchor: run.anchor,+ nodes: run.ids.map((id) => index.byId.get(id)!.node),+ }));+ return prepared(+ { ids: outer.map((entry) => entry.node.id), type: 'removeCanvasLayers' },+ structural({ add, selectedLayerId }),+ {+ postconditions: [+ { ids: removedIds, kind: 'absent' },+ ...unique(outer.map((entry) => `${entry.stack}\0${entry.parentId ?? ''}`)).map((key) => {+ const [stack, parentId] = key.split('\0') as [LayerStackKind, string];+ return siblingOrderAfter(remaining, stack, parentId === '' ? null : parentId);+ }),+ { id: selectionAfter, kind: 'selection' },+ ],+ selectionAfter,+ touchedIds: removedIds,+ touchedStacks,+ }+ );+ };++ const prepareDuplicate = (command: Extract<DocumentCommand, { type: 'duplicate' }>): PrepareEditResult => {+ const ids = unique(command.ids);+ if (ids.length === 0) {+ return { operation: 'duplicate nothing', status: 'unsupported' };+ }+ const found = lookup(ids);+ if ('status' in found) {+ return found;+ }+ const outer = outermostNodes(index, ids);+ const locked = unique(outer.flatMap((entry) => lockedAlong(index, entry.path)));+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ const add: CanvasNodeInsertion[] = [];+ const createdIds: string[] = [];+ const rootIds: string[] = [];+ let expected = stacks;+ for (const entry of outer) {+ const { node } = cloneSubtree(entry.node, command.createId);+ const clone = { ...node, name: `${node.name} copy` };+ const clash = collectSubtree(clone).find((created) => index.byId.has(created.id));+ if (clash) {+ return { reason: 'id-exists', status: 'invalid-target', targetId: clash.id };+ }+ const refusal = limits([clone], entry.path.length, createdIds.length);+ if (refusal) {+ return refusal;+ }+ const anchor = captureInsertionAnchor(expected, {+ aboveId: entry.node.id,+ editRevision: context.editRevision,+ projectId: context.projectId,+ stack: entry.stack,+ });+ add.push({ anchor, nodes: [clone] });+ expected = insertNodesAtAnchor(expected, anchor, [clone]);+ createdIds.push(...collectSubtree(clone).map((created) => created.id));+ rootIds.push(clone.id);+ }+ const selectionAfter = rootIds.at(-1)!;+ return prepared(+ structural({ add, selectedLayerId: selectionAfter }),+ structural({ removeIds: rootIds, selectedLayerId }),+ {+ createdIds,+ postconditions: [+ ...outer.map((entry) => siblingOrderAfter(expected, entry.stack, entry.parentId)),+ { id: selectionAfter, kind: 'selection' },+ ],+ selectionAfter,+ touchedIds: createdIds,+ touchedStacks: stacksTopFirst(outer.map((entry) => entry.stack)),+ }+ );+ };++ const prepareReorder = (orders: readonly ReorderSiblingsCommand[]): PrepareEditResult => {+ if (orders.length === 0) {+ return { operation: 'reorder nothing', status: 'unsupported' };+ }+ if (new Set(orders.map((order) => `${order.stack}\0${order.parentId ?? ''}`)).size !== orders.length) {+ return { operation: 'reorder one sibling list twice', status: 'unsupported' };+ }+ const touchedIds: string[] = [];+ let expected = stacks;+ for (const order of orders) {+ const unknown = order.orderedIds.filter((id) => !index.byId.has(id));+ if (unknown.length > 0) {+ return missing(unknown);+ }+ if (order.parentId !== null) {+ const parent = index.byId.get(order.parentId);+ if (!parent) {+ return missing([order.parentId]);+ }+ if (!isGroupNode(parent.node)) {+ return { reason: 'not-a-group', status: 'invalid-target', targetId: order.parentId };+ }+ if (parent.stack !== order.stack) {+ return { reason: 'foreign-stack', status: 'invalid-target', targetId: order.parentId };+ }+ const locked = frozenBy(index, parent);+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ }+ const current = siblingOrderOf(order.stack, order.parentId).orderedIds;+ const foreign = order.orderedIds.find((id) => {+ const entry = index.byId.get(id)!;+ return entry.stack !== order.stack || entry.parentId !== order.parentId;+ });+ if (foreign !== undefined) {+ return { reason: 'not-siblings', status: 'invalid-target', targetId: foreign };+ }+ const next = reorderSiblings(expected, order);+ if (!next) {+ return { reason: 'not-siblings', status: 'invalid-target', targetId: order.orderedIds[0] ?? current[0]! };+ }+ expected = next;+ touchedIds.push(...order.orderedIds.filter((id, position) => current[position] !== id));+ }+ if (touchedIds.length === 0) {+ return { status: 'unchanged' };+ }+ return prepared(+ {+ orders: orders.map((order) => ({ ...order, orderedIds: [...order.orderedIds] })),+ type: 'reorderCanvasSiblings',+ },+ {+ orders: orders.map((order) => siblingOrderOf(order.stack, order.parentId)),+ type: 'reorderCanvasSiblings',+ },+ {+ postconditions: orders.map((order) => ({ kind: 'sibling-order', ...order })),+ selectionAfter: selectedLayerId,+ touchedIds,+ touchedStacks: stacksTopFirst(orders.map((order) => order.stack)),+ }+ );+ };++ const prepareMove = (command: Extract<DocumentCommand, { type: 'move' }>): PrepareEditResult => {+ const ids = unique(command.ids);+ if (ids.length === 0) {+ return { operation: 'move nothing', status: 'unsupported' };+ }+ const found = lookup(ids);+ if ('status' in found) {+ return found;+ }+ const orders = moveNodesWithinSiblings(index, ids, command.kind);+ return orders.length === 0 ? { status: 'unchanged' } : prepareReorder(orders);+ };++ const prepareReparent = (command: Extract<DocumentCommand, { type: 'reparent' }>): PrepareEditResult => {+ const ids = unique(command.ids);+ if (ids.length === 0) {+ return { operation: 'reparent nothing', status: 'unsupported' };+ }+ const found = lookup(ids);+ if ('status' in found) {+ return found;+ }+ const outer = outermostNodes(index, ids);+ const stack = outer[0]!.stack;+ const foreign = outer.find((entry) => entry.stack !== stack);+ if (foreign) {+ return { reason: 'foreign-stack', status: 'invalid-target', targetId: foreign.node.id };+ }+ const parent = command.parentId === null ? null : index.byId.get(command.parentId);+ if (parent === undefined) {+ return missing([command.parentId!]);+ }+ if (parent && !isGroupNode(parent.node)) {+ return { reason: 'not-a-group', status: 'invalid-target', targetId: parent.node.id };+ }+ if (parent && parent.stack !== stack) {+ return { reason: 'foreign-stack', status: 'invalid-target', targetId: parent.node.id };+ }+ const moving = new Set(outer.map((entry) => entry.node.id));+ if (parent && (moving.has(parent.node.id) || parent.path.some((id) => moving.has(id)))) {+ return { reason: 'cycle', status: 'invalid-target', targetId: parent.node.id };+ }+ const locked = unique([+ ...outer.flatMap((entry) => lockedAlong(index, entry.path)),+ ...(parent ? frozenBy(index, parent) : []),+ ]);+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ const parentDepth = parent ? parent.path.length + 1 : 0;+ const deepest = outer.reduce((depth, entry) => Math.max(depth, levelsBelow(entry.node)), 0);+ if (parentDepth + deepest > CANVAS_MAX_NODE_DEPTH) {+ return { reason: 'depth-exceeded', status: 'invalid-target', targetId: parent?.node.id ?? outer[0]!.node.id };+ }+ const targetChildren = (childrenAt(index, stack, command.parentId) ?? []).filter((node) => !moving.has(node.id));+ let position = targetChildren.length;+ if (command.beforeId !== null) {+ const before = index.byId.get(command.beforeId);+ if (!before) {+ return missing([command.beforeId]);+ }+ if (before.stack !== stack || before.parentId !== command.parentId || moving.has(before.node.id)) {+ return { reason: 'not-siblings', status: 'invalid-target', targetId: command.beforeId };+ }+ position = targetChildren.findIndex((node) => node.id === command.beforeId);+ }+ const orderedIds = [+ ...targetChildren.slice(0, position).map((node) => node.id),+ ...outer.map((entry) => entry.node.id),+ ...targetChildren.slice(position).map((node) => node.id),+ ];+ if (sameValue(orderedIds, siblingOrderOf(stack, command.parentId).orderedIds)) {+ return { status: 'unchanged' };+ }+ const anchor: CanvasNodeInsertionAnchor = {+ afterId: targetChildren[position - 1]?.id ?? null,+ beforeId: targetChildren[position]?.id ?? null,+ capturedEditRevision: context.editRevision,+ parentPath: parent ? [...parent.path, parent.node.id] : [],+ projectId: context.projectId,+ stack,+ };+ const inverseMoves: CanvasNodeMove[] = captureRestoreRuns(index, outer, context);+ const touchedParents = unique([+ `${stack}\0${command.parentId ?? ''}`,+ ...outer.map((entry) => `${entry.stack}\0${entry.parentId ?? ''}`),+ ]);+ return prepared(+ structural({ move: [{ anchor, ids: outer.map((entry) => entry.node.id) }] }),+ structural({ move: inverseMoves }),+ {+ postconditions: [+ { kind: 'sibling-order', orderedIds, parentId: command.parentId, stack },+ ...touchedParents+ .filter((key) => key !== `${stack}\0${command.parentId ?? ''}`)+ .map((key) => {+ const parentId = key.slice(stack.length + 1) || null;+ return {+ kind: 'sibling-order' as const,+ orderedIds: siblingOrderOf(stack, parentId).orderedIds.filter((id) => !moving.has(id)),+ parentId,+ stack,+ };+ }),+ ],+ selectionAfter: selectedLayerId,+ touchedIds: unique([+ ...orderedIds,+ ...outer.flatMap((entry) => collectSubtree(entry.node).map((node) => node.id)),+ ]),+ touchedStacks: [stack],+ }+ );+ };++ const prepareGroup = (command: Extract<DocumentCommand, { type: 'group' }>): PrepareEditResult => {+ const ids = unique(command.ids);+ if (ids.length === 0) {+ return { operation: 'group nothing', status: 'unsupported' };+ }+ if (index.byId.has(command.groupId)) {+ return { reason: 'id-exists', status: 'invalid-target', targetId: command.groupId };+ }+ const found = lookup(ids);+ if ('status' in found) {+ return found;+ }+ const outer = outermostNodes(index, ids);+ const first = outer[0]!;+ const stranger = outer.find((entry) => entry.stack !== first.stack || entry.parentId !== first.parentId);+ if (stranger) {+ return { reason: 'not-siblings', status: 'invalid-target', targetId: stranger.node.id };+ }+ const locked = lockedAlong(index, first.path);+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ const deepest = outer.reduce((depth, entry) => Math.max(depth, levelsBelow(entry.node)), 0);+ if (first.path.length + 1 + deepest > CANVAS_MAX_NODE_DEPTH) {+ return { reason: 'depth-exceeded', status: 'invalid-target', targetId: first.node.id };+ }+ if (index.nodes.length + 1 > CANVAS_MAX_NODE_COUNT) {+ return { reason: 'node-limit', status: 'invalid-target', targetId: command.groupId };+ }+ const group: CanvasGroupContract = {+ children: [],+ id: command.groupId,+ isEnabled: true,+ isLocked: false,+ name: command.name,+ type: 'group',+ };+ const groupAnchor = captureInsertionAnchor(stacks, {+ aboveId: first.node.id,+ editRevision: context.editRevision,+ projectId: context.projectId,+ stack: first.stack,+ });+ const inside: CanvasNodeInsertionAnchor = {+ afterId: null,+ beforeId: null,+ capturedEditRevision: context.editRevision,+ parentPath: [...first.path, command.groupId],+ projectId: context.projectId,+ stack: first.stack,+ };+ const movedIds = outer.map((entry) => entry.node.id);+ const moving = new Set(movedIds);+ const siblingsAfter = siblingOrderOf(first.stack, first.parentId).orderedIds.flatMap((id) =>+ id === first.node.id ? [command.groupId] : moving.has(id) ? [] : [id]+ );+ return prepared(+ structural({+ add: [{ anchor: groupAnchor, nodes: [group] }],+ move: [{ anchor: inside, ids: movedIds }],+ selectedLayerId: command.groupId,+ }),+ structural({ move: captureRestoreRuns(index, outer, context), removeIds: [command.groupId], selectedLayerId }),+ {+ createdIds: [command.groupId],+ postconditions: [+ { kind: 'sibling-order', orderedIds: siblingsAfter, parentId: first.parentId, stack: first.stack },+ { kind: 'sibling-order', orderedIds: movedIds, parentId: command.groupId, stack: first.stack },+ { id: command.groupId, kind: 'selection' },+ ],+ selectionAfter: command.groupId,+ touchedIds: [command.groupId, ...movedIds],+ touchedStacks: [first.stack],+ }+ );+ };++ const prepareUngroup = (command: Extract<DocumentCommand, { type: 'ungroup' }>): PrepareEditResult => {+ const ids = unique(command.ids);+ if (ids.length === 0) {+ return { operation: 'ungroup nothing', status: 'unsupported' };+ }+ const found = lookup(ids);+ if ('status' in found) {+ return found;+ }+ const notGroup = found.entries.find((entry) => !isGroupNode(entry.node));+ if (notGroup) {+ return { actual: notGroup.node.type, expected: ['group'], status: 'wrong-type' };+ }+ const named = new Set(ids);+ const groups = index.nodes.filter((entry) => named.has(entry.node.id));+ const locked = unique(groups.flatMap((entry) => frozenBy(index, entry)));+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ const forward: CanvasNodeMove[] = [];+ const inverseAdd: CanvasNodeInsertion[] = [];+ const inverseMove: CanvasNodeMove[] = [];+ const postconditions: EditPostcondition[] = [];+ const touchedIds: string[] = [];+ let expected = stacks;+ const dissolved = new Set(groups.map((entry) => entry.node.id));+ for (const entry of groups) {+ const group = entry.node as CanvasGroupContract;+ const childIds = group.children.map((child) => child.id);+ const siblings = childrenAt(index, entry.stack, entry.parentId) ?? [];+ const base = {+ capturedEditRevision: context.editRevision,+ parentPath: entry.path,+ projectId: context.projectId,+ stack: entry.stack,+ };+ forward.push({+ anchor: { ...base, afterId: siblings[entry.siblingIndex - 1]?.id ?? null, beforeId: group.id },+ ids: childIds,+ });+ inverseAdd.push({+ anchor: {+ ...base,+ afterId: siblings[entry.siblingIndex - 1]?.id ?? null,+ beforeId: siblings[entry.siblingIndex + 1]?.id ?? null,+ },+ nodes: [{ ...group, children: [] }],+ });+ inverseMove.push({+ anchor: { ...base, afterId: null, beforeId: null, parentPath: [...entry.path, group.id] },+ ids: childIds,+ });+ touchedIds.push(group.id, ...childIds);+ expected = {+ ...expected,+ [entry.stack]: dissolve(expected[entry.stack], dissolved),+ };+ }+ for (const key of unique(+ groups+ .filter((entry) => entry.parentId === null || !dissolved.has(entry.parentId))+ .map((entry) => `${entry.stack}\0${entry.parentId ?? ''}`)+ )) {+ const [stack, parentId] = key.split('\0') as [LayerStackKind, string];+ postconditions.push(siblingOrderAfter(expected, stack, parentId === '' ? null : parentId));+ }+ const selectionAfter =+ selectedLayerId !== null && dissolved.has(selectedLayerId)+ ? (collectSubtree(index.byId.get(selectedLayerId)!.node).find((node) => !dissolved.has(node.id))?.id ??+ repairSelectedLayerId(expected, selectedLayerId, stacks))+ : selectedLayerId;+ postconditions.push({ id: selectionAfter, kind: 'selection' });+ return prepared(+ structural({ move: forward, removeIds: groups.map((entry) => entry.node.id), selectedLayerId: selectionAfter }),+ structural({ add: inverseAdd, move: inverseMove, selectedLayerId }),+ {+ postconditions,+ selectionAfter,+ touchedIds,+ touchedStacks: stacksTopFirst(groups.map((entry) => entry.stack)),+ }+ );+ };++ const preparePatch = (command: Extract<DocumentCommand, { type: 'patch' }>): PrepareEditResult => {+ const entry = index.byId.get(command.id);+ if (!entry) {+ return missing([command.id]);+ }+ if (Object.keys(command.patch).length === 0) {+ return { operation: 'patch nothing', status: 'unsupported' };+ }+ if (isGroupNode(entry.node)) {+ const unsupported = (Object.keys(command.patch) as (keyof CanvasLayerBasePatch)[]).find(+ (key) => !GROUP_PATCH_KEYS.includes(key)+ );+ if (unsupported) {+ return {+ actual: 'group',+ expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask'],+ status: 'wrong-type',+ };+ }+ }+ if (command.before && !sameKeys(command.before, command.patch, PATCH_CONTAINERS)) {+ return { operation: 'patch baseline names other fields', status: 'unsupported' };+ }+ if ((Object.keys(command.patch) as (keyof CanvasLayerBasePatch)[]).some((key) => !GROUP_PATCH_KEYS.includes(key))) {+ const locked = frozenBy(index, entry);+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ }+ const inverse = command.before ?? patchInverse(entry.node, command.patch);+ if (command.before ? sameValue(command.before, command.patch) : isPatchApplied(entry.node, command.patch)) {+ return { status: 'unchanged' };+ }+ return prepared(+ { id: command.id, patch: command.patch, type: 'updateCanvasLayer' },+ { id: command.id, patch: inverse, type: 'updateCanvasLayer' },+ {+ postconditions: [{ id: command.id, kind: 'patched', patch: command.patch }],+ selectionAfter: selectedLayerId,+ touchedIds: [command.id],+ touchedStacks: [entry.stack],+ }+ );+ };++ const configInverse = (layer: CanvasLayerContract, config: CanvasLayerConfigPatch): CanvasLayerConfigPatch => {+ const current = layer as unknown as Record<string, unknown>;+ const inverse: Record<string, unknown> = { layerType: config.layerType };+ for (const [key, value] of Object.entries(config)) {+ if (key === 'layerType') {+ continue;+ }+ const before = current[key];+ inverse[key] =+ (key === 'adapter' || key === 'mask') &&+ typeof value === 'object' &&+ value !== null &&+ typeof before === 'object'+ ? Object.fromEntries(Object.keys(value).map((field) => [field, (before as Record<string, unknown>)[field]]))+ : before;+ }+ return inverse as CanvasLayerConfigPatch;+ };++ /** The unlocked leaf `id` names; content edits are refused inside a locked subtree. */+ const editableLeaf = (id: string): { entry: CanvasNodeEntry; layer: CanvasLayerContract } | DocumentRefusal => {+ const entry = index.byId.get(id);+ if (!entry) {+ return missing([id]);+ }+ if (isGroupNode(entry.node)) {+ return {+ actual: 'group',+ expected: ['raster', 'control', 'regional_guidance', 'inpaint_mask'],+ status: 'wrong-type',+ };+ }+ const locked = frozenBy(index, entry);+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ return { entry, layer: entry.node };+ };++ const preparePatchConfig = (command: Extract<DocumentCommand, { type: 'patch-config' }>): PrepareEditResult => {+ const found = editableLeaf(command.id);+ if ('status' in found) {+ return found;+ }+ const { entry, layer } = found;+ if (layer.type !== command.config.layerType) {+ return { actual: layer.type, expected: [command.config.layerType], status: 'wrong-type' };+ }+ if (Object.keys(command.config).length <= 1) {+ return { operation: 'patch nothing', status: 'unsupported' };+ }+ if (command.before && command.before.layerType !== command.config.layerType) {+ return { operation: 'config baseline names another layer type', status: 'unsupported' };+ }+ if (command.before && !sameKeys(command.before, command.config, CONFIG_CONTAINERS)) {+ return { operation: 'config baseline names other fields', status: 'unsupported' };+ }+ if (command.before ? sameValue(command.before, command.config) : isConfigApplied(layer, command.config)) {+ return { status: 'unchanged' };+ }+ return prepared(+ { config: command.config, id: command.id, type: 'updateCanvasLayerConfig' },+ {+ config: command.before ?? configInverse(layer, command.config),+ id: command.id,+ type: 'updateCanvasLayerConfig',+ },+ {+ postconditions: [{ config: command.config, id: command.id, kind: 'config' }],+ selectionAfter: selectedLayerId,+ touchedIds: [command.id],+ touchedStacks: [entry.stack],+ }+ );+ };++ const preparePatchSource = (command: Extract<DocumentCommand, { type: 'patch-source' }>): PrepareEditResult => {+ const found = editableLeaf(command.id);+ if ('status' in found) {+ return found;+ }+ const { entry, layer } = found;+ if (layer.type !== 'raster' && layer.type !== 'control') {+ return { actual: layer.type, expected: ['raster', 'control'], status: 'wrong-type' };+ }+ if (layer.source === command.source) {+ return { status: 'unchanged' };+ }+ return prepared(+ { id: command.id, source: command.source, type: 'updateCanvasLayerSource' },+ { id: command.id, source: layer.source, type: 'updateCanvasLayerSource' },+ {+ postconditions: [{ id: command.id, kind: 'source', source: command.source }],+ selectionAfter: selectedLayerId,+ touchedIds: [command.id],+ touchedStacks: [entry.stack],+ }+ );+ };++ const prepareFlags = (+ command: Extract<DocumentCommand, { type: 'set-enabled' | 'set-hidden' | 'set-locked' }>+ ): PrepareEditResult => {+ const ids = unique(command.updates.map((update) => update.id));+ if (ids.length === 0) {+ return { operation: `${command.type} nothing`, status: 'unsupported' };+ }+ const found = lookup(ids);+ if ('status' in found) {+ return found;+ }+ if (command.type === 'set-hidden') {+ const notHideable = found.entries.find((entry) =>+ isGroupNode(entry.node) ? !isOverlayStack(entry.stack) : !isHideableLayer(entry.node)+ );+ if (notHideable) {+ return {+ actual: notHideable.node.type,+ expected: ['control', 'inpaint_mask', 'regional_guidance'],+ status: 'wrong-type',+ };+ }+ }+ const detail = (updated: readonly { id: string }[]) => ({+ selectionAfter: selectedLayerId,+ touchedIds: updated.map((update) => update.id),+ touchedStacks: stacksTopFirst(updated.map((update) => index.byId.get(update.id)!.stack)),+ });+ switch (command.type) {+ case 'set-enabled': {+ const updates = command.updates.filter(+ (update) => index.byId.get(update.id)!.node.isEnabled !== update.isEnabled+ );+ if (updates.length === 0) {+ return { status: 'unchanged' };+ }+ return prepared(+ { type: 'setCanvasLayersEnabled', updates },+ {+ type: 'setCanvasLayersEnabled',+ updates: updates.map((update) => ({ id: update.id, isEnabled: index.byId.get(update.id)!.node.isEnabled })),+ },+ {+ ...detail(updates),+ postconditions: updates.map((update) => ({+ id: update.id,+ kind: 'patched',+ patch: { isEnabled: update.isEnabled },+ })),+ }+ );+ }+ case 'set-hidden': {+ const updates = command.updates.filter(+ (update) => isNodeHidden(index.byId.get(update.id)!.node) !== update.isHidden+ );+ if (updates.length === 0) {+ return { status: 'unchanged' };+ }+ return prepared(+ { type: 'setCanvasLayersHidden', updates },+ {+ type: 'setCanvasLayersHidden',+ updates: updates.map((update) => ({+ id: update.id,+ isHidden: isNodeHidden(index.byId.get(update.id)!.node),+ })),+ },+ {+ ...detail(updates),+ postconditions: updates.map((update) => ({ id: update.id, isHidden: update.isHidden, kind: 'hidden' })),+ }+ );+ }+ case 'set-locked': {+ const updates = command.updates.filter(+ (update) => index.byId.get(update.id)!.node.isLocked !== update.isLocked+ );+ if (updates.length === 0) {+ return { status: 'unchanged' };+ }+ return prepared(+ structural({ lockedUpdates: updates }),+ structural({+ lockedUpdates: updates.map((update) => ({+ id: update.id,+ isLocked: index.byId.get(update.id)!.node.isLocked,+ })),+ }),+ {+ ...detail(updates),+ postconditions: updates.map((update) => ({+ id: update.id,+ kind: 'patched',+ patch: { isLocked: update.isLocked },+ })),+ }+ );+ }+ }+ };++ const prepareTranslate = (command: Extract<DocumentCommand, { type: 'translate' }>): PrepareEditResult => {+ const ids = unique(command.ids);+ if (ids.length === 0) {+ return { operation: 'translate nothing', status: 'unsupported' };+ }+ if (!Number.isFinite(command.dx) || !Number.isFinite(command.dy)) {+ return { operation: 'translate by a non-finite delta', status: 'unsupported' };+ }+ const found = lookup(ids);+ if ('status' in found) {+ return found;+ }+ const outer = outermostNodes(index, ids);+ const locked = unique(outer.flatMap((entry) => lockedWithin(index, entry)));+ if (locked.length > 0) {+ return { ids: locked, status: 'locked' };+ }+ const leaves = outer.flatMap((entry) => collectSubtreeLeaves(entry.node));+ if (leaves.length === 0 || (command.dx === 0 && command.dy === 0)) {+ return { status: 'unchanged' };+ }+ const next = leaves.map((leaf) => ({+ id: leaf.id,+ x: leaf.transform.x + command.dx,+ y: leaf.transform.y + command.dy,+ }));+ return prepared(+ { type: 'setCanvasLayerPositions', updates: next },+ {+ type: 'setCanvasLayerPositions',+ updates: leaves.map((leaf) => ({ id: leaf.id, x: leaf.transform.x, y: leaf.transform.y })),+ },+ {+ postconditions: next.map((update) => ({+ id: update.id,+ kind: 'patched',+ patch: { transform: { x: update.x, y: update.y } },+ })),+ selectionAfter: selectedLayerId,+ touchedIds: leaves.map((leaf) => leaf.id),+ touchedStacks: stacksTopFirst(outer.map((entry) => entry.stack)),+ }+ );+ };++ const prepareSelect = (command: Extract<DocumentCommand, { type: 'select' }>): PrepareEditResult => {+ if (command.id !== null && !index.byId.has(command.id)) {+ return missing([command.id]);+ }+ if (command.id === selectedLayerId) {+ return { status: 'unchanged' };+ }+ return prepared(+ { id: command.id, type: 'setCanvasSelectedLayer' },+ { id: selectedLayerId, type: 'setCanvasSelectedLayer' },+ {+ history: 'none',+ postconditions: [{ id: command.id, kind: 'selection' }],+ selectionAfter: command.id,+ touchedIds: [],+ touchedStacks: [],+ }+ );+ };++ return {+ canMergeDown: (upperId) => mergeDownEligibility(document, upperId),+ compileLeaves: () => compileLeaves(index),+ document,+ getEntry: (id) => index.byId.get(id) ?? null,+ getLayer: (id) => {+ const node = index.byId.get(id)?.node;+ return node && !isGroupNode(node) ? node : null;+ },+ getNode: (id) => index.byId.get(id)?.node ?? null,+ getStack: (kind) => stacks[kind],+ prepare: (command) => {+ switch (command.type) {+ case 'insert':+ return prepareInsert(command);+ case 'remove':+ return prepareRemove(command);+ case 'duplicate':+ return prepareDuplicate(command);+ case 'move':+ return prepareMove(command);+ case 'reorder':+ return prepareReorder(command.orders);+ case 'reparent':+ return prepareReparent(command);+ case 'group':+ return prepareGroup(command);+ case 'ungroup':+ return prepareUngroup(command);+ case 'patch':+ return preparePatch(command);+ case 'patch-config':+ return preparePatchConfig(command);+ case 'patch-source':+ return preparePatchSource(command);+ case 'set-enabled':+ case 'set-hidden':+ case 'set-locked':+ return prepareFlags(command);+ case 'translate':+ return prepareTranslate(command);+ case 'select':+ return prepareSelect(command);+ }+ },+ };+};++const stripRemoved = (node: CanvasNodeContract, removed: ReadonlySet<string>): CanvasNodeContract =>+ isGroupNode(node)+ ? {+ ...node,+ children: node.children.filter((child) => !removed.has(child.id)).map((child) => stripRemoved(child, removed)),+ }+ : node;++/** Replaces each dissolved group with its children, in place. */+const dissolve = (nodes: readonly CanvasNodeContract[], dissolved: ReadonlySet<string>): CanvasNodeContract[] =>+ nodes.flatMap((node) => {+ if (!isGroupNode(node)) {+ return [node];+ }+ const children = dissolve(node.children, dissolved);+ return dissolved.has(node.id) ? children : [{ ...node, children }];+ });++export { stackOf as documentStackOf };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.tsdeleted file mode 100644index 8ecee6863e..0000000000--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.budget.test.ts+++ /dev/null@@ -1,162 +0,0 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';--import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { createInitialWorkbenchState } from '@workbench/workbenchState';-import { beforeEach, describe, expect, it } from 'vitest';--import type { FlatDocumentCommand, PreparedFlatEdit } from './flatDocumentCommands';--import { createLargeFlatDocument } from './documentFixtures.testStub';-import {- compileDocumentLeaves,- createFlatDocumentModel,- getFlatDocumentModelDiagnostics,- resetFlatDocumentModelDiagnostics,-} from './flatDocumentModel';-import { ALL_OVERLAY_STACKS_SHOWN, planScreenComposition } from './screenComposition';--const LAYER_COUNT = 2_000;-const context = { editRevision: 0, projectId: 'budget' };--const resetCounters = (): void => {- resetFlatDocumentModelDiagnostics();-};--/** Runs the reducer over a fixture so the next document is the one production consumers see. */-const reduce = (document: CanvasDocumentContractV2, command: FlatDocumentCommand) => {- const initial = createInitialWorkbenchState().projects[0]!;- const project = applyCanvasProjectMutation(initial, {- document,- type: 'replaceCanvasDocument',- });- const accepted = project.canvas.document;- const model = createFlatDocumentModel(accepted, context);- const result = model.prepare(command);- if (result.status !== 'prepared') {- throw new Error(`expected a prepared edit, got ${result.status}`);- }- return { edit: result.edit, model, next: applyCanvasProjectMutation(project, result.edit.forward).canvas.document };-};--type Annotate = (message: string) => unknown;--/** Timing is informational: it is annotated on the test, never asserted. */-const timed = <T>(annotate: Annotate, label: string, run: () => T): T => {- const start = performance.now();- const value = run();- annotate(`${label}: ${(performance.now() - start).toFixed(2)}ms`);- return value;-};--describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {- beforeEach(() => {- resetCounters();- });-- it('builds one index per layer array and none for selection-only changes', ({ annotate }) => {- const project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {- document: createLargeFlatDocument(LAYER_COUNT),- type: 'replaceCanvasDocument',- });- const document = project.canvas.document;- const model = timed(annotate, 'model construction', () => createFlatDocumentModel(document, context));- createFlatDocumentModel(document, context);- model.getLayer('l1999');- model.getStack('control');- expect(model.prepare({ id: 'l7', type: 'select' }).status).toBe('prepared');- expect(model.prepare({ id: 'l0', type: 'select' })).toEqual({ status: 'unchanged' });- const leaves = compileDocumentLeaves(document);-- const reselected = applyCanvasProjectMutation(project, { id: 'l7', type: 'setCanvasSelectedLayer' }).canvas- .document;- expect(reselected).not.toBe(document);- expect(reselected.selectedLayerId).toBe('l7');- expect(createFlatDocumentModel(reselected, context).compileLeaves()).toBe(leaves);- expect(compileDocumentLeaves(reselected)).toBe(leaves);- expect(getFlatDocumentModelDiagnostics()).toMatchObject({ indexBuilds: 1, leafCompilations: 1 });- });-- it('compiles leaves once per document and plans the screen from them', ({ annotate }) => {- const document = createLargeFlatDocument(LAYER_COUNT);- const leaves = timed(annotate, 'leaf compilation', () => compileDocumentLeaves(document));- expect(compileDocumentLeaves(document)).toBe(leaves);- expect(createFlatDocumentModel(document, context).compileLeaves()).toBe(leaves);- expect(getFlatDocumentModelDiagnostics()).toMatchObject({- leafCompilations: 1,- leavesCompiled: LAYER_COUNT,- });-- const plan = timed(annotate, 'screen plan', () =>- planScreenComposition(leaves, { isolationLayerId: null, showOverlayStacks: ALL_OVERLAY_STACKS_SHOWN })- );- expect(plan.leaves).toHaveLength(LAYER_COUNT);- expect(plan.leaves.at(-1)?.stack).toBe('inpaint_mask');- });-- it('recompiles only the patched leaf after a reducer edit', ({ annotate }) => {- const { model, next } = reduce(createLargeFlatDocument(LAYER_COUNT), {- id: 'l5',- patch: { opacity: 0.5 },- type: 'patch',- });- const before = model.compileLeaves();- resetCounters();- 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]);- expect(leaf.layer.opacity).toBe(0.5);- } else {- expect(leaf).toBe(before[index]);- }- });- });-- it('reuses immutable layer leaves without a previous-document argument', () => {- const { model, next } = reduce(createLargeFlatDocument(LAYER_COUNT), {- id: 'l5',- patch: { name: 'x' },- type: 'patch',- });- const before = compileDocumentLeaves(model.document);- resetCounters();- const after = compileDocumentLeaves(next);- expect(getFlatDocumentModelDiagnostics().leavesCompiled).toBe(1);- expect(after[6]).toBe(before[6]);- });-- it('preserves every leaf identity when only stack order changes', () => {- const { model, next } = reduce(createLargeFlatDocument(LAYER_COUNT), { ids: ['l0'], kind: 'back', type: 'move' });- const before = model.compileLeaves();- resetCounters();- 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 }]>([- ['select', { id: 'l9', type: 'select' }, { ids: 0, stacks: 0 }],- ['lock', { type: 'set-locked', updates: [{ id: 'l1', isLocked: true }] }, { ids: 1, stacks: 1 }],- [- 'enable',- {- type: 'set-enabled',- updates: Array.from({ length: 10 }, (_, index) => ({ id: `l${index}`, isEnabled: false })),- },- { ids: 10, stacks: 4 },- ],- ['hide', { type: 'set-hidden', updates: [{ id: 'l1', isHidden: true }] }, { ids: 1, stacks: 1 }],- ['move', { ids: ['l8', 'l12', 'l16'], kind: 'forward', type: 'move' }, { ids: 4, stacks: 1 }],- ['remove', { ids: ['l1', 'l2'], type: 'remove' }, { ids: 2, stacks: 2 }],- ])('prepares a %s edit with exact touched ids and stacks', (_label, command, expected) => {- const model = createFlatDocumentModel(createLargeFlatDocument(LAYER_COUNT), context);- const result = model.prepare(command);- expect(result.status).toBe('prepared');- const edit = (result as { edit: PreparedFlatEdit }).edit;- expect(edit.touchedIds).toHaveLength(expected.ids);- expect(edit.touchedStacks).toHaveLength(expected.stacks);- 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.tsdeleted file mode 100644index 51c7fbd0da..0000000000--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts+++ /dev/null@@ -1,703 +0,0 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { Project } from '@workbench/projectContracts';--import { isHideableLayer } from '@workbench/canvas-engine/document/layerEligibility';-import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';-import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';-import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { createInitialWorkbenchState } from '@workbench/workbenchState';-import { describe, expect, it } from 'vitest';--import type { FlatDocumentCommand, PreparedFlatEdit, PrepareFlatEditResult } from './flatDocumentCommands';--import { layerContract } from './documentFixtures.testStub';-import {- compileDocumentLeaves,- createFlatDocumentModel,- getFlatDocumentModelDiagnostics,- lookupDocumentLayer,- lookupDocumentLeaf,- lookupLayerBelow,- mergeDownEligibility,-} from './flatDocumentModel';-import { checkFlatEditPostconditions } from './postconditions';--const layer = layerContract;--const interleaved = (): CanvasLayerContract[] => [- layer('i1', 'inpaint_mask'),- layer('r1'),- layer('c1', 'control'),- layer('r2'),- layer('g1', 'regional_guidance'),- layer('r3'),-];--const projectWith = (layers: CanvasLayerContract[], selectedLayerId: string | null): Project => {- const initial = createInitialWorkbenchState().projects[0]!;- const project = applyCanvasProjectMutation(initial, {- document: { ...createEmptyCanvasDocumentV2(), layers, selectedLayerId },- type: 'replaceCanvasDocument',- });- if (ids(project.canvas.document).join() !== layers.map((entry) => entry.id).join()) {- throw new Error('fixture document was not accepted by the reducer');- }- return project;-};--const context = (project: Project) => ({ editRevision: 0, projectId: project.id });-const modelOf = (project: Project) => createFlatDocumentModel(project.canvas.document, context(project));--const ids = (document: CanvasDocumentContractV2): string[] => document.layers.map((entry) => entry.id);-const byId = (left: CanvasLayerContract, right: CanvasLayerContract): number => left.id.localeCompare(right.id);-/** The reducer writes an explicit `isHidden: false` on undo where the original layer had no key. */-const withExplicitHidden = (layer: CanvasLayerContract): CanvasLayerContract =>- isHideableLayer(layer) ? { ...layer, isHidden: layer.isHidden === true } : layer;--const roundTrip = (project: Project, command: FlatDocumentCommand): { after: Project; edit: PreparedFlatEdit } => {- const result = modelOf(project).prepare(command);- if (result.status !== 'prepared') {- throw new Error(`expected a prepared edit, got ${JSON.stringify(result)}`);- }- const after = applyCanvasProjectMutation(project, result.edit.forward);- expect(after.canvas.document).not.toBe(project.canvas.document);- expect(checkFlatEditPostconditions(after.canvas.document, result.edit.postconditions)).toBe(true);- expect(after.canvas.document.selectedLayerId).toBe(result.edit.selectionAfter);- const restored = applyCanvasProjectMutation(after, result.edit.inverse).canvas.document;- const original = project.canvas.document;- expect(haveSameStackOrders(restored.layers, original.layers)).toBe(true);- expect([...restored.layers].sort(byId).map(withExplicitHidden)).toEqual(- [...original.layers].sort(byId).map(withExplicitHidden)- );- expect({ ...restored, layers: [] }).toEqual({ ...original, layers: [] });- return { after, edit: result.edit };-};--describe('createFlatDocumentModel', () => {- it('indexes lookup and stack order once per document identity', () => {- const project = projectWith(interleaved(), 'r2');- const before = getFlatDocumentModelDiagnostics().indexBuilds;- const model = modelOf(project);- const again = modelOf(project);-- 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 in document order with world transforms', () => {- const project = projectWith(- [- layer('i1', 'inpaint_mask', { isHidden: true } as Partial<CanvasLayerContract>),- layer('r1', 'raster', { isLocked: true }),- ],- 'r1'- );- const leaves = modelOf(project).compileLeaves();-- 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 });- expect(leaves[1]!.worldTransform).toEqual({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });- });-- it('keeps leaf identity for unaffected layers across an edit and reuses leaves for a selection-only change', () => {- const project = projectWith(interleaved(), 'r2');- const first = modelOf(project);- const leaves = first.compileLeaves();- const beforeDiagnostics = getFlatDocumentModelDiagnostics();-- const selected = applyCanvasProjectMutation(project, { id: 'r1', type: 'setCanvasSelectedLayer' });- const second = createFlatDocumentModel(selected.canvas.document, context(project));- expect(second.compileLeaves()).toBe(leaves);- 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));- const next = third.compileLeaves();- 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',- 'c1',- 'g1',- 'r3',- ]);- expect(next[3]!.layer.name).toBe('Renamed');-- const moved = applyCanvasProjectMutation(renamed, {- stacks: [{ orderedIds: ['r3', 'r1', 'r2'], stack: 'raster' }],- type: 'reorderCanvasLayerStacks',- });- const fourth = createFlatDocumentModel(moved.canvas.document, context(project)).compileLeaves();- expect(fourth.every((leaf) => next.includes(leaf))).toBe(true);- });-- describe('prepare', () => {- it('inserts above the compatible leaf and restores the previous selection on undo', () => {- const project = projectWith(interleaved(), 'r2');- const { after, edit } = roundTrip(project, { aboveId: 'r2', layers: [layer('n1')], type: 'insert' });-- expect(ids(after.canvas.document)).toEqual(['i1', 'r1', 'c1', 'n1', 'r2', 'g1', 'r3']);- expect(edit).toMatchObject({- history: 'record',- postconditions: [- { kind: 'stack-order', orderedIds: ['r1', 'n1', 'r2', 'r3'], stack: 'raster' },- { id: 'n1', kind: 'selection' },- ],- selectionAfter: 'n1',- touchedIds: ['n1'],- touchedStacks: ['raster'],- });- });-- it('inserts a foreign-stack layer at its stack top and honours an explicit selection', () => {- const project = projectWith(interleaved(), 'r2');- const { after } = roundTrip(project, {- aboveId: 'r2',- layers: [layer('m2', 'inpaint_mask')],- selectId: null,- type: 'insert',- });-- expect(ids(after.canvas.document)).toEqual(['m2', 'i1', 'r1', 'c1', 'r2', 'g1', 'r3']);- expect(after.canvas.document.selectedLayerId).toBeNull();- });-- it('keeps the given order for several layers whether or not their stacks are empty', () => {- const populated = roundTrip(projectWith(interleaved(), 'r1'), {- aboveId: null,- layers: [layer('a'), layer('b'), layer('m', 'inpaint_mask')],- type: 'insert',- });- expect(ids(populated.after.canvas.document)).toEqual(['m', 'i1', 'a', 'b', 'r1', 'c1', 'r2', 'g1', 'r3']);- expect(populated.edit.touchedStacks).toEqual(['inpaint_mask', 'raster']);-- const empty = roundTrip(projectWith([layer('c1', 'control')], 'c1'), {- aboveId: null,- layers: [layer('a'), layer('b')],- type: 'insert',- });- expect(ids(empty.after.canvas.document)).toEqual(['a', 'b', 'c1']);- });-- it('removes layers, repairs the selection within the stack, and restores them between their neighbours', () => {- const project = projectWith(interleaved(), 'r2');- const { after, edit } = roundTrip(project, { ids: ['r2', 'i1'], type: 'remove' });-- expect(ids(after.canvas.document)).toEqual(['r1', 'c1', 'g1', 'r3']);- expect(edit).toMatchObject({- selectionAfter: 'r3',- touchedIds: ['r2', 'i1'],- touchedStacks: ['inpaint_mask', 'raster'],- });- });-- it('falls back to another stack when the removed primary had no stack neighbour left', () => {- const project = projectWith(- [layer('c1', 'control'), layer('r1'), layer('r2'), layer('g1', 'regional_guidance')],- 'r2'- );- const { edit } = roundTrip(project, { ids: ['r1', 'r2'], type: 'remove' });- expect(edit.selectionAfter).toBe('g1');- });-- it('duplicates above the source and removes the copy on undo', () => {- const project = projectWith(interleaved(), 'r1');- const { after, edit } = roundTrip(project, { newId: 'r2-copy', sourceId: 'r2', type: 'duplicate' });-- expect(ids(after.canvas.document)).toEqual(['i1', 'r1', 'c1', 'r2-copy', 'r2', 'g1', 'r3']);- expect(after.canvas.document.selectedLayerId).toBe('r2-copy');- expect(edit.postconditions[0]).toEqual({- kind: 'stack-order',- orderedIds: ['r1', 'r2-copy', 'r2', 'r3'],- stack: 'raster',- });- });-- it('moves within stacks and reorders several stacks at once', () => {- const project = projectWith(interleaved(), 'r3');- const moved = roundTrip(project, { ids: ['r3'], kind: 'front', type: 'move' });- expect(ids(moved.after.canvas.document)).toEqual(['i1', 'r3', 'c1', 'r1', 'g1', 'r2']);- expect(moved.edit.touchedIds).toEqual(['r3', 'r1', 'r2']);-- const reordered = roundTrip(project, {- stacks: [- { orderedIds: ['r2', 'r1', 'r3'], stack: 'raster' },- { orderedIds: ['c1'], stack: 'control' },- ],- type: 'reorder',- });- expect(ids(reordered.after.canvas.document)).toEqual(['i1', 'r2', 'c1', 'r1', 'g1', 'r3']);- expect(reordered.edit).toMatchObject({ touchedIds: ['r2', 'r1'], touchedStacks: ['control', 'raster'] });- });-- it('patches base fields and transforms with an exact inverse', () => {- const project = projectWith(interleaved(), 'r1');- const { after, edit } = roundTrip(project, {- id: 'r1',- patch: { name: 'Renamed', opacity: 0.5, transform: { x: 12 } },- type: 'patch',- });-- expect(after.canvas.document.layers[1]).toMatchObject({- name: 'Renamed',- opacity: 0.5,- transform: { x: 12, y: 0 },- });- expect(edit.inverse).toEqual({- id: 'r1',- patch: { name: 'r1', opacity: 1, transform: { x: 0 } },- type: 'updateCanvasLayer',- });- expect(edit.postconditions).toEqual([- { id: 'r1', kind: 'patched', patch: { name: 'Renamed', opacity: 0.5, transform: { x: 12 } } },- ]);- });-- it('patches locked or disabled layers like the current inputs do and reports a same-value patch as unchanged', () => {- const project = projectWith([layer('locked', 'raster', { isEnabled: false, isLocked: true })], 'locked');- const model = modelOf(project);- expect(model.prepare({ id: 'locked', patch: { name: 'x', opacity: 0.2 }, type: 'patch' }).status).toBe(- 'prepared'- );- expect(model.prepare({ id: 'locked', patch: { isEnabled: true, isLocked: false }, type: 'patch' }).status).toBe(- 'prepared'- );- expect(model.prepare({ id: 'locked', patch: { transform: { x: 1 } }, type: 'patch' }).status).toBe('prepared');- expect(model.prepare({ id: 'locked', patch: { name: 'locked', transform: { x: 0 } }, type: 'patch' })).toEqual({- status: 'unchanged',- });- });-- it('takes a pre-gesture baseline so a previewed patch still records a real inverse', () => {- const previewed = applyCanvasProjectMutation(projectWith(interleaved(), 'r1'), {- id: 'r1',- patch: { opacity: 0.4 },- type: 'updateCanvasLayer',- });- const model = modelOf(previewed);- expect(model.prepare({ id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })).toEqual({ status: 'unchanged' });-- const result = model.prepare({ before: { opacity: 1 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' });- expect(result).toMatchObject({- edit: { inverse: { id: 'r1', patch: { opacity: 1 }, type: 'updateCanvasLayer' } },- status: 'prepared',- });- expect(model.prepare({ before: { opacity: 0.4 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })).toEqual({- status: 'unchanged',- });- expect(- model.prepare({ before: { name: 'r1', opacity: 1 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })- ).toEqual({ operation: 'patch baseline names other fields', status: 'unsupported' });- expect(- model.prepare({- before: { adjustments: { brightness: 0, contrast: 0, saturation: 0 }, layerType: 'raster' },- config: {- adjustments: { brightness: 0.2, contrast: 0, curves: { b: [], g: [], r: [[0, 0]] }, saturation: 0 },- layerType: 'raster',- },- id: 'r1',- type: 'patch-config',- }).status- ).toBe('prepared');- expect(- model.prepare({- before: { layerType: 'inpaint_mask', mask: { fill: { color: '#000000', style: 'solid' } } },- config: { layerType: 'inpaint_mask', mask: { offset: { x: 4, y: 4 } } },- id: 'i1',- type: 'patch-config',- })- ).toEqual({ operation: 'config baseline names other fields', status: 'unsupported' });- expect(- model.prepare({- before: { transform: { x: 0 } },- id: 'r1',- patch: { transform: { x: 1, y: 2 } },- type: 'patch',- })- ).toEqual({ operation: 'patch baseline names other fields', status: 'unsupported' });- expect(- model.prepare({- before: { adapter: { weight: 1 }, layerType: 'control' },- config: { adapter: { model: null, weight: 1 }, layerType: 'control' },- id: 'c1',- type: 'patch-config',- })- ).toEqual({ operation: 'config baseline names other fields', status: 'unsupported' });- expect(- model.prepare({- before: { adapter: undefined, layerType: 'control' },- config: { adapter: { weight: 1 }, layerType: 'control' },- id: 'c1',- type: 'patch-config',- })- ).toEqual({ operation: 'config baseline names other fields', status: 'unsupported' });- expect(- model.prepare({- before: { layerType: 'inpaint_mask', mask: { fill: { color: '#000000' } as never } },- config: { layerType: 'inpaint_mask', mask: { fill: { color: '#000000', style: 'solid' } } },- id: 'i1',- type: 'patch-config',- })- ).toEqual({ operation: 'config baseline names other fields', status: 'unsupported' });- expect(- model.prepare({- before: { isTransparencyLocked: false, layerType: 'control' } as never,- config: { isTransparencyLocked: true, layerType: 'raster' },- id: 'r1',- type: 'patch-config',- })- ).toEqual({ operation: 'config baseline names another layer type', status: 'unsupported' });- const defaults = {- beginEndStepPct: [0, 1] as [number, number],- controlMode: null,- kind: 't2i_adapter' as const,- model: null,- weight: 0.5,- };- const baseline = {- beginEndStepPct: [0, 1] as [number, number],- controlMode: 'balanced' as const,- kind: 'controlnet' as const,- model: null,- weight: 1,- };- expect(- model.prepare({- before: { adapter: baseline, layerType: 'control' },- config: { adapter: defaults, layerType: 'control' },- id: 'c1',- type: 'patch-config',- })- ).toMatchObject({- edit: { inverse: { config: { adapter: baseline, layerType: 'control' } } },- status: 'prepared',- });- expect(- modelOf(projectWith(interleaved(), 'r1')).prepare({- before: { opacity: 1 },- id: 'r1',- patch: { opacity: 0.4 },- type: 'patch',- }).status- ).toBe('prepared');-- const fillBefore = { color: '#e07575', style: 'diagonal' as const };- const fillNext = { color: '#00ff00', style: 'diagonal' as const };- const previewedFill = applyCanvasProjectMutation(projectWith(interleaved(), 'i1'), {- config: { layerType: 'inpaint_mask', mask: { fill: fillNext } },- id: 'i1',- type: 'updateCanvasLayerConfig',- });- const fill = modelOf(previewedFill).prepare({- before: { layerType: 'inpaint_mask', mask: { fill: fillBefore } },- config: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },- id: 'i1',- type: 'patch-config',- });- expect(fill).toMatchObject({- edit: { inverse: { config: { layerType: 'inpaint_mask', mask: { fill: fillBefore } }, id: 'i1' } },- status: 'prepared',- });- expect(- modelOf(previewedFill).prepare({- before: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },- config: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },- id: 'i1',- type: 'patch-config',- })- ).toEqual({ status: 'unchanged' });- expect(- modelOf(previewedFill).prepare({- config: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },- id: 'i1',- type: 'patch-config',- })- ).toEqual({ status: 'unchanged' });- });-- it('round-trips config, source and flag commands through the reducer', () => {- const project = projectWith(interleaved(), 'r1');- const control = roundTrip(project, {- config: { adapter: { weight: 0.5 }, layerType: 'control', withTransparencyEffect: true },- id: 'c1',- type: 'patch-config',- });- expect(control.after.canvas.document.layers[2]).toMatchObject({- adapter: { weight: 0.5 },- withTransparencyEffect: true,- });- expect(control.edit.inverse).toEqual({- config: { adapter: { weight: 1 }, layerType: 'control', withTransparencyEffect: false },- id: 'c1',- type: 'updateCanvasLayerConfig',- });-- const source = { bitmap: null, offset: { x: 3, y: 4 }, type: 'paint' as const };- const patched = roundTrip(project, { id: 'r2', source, type: 'patch-source' });- expect((patched.after.canvas.document.layers[3] as { source: unknown }).source).toBe(source);-- const enabled = roundTrip(project, {- type: 'set-enabled',- updates: [- { id: 'r1', isEnabled: false },- { id: 'c1', isEnabled: true },- ],- });- expect(enabled.edit).toMatchObject({ touchedIds: ['r1'], touchedStacks: ['raster'] });-- const hidden = roundTrip(project, { type: 'set-hidden', updates: [{ id: 'c1', isHidden: true }] });- expect(hidden.after.canvas.document.layers[2]).toMatchObject({ isHidden: true });-- const locked = roundTrip(project, { type: 'set-locked', updates: [{ id: 'g1', isLocked: true }] });- expect(locked.after.canvas.document.layers[4]).toMatchObject({ isLocked: true });- });-- it.each<[string, FlatDocumentCommand, PrepareFlatEditResult]>([- [- 'hiding a raster layer',- { type: 'set-hidden', updates: [{ id: 'r1', isHidden: true }] },- { actual: 'raster', expected: ['control', 'inpaint_mask', 'regional_guidance'], status: 'wrong-type' },- ],- [- 'a config patch for another layer type',- { config: { layerType: 'control', withTransparencyEffect: true }, id: 'r1', type: 'patch-config' },- { actual: 'raster', expected: ['control'], status: 'wrong-type' },- ],- [- 'a source patch on a mask',- { id: 'i1', source: { bitmap: null, type: 'paint' }, type: 'patch-source' },- { actual: 'inpaint_mask', expected: ['raster', 'control'], status: 'wrong-type' },- ],- [- 'an empty flag update',- { type: 'set-locked', updates: [] },- { operation: 'set-locked nothing', status: 'unsupported' },- ],- [- 'flags that already hold',- { type: 'set-enabled', updates: [{ id: 'r1', isEnabled: true }] },- { status: 'unchanged' },- ],- ])('answers %s', (_label, command, result) => {- expect(modelOf(projectWith(interleaved(), 'r1')).prepare(command)).toEqual(result);- });-- it('selects without recording history and reports the current selection as unchanged', () => {- const project = projectWith(interleaved(), 'r1');- const { edit } = roundTrip(project, { id: 'c1', type: 'select' });- expect(edit).toMatchObject({ history: 'none', selectionAfter: 'c1', selectionBefore: 'r1', touchedIds: [] });- expect(modelOf(project).prepare({ id: 'r1', type: 'select' })).toEqual({ status: 'unchanged' });- });-- it.each<[string, FlatDocumentCommand, PrepareFlatEditResult]>([- ['a move already at the boundary', { ids: ['r1'], kind: 'front', type: 'move' }, { status: 'unchanged' }],- [- 'a reorder that keeps the order',- { stacks: [{ orderedIds: ['r1', 'r2', 'r3'], stack: 'raster' }], type: 'reorder' },- { status: 'unchanged' },- ],- ])('reports %s as unchanged', (_label, command, result) => {- expect(modelOf(projectWith(interleaved(), 'r1')).prepare(command)).toEqual(result);- });-- it.each<[string, FlatDocumentCommand, PrepareFlatEditResult]>([- ['a missing removal', { ids: ['ghost', 'r1'], type: 'remove' }, { ids: ['ghost'], status: 'missing' }],- ['a locked removal', { ids: ['locked'], type: 'remove' }, { ids: ['locked'], status: 'locked' }],- ['an empty removal', { ids: [], type: 'remove' }, { operation: 'remove nothing', status: 'unsupported' }],- [- 'a clashing insert',- { aboveId: null, layers: [layer('r1')], type: 'insert' },- { reason: 'id-exists', status: 'invalid-target', targetId: 'r1' },- ],- [- 'an empty insert',- { aboveId: null, layers: [], type: 'insert' },- { operation: 'insert nothing', status: 'unsupported' },- ],- [- 'a missing duplicate source',- { newId: 'x', sourceId: 'ghost', type: 'duplicate' },- { ids: ['ghost'], status: 'missing' },- ],- [- 'a duplicate onto an existing id',- { newId: 'r1', sourceId: 'r2', type: 'duplicate' },- { reason: 'id-exists', status: 'invalid-target', targetId: 'r1' },- ],- ['an empty move', { ids: [], kind: 'front', type: 'move' }, { operation: 'move nothing', status: 'unsupported' }],- [- 'a reorder missing a member',- { stacks: [{ orderedIds: ['r1'], stack: 'raster' }], type: 'reorder' },- { reason: 'not-stack-members', status: 'invalid-target', targetId: 'r1' },- ],- [- 'a reorder naming a foreign id',- { stacks: [{ orderedIds: ['r1', 'r2', 'c1'], stack: 'raster' }], type: 'reorder' },- { reason: 'foreign-stack', status: 'invalid-target', targetId: 'c1' },- ],- [- 'a reorder naming an unknown id',- { stacks: [{ orderedIds: ['r1', 'r2', 'ghost'], stack: 'raster' }], type: 'reorder' },- { ids: ['ghost'], status: 'missing' },- ],- [- 'a reorder of one stack twice',- {- stacks: [- { orderedIds: ['r2', 'r1', 'r3'], stack: 'raster' },- { orderedIds: ['r1', 'r2', 'r3'], stack: 'raster' },- ],- type: 'reorder',- },- { operation: 'reorder one stack twice', status: 'unsupported' },- ],- [- 'a patch of nothing',- { id: 'r1', patch: {}, type: 'patch' },- { operation: 'patch nothing', status: 'unsupported' },- ],- ['a selection of a missing layer', { id: 'ghost', type: 'select' }, { ids: ['ghost'], status: 'missing' }],- ])('refuses %s', (_label, command, refusal) => {- const project = projectWith([...interleaved(), layer('locked', 'raster', { isLocked: true })], 'r1');- expect(modelOf(project).prepare(command)).toEqual(refusal);- });-- it('stamps every prepared edit with the project id and edit revision it was built against', () => {- const project = projectWith(interleaved(), 'r1');- const result = createFlatDocumentModel(project.canvas.document, {- editRevision: 7,- projectId: project.id,- }).prepare({- ids: ['r1'],- type: 'remove',- });- expect(result).toMatchObject({ edit: { expectedRevision: 7, projectId: project.id }, status: 'prepared' });- });- });-- describe('canMergeDown', () => {- it('targets the layer directly below in flat order, like the reducer', () => {- const project = projectWith([layer('a'), layer('b'), layer('c1', 'control'), layer('r2')], 'a');- const model = modelOf(project);- expect(model.canMergeDown('a')).toEqual({ lowerId: 'b', status: 'eligible', upperId: 'a' });- expect(model.canMergeDown('b')).toEqual({ reason: 'not-mergeable', status: 'invalid-target', targetId: 'c1' });- });-- it('reports an unmergeable neighbour before a lock and a lock before a disabled layer', () => {- const lockedControl = projectWith([layer('r1'), layer('c1', 'control', { isLocked: true })], null);- expect(modelOf(lockedControl).canMergeDown('r1')).toEqual({- reason: 'not-mergeable',- status: 'invalid-target',- targetId: 'c1',- });- const lockedUpper = projectWith([layer('a', 'raster', { isEnabled: false, isLocked: true }), layer('b')], null);- expect(modelOf(lockedUpper).canMergeDown('a')).toEqual({ ids: ['a'], status: 'locked' });- });-- it.each<[string, CanvasLayerContract[], string, object]>([- ['the bottom layer', interleaved(), 'r3', { reason: 'no-layer-below', status: 'invalid-target', targetId: 'r3' }],- ['a mask', interleaved(), 'i1', { actual: 'inpaint_mask', expected: ['raster'], status: 'wrong-type' }],- ['a missing id', interleaved(), 'ghost', { ids: ['ghost'], status: 'missing' }],- [- 'a locked lower layer',- [layer('a'), layer('b', 'raster', { isLocked: true })],- 'a',- { ids: ['b'], status: 'locked' },- ],- [- 'a disabled upper layer',- [layer('a', 'raster', { isEnabled: false }), layer('b')],- 'a',- { reason: 'not-mergeable', status: 'invalid-target', targetId: 'a' },- ],- ])('refuses %s', (_label, layers, upperId, refusal) => {- expect(modelOf(projectWith(layers, null)).canMergeDown(upperId)).toEqual(refusal);- });- });-});--describe('document-level seam', () => {- it('looks layers and leaves up through the same index the model uses', () => {- const document = projectWith(interleaved(), 'r1').canvas.document;- expect(lookupDocumentLayer(document, 'c1')).toBe(document.layers.find((layer) => layer.id === 'c1'));- expect(lookupDocumentLayer(document, 'nope')).toBeNull();- expect(lookupDocumentLeaf(document, 'c1')).toBe(compileDocumentLeaves(document).find((leaf) => leaf.id === 'c1'));- expect(lookupDocumentLeaf(document, 'nope')).toBeNull();- });-- 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);- expect(reused).toBe(untouched);-- const renamed: CanvasDocumentContractV2 = {- ...before,- layers: before.layers.map((layer) => (layer.id === 'r1' ? { ...layer, name: 'renamed' } : layer)),- };- 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'));- });-- it('finds the layer directly below in flat order across stacks', () => {- const document = projectWith(interleaved(), 'r1').canvas.document;- expect(lookupLayerBelow(document, 'r1')?.id).toBe('c1');- expect(lookupLayerBelow(document, 'r3')).toBeNull();- expect(lookupLayerBelow(document, 'nope')).toBeNull();- });-- it('shares the merge-down rule with the model', () => {- const project = projectWith(interleaved(), 'r1');- const model = modelOf(project);- for (const layer of project.canvas.document.layers) {- expect(mergeDownEligibility(project.canvas.document, layer.id)).toEqual(model.canMergeDown(layer.id));- }- });-});--describe('checkFlatEditPostconditions', () => {- const document = projectWith(interleaved(), 'r2').canvas.document;-- it.each([- ['present ids', { ids: ['r1', 'c1'], kind: 'present' as const }, true],- ['a missing present id', { ids: ['r1', 'ghost'], kind: 'present' as const }, false],- ['absent ids', { ids: ['ghost'], kind: 'absent' as const }, true],- ['a present absent id', { ids: ['r1'], kind: 'absent' as const }, false],- [- 'the exact stack order',- { kind: 'stack-order' as const, orderedIds: ['r1', 'r2', 'r3'], stack: 'raster' as const },- true,- ],- [- 'a shorter stack order',- { kind: 'stack-order' as const, orderedIds: ['r1', 'r2'], stack: 'raster' as const },- false,- ],- [- 'a permuted stack order',- { kind: 'stack-order' as const, orderedIds: ['r2', 'r1', 'r3'], stack: 'raster' as const },- false,- ],- ['the selection', { id: 'r2', kind: 'selection' as const }, true],- ['another selection', { id: 'r1', kind: 'selection' as const }, false],- ['an applied patch', { id: 'r1', kind: 'patched' as const, patch: { name: 'r1', transform: { x: 0 } } }, true],- ['an unapplied patch', { id: 'r1', kind: 'patched' as const, patch: { name: 'r1', transform: { x: 3 } } }, false],- ['a patch of a missing layer', { id: 'ghost', kind: 'patched' as const, patch: { name: 'x' } }, false],- ])('checks %s', (_label, postcondition, expected) => {- expect(checkFlatEditPostconditions(document, [postcondition])).toBe(expected);- });-});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.tsdeleted file mode 100644index 70aef92259..0000000000--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts+++ /dev/null@@ -1,726 +0,0 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { FlatLayerInsertion } from '@workbench/canvas-engine/document/insertionAnchors';-import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';-import type {- CanvasLayerBasePatch,- CanvasLayerConfigPatch,- CanvasProjectMutation,-} from '@workbench/canvas-engine/mutationContracts';--import {- captureInsertionAnchor,- captureRestoreAnchor,- insertLayersAtAnchor,-} from '@workbench/canvas-engine/document/insertionAnchors';-import {- isHideableLayer,- isLayerContributing,- isLayerHidden,- isPixelBackedLayer,-} from '@workbench/canvas-engine/document/layerEligibility';-import {- getStackOrder,- LAYER_STACKS_TOP_FIRST,- layerStackOf,- moveLayersWithinStacks,- reorderLayerStack,-} from '@workbench/canvas-engine/document/layerStacks';-import { repairSelectedLayerId } from '@workbench/canvas-engine/document/selectionRepair';--import type {- FlatDocumentCommand,- FlatDocumentRefusal,- MergeDownEligibility,- PreparedFlatEdit,- PrepareFlatEditResult,-} from './flatDocumentCommands';-import type { FlatEditPostcondition } from './postconditions';-import type { SemanticLeafV2 } from './semanticLeaf';--import { isConfigApplied, isPatchApplied, sameValue } from './postconditions';-import { compileSemanticLeaf } from './semanticLeaf';--export interface FlatDocumentModelContext {- readonly projectId: string;- readonly editRevision: number;-}--/**- * 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 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;- getLayer(id: string): CanvasLayerContract | null;- getStack(kind: LayerStackKind): readonly CanvasLayerContract[];- compileLeaves(): readonly SemanticLeafV2[];- canMergeDown(upperId: string): MergeDownEligibility;- prepare(command: FlatDocumentCommand): PrepareFlatEditResult;-}--interface LayerIndexEntry {- readonly layer: CanvasLayerContract;- readonly index: number;- readonly stack: LayerStackKind;- readonly stackIndex: number;-}--interface DocumentIndex {- readonly byId: ReadonlyMap<string, LayerIndexEntry>;- readonly stacks: Readonly<Record<LayerStackKind, readonly CanvasLayerContract[]>>;- leaves: readonly SemanticLeafV2[] | null;-}--export interface FlatDocumentModelDiagnostics {- readonly indexBuilds: number;- readonly leafCompilations: number;- readonly leavesCompiled: number;-}--/** Internal deterministic instrumentation; production logic never reads it. */-const diagnostics = { indexBuilds: 0, leafCompilations: 0, leavesCompiled: 0 };--/** Immutable snapshot for deterministic budget tests and diagnostics. */-export const getFlatDocumentModelDiagnostics = (): FlatDocumentModelDiagnostics => ({ ...diagnostics });--/** 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 => {- diagnostics.indexBuilds += 1;- const byId = new Map<string, LayerIndexEntry>();- const stacks: Record<LayerStackKind, CanvasLayerContract[]> = {- control: [],- inpaint_mask: [],- raster: [],- regional_guidance: [],- };- layers.forEach((layer, index) => {- const stack = layerStackOf(layer);- byId.set(layer.id, { index, layer, stack, stackIndex: stacks[stack].length });- stacks[stack].push(layer);- });- return { byId, leaves: null, stacks };-};--/** Indexes are keyed on the layer array, so a selection-only document change reuses them. */-const indexOf = (document: CanvasDocumentContractV2): DocumentIndex => {- const existing = indexes.get(document.layers);- if (existing) {- return existing;- }- const built = buildIndex(document.layers);- indexes.set(document.layers, built);- return built;-};--const compileLeaves = (document: CanvasDocumentContractV2, index: DocumentIndex): readonly SemanticLeafV2[] => {- if (index.leaves) {- return index.leaves;- }- diagnostics.leafCompilations += 1;- const leaves = document.layers.map((layer) => {- 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;- return leaves;-};--const missing = (ids: readonly string[]): FlatDocumentRefusal => ({ ids, status: 'missing' });--/** The layer with `id`, through the per-document index. */-export const lookupDocumentLayer = (document: CanvasDocumentContractV2, id: string): CanvasLayerContract | null =>- indexOf(document).byId.get(id)?.layer ?? null;--/** 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 => {- const entry = indexOf(document).byId.get(id);- return entry ? (compileDocumentLeaves(document)[entry.index] ?? null) : null;-};--/** The layer directly below `id` in flat order, whatever its stack; `null` at the bottom or when absent. */-export const lookupLayerBelow = (document: CanvasDocumentContractV2, id: string): CanvasLayerContract | null => {- const entry = indexOf(document).byId.get(id);- return entry ? (document.layers[entry.index + 1] ?? null) : null;-};--/** Merge-down joins a raster layer with the layer directly below it in flat order, mirroring the reducer. */-export const mergeDownEligibility = (document: CanvasDocumentContractV2, upperId: string): MergeDownEligibility => {- const upper = indexOf(document).byId.get(upperId);- if (!upper) {- return missing([upperId]);- }- if (upper.stack !== 'raster') {- return { actual: upper.stack, expected: ['raster'], status: 'wrong-type' };- }- const lower = lookupLayerBelow(document, upperId);- if (!lower) {- return { reason: 'no-layer-below', status: 'invalid-target', targetId: upperId };- }- const unmergeable = [upper.layer, lower].find((layer) => layer.type !== 'raster' || !isPixelBackedLayer(layer));- if (unmergeable) {- return { reason: 'not-mergeable', status: 'invalid-target', targetId: unmergeable.id };- }- const locked = [upper.layer, lower].filter((layer) => layer.isLocked).map((layer) => layer.id);- if (locked.length > 0) {- return { ids: locked, status: 'locked' };- }- const disabled = [upper.layer, lower].find((layer) => !isLayerContributing(layer));- if (disabled) {- return { reason: 'not-mergeable', status: 'invalid-target', targetId: disabled.id };- }- return { lowerId: lower.id, status: 'eligible', upperId };-};--const unique = <T>(values: readonly T[]): T[] => [...new Set(values)];--/**- * Whether two patches name the same fields, descending only into the partial containers listed in- * `containers` as dotted paths; every other value is compared as a whole.- */-const sameKeys = (- left: Record<string, unknown>,- right: Record<string, unknown>,- containers: readonly string[],- path = ''-): boolean => {- const leftKeys = Object.keys(left).sort();- const rightKeys = Object.keys(right).sort();- return (- leftKeys.length === rightKeys.length &&- leftKeys.every((key, position) => key === rightKeys[position]) &&- leftKeys.every((key) => {- const keyPath = path ? `${path}.${key}` : key;- if (!containers.includes(keyPath)) {- return true;- }- const a = left[key];- const b = right[key];- return typeof a === 'object' && a !== null && typeof b === 'object' && b !== null- ? sameKeys(a as Record<string, unknown>, b as Record<string, unknown>, containers, keyPath)- : a === undefined && b === undefined;- })- );-};--const PATCH_CONTAINERS = ['transform'] as const;-const CONFIG_CONTAINERS = ['adapter', 'mask', 'mask.fill'] as const;--const stacksTopFirst = (stacks: readonly LayerStackKind[]): LayerStackKind[] =>- LAYER_STACKS_TOP_FIRST.filter((stack) => stacks.includes(stack));--const stackOrders = (- layers: readonly CanvasLayerContract[],- stacks: readonly LayerStackKind[]-): FlatEditPostcondition[] =>- stacks.map((stack) => ({ kind: 'stack-order', orderedIds: getStackOrder(layers, stack).orderedIds, stack }));--const patchInverse = (layer: CanvasLayerContract, patch: CanvasLayerBasePatch): CanvasLayerBasePatch => {- const inverse: Record<string, unknown> = {};- for (const key of Object.keys(patch) as (keyof CanvasLayerBasePatch)[]) {- if (key === 'transform') {- const transform: Record<string, number> = {};- for (const axis of Object.keys(patch.transform ?? {}) as (keyof CanvasLayerContract['transform'])[]) {- transform[axis] = layer.transform[axis];- }- inverse.transform = transform;- } else {- inverse[key] = layer[key];- }- }- return inverse as CanvasLayerBasePatch;-};--export const createFlatDocumentModel = (- document: CanvasDocumentContractV2,- context: FlatDocumentModelContext-): FlatCanvasDocumentModel => {- const index = indexOf(document);- const { layers, selectedLayerId } = document;-- const lookup = (ids: readonly string[]): { entries: LayerIndexEntry[] } | FlatDocumentRefusal => {- const absent = ids.filter((id) => !index.byId.has(id));- return absent.length > 0 ? missing(absent) : { entries: ids.map((id) => index.byId.get(id)!) };- };-- const prepared = (- forward: CanvasProjectMutation,- inverse: CanvasProjectMutation,- detail: Omit<- PreparedFlatEdit,- 'forward' | 'inverse' | 'projectId' | 'expectedRevision' | 'selectionBefore' | 'rasterWork'- >- ): PrepareFlatEditResult => ({- edit: {- ...detail,- expectedRevision: context.editRevision,- forward,- inverse,- projectId: context.projectId,- rasterWork: null,- selectionBefore: selectedLayerId,- },- status: 'prepared',- });-- const prepareInsert = (command: Extract<FlatDocumentCommand, { type: 'insert' }>): PrepareFlatEditResult => {- if (command.layers.length === 0) {- return { operation: 'insert nothing', status: 'unsupported' };- }- const ids = command.layers.map((layer) => layer.id);- const clash = ids.find((id, at) => index.byId.has(id) || ids.indexOf(id) !== at);- if (clash !== undefined) {- return { reason: 'id-exists', status: 'invalid-target', targetId: clash };- }- const selectionAfter = command.selectId === undefined ? ids.at(-1)! : command.selectId;- if (selectionAfter !== null && !ids.includes(selectionAfter) && !index.byId.has(selectionAfter)) {- return missing([selectionAfter]);- }- const touchedStacks = stacksTopFirst(command.layers.map(layerStackOf));- const add: FlatLayerInsertion[] = touchedStacks.map((stack) => ({- anchor: captureInsertionAnchor(layers, {- aboveId: command.aboveId,- editRevision: context.editRevision,- projectId: context.projectId,- stack,- }),- layers: command.layers.filter((layer) => layerStackOf(layer) === stack),- }));- const expected = add.reduce(- (next, insertion) => insertLayersAtAnchor(next, insertion.anchor, insertion.layers),- layers- );- return prepared(- { add, enabledUpdates: [], selectedLayerId: selectionAfter, type: 'applyCanvasLayerStackMutation' },- { enabledUpdates: [], removeIds: ids, selectedLayerId, type: 'applyCanvasLayerStackMutation' },- {- history: 'record',- postconditions: [...stackOrders(expected, touchedStacks), { id: selectionAfter, kind: 'selection' }],- selectionAfter,- touchedIds: ids,- touchedStacks,- }- );- };-- const prepareRemove = (command: Extract<FlatDocumentCommand, { type: 'remove' }>): PrepareFlatEditResult => {- const ids = unique(command.ids);- if (ids.length === 0) {- return { operation: 'remove nothing', status: 'unsupported' };- }- const found = lookup(ids);- if ('status' in found) {- return found;- }- const locked = found.entries.filter((entry) => entry.layer.isLocked).map((entry) => entry.layer.id);- if (locked.length > 0) {- return { ids: locked, status: 'locked' };- }- const removed = new Set(ids);- const remaining = layers.filter((layer) => !removed.has(layer.id));- const selectionAfter = repairSelectedLayerId(remaining, selectedLayerId, layers);- const touchedStacks = stacksTopFirst(found.entries.map((entry) => entry.stack));- const add: FlatLayerInsertion[] = layers- .filter((layer) => removed.has(layer.id))- .map((layer) => ({- anchor: captureRestoreAnchor(layers, layer.id, context.projectId, context.editRevision)!,- layers: [layer],- }));- return prepared(- { ids: [...ids], type: 'removeCanvasLayers' },- { add, enabledUpdates: [], selectedLayerId, type: 'applyCanvasLayerStackMutation' },- {- history: 'record',- postconditions: [...stackOrders(remaining, touchedStacks), { id: selectionAfter, kind: 'selection' }],- selectionAfter,- touchedIds: ids,- touchedStacks,- }- );- };-- const prepareDuplicate = (command: Extract<FlatDocumentCommand, { type: 'duplicate' }>): PrepareFlatEditResult => {- const source = index.byId.get(command.sourceId);- if (!source) {- return missing([command.sourceId]);- }- if (index.byId.has(command.newId)) {- return { reason: 'id-exists', status: 'invalid-target', targetId: command.newId };- }- const stackIds = getStackOrder(layers, source.stack).orderedIds;- const orderedIds = [...stackIds.slice(0, source.stackIndex), command.newId, ...stackIds.slice(source.stackIndex)];- return prepared(- { newId: command.newId, sourceId: command.sourceId, type: 'duplicateCanvasLayer' },- { enabledUpdates: [], removeIds: [command.newId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },- {- history: 'record',- postconditions: [- { kind: 'stack-order', orderedIds, stack: source.stack },- { id: command.newId, kind: 'selection' },- ],- selectionAfter: command.newId,- touchedIds: [command.newId],- touchedStacks: [source.stack],- }- );- };-- const prepareReorder = (- stacks: readonly { stack: LayerStackKind; orderedIds: readonly string[] }[]- ): PrepareFlatEditResult => {- if (stacks.length === 0) {- return { operation: 'reorder nothing', status: 'unsupported' };- }- if (new Set(stacks.map((command) => command.stack)).size !== stacks.length) {- return { operation: 'reorder one stack twice', status: 'unsupported' };- }- const touchedIds: string[] = [];- for (const command of stacks) {- const current = getStackOrder(layers, command.stack).orderedIds;- const unknown = command.orderedIds.filter((id) => !index.byId.has(id));- if (unknown.length > 0) {- return missing(unknown);- }- const foreign = command.orderedIds.find((id) => index.byId.get(id)!.stack !== command.stack);- if (foreign !== undefined) {- return { reason: 'foreign-stack', status: 'invalid-target', targetId: foreign };- }- if (!reorderLayerStack(layers, command)) {- return {- reason: 'not-stack-members',- status: 'invalid-target',- targetId: command.orderedIds[0] ?? current[0]!,- };- }- touchedIds.push(...command.orderedIds.filter((id, position) => current[position] !== id));- }- if (touchedIds.length === 0) {- return { status: 'unchanged' };- }- return prepared(- {- stacks: stacks.map((command) => ({ orderedIds: [...command.orderedIds], stack: command.stack })),- type: 'reorderCanvasLayerStacks',- },- { stacks: stacks.map((command) => getStackOrder(layers, command.stack)), type: 'reorderCanvasLayerStacks' },- {- history: 'record',- postconditions: stacks.map((command) => ({- kind: 'stack-order',- orderedIds: command.orderedIds,- stack: command.stack,- })),- selectionAfter: selectedLayerId,- touchedIds,- touchedStacks: stacksTopFirst(stacks.map((command) => command.stack)),- }- );- };-- const prepareMove = (command: Extract<FlatDocumentCommand, { type: 'move' }>): PrepareFlatEditResult => {- const ids = unique(command.ids);- if (ids.length === 0) {- return { operation: 'move nothing', status: 'unsupported' };- }- const found = lookup(ids);- if ('status' in found) {- return found;- }- const stacks = moveLayersWithinStacks(layers, ids, command.kind);- return stacks.length === 0 ? { status: 'unchanged' } : prepareReorder(stacks);- };-- const preparePatch = (command: Extract<FlatDocumentCommand, { type: 'patch' }>): PrepareFlatEditResult => {- const entry = index.byId.get(command.id);- if (!entry) {- return missing([command.id]);- }- if (Object.keys(command.patch).length === 0) {- return { operation: 'patch nothing', status: 'unsupported' };- }- if (command.before && !sameKeys(command.before, command.patch, PATCH_CONTAINERS)) {- return { operation: 'patch baseline names other fields', status: 'unsupported' };- }- const inverse = command.before ?? patchInverse(entry.layer, command.patch);- if (command.before ? sameValue(command.before, command.patch) : isPatchApplied(entry.layer, command.patch)) {- return { status: 'unchanged' };- }- return prepared(- { id: command.id, patch: command.patch, type: 'updateCanvasLayer' },- { id: command.id, patch: inverse, type: 'updateCanvasLayer' },- {- history: 'record',- postconditions: [{ id: command.id, kind: 'patched', patch: command.patch }],- selectionAfter: selectedLayerId,- touchedIds: [command.id],- touchedStacks: [entry.stack],- }- );- };-- const configInverse = (layer: CanvasLayerContract, config: CanvasLayerConfigPatch): CanvasLayerConfigPatch => {- const current = layer as unknown as Record<string, unknown>;- const inverse: Record<string, unknown> = { layerType: config.layerType };- for (const [key, value] of Object.entries(config)) {- if (key === 'layerType') {- continue;- }- const before = current[key];- inverse[key] =- (key === 'adapter' || key === 'mask') &&- typeof value === 'object' &&- value !== null &&- typeof before === 'object'- ? Object.fromEntries(Object.keys(value).map((field) => [field, (before as Record<string, unknown>)[field]]))- : before;- }- return inverse as CanvasLayerConfigPatch;- };-- const preparePatchConfig = (- command: Extract<FlatDocumentCommand, { type: 'patch-config' }>- ): PrepareFlatEditResult => {- const entry = index.byId.get(command.id);- if (!entry) {- return missing([command.id]);- }- if (entry.layer.type !== command.config.layerType) {- return { actual: entry.layer.type, expected: [command.config.layerType], status: 'wrong-type' };- }- if (Object.keys(command.config).length <= 1) {- return { operation: 'patch nothing', status: 'unsupported' };- }- if (command.before && command.before.layerType !== command.config.layerType) {- return { operation: 'config baseline names another layer type', status: 'unsupported' };- }- if (command.before && !sameKeys(command.before, command.config, CONFIG_CONTAINERS)) {- return { operation: 'config baseline names other fields', status: 'unsupported' };- }- if (command.before ? sameValue(command.before, command.config) : isConfigApplied(entry.layer, command.config)) {- return { status: 'unchanged' };- }- return prepared(- { config: command.config, id: command.id, type: 'updateCanvasLayerConfig' },- {- config: command.before ?? configInverse(entry.layer, command.config),- id: command.id,- type: 'updateCanvasLayerConfig',- },- {- history: 'record',- postconditions: [{ config: command.config, id: command.id, kind: 'config' }],- selectionAfter: selectedLayerId,- touchedIds: [command.id],- touchedStacks: [entry.stack],- }- );- };-- const preparePatchSource = (- command: Extract<FlatDocumentCommand, { type: 'patch-source' }>- ): PrepareFlatEditResult => {- const entry = index.byId.get(command.id);- if (!entry) {- return missing([command.id]);- }- if (entry.layer.type !== 'raster' && entry.layer.type !== 'control') {- return { actual: entry.layer.type, expected: ['raster', 'control'], status: 'wrong-type' };- }- if (entry.layer.source === command.source) {- return { status: 'unchanged' };- }- return prepared(- { id: command.id, source: command.source, type: 'updateCanvasLayerSource' },- { id: command.id, source: entry.layer.source, type: 'updateCanvasLayerSource' },- {- history: 'record',- postconditions: [{ id: command.id, kind: 'source', source: command.source }],- selectionAfter: selectedLayerId,- touchedIds: [command.id],- touchedStacks: [entry.stack],- }- );- };-- const prepareFlags = (- command: Extract<FlatDocumentCommand, { type: 'set-enabled' | 'set-hidden' | 'set-locked' }>- ): PrepareFlatEditResult => {- const ids = unique(command.updates.map((update) => update.id));- if (ids.length === 0) {- return { operation: `${command.type} nothing`, status: 'unsupported' };- }- const found = lookup(ids);- if ('status' in found) {- return found;- }- if (command.type === 'set-hidden') {- const notHideable = found.entries.find((entry) => !isHideableLayer(entry.layer));- if (notHideable) {- return {- actual: notHideable.layer.type,- expected: ['control', 'inpaint_mask', 'regional_guidance'],- status: 'wrong-type',- };- }- }- const detail = (updated: readonly { id: string }[]) => ({- history: 'record' as const,- selectionAfter: selectedLayerId,- touchedIds: updated.map((update) => update.id),- touchedStacks: stacksTopFirst(updated.map((update) => index.byId.get(update.id)!.stack)),- });- switch (command.type) {- case 'set-enabled': {- const updates = command.updates.filter(- (update) => index.byId.get(update.id)!.layer.isEnabled !== update.isEnabled- );- if (updates.length === 0) {- return { status: 'unchanged' };- }- return prepared(- { type: 'setCanvasLayersEnabled', updates },- {- type: 'setCanvasLayersEnabled',- updates: updates.map((update) => ({- id: update.id,- isEnabled: index.byId.get(update.id)!.layer.isEnabled,- })),- },- {- ...detail(updates),- postconditions: updates.map((update) => ({- id: update.id,- kind: 'patched',- patch: { isEnabled: update.isEnabled },- })),- }- );- }- case 'set-hidden': {- const updates = command.updates.filter(- (update) => isLayerHidden(index.byId.get(update.id)!.layer) !== update.isHidden- );- if (updates.length === 0) {- return { status: 'unchanged' };- }- return prepared(- { type: 'setCanvasLayersHidden', updates },- {- type: 'setCanvasLayersHidden',- updates: updates.map((update) => ({- id: update.id,- isHidden: isLayerHidden(index.byId.get(update.id)!.layer),- })),- },- {- ...detail(updates),- postconditions: updates.map((update) => ({ id: update.id, isHidden: update.isHidden, kind: 'hidden' })),- }- );- }- case 'set-locked': {- const updates = command.updates.filter(- (update) => index.byId.get(update.id)!.layer.isLocked !== update.isLocked- );- if (updates.length === 0) {- return { status: 'unchanged' };- }- return prepared(- { enabledUpdates: [], lockedUpdates: updates, type: 'applyCanvasLayerStackMutation' },- {- enabledUpdates: [],- lockedUpdates: updates.map((update) => ({- id: update.id,- isLocked: index.byId.get(update.id)!.layer.isLocked,- })),- type: 'applyCanvasLayerStackMutation',- },- {- ...detail(updates),- postconditions: updates.map((update) => ({- id: update.id,- kind: 'patched',- patch: { isLocked: update.isLocked },- })),- }- );- }- }- };-- const prepareSelect = (command: Extract<FlatDocumentCommand, { type: 'select' }>): PrepareFlatEditResult => {- if (command.id !== null && !index.byId.has(command.id)) {- return missing([command.id]);- }- if (command.id === selectedLayerId) {- return { status: 'unchanged' };- }- return prepared(- { id: command.id, type: 'setCanvasSelectedLayer' },- { id: selectedLayerId, type: 'setCanvasSelectedLayer' },- {- history: 'none',- postconditions: [{ id: command.id, kind: 'selection' }],- selectionAfter: command.id,- touchedIds: [],- touchedStacks: [],- }- );- };-- return {- canMergeDown: (upperId) => mergeDownEligibility(document, upperId),- compileLeaves: () => compileLeaves(document, index),- document,- getLayer: (id) => index.byId.get(id)?.layer ?? null,- getStack: (kind) => index.stacks[kind],- prepare: (command) => {- switch (command.type) {- case 'insert':- return prepareInsert(command);- case 'remove':- return prepareRemove(command);- case 'duplicate':- return prepareDuplicate(command);- case 'move':- return prepareMove(command);- case 'reorder':- return prepareReorder(command.stacks);- case 'patch':- return preparePatch(command);- case 'patch-config':- return preparePatchConfig(command);- case 'patch-source':- return preparePatchSource(command);- case 'set-enabled':- case 'set-hidden':- case 'set-locked':- return prepareFlags(command);- case 'select':- return prepareSelect(command);- }- },- };-};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.tsindex b8f431d55e..531d9a8075 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts@@ -1,19 +1,28 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,+ CanvasNodeContract,} from '@workbench/canvas-engine/contracts';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { CanvasLayerBasePatch, CanvasLayerConfigPatch } from '@workbench/canvas-engine/mutationContracts';-import { isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';-import { getStackOrder } from '@workbench/canvas-engine/document/layerStacks';+import { getDocumentIndex, getDocumentNode } from '@workbench/canvas-engine/document/documentIndex';+import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';+import { isNodeHidden } from '@workbench/canvas-engine/document/layerEligibility';+import { getSiblingOrder } from '@workbench/canvas-engine/document/layerStacks';+import { GROUP_PATCH_KEYS } from '@workbench/canvas-engine/mutationContracts';/** What a document must show after a prepared edit landed; evaluated against the reducer document. */-export type FlatEditPostcondition =+export type EditPostcondition =| { readonly kind: 'present'; readonly ids: readonly string[] }| { readonly kind: 'absent'; readonly ids: readonly string[] }- | { readonly kind: 'stack-order'; readonly stack: LayerStackKind; readonly orderedIds: readonly string[] }+ | {+ readonly kind: 'sibling-order';+ readonly stack: LayerStackKind;+ readonly parentId: string | null;+ readonly orderedIds: readonly string[];+ }| { readonly kind: 'selection'; readonly id: string | null }| { readonly kind: 'patched'; readonly id: string; readonly patch: CanvasLayerBasePatch }| { readonly kind: 'config'; readonly id: string; readonly config: CanvasLayerConfigPatch }@@ -42,22 +51,25 @@ export const sameValue = (left: unknown, right: unknown): boolean => {return keys.length === Object.keys(right).length && keys.every((key) => sameValue(left[key], right[key]));};-/** Whether every field named by `patch` already holds its value on `layer`. */-export const isPatchApplied = (layer: CanvasLayerContract, patch: CanvasLayerBasePatch): boolean =>- (Object.keys(patch) as (keyof CanvasLayerBasePatch)[]).every((key) =>- key === 'transform'+/** Whether every field named by `patch` already holds its value on `node`. */+export const isPatchApplied = (node: CanvasNodeContract, patch: CanvasLayerBasePatch): boolean =>+ (Object.keys(patch) as (keyof CanvasLayerBasePatch)[]).every((key) => {+ if (isGroupNode(node)) {+ return GROUP_PATCH_KEYS.includes(key) && node[key as 'name' | 'isEnabled' | 'isLocked'] === patch[key];+ }+ return key === 'transform'? (Object.keys(patch.transform ?? {}) as (keyof CanvasLayerContract['transform'])[]).every(- (axis) => layer.transform[axis] === patch.transform?.[axis]+ (axis) => node.transform[axis] === patch.transform?.[axis])- : layer[key] === patch[key]- );+ : node[key] === patch[key];+ });/** Whether every field named by `config` already holds its value; nested partials compare field by field. */-export const isConfigApplied = (layer: CanvasLayerContract, config: CanvasLayerConfigPatch): boolean => {- if (layer.type !== config.layerType) {+export const isConfigApplied = (node: CanvasNodeContract, config: CanvasLayerConfigPatch): boolean => {+ if (node.type !== config.layerType) {return false;}- const target = layer as unknown as Record<string, unknown>;+ const target = node as unknown as Record<string, unknown>;return Object.entries(config).every(([key, value]) => {if (key === 'layerType') {return true;@@ -69,40 +81,43 @@ export const isConfigApplied = (layer: CanvasLayerContract, config: CanvasLayerC});};-export const checkFlatEditPostconditions = (- document: CanvasDocumentContractV2,- postconditions: readonly FlatEditPostcondition[]-): boolean =>- postconditions.every((postcondition) => {+const sameOrder = (left: readonly string[], right: readonly string[]): boolean =>+ left.length === right.length && left.every((id, index) => id === right[index]);++export const checkEditPostconditions = (+ document: CanvasDocumentContractV3,+ postconditions: readonly EditPostcondition[]+): boolean => {+ const index = getDocumentIndex(document);+ return postconditions.every((postcondition) => {switch (postcondition.kind) {case 'present':- return postcondition.ids.every((id) => document.layers.some((layer) => layer.id === id));+ return postcondition.ids.every((id) => index.byId.has(id));case 'absent':- return postcondition.ids.every((id) => !document.layers.some((layer) => layer.id === id));- case 'stack-order': {- const { orderedIds } = getStackOrder(document.layers, postcondition.stack);- return (- orderedIds.length === postcondition.orderedIds.length &&- orderedIds.every((id, index) => id === postcondition.orderedIds[index])+ return postcondition.ids.every((id) => !index.byId.has(id));+ case 'sibling-order':+ return sameOrder(+ getSiblingOrder(document.stacks, postcondition.stack, postcondition.parentId).orderedIds,+ postcondition.orderedIds);- }case 'selection':return document.selectedLayerId === postcondition.id;case 'patched': {- const layer = document.layers.find((candidate) => candidate.id === postcondition.id);- return layer !== undefined && isPatchApplied(layer, postcondition.patch);+ const node = getDocumentNode(document, postcondition.id);+ return node !== null && isPatchApplied(node, postcondition.patch);}case 'config': {- const layer = document.layers.find((candidate) => candidate.id === postcondition.id);- return layer !== undefined && isConfigApplied(layer, postcondition.config);+ const node = getDocumentNode(document, postcondition.id);+ return node !== null && isConfigApplied(node, postcondition.config);}case 'source': {- const layer = document.layers.find((candidate) => candidate.id === postcondition.id);- return layer !== undefined && 'source' in layer && layer.source === postcondition.source;+ const node = getDocumentNode(document, postcondition.id);+ return node !== null && 'source' in node && node.source === postcondition.source;}case 'hidden': {- const layer = document.layers.find((candidate) => candidate.id === postcondition.id);- return layer !== undefined && isLayerHidden(layer) === postcondition.isHidden;+ const node = getDocumentNode(document, postcondition.id);+ return node !== null && isNodeHidden(node) === postcondition.isHidden;}}});+};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.tsindex 6330a98272..678f8c249b 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@@ -1,21 +1,17 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';import type { CanvasScreenViewState } from './screenComposition';+import { documentFrom, groupContract, layerContract } from './documentFixtures.testStub';+import { compileDocumentLeaves } from './documentModel';import { planScreenComposition } from './screenComposition';-import { compileSemanticLeaf } from './semanticLeaf';-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 layer = (id: string, type: CanvasLayerContract['type'], overrides: Partial<CanvasLayerContract> = {}) =>+ layerContract(id, type, overrides);++const leaves = (nodes: readonly CanvasNodeContract[]) => compileDocumentLeaves(documentFrom(nodes));const view = (overrides: Partial<CanvasScreenViewState> = {}): CanvasScreenViewState => ({isolationLayerId: null,@@ -23,45 +19,71 @@ const view = (overrides: Partial<CanvasScreenViewState> = {}): CanvasScreenViewS...overrides,});-const leaves = [- leaf('i1', 'inpaint_mask'),- leaf('r1', 'raster'),- leaf('c1', 'control', { isHidden: true } as Partial<CanvasLayerContract>),- leaf('r2', 'raster', { isEnabled: false }),- leaf('g1', 'regional_guidance'),- leaf('r3', 'raster'),-];-const drawn = (plan: ReturnType<typeof planScreenComposition>): string[] => plan.leaves.map((leaf) => leaf.id);describe('planScreenComposition', () => {- it('draws contributing, unhidden leaves stack by stack, bottom first', () => {- expect(drawn(planScreenComposition(leaves, view()))).toEqual(['r3', 'r1', 'g1', 'i1']);+ it('draws stacks bottom first and each stack bottom-most leaf first', () => {+ const plan = planScreenComposition(+ leaves([layer('m1', 'inpaint_mask'), layer('c1', 'control'), layer('r1', 'raster'), layer('r2', 'raster')]),+ view()+ );+ expect(drawn(plan)).toEqual(['r2', 'r1', 'c1', 'm1']);+ });++ it('skips disabled and document-hidden leaves and leaves an ancestor gates its descendants', () => {+ const plan = planScreenComposition(+ leaves([+ layer('r1', 'raster', { isEnabled: false }),+ groupContract('off', [layer('r2', 'raster')], { isEnabled: false }),+ groupContract('hidden', [layer('c2', 'control')], { isHidden: true }),+ layer('c1', 'control', { isHidden: true } as Partial<CanvasLayerContract>),+ layer('r3', 'raster'),+ ]),+ view()+ );+ expect(drawn(plan)).toEqual(['r3']);});- it('applies overlay stack switches without touching raster leaves', () => {+ it('switches whole overlay stacks off without touching raster', () => {const plan = planScreenComposition(- leaves,- view({ showOverlayStacks: { control: true, inpaint_mask: false, regional_guidance: false } })+ leaves([layer('m1', 'inpaint_mask'), layer('c1', 'control'), layer('r1', 'raster')]),+ view({ showOverlayStacks: { control: false, inpaint_mask: true, regional_guidance: true } }));- expect(drawn(plan)).toEqual(['r3', 'r1']);+ expect(drawn(plan)).toEqual(['r1', 'm1']);});- it('isolates one drawable leaf regardless of the stack switches', () => {+ it('isolates one leaf, overriding its own and its ancestors visibility and every stack switch', () => {const plan = planScreenComposition(- leaves,+ leaves([+ groupContract(+ 'g',+ [layer('c1', 'control', { isEnabled: false, isHidden: true } as Partial<CanvasLayerContract>)],+ {+ isEnabled: false,+ }+ ),+ layer('r1', 'raster'),+ ]),view({- isolationLayerId: 'g1',+ isolationLayerId: 'c1',showOverlayStacks: { control: false, inpaint_mask: false, regional_guidance: false },}));- expect(plan).toEqual({ isolationLayerId: 'g1', leaves: [leaves[4]] });- expect(drawn(planScreenComposition(leaves, view({ isolationLayerId: 'r1' })))).toEqual(['r1']);+ expect(drawn(plan)).toEqual(['c1']);+ expect(plan.isolationLayerId).toBe('c1');});- 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([]);+ it('isolates a group as every leaf beneath it', () => {+ const plan = planScreenComposition(+ leaves([+ groupContract('g', [+ layer('r1', 'raster'),+ groupContract('inner', [layer('r2', 'raster', { isEnabled: false })]),+ ]),+ layer('r3', 'raster'),+ ]),+ view({ isolationLayerId: 'g' })+ );+ expect(drawn(plan)).toEqual(['r2', 'r1']);});});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.tsindex 0387f6214e..7389c4fd71 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@@ -2,17 +2,18 @@ import type { LayerStackKind, OverlayStackKind } from '@workbench/canvas-engine/import { LAYER_STACK_ORDER } from '@workbench/canvas-engine/document/layerStacks';-import type { SemanticLeafV2 } from './semanticLeaf';+import type { SemanticLeaf } from './semanticLeaf';/** Screen-only state that never enters the document: overlay stack switches and isolation. */export interface CanvasScreenViewState {readonly showOverlayStacks: Readonly<Record<OverlayStackKind, boolean>>;+ /** A leaf or a group; a group isolates its descendant leaves. */readonly isolationLayerId: string | null;}/** Leaves to draw, bottom first, after the view state is applied to the document facts. */export interface ScreenCompositionPlan {- readonly leaves: readonly SemanticLeafV2[];+ readonly leaves: readonly SemanticLeaf[];readonly isolationLayerId: string | null;}@@ -26,24 +27,27 @@ export const ALL_OVERLAY_STACKS_SHOWN: Readonly<Record<OverlayStackKind, booleanconst isStackShown = (stack: LayerStackKind, view: CanvasScreenViewState): boolean =>stack === 'raster' || view.showOverlayStacks[stack];+export const isLeafIsolated = (leaf: SemanticLeaf, isolationLayerId: string | null): boolean =>+ isolationLayerId !== null && (leaf.id === isolationLayerId || leaf.parentIds.includes(isolationLayerId));+/*** 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 =>+export const isLeafDrawableForScreen = (leaf: SemanticLeaf, isIsolated: boolean): boolean =>isIsolated || (leaf.contributionEnabled && !leaf.documentHidden);-/** Isolation narrows the frame to one leaf and overrides the document's visibility flags. */+/** Isolation narrows the frame to one leaf or subtree and overrides the document's visibility flags. */export const planScreenComposition = (- leaves: readonly SemanticLeafV2[],+ leaves: readonly SemanticLeaf[],view: CanvasScreenViewState): ScreenCompositionPlan => {- const drawn: SemanticLeafV2[] = [];+ const drawn: SemanticLeaf[] = [];for (const stack of LAYER_STACK_ORDER) {for (let index = leaves.length - 1; index >= 0; index -= 1) {const leaf = leaves[index]!;- const isIsolated = view.isolationLayerId === leaf.id;+ const isIsolated = isLeafIsolated(leaf, view.isolationLayerId);if (leaf.stack !== stack || !isLeafDrawableForScreen(leaf, isIsolated)) {continue;}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.tsindex 228d6d023b..17488a6ffb 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@@ -1,29 +1,41 @@import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeEntry } from '@workbench/canvas-engine/document/documentIndex';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { Mat2d } from '@workbench/canvas-engine/types';-import { isLayerContributing, isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';-import { layerStackOf } from '@workbench/canvas-engine/document/layerStacks';+import { isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';-/** Document facts about one layer; nothing about the screen, the panel or the session. */-export interface SemanticLeafV2 {+/**+ * Document facts about one leaf, with its ancestors already applied; nothing about the screen,+ * the panel or the session. Ordering belongs to the sequence a leaf is returned in.+ */+export interface SemanticLeaf {readonly id: string;readonly stack: LayerStackKind;+ /** Ancestor group ids, root first. */+ readonly parentIds: readonly string[];readonly layer: CanvasLayerContract;+ /** The leaf and every ancestor are enabled. */readonly contributionEnabled: boolean;+ /** The leaf or an ancestor is display-hidden. */readonly documentHidden: boolean;+ /** The leaf's own lock, as the panel shows it. */readonly locked: boolean;+ /** The leaf or an ancestor is locked; edits refuse on this. */+ readonly effectiveLocked: boolean;readonly worldTransform: Mat2d;}-export const compileSemanticLeaf = (layer: CanvasLayerContract): SemanticLeafV2 => ({- contributionEnabled: isLayerContributing(layer),- documentHidden: isLayerHidden(layer),+export const compileSemanticLeaf = (layer: CanvasLayerContract, entry: CanvasNodeEntry): SemanticLeaf => ({+ contributionEnabled: entry.ancestorsEnabled && layer.isEnabled,+ documentHidden: entry.ancestorsHidden || isLayerHidden(layer),+ effectiveLocked: entry.ancestorsLocked || layer.isLocked,id: layer.id,layer,locked: layer.isLocked,- stack: layerStackOf(layer),+ parentIds: entry.path,+ stack: entry.stack,worldTransform: fromTRS({ x: layer.transform.x, y: layer.transform.y },layer.transform.rotation,@@ -31,3 +43,16 @@ export const compileSemanticLeaf = (layer: CanvasLayerContract): SemanticLeafV2layer.transform.scaleY),});++/** Whether a cached leaf still describes `layer` in the place `entry` gives it. */+export const isSemanticLeafCurrent = (+ leaf: SemanticLeaf,+ layer: CanvasLayerContract,+ entry: CanvasNodeEntry+): boolean =>+ leaf.layer === layer &&+ leaf.contributionEnabled === (entry.ancestorsEnabled && layer.isEnabled) &&+ leaf.documentHidden === (entry.ancestorsHidden || isLayerHidden(layer)) &&+ leaf.effectiveLocked === (entry.ancestorsLocked || layer.isLocked) &&+ leaf.parentIds.length === entry.path.length &&+ leaf.parentIds.every((id, index) => id === entry.path[index]);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.tsnew file mode 100644index 0000000000..84480d5c17--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts@@ -0,0 +1,169 @@+import type {+ CanvasDocumentContractV3,+ CanvasGroupContract,+ CanvasLayerContract,+ CanvasLayerStackKind,+ CanvasNodeContract,+ CanvasStackForests,+} from '@workbench/canvas-engine/contracts';++import { isGroupNode } from './documentTree';++/** Document facts about one node's place in its forest. */+export interface CanvasNodeEntry {+ readonly node: CanvasNodeContract;+ readonly stack: CanvasLayerStackKind;+ readonly parentId: string | null;+ /** Ancestor ids, root first; `path.length` is the node's depth. */+ readonly path: readonly string[];+ readonly siblingIndex: number;+ /** Position among every node, stacks top first, each stack in preorder. */+ readonly order: number;+ /** Whether every ancestor is enabled, unlocked, or unhidden respectively. */+ readonly ancestorsEnabled: boolean;+ readonly ancestorsLocked: boolean;+ readonly ancestorsHidden: boolean;+}++/**+ * The per-forest index shared by the reducer, the mirror and the document model. It is keyed on+ * the `stacks` object, which the reducer preserves across selection, bbox and geometry-only edits.+ */+export interface CanvasDocumentIndex {+ readonly stacks: CanvasStackForests;+ readonly byId: ReadonlyMap<string, CanvasNodeEntry>;+ /** Every node, stacks top first, each in preorder. */+ readonly nodes: readonly CanvasNodeEntry[];+ /** Every leaf, in the same order. */+ readonly leaves: readonly CanvasLayerContract[];+ readonly maxDepth: number;+}++const STACKS_TOP_FIRST: readonly CanvasLayerStackKind[] = ['inpaint_mask', 'regional_guidance', 'control', 'raster'];++const diagnostics = { indexBuilds: 0 };++export const getDocumentIndexBuildCount = (): number => diagnostics.indexBuilds;++export const resetDocumentIndexBuildCount = (): void => {+ diagnostics.indexBuilds = 0;+};++type DocumentView = Pick<CanvasDocumentContractV3, 'stacks'> | null | undefined;++const EMPTY_LEAVES: readonly CanvasLayerContract[] = [];++const indexes = new WeakMap<CanvasStackForests, CanvasDocumentIndex>();++const build = (stacks: CanvasStackForests): CanvasDocumentIndex => {+ diagnostics.indexBuilds += 1;+ const byId = new Map<string, CanvasNodeEntry>();+ const nodes: CanvasNodeEntry[] = [];+ const leaves: CanvasLayerContract[] = [];+ let maxDepth = 0;+ const visit = (+ children: readonly CanvasNodeContract[],+ stack: CanvasLayerStackKind,+ parent: CanvasGroupContract | null,+ path: readonly string[],+ ancestorsEnabled: boolean,+ ancestorsLocked: boolean,+ ancestorsHidden: boolean+ ): void => {+ maxDepth = Math.max(maxDepth, path.length);+ children.forEach((node, siblingIndex) => {+ const entry: CanvasNodeEntry = {+ ancestorsEnabled,+ ancestorsHidden,+ ancestorsLocked,+ node,+ order: nodes.length,+ parentId: parent?.id ?? null,+ path,+ siblingIndex,+ stack,+ };+ byId.set(node.id, entry);+ nodes.push(entry);+ if (isGroupNode(node)) {+ visit(+ node.children,+ stack,+ node,+ [...path, node.id],+ ancestorsEnabled && node.isEnabled,+ ancestorsLocked || node.isLocked,+ ancestorsHidden || node.isHidden === true+ );+ } else {+ leaves.push(node);+ }+ });+ };+ for (const stack of STACKS_TOP_FIRST) {+ visit(stacks[stack], stack, null, [], true, false, false);+ }+ return { byId, leaves, maxDepth, nodes, stacks };+};++export const indexStacks = (stacks: CanvasStackForests): CanvasDocumentIndex => {+ const existing = indexes.get(stacks);+ if (existing) {+ return existing;+ }+ const built = build(stacks);+ indexes.set(stacks, built);+ return built;+};++export const getDocumentIndex = (document: Pick<CanvasDocumentContractV3, 'stacks'>): CanvasDocumentIndex =>+ indexStacks(document.stacks);++/** The document's leaves, stacks top first, each in preorder; the same array while `stacks` is unchanged. */+export const getDocumentLeaves = (document: DocumentView): readonly CanvasLayerContract[] =>+ document ? indexStacks(document.stacks).leaves : EMPTY_LEAVES;++export const getDocumentNode = (document: DocumentView, id: string | null | undefined): CanvasNodeContract | null =>+ document && id ? (indexStacks(document.stacks).byId.get(id)?.node ?? null) : null;++/** The leaf with `id`, or `null` when absent, a group, or there is no document. */+export const getDocumentLayer = (document: DocumentView, id: string | null | undefined): CanvasLayerContract | null => {+ const node = getDocumentNode(document, id);+ return node && !isGroupNode(node) ? node : null;+};++export const hasDocumentNode = (document: DocumentView, id: string): boolean =>+ !!document && indexStacks(document.stacks).byId.has(id);++/** True only when a document exists and holds no node with `id`. */+export const isNodeAbsent = (document: DocumentView, id: string): boolean =>+ !!document && !indexStacks(document.stacks).byId.has(id);++/** Whether `ancestorId` is `id` itself or one of its ancestors. */+export const isSelfOrAncestor = (index: CanvasDocumentIndex, id: string, ancestorId: string): boolean =>+ id === ancestorId || (index.byId.get(id)?.path.includes(ancestorId) ?? false);++/** Drops every id whose ancestor is also listed, keeping document order. */+export const outermostNodes = (index: CanvasDocumentIndex, ids: Iterable<string>): CanvasNodeEntry[] => {+ const selected = new Set(ids);+ const outer: CanvasNodeEntry[] = [];+ for (const entry of index.nodes) {+ if (selected.has(entry.node.id) && !entry.path.some((ancestor) => selected.has(ancestor))) {+ outer.push(entry);+ }+ }+ return outer;+};++/** The child list `parentId` names, read through the index; `null` when the parent is not a group of `stack`. */+export const childrenAt = (+ index: CanvasDocumentIndex,+ stack: CanvasLayerStackKind,+ parentId: string | null+): readonly CanvasNodeContract[] | null => {+ if (parentId === null) {+ return index.stacks[stack];+ }+ const parent = index.byId.get(parentId);+ return parent && parent.stack === stack && isGroupNode(parent.node) ? parent.node.children : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.tsindex ce0a2519ff..064fe25166 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts@@ -1,16 +1,19 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasRasterLayerContractV2,CanvasStagingAreaContractV2,- CanvasStateContractV2,+ CanvasStateContractV3,+ CanvasNodeContract,} from '@workbench/canvas-engine/contracts';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it, vi } from 'vitest';import type { DocumentMirrorCallbacks } from './documentMirror';+import { getDocumentLeaves } from './documentIndex';import { createDocumentMirror } from './documentMirror';const rasterLayer = (id: string, overrides: Partial<CanvasRasterLayerContractV2> = {}): CanvasLayerContract => ({@@ -27,15 +30,15 @@ const rasterLayer = (id: string, overrides: Partial<CanvasRasterLayerContractV2>});const makeDoc = (- layers: CanvasLayerContract[],- overrides: Partial<CanvasDocumentContractV2> = {}-): CanvasDocumentContractV2 => ({+ layers: CanvasNodeContract[],+ overrides: Partial<CanvasDocumentContractV3> = {}+): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 100,...overrides,});@@ -49,17 +52,17 @@ const makeStaging = (): CanvasStagingAreaContractV2 => ({selectedImageIndex: 0,});-const makeCanvas = (document: CanvasDocumentContractV2, documentRevision = 0): CanvasStateContractV2 => ({+const makeCanvas = (document: CanvasDocumentContractV3, documentRevision = 0): CanvasStateContractV3 => ({document,documentRevision,snapshots: [],stagingArea: makeStaging(),- version: 2,+ version: 3,});interface FakeProject {id: string;- canvas: CanvasStateContractV2;+ canvas: CanvasStateContractV3;}const createFakeStore = (projects: FakeProject[]) => {@@ -95,7 +98,7 @@ const spyCallbacks = () => ({});describe('createDocumentMirror: selection changes', () => {- const withSelection = (doc: CanvasDocumentContractV2, selectedLayerId: string | null): CanvasDocumentContractV2 => ({+ const withSelection = (doc: CanvasDocumentContractV3, selectedLayerId: string | null): CanvasDocumentContractV3 => ({...doc,selectedLayerId,});@@ -112,7 +115,7 @@ describe('createDocumentMirror: selection changes', () => {createDocumentMirror(store, 'p1', callbacks);const nextDoc = withSelection(doc, 'b');- expect(nextDoc.layers).toBe(doc.layers);+ expect(nextDoc.stacks).toBe(doc.stacks);store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });expect(callbacks.onSelectionChanged).toHaveBeenCalledTimes(1);@@ -131,7 +134,7 @@ describe('createDocumentMirror: selection changes', () => {const callbacks = spyCallbacks();createDocumentMirror(store, 'p1', callbacks);- const nextDoc: CanvasDocumentContractV2 = { ...doc, layers: [{ ...a, opacity: 0.5 }] };+ const nextDoc: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([{ ...a, opacity: 0.5 }]) };store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenCalledTimes(1);@@ -147,7 +150,7 @@ describe('createDocumentMirror: selection changes', () => {const callbacks = spyCallbacks();createDocumentMirror(store, 'p1', callbacks);- const nextDoc: CanvasDocumentContractV2 = { ...doc, layers: [b], selectedLayerId: 'b' };+ const nextDoc: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([b]), selectedLayerId: 'b' };store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenCalledTimes(1);@@ -178,7 +181,7 @@ describe('createDocumentMirror', () => {const store = createFakeStore([{ canvas, id: 'p1' }]);const callbacks = spyCallbacks();const mirror = createDocumentMirror(store, 'p1', callbacks);- const updated: CanvasDocumentContractV2 = { ...doc, layers: [{ ...a, opacity: 0.5 }] };+ const updated: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([{ ...a, opacity: 0.5 }]) };store.replaceStateSilently({ projects: [{ canvas: { ...canvas, document: updated }, id: 'p1' }] });expect(mirror.getDocument()).toBe(doc);@@ -201,7 +204,7 @@ describe('createDocumentMirror', () => {// Replace only layer `a` (new object), keep `b` identity. A prop-only edit// (like the reducer's `updateCanvasLayer`) keeps the `source` reference, so// the id is reported as changed but NOT source-changed.- const nextDoc: CanvasDocumentContractV2 = { ...doc, layers: [{ ...a, opacity: 0.5 }, b] };+ const nextDoc: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([{ ...a, opacity: 0.5 }, b]) };store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenCalledTimes(1);@@ -221,15 +224,17 @@ describe('createDocumentMirror', () => {// Prop-only edit (opacity): spreading the prior layer preserves its `source`// reference exactly as the reducer does, so the engine must NOT re-rasterize// (which would clear an unflushed paint layer).- const opacityEdit: CanvasDocumentContractV2 = { ...doc, layers: [{ ...a, opacity: 0.5 }] };+ const opacityEdit: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([{ ...a, opacity: 0.5 }]) };store.setState({ projects: [{ canvas: { ...canvas, document: opacityEdit }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], []);// Genuine source swap (new `source` object): reported as source-changed.- const swapped = store.getState().projects[0]!.canvas.document.layers[0] as CanvasRasterLayerContractV2;- const sourceSwap: CanvasDocumentContractV2 = {+ const swapped = getDocumentLeaves(store.getState().projects[0]!.canvas.document)[0] as CanvasRasterLayerContractV2;+ const sourceSwap: CanvasDocumentContractV3 = {...doc,- layers: [{ ...swapped, source: { image: { height: 10, imageName: 'a-v2', width: 10 }, type: 'image' } }],+ stacks: stacksFrom([+ { ...swapped, source: { image: { height: 10, imageName: 'a-v2', width: 10 }, type: 'image' } },+ ]),};store.setState({ projects: [{ canvas: { ...canvas, document: sourceSwap }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], ['a']);@@ -255,18 +260,22 @@ describe('createDocumentMirror', () => {// A fill-only change (new `mask` object, same `bitmap` ref): reported as// changed but NOT source-changed — invalidating would clear unflushed strokes.- const fillEdit: CanvasDocumentContractV2 = {+ const fillEdit: CanvasDocumentContractV3 = {...doc,- layers: [{ ...mask, mask: { bitmap: null, fill: { color: '#00ff00', style: 'grid' } } }],+ stacks: stacksFrom([{ ...mask, mask: { bitmap: null, fill: { color: '#00ff00', style: 'grid' } } }]),};store.setState({ projects: [{ canvas: { ...canvas, document: fillEdit }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['m'], []);// A bitmap swap (persistence round-trip / undo): reported as source-changed.- const current = store.getState().projects[0]!.canvas.document.layers[0] as CanvasInpaintMaskLayerContract;- const bitmapSwap: CanvasDocumentContractV2 = {+ const current = getDocumentLeaves(+ store.getState().projects[0]!.canvas.document+ )[0] as CanvasInpaintMaskLayerContract;+ const bitmapSwap: CanvasDocumentContractV3 = {...doc,- layers: [{ ...current, mask: { ...current.mask, bitmap: { height: 20, imageName: 'mask-v1', width: 30 } } }],+ stacks: stacksFrom([+ { ...current, mask: { ...current.mask, bitmap: { height: 20, imageName: 'mask-v1', width: 30 } } },+ ]),};store.setState({ projects: [{ canvas: { ...canvas, document: bitmapSwap }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['m'], ['m']);@@ -282,11 +291,13 @@ describe('createDocumentMirror', () => {const b = rasterLayer('b');// Added layers are reported as source-changed (no prior cache to keep).- store.setState({ projects: [{ canvas: { ...canvas, document: { ...doc, layers: [b, a] } }, id: 'p1' }] });+ store.setState({+ projects: [{ canvas: { ...canvas, document: { ...doc, stacks: stacksFrom([b, a]) } }, id: 'p1' }],+ });expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['b'], ['b']);// A removal is a change but not a source change (the id has no incoming source).- store.setState({ projects: [{ canvas: { ...canvas, document: { ...doc, layers: [b] } }, id: 'p1' }] });+ store.setState({ projects: [{ canvas: { ...canvas, document: { ...doc, stacks: stacksFrom([b]) } }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], []);});@@ -300,7 +311,9 @@ describe('createDocumentMirror', () => {createDocumentMirror(store, 'p1', callbacks);// New array reference, same element references, swapped order.- store.setState({ projects: [{ canvas: { ...canvas, document: { ...doc, layers: [b, a] } }, id: 'p1' }] });+ store.setState({+ projects: [{ canvas: { ...canvas, document: { ...doc, stacks: stacksFrom([b, a]) } }, id: 'p1' }],+ });expect(callbacks.onLayerOrderChanged).toHaveBeenCalledTimes(1);expect(callbacks.onLayersChanged).not.toHaveBeenCalled();@@ -318,7 +331,9 @@ describe('createDocumentMirror', () => {createDocumentMirror(store, 'p1', callbacks);// New array reference, same element references, same order: a true no-op churn.- store.setState({ projects: [{ canvas: { ...canvas, document: { ...doc, layers: [a, b] } }, id: 'p1' }] });+ store.setState({+ projects: [{ canvas: { ...canvas, document: { ...doc, stacks: stacksFrom([a, b]) } }, id: 'p1' }],+ });expect(callbacks.onLayerOrderChanged).not.toHaveBeenCalled();expect(callbacks.onLayersChanged).not.toHaveBeenCalled();@@ -363,7 +378,7 @@ describe('createDocumentMirror', () => {const callbacks = spyCallbacks();createDocumentMirror(store, 'p1', callbacks);- const nextDoc: CanvasDocumentContractV2 = { ...doc, layers: [{ ...a, opacity: 0.5 }] };+ const nextDoc: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([{ ...a, opacity: 0.5 }]) };store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });expect(callbacks.onDocumentReplaced).not.toHaveBeenCalled();@@ -454,3 +469,68 @@ describe('createDocumentMirror', () => {expect(callbacks.onLayersChanged).not.toHaveBeenCalled();});});++describe('createDocumentMirror: groups', () => {+ const setup = (doc: CanvasDocumentContractV3) => {+ const canvas = makeCanvas(doc);+ const store = createFakeStore([{ canvas, id: 'p1' }]);+ const callbacks = spyCallbacks();+ createDocumentMirror(store, 'p1', callbacks);+ const set = (next: CanvasDocumentContractV3) =>+ store.setState({ projects: [{ canvas: { ...canvas, document: next }, id: 'p1' }] });+ return { callbacks, set };+ };++ it('reports every descendant leaf as changed but not source-changed when a group flag flips', () => {+ const a = rasterLayer('a');+ const b = rasterLayer('b');+ const c = rasterLayer('c');+ const doc = makeDoc([groupContract('g', [a, groupContract('h', [b])]), c]);+ const { callbacks, set } = setup(doc);++ set({ ...doc, stacks: stacksFrom([groupContract('g', [a, groupContract('h', [b])], { isEnabled: false }), c]) });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a', 'b'], []);+ expect(callbacks.onLayerOrderChanged).not.toHaveBeenCalled();+ });++ it('stays silent on a group rename that changes no leaf and no structure', () => {+ const a = rasterLayer('a');+ const doc = makeDoc([groupContract('g', [a])]);+ const { callbacks, set } = setup(doc);++ set({ ...doc, stacks: stacksFrom([groupContract('g', [a], { name: 'Folder' })]) });+ expect(callbacks.onLayersChanged).not.toHaveBeenCalled();+ expect(callbacks.onLayerOrderChanged).not.toHaveBeenCalled();+ });++ it('reports a reparent as an order change when leaves and their effective state are unchanged', () => {+ const a = rasterLayer('a');+ const b = rasterLayer('b');+ const doc = makeDoc([groupContract('g', [a]), b]);+ const { callbacks, set } = setup(doc);++ set({ ...doc, stacks: stacksFrom([groupContract('g', [a, b])]) });+ expect(callbacks.onLayerOrderChanged).toHaveBeenCalledTimes(1);+ expect(callbacks.onLayersChanged).not.toHaveBeenCalled();+ });++ it('reports a reparent into a disabled group as a leaf change', () => {+ const a = rasterLayer('a');+ const b = rasterLayer('b');+ const doc = makeDoc([groupContract('g', [a], { isEnabled: false }), b]);+ const { callbacks, set } = setup(doc);++ set({ ...doc, stacks: stacksFrom([groupContract('g', [a, b], { isEnabled: false })]) });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['b'], []);+ });++ it('reports the leaves of a removed group as removed, never the group id', () => {+ const a = rasterLayer('a');+ const b = rasterLayer('b');+ const doc = makeDoc([groupContract('g', [a]), b]);+ const { callbacks, set } = setup(doc);++ set({ ...doc, stacks: stacksFrom([b]) });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], []);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.tsindex 6079c181cb..68d41ace8f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts@@ -1,32 +1,32 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,+ CanvasLayerContract,CanvasStagingAreaContractV2,- CanvasStateContractV2,+ CanvasStateContractV3,} from '@workbench/canvas-engine/contracts';+import { getDocumentIndex, type CanvasDocumentIndex, type CanvasNodeEntry } from './documentIndex';+import { isGroupNode } from './documentTree';+/** The minimal store shape the mirror depends on (a superset of `WorkbenchStore`). */export interface DocumentMirrorStore {- getCanvasState?(): CanvasStateContractV2 | null;- getState?(): { projects: readonly { id: string; canvas: CanvasStateContractV2 }[] };+ getCanvasState?(): CanvasStateContractV3 | null;+ getState?(): { projects: readonly { id: string; canvas: CanvasStateContractV3 }[] };subscribe(listener: () => void): () => void;}/** Callbacks fired when the mirrored document changes. */export interface DocumentMirrorCallbacks {/**- * One or more layers were added, removed, or replaced (the `changed` ids).- * `sourceChanged` is the subset whose rasterization source (`source` for- * raster/control layers, `mask` for guidance/mask layers) reference changed,- * plus any newly added layer — i.e. the layers whose cached pixels are now- * stale. A prop/transform-only edit reports the id in `changed` but NOT in- * `sourceChanged`, so the engine keeps (rather than clears) its raster cache.+ * One or more leaves were added, removed, replaced, or had their effective state changed by an+ * ancestor (the `changed` ids). `sourceChanged` is the subset whose rasterization source+ * (`source` for raster/control layers, `mask.bitmap` for guidance/mask layers) changed, plus any+ * newly added leaf: the leaves whose cached pixels are now stale. A property, transform, or+ * ancestor-flag change reports the id in `changed` but not in `sourceChanged`, so the engine+ * keeps its raster cache.*/onLayersChanged(changed: string[], sourceChanged: string[]): void;- /**- * The layers array was reordered (a new array reference, same element- * references, different sequence) — recomposite the document with the new- * z-order, but nothing needs re-rasterizing.- */+ /** The forests were restructured without any leaf changing: recomposite with the new order. */onLayerOrderChanged(): void;/** The document was replaced wholesale (dims/background change, appear/disappear) — full invalidate. */onDocumentReplaced(): void;@@ -35,12 +35,10 @@ export interface DocumentMirrorCallbacks {/** The staging area changed. */onStagingChanged(): void;/**- * The document's `selectedLayerId` changed. A selection-only edit produces a- * new `document` object with the SAME `layers` reference and an equal `bbox`,- * so none of the other callbacks fire for it — this is the only signal. The- * engine uses it to repaint selection-derived chrome (the move-tool outline,- * the transform frame) and to close out per-layer transient sessions, since- * the layer panel is the sole authority on which layer is active.+ * The document's `selectedLayerId` changed. A selection-only edit produces a new `document`+ * object with the same `stacks` reference and an equal `bbox`, so none of the other callbacks+ * fire for it. The engine uses it to repaint selection-derived chrome and to close per-layer+ * transient sessions, since the layer panel is the sole authority on which node is active.*/onSelectionChanged?(selectedLayerId: string | null): void;}@@ -48,97 +46,86 @@ export interface DocumentMirrorCallbacks {/** The imperative mirror handle. */export interface DocumentMirror {/** The current mirrored document, or `null` if the project is gone. */- getDocument(): CanvasDocumentContractV2 | null;+ getDocument(): CanvasDocumentContractV3 | null;/** Synchronously reconciles from store state when ordinary notification was interrupted. */refresh(): void;/** Removes the store subscription. */dispose(): void;}-type Bbox = CanvasDocumentContractV2['bbox'];+type Bbox = CanvasDocumentContractV3['bbox'];const bboxEqual = (a: Bbox, b: Bbox): boolean =>a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;/**- * The reference whose change requires re-rasterizing a layer's cache: the- * `source` for raster/control layers, the mask's `bitmap` for guidance/mask- * layers. The reducer preserves this reference across a prop/transform-only edit- * (it spreads `...layer`), so comparing it distinguishes a genuine source swap- * from an opacity/blend/lock/visibility/rename/nudge tweak.- *- * For masks the reference is the mask BITMAP, not the whole `mask` object: the- * cache holds only the alpha stencil, so a fill-only change (colour/style/noise/- * denoise-limit) must NOT invalidate it. Invalidating on a fill tweak would- * re-rasterize from `mask.bitmap` — clearing unflushed brush strokes that live- * only in the cache — while the compositor already reads the fresh fill from the- * mirror at draw time. A genuine bitmap swap (persistence round-trip, undo,- * import) still changes this reference and re-rasterizes (guarded by self-echo).+ * The reference whose change requires re-rasterizing a leaf's cache: the `source` for+ * raster/control layers, the mask's `bitmap` for guidance/mask layers. The reducer preserves this+ * reference across a property-only edit, so comparing it distinguishes a genuine source swap from+ * an opacity/blend/lock/visibility/rename/nudge tweak. For masks the reference is the bitmap, not+ * the whole `mask`: the cache holds only the alpha stencil, so a fill-only change must not clear+ * unflushed strokes that live only in the cache.*/-const rasterSourceRef = (layer: CanvasDocumentContractV2['layers'][number]): unknown =>+const rasterSourceRef = (layer: CanvasLayerContract): unknown =>layer.type === 'raster' || layer.type === 'control' ? layer.source : layer.mask.bitmap;+const effectiveKey = (entry: CanvasNodeEntry): string =>+ `${entry.ancestorsEnabled ? 1 : 0}${entry.ancestorsLocked ? 1 : 0}${entry.ancestorsHidden ? 1 : 0}`;++interface ForestDiff {+ changed: string[];+ sourceChanged: string[];+ restructured: boolean;+}+/**- * Diffs two layer arrays by object identity, keyed by layer id. Returns the ids- * of layers that were added, removed, or replaced (`changed`), and the subset- * whose rasterization source reference changed or that were newly added- * (`sourceChanged`) — the layers whose cached pixels are now stale.+ * Diffs two forests by leaf identity and ancestor-effective state. A leaf whose object is unchanged+ * but whose ancestors now enable, lock or hide it differently is reported as changed, because its+ * rendered contribution changed even though nothing about it did.*/-const diffLayers = (- prev: readonly CanvasDocumentContractV2['layers'][number][],- next: readonly CanvasDocumentContractV2['layers'][number][]-): { changed: string[]; sourceChanged: string[] } => {- const prevById = new Map(prev.map((layer) => [layer.id, layer]));- const nextById = new Map(next.map((layer) => [layer.id, layer]));+const diffForests = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex): ForestDiff => {const changed = new Set<string>();const sourceChanged = new Set<string>();-- for (const layer of next) {- const before = prevById.get(layer.id);+ let restructured = false;+ for (const entry of next.nodes) {+ const before = prev.byId.get(entry.node.id);if (!before) {- // Added: no prior cache, so its source is new by definition.- changed.add(layer.id);- sourceChanged.add(layer.id);- } else if (before !== layer) {- changed.add(layer.id);- if (rasterSourceRef(before) !== rasterSourceRef(layer)) {- sourceChanged.add(layer.id);+ restructured = true;+ if (!isGroupNode(entry.node)) {+ changed.add(entry.node.id);+ sourceChanged.add(entry.node.id);}+ continue;}- }- for (const layer of prev) {- if (!nextById.has(layer.id)) {- // Removed: reported so the engine drops its cache. Not a source change.- changed.add(layer.id);+ if (before.parentId !== entry.parentId || before.order !== entry.order) {+ restructured = true;+ }+ if (isGroupNode(entry.node)) {+ continue;+ }+ if (before.node !== entry.node) {+ changed.add(entry.node.id);+ if (rasterSourceRef(before.node as CanvasLayerContract) !== rasterSourceRef(entry.node)) {+ sourceChanged.add(entry.node.id);+ }+ } else if (effectiveKey(before) !== effectiveKey(entry)) {+ changed.add(entry.node.id);}}- return { changed: [...changed], sourceChanged: [...sourceChanged] };-};--/**- * True when two layer arrays hold the same ids in a different sequence.- * Only meaningful to call once `diffLayers` has already confirmed no id was- * added, removed, or replaced by reference.- */-const layerOrderChanged = (- prev: readonly CanvasDocumentContractV2['layers'][number][],- next: readonly CanvasDocumentContractV2['layers'][number][]-): boolean => {- if (prev.length !== next.length) {- return true;- }- for (let i = 0; i < prev.length; i++) {- if (prev[i]?.id !== next[i]?.id) {- return true;+ for (const entry of prev.nodes) {+ if (!next.byId.has(entry.node.id)) {+ restructured = true;+ if (!isGroupNode(entry.node)) {+ changed.add(entry.node.id);+ }}}- return false;+ return { changed: [...changed], restructured, sourceChanged: [...sourceChanged] };};/**- * Creates a document mirror bound to `projectId`. Subscribes immediately and- * seeds the last-seen references from the current state (so no spurious- * callback fires on creation).+ * Creates a document mirror bound to `projectId`. Subscribes immediately and seeds the last-seen+ * references from the current state, so no spurious callback fires on creation.*/export const createDocumentMirror = (store: DocumentMirrorStore,@@ -150,13 +137,13 @@ export const createDocumentMirror = (if (!callbacks) {throw new Error('DocumentMirror callbacks are required.');}- const selectCanvas = (): CanvasStateContractV2 | null =>+ const selectCanvas = (): CanvasStateContractV3 | null =>store.getCanvasState?.() ??(projectId === null? null: (store.getState?.().projects.find((project) => project.id === projectId)?.canvas ?? null));- let lastDoc: CanvasDocumentContractV2 | null = selectCanvas()?.document ?? null;+ let lastDoc: CanvasDocumentContractV3 | null = selectCanvas()?.document ?? null;let lastRevision: number = selectCanvas()?.documentRevision ?? 0;let lastStaging: CanvasStagingAreaContractV2 | null = selectCanvas()?.stagingArea ?? null;@@ -174,7 +161,6 @@ export const createDocumentMirror = (lastRevision = revision;if (!prevDoc || !doc) {- // Document appeared or disappeared: treat as a full replacement.callbacks.onDocumentReplaced();} else if (revision !== prevRevision ||@@ -182,15 +168,13 @@ export const createDocumentMirror = (prevDoc.height !== doc.height ||prevDoc.background !== doc.background) {- // A wholesale swap (revision bump) or a dims/background change: the pixel- // history no longer describes the live document.callbacks.onDocumentReplaced();} else {- if (prevDoc.layers !== doc.layers) {- const { changed, sourceChanged } = diffLayers(prevDoc.layers, doc.layers);- if (changed.length > 0) {- callbacks.onLayersChanged(changed, sourceChanged);- } else if (layerOrderChanged(prevDoc.layers, doc.layers)) {+ if (prevDoc.stacks !== doc.stacks) {+ const diff = diffForests(getDocumentIndex(prevDoc), getDocumentIndex(doc));+ if (diff.changed.length > 0) {+ callbacks.onLayersChanged(diff.changed, diff.sourceChanged);+ } else if (diff.restructured) {callbacks.onLayerOrderChanged();}}@@ -199,8 +183,6 @@ export const createDocumentMirror = (}}- // Fired last, so an observer that tears down per-layer transient state- // (transform session, floating selection) sees the reconciled layer set.const selectedLayerId = doc?.selectedLayerId ?? null;if (selectedLayerId !== prevSelectedLayerId) {callbacks.onSelectionChanged?.(selectedLayerId);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.tsnew file mode 100644index 0000000000..976dff7c6f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.ts@@ -0,0 +1,128 @@+import type { CanvasGroupContract, CanvasStackForests } from '@workbench/canvas-engine/contracts';++import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { describe, expect, it } from 'vitest';++import { getDocumentIndex, isSelfOrAncestor, outermostNodes } from './documentIndex';+import {+ cloneSubtree,+ collectSubtree,+ collectSubtreeLeaves,+ insertNodes,+ removeNodes,+ subtreeDepth,+ updateNodes,+} from './documentTree';++const layer = layerContract;+const group = groupContract;++/** raster: r1, g1[r2, g2[r3]], r4 · control: c1 */+const stacks = (): CanvasStackForests =>+ stacksFrom([+ layer('r1'),+ group('g1', [layer('r2'), group('g2', [layer('r3')])]),+ layer('r4'),+ layer('c1', 'control'),+ ]);++const g1 = (forest: CanvasStackForests): CanvasGroupContract => forest.raster[1] as CanvasGroupContract;++describe('document tree', () => {+ it('walks subtrees in preorder and measures nesting', () => {+ const forest = stacks();+ expect(collectSubtree(g1(forest)).map((node) => node.id)).toEqual(['g1', 'r2', 'g2', 'r3']);+ expect(collectSubtreeLeaves(g1(forest)).map((node) => node.id)).toEqual(['r2', 'r3']);+ expect(subtreeDepth(g1(forest))).toBe(2);+ expect(subtreeDepth(forest.raster[0]!)).toBe(0);+ expect(subtreeDepth(group('empty'))).toBe(0);+ });++ it('updates nodes in place while sharing every untouched node, and returns the same forests for a no-op', () => {+ const before = stacks();+ const after = updateNodes(before, new Map([['r3', (node) => ({ ...node, name: 'renamed' })]]));++ expect(after).not.toBe(before);+ expect(after.control).toBe(before.control);+ expect(after.raster[0]).toBe(before.raster[0]);+ expect(after.raster[2]).toBe(before.raster[2]);+ expect(g1(after)).not.toBe(g1(before));+ expect(g1(after).children[0]).toBe(g1(before).children[0]);+ expect(collectSubtreeLeaves(g1(after))[1]?.name).toBe('renamed');+ expect(updateNodes(before, new Map([['r3', (node) => node]]))).toBe(before);+ expect(updateNodes(before, new Map([['ghost', (node) => ({ ...node, name: 'x' })]]))).toBe(before);+ });++ it('removes subtrees and shares the untouched forests', () => {+ const before = stacks();+ const after = removeNodes(before, new Set(['g2', 'r4']));++ expect(getDocumentIndex({ stacks: after }).nodes.map((entry) => entry.node.id)).toEqual(['c1', 'r1', 'g1', 'r2']);+ expect(after.control).toBe(before.control);+ expect(removeNodes(before, new Set(['ghost']))).toBe(before);+ });++ it('inserts into the root or a group at a clamped index and refuses a leaf parent', () => {+ const before = stacks();+ expect(+ getDocumentIndex({ stacks: insertNodes(before, 'raster', null, 99, [layer('n')])! }).stacks.raster.at(-1)?.id+ ).toBe('n');+ expect(g1(insertNodes(before, 'raster', 'g1', 1, [layer('n')])!).children.map((node) => node.id)).toEqual([+ 'r2',+ 'n',+ 'g2',+ ]);+ expect(insertNodes(before, 'raster', 'r1', 0, [layer('n')])).toBeNull();+ });++ it('clones a subtree with fresh ids and no shared objects', () => {+ let next = 0;+ const source = g1(stacks());+ const { ids, node } = cloneSubtree(source, () => `id${next++}`);++ expect(collectSubtree(node).map((entry) => entry.id)).toEqual(['id0', 'id1', 'id2', 'id3']);+ expect(ids.get('r3')).toBe('id3');+ expect((node as CanvasGroupContract).children[0]).not.toBe(source.children[0]);+ expect(collectSubtreeLeaves(node)[0]!.transform).not.toBe(collectSubtreeLeaves(source)[0]!.transform);+ });+});++describe('document index', () => {+ it('records parent, path, sibling index, order and ancestor-effective state per node', () => {+ const forest = stacksFrom([+ layer('r1'),+ group('g1', [layer('r2'), group('g2', [layer('r3')], { isLocked: true })], { isEnabled: false }),+ layer('c1', 'control', { isHidden: true } as never),+ ]);+ const index = getDocumentIndex({ stacks: forest });++ expect(index.nodes.map((entry) => entry.node.id)).toEqual(['c1', 'r1', 'g1', 'r2', 'g2', 'r3']);+ expect(index.leaves.map((leaf) => leaf.id)).toEqual(['c1', 'r1', 'r2', 'r3']);+ expect(index.byId.get('r3')).toMatchObject({+ ancestorsEnabled: false,+ ancestorsHidden: false,+ ancestorsLocked: true,+ order: 5,+ parentId: 'g2',+ path: ['g1', 'g2'],+ siblingIndex: 0,+ stack: 'raster',+ });+ expect(index.byId.get('r2')).toMatchObject({ ancestorsEnabled: false, ancestorsLocked: false, siblingIndex: 0 });+ expect(index.byId.get('c1')).toMatchObject({ ancestorsHidden: false, path: [], stack: 'control' });+ expect(index.maxDepth).toBe(2);+ expect(getDocumentIndex({ stacks: forest })).toBe(index);+ });++ it('answers ancestry and keeps only the outermost of a nested selection', () => {+ const index = getDocumentIndex({ stacks: stacks() });+ expect(isSelfOrAncestor(index, 'r3', 'g1')).toBe(true);+ expect(isSelfOrAncestor(index, 'g1', 'g1')).toBe(true);+ expect(isSelfOrAncestor(index, 'r1', 'g1')).toBe(false);+ expect(outermostNodes(index, ['r3', 'g1', 'r4', 'r2']).map((entry) => entry.node.id)).toEqual(['g1', 'r4']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.tsnew file mode 100644index 0000000000..95ed0210c7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts@@ -0,0 +1,223 @@+import type {+ CanvasGroupContract,+ CanvasLayerContract,+ CanvasLayerStackKind,+ CanvasNodeContract,+ CanvasStackForests,+} from '@workbench/canvas-engine/contracts';++export const isGroupNode = (node: CanvasNodeContract): node is CanvasGroupContract => node.type === 'group';++export const isLeafNode = (node: CanvasNodeContract): node is CanvasLayerContract => node.type !== 'group';++/** The child list `parentId` names in `stack`: the forest roots for `null`, else the group's children. */+export const childrenOf = (+ stacks: CanvasStackForests,+ stack: CanvasLayerStackKind,+ parentId: string | null+): readonly CanvasNodeContract[] | null => {+ if (parentId === null) {+ return stacks[stack];+ }+ const group = findNode(stacks[stack], parentId);+ return group && isGroupNode(group) ? group.children : null;+};++const findNode = (nodes: readonly CanvasNodeContract[], id: string): CanvasNodeContract | null => {+ for (const node of nodes) {+ if (node.id === id) {+ return node;+ }+ if (isGroupNode(node)) {+ const found = findNode(node.children, id);+ if (found) {+ return found;+ }+ }+ }+ return null;+};++/** Every node of the subtree rooted at `node`, preorder, including `node`. */+export const collectSubtree = (node: CanvasNodeContract, into: CanvasNodeContract[] = []): CanvasNodeContract[] => {+ into.push(node);+ if (isGroupNode(node)) {+ for (const child of node.children) {+ collectSubtree(child, into);+ }+ }+ return into;+};++/** The leaves of the subtree rooted at `node`, preorder. */+export const collectSubtreeLeaves = (+ node: CanvasNodeContract,+ into: CanvasLayerContract[] = []+): CanvasLayerContract[] => {+ if (isGroupNode(node)) {+ for (const child of node.children) {+ collectSubtreeLeaves(child, into);+ }+ } else {+ into.push(node);+ }+ return into;+};++/** How many levels of groups `node` nests: 0 for a leaf or an empty group. */+export const subtreeDepth = (node: CanvasNodeContract): number =>+ isGroupNode(node) ? node.children.reduce((deepest, child) => Math.max(deepest, subtreeDepth(child) + 1), 0) : 0;++/** A deep copy of the subtree with every id re-minted; `ids` maps old ids to new ones. */+export const cloneSubtree = (+ node: CanvasNodeContract,+ createId: () => string,+ ids = new Map<string, string>()+): { node: CanvasNodeContract; ids: Map<string, string> } => {+ const id = createId();+ ids.set(node.id, id);+ if (isGroupNode(node)) {+ const children = node.children.map((child) => cloneSubtree(child, createId, ids).node);+ return { ids, node: { ...node, children, id } };+ }+ return { ids, node: { ...structuredClone(node), id } };+};++const replaceIn = (+ nodes: readonly CanvasNodeContract[],+ parentId: string,+ replacement: (children: readonly CanvasNodeContract[]) => readonly CanvasNodeContract[]+): readonly CanvasNodeContract[] => {+ let changed = false;+ const next = nodes.map((node) => {+ if (!isGroupNode(node)) {+ return node;+ }+ const children =+ node.id === parentId ? replacement(node.children) : replaceIn(node.children, parentId, replacement);+ if (children === node.children) {+ return node;+ }+ changed = true;+ return { ...node, children: [...children] };+ });+ return changed ? next : nodes;+};++/** Replaces one child list, sharing every untouched node; the same forests when nothing changed. */+export const replaceChildren = (+ stacks: CanvasStackForests,+ stack: CanvasLayerStackKind,+ parentId: string | null,+ children: readonly CanvasNodeContract[]+): CanvasStackForests => {+ const roots = parentId === null ? children : replaceIn(stacks[stack], parentId, () => children);+ return roots === stacks[stack] ? stacks : { ...stacks, [stack]: [...roots] };+};++/**+ * Rewrites every node named by `updates` in place, sharing every untouched node. Groups are+ * rebuilt only along the paths to a changed node; the same forests come back when nothing changed.+ */+export const updateNodes = (+ stacks: CanvasStackForests,+ updates: ReadonlyMap<string, (node: CanvasNodeContract) => CanvasNodeContract>+): CanvasStackForests => {+ if (updates.size === 0) {+ return stacks;+ }+ const visit = (nodes: readonly CanvasNodeContract[]): readonly CanvasNodeContract[] => {+ let changed = false;+ const next = nodes.map((node) => {+ let current = node;+ if (isGroupNode(current)) {+ const children = visit(current.children);+ if (children !== current.children) {+ current = { ...current, children: [...children] };+ }+ }+ const update = updates.get(current.id);+ if (update) {+ current = update(current);+ }+ changed ||= current !== node;+ return current;+ });+ return changed ? next : nodes;+ };+ let result = stacks;+ for (const stack of Object.keys(stacks) as CanvasLayerStackKind[]) {+ const roots = visit(stacks[stack]);+ if (roots !== stacks[stack]) {+ result = result === stacks ? { ...stacks } : result;+ result[stack] = [...roots];+ }+ }+ return result;+};++/** Removes the subtrees rooted at `ids`, sharing every untouched node. */+export const removeNodes = (stacks: CanvasStackForests, ids: ReadonlySet<string>): CanvasStackForests => {+ if (ids.size === 0) {+ return stacks;+ }+ const visit = (nodes: readonly CanvasNodeContract[]): readonly CanvasNodeContract[] => {+ let changed = false;+ const next: CanvasNodeContract[] = [];+ for (const node of nodes) {+ if (ids.has(node.id)) {+ changed = true;+ continue;+ }+ if (isGroupNode(node)) {+ const children = visit(node.children);+ if (children !== node.children) {+ changed = true;+ next.push({ ...node, children: [...children] });+ continue;+ }+ }+ next.push(node);+ }+ return changed ? next : nodes;+ };+ let result = stacks;+ for (const stack of Object.keys(stacks) as CanvasLayerStackKind[]) {+ const roots = visit(stacks[stack]);+ if (roots !== stacks[stack]) {+ result = result === stacks ? { ...stacks } : result;+ result[stack] = [...roots];+ }+ }+ return result;+};++/** Inserts `nodes` into the child list `parentId` names at `index` (clamped), sharing every other node. */+export const insertNodes = (+ stacks: CanvasStackForests,+ stack: CanvasLayerStackKind,+ parentId: string | null,+ index: number,+ nodes: readonly CanvasNodeContract[]+): CanvasStackForests | null => {+ const children = childrenOf(stacks, stack, parentId);+ if (!children) {+ return null;+ }+ const at = Math.max(0, Math.min(index, children.length));+ return replaceChildren(stacks, stack, parentId, [...children.slice(0, at), ...nodes, ...children.slice(at)]);+};++export const EMPTY_STACKS: CanvasStackForests = {+ control: [],+ inpaint_mask: [],+ raster: [],+ regional_guidance: [],+};++export const createEmptyStacks = (): CanvasStackForests => ({+ control: [],+ inpaint_mask: [],+ raster: [],+ regional_guidance: [],+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.test.tsindex 15ee56ce9b..94c3bb92cb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.test.ts@@ -1,102 +1,157 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeContract, CanvasStackForests } from '@workbench/canvas-engine/contracts';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';+import { getDocumentIndex } from './documentIndex';+import { removeNodes } from './documentTree';import {captureInsertionAnchor,captureRestoreAnchor,- insertLayersAtAnchor,- resolveInsertionIndex,+ insertNodesAtAnchor,+ resolveInsertionTarget,} from './insertionAnchors';-const layer = (id: string, type: CanvasLayerContract['type'] = 'raster'): CanvasLayerContract =>- ({ id, type }) as CanvasLayerContract;+const layer = layerContract;+const group = groupContract;++/**+ * raster: r1, g1[r2, g2[r3], r4], r5 · control: c1+ */+const stacks = (): CanvasStackForests =>+ stacksFrom([+ layer('r1'),+ group('g1', [layer('r2'), group('g2', [layer('r3')]), layer('r4')]),+ layer('r5'),+ layer('c1', 'control'),+ ]);-const layers = [layer('i1', 'inpaint_mask'), layer('r1'), layer('c1', 'control'), layer('r2'), layer('r3')];-const ids = (entries: readonly CanvasLayerContract[]): string[] => entries.map((entry) => entry.id);const capture = { editRevision: 7, projectId: 'p' };+const preorder = (forest: CanvasStackForests, stack: 'raster' | 'control' = 'raster'): string[] =>+ getDocumentIndex({ stacks: forest })+ .nodes.filter((entry) => entry.stack === stack)+ .map((entry) => `${' '.repeat(entry.path.length)}${entry.node.id}`);describe('captureInsertionAnchor', () => {- it('anchors above a compatible leaf and remembers the same-stack member above it', () => {- expect(captureInsertionAnchor(layers, { ...capture, aboveId: 'r2', stack: 'raster' })).toEqual({- afterId: 'r1',- beforeId: 'r2',+ it('anchors above a node under its own parent and remembers the sibling above it', () => {+ expect(captureInsertionAnchor(stacks(), { ...capture, aboveId: 'r4', stack: 'raster' })).toEqual({+ afterId: 'g2',+ beforeId: 'r4',capturedEditRevision: 7,+ parentPath: ['g1'],projectId: 'p',stack: 'raster',});- expect(captureInsertionAnchor(layers, { ...capture, aboveId: 'r1', stack: 'raster' })).toMatchObject({+ expect(captureInsertionAnchor(stacks(), { ...capture, aboveId: 'r3', stack: 'raster' })).toMatchObject({afterId: null,- beforeId: 'r1',+ beforeId: 'r3',+ parentPath: ['g1', 'g2'],});});- it('falls back to the stack top for an incompatible, absent, or omitted leaf', () => {- const top = { afterId: null, beforeId: 'r1', capturedEditRevision: 7, projectId: 'p', stack: 'raster' };+ it('anchors inside a group at its top when asked to', () => {+ expect(captureInsertionAnchor(stacks(), { ...capture, insideId: 'g1', stack: 'raster' })).toMatchObject({+ afterId: null,+ beforeId: 'r2',+ parentPath: ['g1'],+ });+ expect(+ captureInsertionAnchor(stacks(), { ...capture, aboveId: 'r5', insideId: 'r1', stack: 'raster' })+ ).toMatchObject({ beforeId: 'r5', parentPath: [] });+ });++ it('falls back to the stack top for an incompatible, absent, or omitted node', () => {+ const top = {+ afterId: null,+ beforeId: 'r1',+ capturedEditRevision: 7,+ parentPath: [],+ projectId: 'p',+ stack: 'raster',+ };- expect(captureInsertionAnchor(layers, { ...capture, aboveId: 'c1', stack: 'raster' })).toEqual(top);- expect(captureInsertionAnchor(layers, { ...capture, aboveId: 'ghost', stack: 'raster' })).toEqual(top);- expect(captureInsertionAnchor(layers, { ...capture, stack: 'raster' })).toEqual(top);- expect(captureInsertionAnchor(layers, { ...capture, stack: 'regional_guidance' })).toMatchObject({+ expect(captureInsertionAnchor(stacks(), { ...capture, aboveId: 'c1', stack: 'raster' })).toEqual(top);+ expect(captureInsertionAnchor(stacks(), { ...capture, aboveId: 'ghost', stack: 'raster' })).toEqual(top);+ expect(captureInsertionAnchor(stacks(), { ...capture, stack: 'raster' })).toEqual(top);+ expect(captureInsertionAnchor(stacks(), { ...capture, stack: 'regional_guidance' })).toMatchObject({afterId: null,beforeId: null,+ parentPath: [],});});});describe('captureRestoreAnchor', () => {- it('captures the same-stack neighbours on both sides', () => {- expect(captureRestoreAnchor(layers, 'r2', 'p', 3)).toEqual({- afterId: 'r1',- beforeId: 'r3',+ it('captures the siblings on both sides and the parent path', () => {+ expect(captureRestoreAnchor(stacks(), 'g2', 'p', 3)).toEqual({+ afterId: 'r2',+ beforeId: 'r4',capturedEditRevision: 3,+ parentPath: ['g1'],projectId: 'p',stack: 'raster',});- expect(captureRestoreAnchor(layers, 'c1', 'p', 3)).toMatchObject({+ expect(captureRestoreAnchor(stacks(), 'c1', 'p', 3)).toMatchObject({afterId: null,beforeId: null,stack: 'control',});- expect(captureRestoreAnchor(layers, 'ghost', 'p', 3)).toBeNull();+ expect(captureRestoreAnchor(stacks(), 'ghost', 'p', 3)).toBeNull();});});-describe('resolveInsertionIndex', () => {- const anchor = captureInsertionAnchor(layers, { ...capture, aboveId: 'r2', stack: 'raster' });+describe('resolveInsertionTarget', () => {+ const anchor = captureInsertionAnchor(stacks(), { ...capture, aboveId: 'r4', stack: 'raster' });- it('lands before a surviving beforeId', () => {- expect(resolveInsertionIndex(layers, anchor)).toBe(3);+ it('lands before a surviving beforeId under its current parent', () => {+ expect(resolveInsertionTarget(stacks(), anchor)).toEqual({ index: 2, parentId: 'g1' });+ });++ it('follows a moved beforeId to its new parent', () => {+ const moved = stacksFrom([+ layer('r4'),+ layer('r1'),+ group('g1', [layer('r2'), group('g2', [layer('r3')])]),+ layer('r5'),+ ]);+ expect(resolveInsertionTarget(moved, anchor)).toEqual({ index: 0, parentId: null });});it('lands after a surviving afterId once beforeId is gone', () => {- const withoutR2 = layers.filter((entry) => entry.id !== 'r2');- expect(resolveInsertionIndex(withoutR2, anchor)).toBe(2);+ expect(resolveInsertionTarget(removeNodes(stacks(), new Set(['r4'])), anchor)).toEqual({+ index: 2,+ parentId: 'g1',+ });});- it('lands at the stack top when neither survives, or at 0 for an empty stack', () => {- const onlyR3 = [layer('i1', 'inpaint_mask'), layer('c1', 'control'), layer('r3')];- expect(resolveInsertionIndex(onlyR3, anchor)).toBe(2);- expect(resolveInsertionIndex([layer('i1', 'inpaint_mask')], anchor)).toBe(0);+ it('lands at the top of the captured parent, then the nearest surviving ancestor, then the stack top', () => {+ const inner = captureInsertionAnchor(stacks(), { ...capture, aboveId: 'r3', stack: 'raster' });+ expect(resolveInsertionTarget(removeNodes(stacks(), new Set(['r3'])), inner)).toEqual({ index: 0, parentId: 'g2' });+ expect(resolveInsertionTarget(removeNodes(stacks(), new Set(['g2'])), inner)).toEqual({ index: 0, parentId: 'g1' });+ expect(resolveInsertionTarget(removeNodes(stacks(), new Set(['g1'])), inner)).toEqual({ index: 0, parentId: null });});it('ignores ids that moved to another stack', () => {- const retyped = layers.map((entry) => (entry.id === 'r2' ? layer('r2', 'control') : entry));- expect(resolveInsertionIndex(retyped, anchor)).toBe(2);+ const retyped = stacksFrom([layer('r1'), group('g1', [layer('r2')]), layer('r4', 'control')]);+ expect(resolveInsertionTarget(retyped, anchor)).toEqual({ index: 0, parentId: 'g1' });});});-describe('insertLayersAtAnchor', () => {- it('splices the inserted layers at the resolved index', () => {- const anchor = captureInsertionAnchor(layers, { ...capture, aboveId: 'r2', stack: 'raster' });- expect(ids(insertLayersAtAnchor(layers, anchor, [layer('n1'), layer('n2')]))).toEqual([- 'i1',- 'r1',- 'c1',- 'n1',- 'n2',- 'r2',- 'r3',- ]);+describe('insertNodesAtAnchor', () => {+ it('splices the nodes at the resolved target and shares every untouched node', () => {+ const before = stacks();+ const anchor = captureInsertionAnchor(before, { ...capture, aboveId: 'r4', stack: 'raster' });+ const after = insertNodesAtAnchor(before, anchor, [layer('n1'), layer('n2')]);++ expect(preorder(after)).toEqual(['r1', 'g1', ' r2', ' g2', ' r3', ' n1', ' n2', ' r4', 'r5']);+ expect(after.control).toBe(before.control);+ expect(after.raster[0]).toBe(before.raster[0]);+ expect((after.raster[1] as { children: CanvasNodeContract[] }).children[1]).toBe(+ (before.raster[1] as { children: CanvasNodeContract[] }).children[1]+ );});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.testStub.tsindex f21845adc5..3a8dd1d82e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.testStub.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.testStub.ts@@ -1,20 +1,22 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasStackForests } from '@workbench/canvas-engine/contracts';-import type { FlatLayerInsertionAnchor } from './insertionAnchors';+import type { CanvasNodeInsertionAnchor } from './insertionAnchors';import type { LayerStackKind } from './layerStacks';+import { EMPTY_STACKS } from './documentTree';import { captureInsertionAnchor } from './insertionAnchors';-export const stackTopAnchor = (projectId: string, stack: LayerStackKind = 'raster'): FlatLayerInsertionAnchor => ({+export const stackTopAnchor = (projectId: string, stack: LayerStackKind = 'raster'): CanvasNodeInsertionAnchor => ({afterId: null,beforeId: null,capturedEditRevision: 0,+ parentPath: [],projectId,stack,});-/** Captures the way the engine does, against whatever `getLayers` returns at call time. */+/** Captures the way the engine does, against whatever `getStacks` returns at call time. */export const createTestInsertionAnchorCapture =- (projectId: string, getLayers: () => readonly CanvasLayerContract[] = () => []) =>- (stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor =>- captureInsertionAnchor(getLayers(), { aboveId, editRevision: 0, projectId, stack });+ (projectId: string, getStacks: () => CanvasStackForests = () => EMPTY_STACKS) =>+ (stack: LayerStackKind, aboveId: string | null): CanvasNodeInsertionAnchor =>+ captureInsertionAnchor(getStacks(), { aboveId, editRevision: 0, projectId, stack });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.tsindex 31cfd7935a..fd8f7e099a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts@@ -1,122 +1,154 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeContract, CanvasStackForests } from '@workbench/canvas-engine/contracts';import type { LayerStackKind } from './layerStacks';+import { indexStacks, type CanvasDocumentIndex } from './documentIndex';+import { insertNodes, isGroupNode } from './documentTree';+/**- * Where a new layer lands in its stack, captured once against the document the caller saw.- * Resolution is exact: before a surviving `beforeId`, else after a surviving `afterId`, else at- * the top of `stack`. Ids that no longer belong to `stack` count as gone. The reducer refuses an- * anchor from another project; a structural commit refuses one captured at an older edit revision.+ * Where new nodes land in their stack, captured once against the document the caller saw.+ * Resolution is exact and in this order: before a surviving `beforeId` under its current parent,+ * after a surviving `afterId` under its current parent, at the top of the surviving captured+ * parent, at the top of the nearest surviving group on the captured parent path, at the top of+ * the stack. Ids that no longer belong to `stack` count as gone. The reducer refuses an anchor+ * from another project; a structural commit refuses one captured at an older edit revision.*/-export interface FlatLayerInsertionAnchor {+export interface CanvasNodeInsertionAnchor {readonly projectId: string;readonly stack: LayerStackKind;+ /** Ancestor ids of the target parent, root first; empty for the stack root. */+ readonly parentPath: readonly string[];readonly beforeId: string | null;readonly afterId: string | null;readonly capturedEditRevision: number;}-export interface FlatLayerInsertion {- readonly anchor: FlatLayerInsertionAnchor;- readonly layers: readonly CanvasLayerContract[];+export interface CanvasNodeInsertion {+ readonly anchor: CanvasNodeInsertionAnchor;+ readonly nodes: readonly CanvasNodeContract[];+}++/** Subtrees to detach and reinsert at `anchor`, keeping their relative order. */+export interface CanvasNodeMove {+ readonly ids: readonly string[];+ readonly anchor: CanvasNodeInsertionAnchor;}export interface InsertionAnchorCapture {readonly projectId: string;readonly stack: LayerStackKind;readonly editRevision: number;- /** Land directly above this layer when it belongs to `stack`; otherwise at the stack top. */+ /** Land directly above this node when it belongs to `stack`; otherwise at the stack top. */readonly aboveId?: string | null;+ /** Land at the top of this group when it belongs to `stack`; takes precedence over `aboveId`. */+ readonly insideId?: string | null;}-const stackMemberIndex = (layers: readonly CanvasLayerContract[], stack: LayerStackKind, id: string | null): number =>- id === null ? -1 : layers.findIndex((layer) => layer.id === id && layer.type === stack);--const nearestAbove = (- layers: readonly CanvasLayerContract[],- index: number,- stack: LayerStackKind-): CanvasLayerContract | undefined => {- for (let position = index - 1; position >= 0; position -= 1) {- if (layers[position]!.type === stack) {- return layers[position];- }- }- return undefined;-};--const nearestBelow = (- layers: readonly CanvasLayerContract[],- index: number,- stack: LayerStackKind-): CanvasLayerContract | undefined => layers.slice(index + 1).find((layer) => layer.type === stack);+export interface ResolvedInsertionTarget {+ readonly parentId: string | null;+ readonly index: number;+}export const captureInsertionAnchor = (- layers: readonly CanvasLayerContract[],+ stacks: CanvasStackForests,capture: InsertionAnchorCapture-): FlatLayerInsertionAnchor => {+): CanvasNodeInsertionAnchor => {const { editRevision, projectId, stack } = capture;- const leafIndex = stackMemberIndex(layers, stack, capture.aboveId ?? null);- if (leafIndex >= 0) {+ const index = indexStacks(stacks);+ const inside = capture.insideId ? index.byId.get(capture.insideId) : undefined;+ if (inside && inside.stack === stack && isGroupNode(inside.node)) {+ return {+ afterId: null,+ beforeId: inside.node.children[0]?.id ?? null,+ capturedEditRevision: editRevision,+ parentPath: [...inside.path, inside.node.id],+ projectId,+ stack,+ };+ }+ const above = capture.aboveId ? index.byId.get(capture.aboveId) : undefined;+ if (above && above.stack === stack) {+ const siblings =+ above.parentId === null+ ? stacks[stack]+ : (index.byId.get(above.parentId)!.node as { children: CanvasNodeContract[] }).children;return {- afterId: nearestAbove(layers, leafIndex, stack)?.id ?? null,- beforeId: layers[leafIndex]!.id,+ afterId: siblings[above.siblingIndex - 1]?.id ?? null,+ beforeId: above.node.id,capturedEditRevision: editRevision,+ parentPath: above.path,projectId,stack,};}return {afterId: null,- beforeId: layers.find((layer) => layer.type === stack)?.id ?? null,+ beforeId: stacks[stack][0]?.id ?? null,capturedEditRevision: editRevision,+ parentPath: [],projectId,stack,};};-/** The anchor that puts `layerId` back between its current same-stack neighbours once removed. */+/** The anchor that puts `nodeId` back between its current siblings once removed. */export const captureRestoreAnchor = (- layers: readonly CanvasLayerContract[],- layerId: string,+ stacks: CanvasStackForests,+ nodeId: string,projectId: string,editRevision: number-): FlatLayerInsertionAnchor | null => {- const index = layers.findIndex((layer) => layer.id === layerId);- if (index < 0) {+): CanvasNodeInsertionAnchor | null => {+ const index = indexStacks(stacks);+ const entry = index.byId.get(nodeId);+ if (!entry) {return null;}- const stack = layers[index]!.type;+ const siblings =+ entry.parentId === null+ ? stacks[entry.stack]+ : (index.byId.get(entry.parentId)!.node as { children: CanvasNodeContract[] }).children;return {- afterId: nearestAbove(layers, index, stack)?.id ?? null,- beforeId: nearestBelow(layers, index, stack)?.id ?? null,+ afterId: siblings[entry.siblingIndex - 1]?.id ?? null,+ beforeId: siblings[entry.siblingIndex + 1]?.id ?? null,capturedEditRevision: editRevision,+ parentPath: entry.path,projectId,- stack,+ stack: entry.stack,};};-export const resolveInsertionIndex = (- layers: readonly CanvasLayerContract[],- anchor: FlatLayerInsertionAnchor-): number => {- const before = stackMemberIndex(layers, anchor.stack, anchor.beforeId);- if (before >= 0) {- return before;+const survivingGroup = (index: CanvasDocumentIndex, stack: LayerStackKind, id: string): boolean => {+ const entry = index.byId.get(id);+ return !!entry && entry.stack === stack && isGroupNode(entry.node);+};++export const resolveInsertionTarget = (+ stacks: CanvasStackForests,+ anchor: CanvasNodeInsertionAnchor+): ResolvedInsertionTarget => {+ const index = indexStacks(stacks);+ const before = anchor.beforeId ? index.byId.get(anchor.beforeId) : undefined;+ if (before && before.stack === anchor.stack) {+ return { index: before.siblingIndex, parentId: before.parentId };}- const after = stackMemberIndex(layers, anchor.stack, anchor.afterId);- if (after >= 0) {- return after + 1;+ const after = anchor.afterId ? index.byId.get(anchor.afterId) : undefined;+ if (after && after.stack === anchor.stack) {+ return { index: after.siblingIndex + 1, parentId: after.parentId };+ }+ for (let position = anchor.parentPath.length - 1; position >= 0; position -= 1) {+ const id = anchor.parentPath[position]!;+ if (survivingGroup(index, anchor.stack, id)) {+ return { index: 0, parentId: id };+ }}- const top = layers.findIndex((layer) => layer.type === anchor.stack);- return top >= 0 ? top : 0;+ return { index: 0, parentId: null };};-export const insertLayersAtAnchor = <Layer extends CanvasLayerContract>(- layers: readonly Layer[],- anchor: FlatLayerInsertionAnchor,- inserted: readonly Layer[]-): Layer[] => {- const index = resolveInsertionIndex(layers, anchor);- return [...layers.slice(0, index), ...inserted, ...layers.slice(index)];+export const insertNodesAtAnchor = (+ stacks: CanvasStackForests,+ anchor: CanvasNodeInsertionAnchor,+ nodes: readonly CanvasNodeContract[]+): CanvasStackForests => {+ const target = resolveInsertionTarget(stacks, anchor);+ return insertNodes(stacks, anchor.stack, target.parentId, target.index, nodes) ?? stacks;};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.tsindex 595f28dd28..533120d86c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts@@ -1,4 +1,7 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/contracts';+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';++import { isGroupNode } from './documentTree';/** Whether the layer takes part in rendering, generation and export. Display hiding never changes this. */export const isLayerContributing = (layer: CanvasLayerContract): boolean => layer.isEnabled;@@ -20,9 +23,12 @@ export type HideableLayer = Extract<CanvasLayerContract, { type: 'control' | 'inexport const isHideableLayer = (layer: CanvasLayerContract): layer is HideableLayer =>layer.type === 'control' || layer.type === 'inpaint_mask' || layer.type === 'regional_guidance';-/** Display only: generation and export never consult it. */+/** Display only: generation and export never consult it. Groups are hideable in overlay stacks. */export const isLayerHidden = (layer: CanvasLayerContract): boolean => isHideableLayer(layer) && layer.isHidden === true;+export const isNodeHidden = (node: CanvasNodeContract): boolean =>+ isGroupNode(node) ? node.isHidden === true : isLayerHidden(node);+/** Whether the layer holds pixels rather than a parametric source. */export const isPixelBackedLayer = (layer: CanvasLayerContract): boolean =>(layer.type === 'raster' || layer.type === 'control') &&@@ -31,3 +37,15 @@ export const isPixelBackedLayer = (layer: CanvasLayerContract): boolean =>/** Enabled, unlocked raster pixels the engine can merge into or delete: masks, control, and parametric sources are not. */export const isMergeableRasterLayer = (layer: CanvasLayerContract): boolean =>isLayerEditable(layer) && layer.type === 'raster' && isPixelBackedLayer(layer);++/** {@link isLayerEditable} with the leaf's ancestors applied: a disabled or locked group gates every descendant. */+export const isLeafEditable = (leaf: SemanticLeaf | null | undefined): leaf is SemanticLeaf =>+ !!leaf && leaf.contributionEnabled && !leaf.effectiveLocked;++/** {@link isLayerPaintable} with the leaf's ancestors applied. */+export const isLeafPaintable = (leaf: SemanticLeaf | null | undefined): leaf is SemanticLeaf =>+ isLeafEditable(leaf) && leaf.layer.type !== 'control';++/** {@link isMergeableRasterLayer} with the leaf's ancestors applied. */+export const isMergeableRasterLeaf = (leaf: SemanticLeaf | null | undefined): leaf is SemanticLeaf =>+ isLeafEditable(leaf) && leaf.layer.type === 'raster' && isPixelBackedLayer(leaf.layer);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.tsindex cfdbcbcbe1..4f81ab4262 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts@@ -1,22 +1,31 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasStackForests } from '@workbench/canvas-engine/contracts';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';+import { getDocumentIndex } from './documentIndex';import {- getStackOrder,- haveSameStackOrders,+ getSiblingOrder,+ haveSameStructure,LAYER_STACK_ORDER,LAYER_STACKS_TOP_FIRST,- moveLayersWithinStacks,- reorderLayerStack,+ moveNodesWithinSiblings,+ reorderSiblings,} from './layerStacks';-const layer = (id: string, type: CanvasLayerContract['type']): CanvasLayerContract =>- ({ id, isEnabled: true, isLocked: false, type }) as CanvasLayerContract;+const layer = layerContract;+const group = groupContract;++/** raster: r1, g1[r2, r3], r4 · control: c1 */+const stacks = (): CanvasStackForests =>+ stacksFrom([layer('r1'), group('g1', [layer('r2'), layer('r3')]), layer('r4'), layer('c1', 'control')]);-const layers = [layer('i1', 'inpaint_mask'), layer('r1', 'raster'), layer('c1', 'control'), layer('r2', 'raster')];-const ids = (entries: readonly CanvasLayerContract[] | null | undefined): string[] | undefined =>- entries?.map((entry) => entry.id);+const ids = (forest: CanvasStackForests | null): string[] | undefined =>+ forest ? getDocumentIndex({ stacks: forest }).nodes.map((entry) => entry.node.id) : undefined;describe('layer stacks', () => {it('declares one composite order and its panel mirror', () => {@@ -24,87 +33,112 @@ describe('layer stacks', () => {expect(LAYER_STACKS_TOP_FIRST).toEqual([...LAYER_STACK_ORDER].reverse());});- it('reads a stack in flat order, empty stacks included', () => {- expect(getStackOrder(layers, 'raster')).toEqual({ orderedIds: ['r1', 'r2'], stack: 'raster' });- expect(getStackOrder(layers, 'regional_guidance')).toEqual({ orderedIds: [], stack: 'regional_guidance' });+ it('reads a sibling list for the root and for a group, empty lists included', () => {+ expect(getSiblingOrder(stacks(), 'raster', null)).toEqual({+ orderedIds: ['r1', 'g1', 'r4'],+ parentId: null,+ stack: 'raster',+ });+ expect(getSiblingOrder(stacks(), 'raster', 'g1')).toEqual({+ orderedIds: ['r2', 'r3'],+ parentId: 'g1',+ stack: 'raster',+ });+ expect(getSiblingOrder(stacks(), 'regional_guidance', null)).toEqual({+ orderedIds: [],+ parentId: null,+ stack: 'regional_guidance',+ });+ expect(getSiblingOrder(stacks(), 'raster', 'r1')).toEqual({ orderedIds: [], parentId: 'r1', stack: 'raster' });});- it('reorders a stack inside its own slots and keeps other layers where they are', () => {- const next = reorderLayerStack(layers, { orderedIds: ['r2', 'r1'], stack: 'raster' });+ it('reorders one sibling list and shares every other node', () => {+ const before = stacks();+ const next = reorderSiblings(before, { orderedIds: ['r3', 'r2'], parentId: 'g1', stack: 'raster' });- expect(ids(next)).toEqual(['i1', 'r2', 'c1', 'r1']);- expect(next?.[0]).toBe(layers[0]);+ expect(ids(next)).toEqual(['c1', 'r1', 'g1', 'r3', 'r2', 'r4']);+ expect(next?.control).toBe(before.control);+ expect(next?.raster[0]).toBe(before.raster[0]);+ expect(next?.raster[2]).toBe(before.raster[2]);});- it('compares documents by their stack orders, not their flat interleaving', () => {- const interleaved = [- layer('r1', 'raster'),- layer('i1', 'inpaint_mask'),- layer('c1', 'control'),- layer('r2', 'raster'),- ];-- expect(haveSameStackOrders(layers, interleaved)).toBe(true);- expect(haveSameStackOrders(layers, [...layers].reverse())).toBe(false);- expect(haveSameStackOrders(layers, layers.slice(1))).toBe(false);+ it('compares forests by structure, not identity', () => {+ expect(haveSameStructure(stacks(), stacks())).toBe(true);+ expect(+ haveSameStructure(+ stacks(),+ stacksFrom([layer('r1'), group('g1', [layer('r3'), layer('r2')]), layer('r4'), layer('c1', 'control')])+ )+ ).toBe(false);+ expect(+ haveSameStructure(+ stacks(),+ stacksFrom([layer('r1'), layer('r2'), group('g1', [layer('r3')]), layer('r4'), layer('c1', 'control')])+ )+ ).toBe(false);+ expect(+ haveSameStructure(stacks(), stacksFrom([layer('r1'), group('g1', [layer('r2'), layer('r3')]), layer('r4')]))+ ).toBe(false);});- it('accepts an unchanged order, a single-member stack, and an empty stack', () => {- expect(ids(reorderLayerStack(layers, { orderedIds: ['r1', 'r2'], stack: 'raster' }))).toEqual(ids(layers));- expect(ids(reorderLayerStack(layers, { orderedIds: ['c1'], stack: 'control' }))).toEqual(ids(layers));- expect(ids(reorderLayerStack(layers, { orderedIds: [], stack: 'regional_guidance' }))).toEqual(ids(layers));+ it('accepts an unchanged order, a single member, and an empty list', () => {+ expect(ids(reorderSiblings(stacks(), { orderedIds: ['r1', 'g1', 'r4'], parentId: null, stack: 'raster' }))).toEqual(+ ids(stacks())+ );+ expect(ids(reorderSiblings(stacks(), { orderedIds: ['c1'], parentId: null, stack: 'control' }))).toEqual(+ ids(stacks())+ );+ expect(ids(reorderSiblings(stacks(), { orderedIds: [], parentId: null, stack: 'regional_guidance' }))).toEqual(+ ids(stacks())+ );});it.each([- ['a missing member', 'raster', ['r1']],- ['a duplicate', 'raster', ['r1', 'r1']],- ['a foreign id', 'raster', ['r1', 'x']],- ['a member of another stack', 'raster', ['r1', 'c1']],- ['members for an empty stack', 'regional_guidance', ['r1']],- ] as const)('refuses %s', (_label, stack, orderedIds) => {- expect(reorderLayerStack(layers, { orderedIds, stack })).toBeNull();+ ['a missing member', 'raster', null, ['r1']],+ ['a duplicate', 'raster', null, ['r1', 'r1', 'r4']],+ ['a foreign id', 'raster', null, ['r1', 'g1', 'x']],+ ['a member of another list', 'raster', null, ['r1', 'g1', 'r2']],+ ['a leaf as parent', 'raster', 'r1', ['r2']],+ ['members for an empty list', 'regional_guidance', null, ['r1']],+ ] as const)('refuses %s', (_label, stack, parentId, orderedIds) => {+ expect(reorderSiblings(stacks(), { orderedIds, parentId, stack })).toBeNull();});});-describe('moveLayersWithinStacks', () => {- const stacked = [- layer('i1', 'inpaint_mask'),- layer('r1', 'raster'),- layer('g1', 'regional_guidance'),- layer('r2', 'raster'),- layer('i2', 'inpaint_mask'),- layer('r3', 'raster'),- layer('g2', 'regional_guidance'),- layer('r4', 'raster'),- ];-- it('moves selected layers forward one place independently in each stack, top stack first', () => {- expect(moveLayersWithinStacks(stacked, ['i2', 'r2', 'r4', 'g2'], 'forward')).toEqual([- { orderedIds: ['i2', 'i1'], stack: 'inpaint_mask' },- { orderedIds: ['g2', 'g1'], stack: 'regional_guidance' },- { orderedIds: ['r2', 'r1', 'r4', 'r3'], stack: 'raster' },+describe('moveNodesWithinSiblings', () => {+ /** raster: r1, g1[r2, r3, r4], r5 · inpaint: i1, i2 */+ const forest = (): CanvasStackForests =>+ stacksFrom([+ layer('r1'),+ group('g1', [layer('r2'), layer('r3'), layer('r4')]),+ layer('r5'),+ layer('i1', 'inpaint_mask'),+ layer('i2', 'inpaint_mask'),]);- });+ const index = () => getDocumentIndex({ stacks: forest() });- it('moves selected layers to the back of their own stacks while preserving their order', () => {- expect(moveLayersWithinStacks(stacked, ['i1', 'r1', 'r3', 'g1'], 'back')).toEqual([- { orderedIds: ['i2', 'i1'], stack: 'inpaint_mask' },- { orderedIds: ['g2', 'g1'], stack: 'regional_guidance' },- { orderedIds: ['r2', 'r4', 'r1', 'r3'], stack: 'raster' },+ it('moves selected nodes one place within each sibling list, lists ordered by their first selected member', () => {+ expect(moveNodesWithinSiblings(index(), ['i2', 'r3', 'r5'], 'forward')).toEqual([+ { orderedIds: ['i2', 'i1'], parentId: null, stack: 'inpaint_mask' },+ { orderedIds: ['r3', 'r2', 'r4'], parentId: 'g1', stack: 'raster' },+ { orderedIds: ['r1', 'r5', 'g1'], parentId: null, stack: 'raster' },]);});- it('moves a single layer one step or to the boundary', () => {- expect(moveLayersWithinStacks(stacked, ['r3'], 'backward')).toEqual([- { orderedIds: ['r1', 'r2', 'r4', 'r3'], stack: 'raster' },+ it('moves a selection to the back of its own list while preserving its order', () => {+ expect(moveNodesWithinSiblings(index(), ['r2', 'r3'], 'back')).toEqual([+ { orderedIds: ['r4', 'r2', 'r3'], parentId: 'g1', stack: 'raster' },]);- expect(moveLayersWithinStacks(stacked, ['r3'], 'front')).toEqual([- { orderedIds: ['r3', 'r1', 'r2', 'r4'], stack: 'raster' },+ });++ it('moves a selected group with its descendants and ignores selected descendants of a selected ancestor', () => {+ expect(moveNodesWithinSiblings(index(), ['g1', 'r3'], 'front')).toEqual([+ { orderedIds: ['g1', 'r1', 'r5'], parentId: null, stack: 'raster' },]);});- it('returns no commands when every selected layer is already at the requested boundary', () => {- expect(moveLayersWithinStacks(stacked, ['i1', 'r1', 'g1'], 'front')).toEqual([]);- expect(moveLayersWithinStacks(stacked, ['ghost'], 'front')).toEqual([]);+ it('returns no commands when every selected node is already at the requested boundary', () => {+ expect(moveNodesWithinSiblings(index(), ['r1', 'r2', 'i1'], 'front')).toEqual([]);+ expect(moveNodesWithinSiblings(index(), ['ghost'], 'front')).toEqual([]);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.tsindex 6a3a8380c5..23b9170920 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts@@ -1,11 +1,19 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type {+ CanvasLayerContract,+ CanvasLayerStackKind,+ CanvasNodeContract,+ CanvasStackForests,+} from '@workbench/canvas-engine/contracts';++import { childrenAt, indexStacks, type CanvasDocumentIndex } from './documentIndex';+import { childrenOf, isGroupNode, replaceChildren } from './documentTree';/**- * The four flat stacks of a v2 document. A layer's stack is its type; the compositor draws the- * stacks bottom to top in {@link LAYER_STACK_ORDER} and the Layers panel lists them top first, so a- * layer's index in `document.layers` only orders it against other members of its own stack.+ * The four stack forests of a v3 document. The compositor draws the stacks bottom to top in+ * {@link LAYER_STACK_ORDER} and the Layers panel lists them top first; within a stack, nodes are+ * ordered by their depth-first preorder position, top first.*/-export type LayerStackKind = CanvasLayerContract['type'];+export type LayerStackKind = CanvasLayerStackKind;export type OverlayStackKind = Exclude<LayerStackKind, 'raster'>;@@ -15,60 +23,74 @@ export const LAYER_STACKS_TOP_FIRST: readonly LayerStackKind[] = [...LAYER_STACKexport const layerStackOf = (layer: CanvasLayerContract): LayerStackKind => layer.type;-/** Reorders one stack; `orderedIds` must be exactly the stack's current members, top first. */-export interface ReorderFlatStackCommand {+export const isOverlayStack = (stack: LayerStackKind): stack is OverlayStackKind => stack !== 'raster';++/** Reorders one sibling list; `orderedIds` must be exactly the parent's current children, top first. */+export interface ReorderSiblingsCommand {readonly stack: LayerStackKind;+ readonly parentId: string | null;readonly orderedIds: readonly string[];}-export const getStackOrder = (- layers: readonly CanvasLayerContract[],- stack: LayerStackKind-): ReorderFlatStackCommand => ({- orderedIds: layers.filter((layer) => layer.type === stack).map((layer) => layer.id),+export const getSiblingOrder = (+ stacks: CanvasStackForests,+ stack: LayerStackKind,+ parentId: string | null+): ReorderSiblingsCommand => ({+ orderedIds: (childrenOf(stacks, stack, parentId) ?? []).map((node) => node.id),+ parentId,stack,});+const sameIds = (a: readonly string[], b: readonly string[]): boolean =>+ a.length === b.length && a.every((id, index) => id === b[index]);+/**- * Writes the command's order back into the flat slots its stack occupies, leaving every other- * stack untouched. Returns `null` when the ids are not exactly the stack's members.+ * Writes the command's order back into its parent's child list, leaving every other node untouched.+ * Returns `null` when the ids are not exactly the parent's children.*/-export const reorderLayerStack = <Layer extends CanvasLayerContract>(- layers: readonly Layer[],- command: ReorderFlatStackCommand-): Layer[] | null => {- const slots: number[] = [];- const byId = new Map<string, Layer>();- layers.forEach((layer, index) => {- if (layer.type === command.stack) {- slots.push(index);- byId.set(layer.id, layer);- }- });- if (command.orderedIds.length !== slots.length || new Set(command.orderedIds).size !== slots.length) {+export const reorderSiblings = (+ stacks: CanvasStackForests,+ command: ReorderSiblingsCommand+): CanvasStackForests | null => {+ const children = childrenOf(stacks, command.stack, command.parentId);+ if (!children || children.length !== command.orderedIds.length) {return null;}- const next = [...layers];- for (const [position, id] of command.orderedIds.entries()) {- const layer = byId.get(id);- if (!layer) {+ const byId = new Map(children.map((node) => [node.id, node]));+ if (byId.size !== command.orderedIds.length || new Set(command.orderedIds).size !== command.orderedIds.length) {+ return null;+ }+ const next: CanvasNodeContract[] = [];+ for (const id of command.orderedIds) {+ const node = byId.get(id);+ if (!node) {return null;}- next[slots[position]!] = layer;+ next.push(node);}- return next;+ return next.every((node, index) => node === children[index])+ ? stacks+ : replaceChildren(stacks, command.stack, command.parentId, next);};-/** Whether both documents hold the same members in the same order within every stack. */-export const haveSameStackOrders = (a: readonly CanvasLayerContract[], b: readonly CanvasLayerContract[]): boolean =>- a.length === b.length &&- LAYER_STACK_ORDER.every((stack) => {- const left = getStackOrder(a, stack).orderedIds;- const right = getStackOrder(b, stack).orderedIds;- return left.length === right.length && left.every((id, index) => id === right[index]);- });+/** Whether both forests hold the same nodes under the same parents in the same order, per stack. */+export const haveSameStructure = (a: CanvasStackForests, b: CanvasStackForests): boolean => {+ if (a === b) {+ return true;+ }+ const left = indexStacks(a).nodes;+ const right = indexStacks(b).nodes;+ return (+ left.length === right.length &&+ left.every((entry, index) => {+ const other = right[index]!;+ return entry.node.id === other.node.id && entry.parentId === other.parentId && entry.stack === other.stack;+ })+ );+};-/** A z-move within a stack; index 0 is the front (top). */+/** A z-move among siblings; index 0 is the front (top). */export type LayerStackMoveKind = 'front' | 'forward' | 'backward' | 'back';const moveSelectedIds = (@@ -99,22 +121,37 @@ const moveSelectedIds = (};/**- * Moves every selected layer within its own stack, selected members keeping their relative order.- * Returns one command per stack whose order changes, top stack first.+ * Moves every selected node among its own siblings, selected members keeping their relative order.+ * A selected node whose ancestor is also selected moves with the ancestor. Returns one command per+ * sibling list whose order changes, in document order.*/-export const moveLayersWithinStacks = (- layers: readonly CanvasLayerContract[],+export const moveNodesWithinSiblings = (+ index: CanvasDocumentIndex,selectedIds: readonly string[],kind: LayerStackMoveKind-): ReorderFlatStackCommand[] => {+): ReorderSiblingsCommand[] => {const selected = new Set(selectedIds);- const commands: ReorderFlatStackCommand[] = [];- for (const stack of LAYER_STACKS_TOP_FIRST) {- const { orderedIds } = getStackOrder(layers, stack);+ const parents: { stack: LayerStackKind; parentId: string | null }[] = [];+ const seen = new Set<string>();+ for (const entry of index.nodes) {+ if (!selected.has(entry.node.id) || entry.path.some((ancestor) => selected.has(ancestor))) {+ continue;+ }+ const key = `${entry.stack}\0${entry.parentId ?? ''}`;+ if (!seen.has(key)) {+ seen.add(key);+ parents.push({ parentId: entry.parentId, stack: entry.stack });+ }+ }+ const commands: ReorderSiblingsCommand[] = [];+ for (const { parentId, stack } of parents) {+ const orderedIds = (childrenAt(index, stack, parentId) ?? []).map((node) => node.id);const moved = moveSelectedIds(orderedIds, selected, kind);- if (moved.some((id, index) => id !== orderedIds[index])) {- commands.push({ orderedIds: moved, stack });+ if (!sameIds(moved, orderedIds)) {+ commands.push({ orderedIds: moved, parentId, stack });}}return commands;};++export { isGroupNode };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.tsindex 1705c36f1c..07c7fe4d76 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts@@ -1,9 +1,11 @@-import type {- CanvasInpaintMaskLayerContract,- CanvasLayerContract,- CanvasRasterLayerContractV2,-} from '@workbench/canvas-engine/contracts';+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import {+ documentFrom,+ groupContract,+ layerContract,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';import { describe, expect, it } from 'vitest';import {@@ -13,31 +15,8 @@ import {getMergeVisibleRasterLayers,} from './mergeVisible';-const raster = (id: string, overrides: Partial<CanvasRasterLayerContractV2> = {}): CanvasRasterLayerContractV2 => ({- blendMode: 'normal',- id,- isEnabled: true,- isLocked: false,- name: id,- opacity: 1,- source: { bitmap: null, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- ...overrides,-});--const mask = (id: string): CanvasInpaintMaskLayerContract => ({- blendMode: 'normal',- id,- isEnabled: true,- isLocked: false,- mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' } },- name: id,- opacity: 1,- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'inpaint_mask',-});-+const raster = (id: string, overrides: Partial<CanvasLayerContract> = {}) => layerContract(id, 'raster', overrides);+const mask = (id: string) => layerContract(id, 'inpaint_mask');const gradientRaster = (id: string): CanvasLayerContract =>raster(id, {source: {@@ -51,82 +30,86 @@ const gradientRaster = (id: string): CanvasLayerContract =>type: 'gradient',width: 10,},- });+ } as Partial<CanvasLayerContract>);-describe('getMergeVisibleRasterLayers', () => {- const hasContent = (id: string): boolean => id !== 'empty';+const hasContent = (id: string): boolean => id !== 'empty';+const leavesOf = (nodes: Parameters<typeof documentFrom>[0]) => compileDocumentLeaves(documentFrom(nodes));- it('returns every visible raster with content in stack order', () => {- const layers = [+describe('getMergeVisibleRasterLayers', () => {+ it('returns every contributing raster with content in stack order, descending into groups', () => {+ const leaves = leavesOf([raster('top'),mask('mask'),- raster('hidden', { isEnabled: false }),+ groupContract('g', [raster('inner'), raster('hidden', { isEnabled: false })]),+ groupContract('off', [raster('gated')], { isEnabled: false }),raster('locked', { isLocked: true }),gradientRaster('gradient'),raster('empty'),raster('bottom'),- ];+ ]);- expect(getMergeVisibleRasterLayers(layers, hasContent).map((layer) => layer.id)).toEqual([+ expect(getMergeVisibleRasterLayers(leaves, hasContent).map((layer) => layer.id)).toEqual(['top',+ 'inner','locked','gradient','bottom',]);- expect(canMergeVisibleRasters(layers, hasContent)).toBe(true);+ expect(canMergeVisibleRasters(leaves, hasContent)).toBe(true);});- it('requires at least two visible raster layers with content', () => {- expect(canMergeVisibleRasters([raster('one')], hasContent)).toBe(false);- expect(canMergeVisibleRasters([raster('one'), raster('hidden', { isEnabled: false })], hasContent)).toBe(false);- expect(canMergeVisibleRasters([raster('one'), raster('empty')], hasContent)).toBe(false);+ it('requires at least two contributing raster layers with content', () => {+ expect(canMergeVisibleRasters(leavesOf([raster('one')]), hasContent)).toBe(false);+ expect(canMergeVisibleRasters(leavesOf([raster('one'), raster('hidden', { isEnabled: false })]), hasContent)).toBe(+ false+ );+ expect(canMergeVisibleRasters(leavesOf([raster('one'), raster('empty')]), hasContent)).toBe(false);expect(canMergeVisibleRasters([], hasContent)).toBe(false);});});describe('merge-selected eligibility', () => {- const hasContent = (id: string): boolean => id !== 'empty';-- it('treats other layer groups as harmless gaps in a contiguous raster selection', () => {- const layers = [raster('top'), mask('mask'), raster('bottom')];- const selected = new Set(['top', 'bottom']);+ const check = (nodes: Parameters<typeof documentFrom>[0], ids: string[]) => {+ const document = documentFrom(nodes);+ const selected = new Set(ids);+ return {+ contiguous: areSelectedRasterLayersContiguous(document, selected),+ mergeable: canMergeSelectedRasters(document, compileDocumentLeaves(document), selected, hasContent),+ };+ };- expect(areSelectedRasterLayersContiguous(layers, selected)).toBe(true);- expect(canMergeSelectedRasters(layers, selected, hasContent)).toBe(true);+ it('accepts adjacent raster siblings at the root or inside one group', () => {+ expect(check([raster('top'), raster('bottom'), mask('mask')], ['top', 'bottom'])).toEqual({+ contiguous: true,+ mergeable: true,+ });+ expect(check([groupContract('g', [raster('a'), raster('b')])], ['a', 'b'])).toEqual({+ contiguous: true,+ mergeable: true,+ });});- it('rejects a selection spanning an unselected raster', () => {- const layers = [raster('top'), raster('middle'), raster('bottom')];- const selected = new Set(['top', 'bottom']);-- expect(areSelectedRasterLayersContiguous(layers, selected)).toBe(false);- expect(canMergeSelectedRasters(layers, selected, hasContent)).toBe(false);+ it('rejects a selection spanning an unselected sibling, a group, or two parents', () => {+ expect(check([raster('top'), raster('middle'), raster('bottom')], ['top', 'bottom']).contiguous).toBe(false);+ expect(+ check([raster('top'), groupContract('g', [raster('x')]), raster('bottom')], ['top', 'bottom']).contiguous+ ).toBe(false);+ expect(check([raster('top'), groupContract('g', [raster('inner')])], ['top', 'inner']).contiguous).toBe(false);+ expect(check([raster('top'), groupContract('g', [raster('inner')])], ['top', 'g']).contiguous).toBe(false);});- it('rejects empty, locked, hidden, or non-normal raster contributors', () => {- expect(canMergeSelectedRasters([raster('top'), raster('empty')], new Set(['top', 'empty']), hasContent)).toBe(+ it('rejects empty, locked, gated, disabled, or non-normal raster contributors', () => {+ expect(check([raster('top'), raster('empty')], ['top', 'empty']).mergeable).toBe(false);+ expect(check([raster('top'), raster('bottom', { isLocked: true })], ['top', 'bottom']).mergeable).toBe(false);+ expect(check([raster('top'), raster('bottom', { isEnabled: false })], ['top', 'bottom']).mergeable).toBe(false);+ expect(check([raster('top'), raster('bottom', { blendMode: 'multiply' })], ['top', 'bottom']).mergeable).toBe(+ false+ );+ expect(check([groupContract('g', [raster('a'), raster('b')], { isLocked: true })], ['a', 'b']).mergeable).toBe(+ false+ );+ expect(check([groupContract('g', [raster('a'), raster('b')], { isEnabled: false })], ['a', 'b']).mergeable).toBe(false);- expect(- canMergeSelectedRasters(- [raster('top'), raster('bottom', { isLocked: true })],- new Set(['top', 'bottom']),- hasContent- )- ).toBe(false);- expect(- canMergeSelectedRasters(- [raster('top'), raster('bottom', { isEnabled: false })],- new Set(['top', 'bottom']),- hasContent- )- ).toBe(false);- expect(- canMergeSelectedRasters(- [raster('top'), raster('bottom', { blendMode: 'multiply' })],- new Set(['top', 'bottom']),- hasContent- )- ).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.tsindex 461da729f6..06054b0288 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts@@ -1,50 +1,67 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';-import { isLayerContributing, isLayerEditable } from './layerEligibility';+import { getDocumentIndex } from './documentIndex';+import { isLayerEditable } from './layerEligibility';export type HasMergeVisibleContent = (layerId: string) => boolean;-/** Returns eligible contributors in document order (top-most first). */+/** Contributing raster leaves with content, top first. */export const getMergeVisibleRasterLayers = (- layers: readonly CanvasLayerContract[],+ leaves: readonly SemanticLeaf[],hasContent: HasMergeVisibleContent): CanvasLayerContract[] =>- layers.filter((layer) => layer.type === 'raster' && isLayerContributing(layer) && hasContent(layer.id));+ leaves+ .filter((leaf) => leaf.stack === 'raster' && leaf.contributionEnabled && hasContent(leaf.id))+ .map((leaf) => leaf.layer);-/** Whether the raster group's merge-visible action has at least two contributors. */-export const canMergeVisibleRasters = (- layers: readonly CanvasLayerContract[],- hasContent: HasMergeVisibleContent-): boolean => getMergeVisibleRasterLayers(layers, hasContent).length >= 2;+/** Whether the raster stack's merge-visible action has at least two contributors. */+export const canMergeVisibleRasters = (leaves: readonly SemanticLeaf[], hasContent: HasMergeVisibleContent): boolean =>+ getMergeVisibleRasterLayers(leaves, hasContent).length >= 2;/**- * Destructive merge-selected may only collapse one uninterrupted span of the- * raster stack. Other layer groups do not participate in raster compositing- * order, so a mask/control layer between two selected rasters is harmless; an- * unselected raster between them is not.+ * Destructive merge-selected may only collapse one uninterrupted run of raster siblings: leaves+ * under one parent with nothing between them, since any node in between takes part in the+ * composite between the selected layers.*/export const areSelectedRasterLayersContiguous = (- layers: readonly CanvasLayerContract[],+ document: Pick<CanvasDocumentContractV3, 'stacks'>,selectedLayerIds: ReadonlySet<string>): boolean => {- const rasterLayers = layers.filter((layer) => layer.type === 'raster');- const selectedIndexes = rasterLayers.flatMap((layer, index) => (selectedLayerIds.has(layer.id) ? [index] : []));- if (selectedIndexes.length < 2 || selectedIndexes.length !== selectedLayerIds.size) {+ if (selectedLayerIds.size < 2) {+ return false;+ }+ const index = getDocumentIndex(document);+ const entries = [...selectedLayerIds].map((id) => index.byId.get(id));+ const first = entries[0];+ if (+ !first ||+ entries.some(+ (entry) => !entry || entry.node.type !== 'raster' || entry.stack !== 'raster' || entry.parentId !== first.parentId+ )+ ) {return false;}- return selectedIndexes.at(-1)! - selectedIndexes[0]! + 1 === selectedIndexes.length;+ const positions = entries.map((entry) => entry!.siblingIndex).sort((a, b) => a - b);+ return positions.at(-1)! - positions[0]! + 1 === positions.length;};/** Whether merge-selected can flatten the exact selection without changing the rendered composite. */export const canMergeSelectedRasters = (- layers: readonly CanvasLayerContract[],+ document: Pick<CanvasDocumentContractV3, 'stacks'>,+ leaves: readonly SemanticLeaf[],selectedLayerIds: ReadonlySet<string>,hasContent: HasMergeVisibleContent): boolean =>- areSelectedRasterLayersContiguous(layers, selectedLayerIds) &&- layers- .filter((layer) => selectedLayerIds.has(layer.id))+ areSelectedRasterLayersContiguous(document, selectedLayerIds) &&+ leaves+ .filter((leaf) => selectedLayerIds.has(leaf.id)).every(- (layer) =>- layer.type === 'raster' && isLayerEditable(layer) && layer.blendMode === 'normal' && hasContent(layer.id)+ (leaf) =>+ leaf.stack === 'raster' &&+ leaf.contributionEnabled &&+ !leaf.effectiveLocked &&+ isLayerEditable(leaf.layer) &&+ leaf.layer.blendMode === 'normal' &&+ hasContent(leaf.id));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.test.tsindex 3a5f64f20f..add7f7a33c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.test.ts@@ -1,52 +1,72 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasStackForests } from '@workbench/canvas-engine/contracts';-import { flatDocument, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import {+ documentFrom,+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { applyCanvasProjectMutation, type CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it } from 'vitest';+import { removeNodes } from './documentTree';import { repairSelectedLayerId } from './selectionRepair';-const layer = (id: string, type: CanvasLayerContract['type'] = 'raster'): CanvasLayerContract =>- ({ id, type }) as CanvasLayerContract;-const previous = ['a', 'b', 'c', 'd'].map((id) => layer(id));-const without = (...ids: string[]) => previous.filter((entry) => !ids.includes(entry.id));+const layer = layerContract;+const group = groupContract;++const previous = (): CanvasStackForests => stacksFrom(['a', 'b', 'c', 'd'].map((id) => layer(id)));+const without = (...ids: string[]): CanvasStackForests => removeNodes(previous(), new Set(ids));describe('repairSelectedLayerId', () => {it.each([- ['keeps a surviving selection', without('a'), 'b', previous, 'b'],- ['keeps null', previous, null, previous, null],- ['moves below first', without('b'), 'b', previous, 'c'],- ['moves above when nothing survives below', without('c', 'd'), 'd', previous, 'b'],- ['moves through a removed run', without('b', 'c'), 'b', previous, 'd'],+ ['keeps a surviving selection', without('a'), 'b', previous(), 'b'],+ ['keeps null', previous(), null, previous(), null],+ ['moves below first', without('b'), 'b', previous(), 'c'],+ ['moves above when nothing survives below', without('c', 'd'), 'd', previous(), 'b'],+ ['moves through a removed run', without('b', 'c'), 'b', previous(), 'd'],['falls back to the top without a previous order', without('b'), 'b', undefined, 'a'],- ['falls back to the top when the selection was never present', without('b'), 'x', previous, 'a'],- ['clears on an empty document', [], 'b', previous, null],- ['clears on an empty document without a previous order', [], 'b', undefined, null],- ])('%s', (_label, layers, selected, previousLayers, expected) => {- expect(repairSelectedLayerId(layers, selected, previousLayers)).toBe(expected);+ ['falls back to the top when the selection was never present', without('b'), 'x', previous(), 'a'],+ ['clears on an empty document', stacksFrom([]), 'b', previous(), null],+ ['clears on an empty document without a previous order', stacksFrom([]), 'b', undefined, null],+ ])('%s', (_label, stacks, selected, previousStacks, expected) => {+ expect(repairSelectedLayerId(stacks, selected, previousStacks)).toBe(expected);});- it('prefers a neighbour in the same stack over a closer one in another stack', () => {- const mixed = [layer('i1', 'inpaint_mask'), layer('r1'), layer('c1', 'control'), layer('r2')];- const withoutR1 = mixed.filter((entry) => entry.id !== 'r1');+ it('prefers a sibling, then the parent, then the nearest node of the same stack', () => {+ /** raster: r1, g1[r2, r3], r4 · control: c1 */+ const tree = stacksFrom([+ layer('r1'),+ group('g1', [layer('r2'), layer('r3')]),+ layer('r4'),+ layer('c1', 'control'),+ ]);++ expect(repairSelectedLayerId(removeNodes(tree, new Set(['r2'])), 'r2', tree)).toBe('r3');+ expect(repairSelectedLayerId(removeNodes(tree, new Set(['r2', 'r3'])), 'r2', tree)).toBe('g1');+ expect(repairSelectedLayerId(removeNodes(tree, new Set(['g1'])), 'r2', tree)).toBe('r4');+ expect(repairSelectedLayerId(removeNodes(tree, new Set(['g1', 'r4'])), 'g1', tree)).toBe('r1');+ expect(repairSelectedLayerId(removeNodes(tree, new Set(['r1', 'g1', 'r4'])), 'g1', tree)).toBe('c1');+ });- expect(repairSelectedLayerId(withoutR1, 'r1', mixed)).toBe('r2');- expect(repairSelectedLayerId([mixed[0]!, mixed[2]!], 'r1', mixed)).toBe('c1');+ it('selects the top node of the top-first stacks when there is no previous order', () => {+ const tree = stacksFrom([layer('r1'), layer('i1', 'inpaint_mask')]);+ expect(repairSelectedLayerId(tree, 'ghost')).toBe('i1');});});describe('selection repair through the reducer', () => {- const layers = () => [- layerContract('i1', 'inpaint_mask'),- layerContract('r1'),- layerContract('c1', 'control'),- layerContract('r2'),- layerContract('r3'),+ const nodes = () => [+ layer('i1', 'inpaint_mask'),+ layer('r1'),+ layer('c1', 'control'),+ group('g1', [layer('r2'), layer('r3')]),+ layer('r4'),];- const reduce = (selectedLayerId: string | null, mutation: CanvasProjectMutation, initialLayers = layers()) => {+ const reduce = (selectedLayerId: string | null, mutation: CanvasProjectMutation) => {const project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {- document: flatDocument(initialLayers, selectedLayerId),+ document: documentFrom(nodes(), selectedLayerId),type: 'replaceCanvasDocument',});return applyCanvasProjectMutation(project, mutation).canvas.document.selectedLayerId;@@ -55,15 +75,15 @@ describe('selection repair through the reducer', () => {it.each<[string, string | null, CanvasProjectMutation, string | null]>([['remove keeps a surviving selection', 'r2', { ids: ['r1'], type: 'removeCanvasLayers' }, 'r2'],- ['remove moves to the same-stack neighbour below', 'r1', { ids: ['r1'], type: 'removeCanvasLayers' }, 'r2'],+ ['remove moves to the sibling below', 'r2', { ids: ['r2'], type: 'removeCanvasLayers' }, 'r3'],[- 'remove moves above within the stack when nothing survives below',+ 'remove moves to the parent when the group empties','r3',- { ids: ['r3'], type: 'removeCanvasLayers' },- 'r2',+ { ids: ['r2', 'r3'], type: 'removeCanvasLayers' },+ 'g1',],- ['remove falls back across stacks when the stack empties', 'c1', { ids: ['c1'], type: 'removeCanvasLayers' }, 'r2'],- ['duplicate selects the copy', 'r1', { newId: 'r1-copy', sourceId: 'r1', type: 'duplicateCanvasLayer' }, 'r1-copy'],+ ['remove of a selected group moves to a stack neighbour', 'g1', { ids: ['g1'], type: 'removeCanvasLayers' }, 'r4'],+ ['remove falls back across stacks when the stack empties', 'c1', { ids: ['c1'], type: 'removeCanvasLayers' }, 'r1'],['merge down moves the selection onto the merged layer','r2',@@ -79,25 +99,25 @@ describe('selection repair through the reducer', () => {['replacement keeps a selection the new document holds','r1',- { document: flatDocument([layerContract('r1')], 'r1'), type: 'replaceCanvasDocument' },+ { document: documentFrom([layer('r1')], 'r1'), type: 'replaceCanvasDocument' },'r1',],['replacement selects the top when its selection is absent','r1',- { document: flatDocument([layerContract('x'), layerContract('y')], 'nope'), type: 'replaceCanvasDocument' },+ { document: documentFrom([layer('x'), layer('y')], 'nope'), type: 'replaceCanvasDocument' },'x',],['an emptied document clears the selection','r1',- { ids: ['i1', 'r1', 'c1', 'r2', 'r3'], type: 'removeCanvasLayers' },+ { ids: ['i1', 'r1', 'c1', 'g1', 'r4'], type: 'removeCanvasLayers' },null,],['an empty replacement clears the selection','r1',- { document: flatDocument([], 'r1'), type: 'replaceCanvasDocument' },+ { document: documentFrom([], 'r1'), type: 'replaceCanvasDocument' },null,],])('%s', (_label, selected, mutation, expected) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.tsindex 7590a17436..8dfc664183 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.ts@@ -1,51 +1,63 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasStackForests } from '@workbench/canvas-engine/contracts';-const nearestSurviving = (- previousLayers: readonly CanvasLayerContract[],- previousIndex: number,- accept: (layer: CanvasLayerContract) => boolean+import { indexStacks, type CanvasDocumentIndex, type CanvasNodeEntry } from './documentIndex';++const nearestInOrder = (+ entries: readonly CanvasNodeEntry[],+ from: number,+ accept: (entry: CanvasNodeEntry) => boolean): string | null => {- for (let index = previousIndex + 1; index < previousLayers.length; index += 1) {- const layer = previousLayers[index]!;- if (accept(layer)) {- return layer.id;+ for (let position = from + 1; position < entries.length; position += 1) {+ if (accept(entries[position]!)) {+ return entries[position]!.node.id;}}- for (let index = previousIndex - 1; index >= 0; index -= 1) {- const layer = previousLayers[index]!;- if (accept(layer)) {- return layer.id;+ for (let position = from - 1; position >= 0; position -= 1) {+ if (accept(entries[position]!)) {+ return entries[position]!.node.id;}}return null;};+const siblingsOf = (index: CanvasDocumentIndex, entry: CanvasNodeEntry): readonly CanvasNodeEntry[] =>+ index.nodes.filter((candidate) => candidate.stack === entry.stack && candidate.parentId === entry.parentId);+/**- * The primary selection after `layers` replaced `previousLayers`. A surviving selection is kept.- * A removed one moves to its nearest surviving neighbour in the previous order, preferring its own- * stack, below first, then above; without a previous order the top layer is selected.+ * The primary selection after `stacks` replaced `previous`. A surviving selection is kept. A removed+ * one moves to its nearest surviving sibling in the previous order (below first, then above), then+ * to its previous parent, then to the nearest surviving node of its stack, then to the nearest+ * surviving node of any stack; without a previous order the top node is selected.*/export const repairSelectedLayerId = (- layers: readonly CanvasLayerContract[],+ stacks: CanvasStackForests,selectedLayerId: string | null,- previousLayers?: readonly CanvasLayerContract[]+ previous?: CanvasStackForests): string | null => {if (selectedLayerId === null) {return null;}- const surviving = new Set(layers.map((layer) => layer.id));- if (surviving.has(selectedLayerId)) {+ const next = indexStacks(stacks);+ if (next.byId.has(selectedLayerId)) {return selectedLayerId;}- const previousIndex = previousLayers?.findIndex((layer) => layer.id === selectedLayerId) ?? -1;- if (previousLayers && previousIndex >= 0) {- const stack = previousLayers[previousIndex]!.type;+ const survives = (entry: CanvasNodeEntry): boolean => next.byId.has(entry.node.id);+ const before = previous ? indexStacks(previous) : null;+ const entry = before?.byId.get(selectedLayerId);+ if (before && entry) {+ const siblings = siblingsOf(before, entry);return (- nearestSurviving(previousLayers, previousIndex, (layer) => surviving.has(layer.id) && layer.type === stack) ??- nearestSurviving(previousLayers, previousIndex, (layer) => surviving.has(layer.id)) ??- layers[0]?.id ??+ nearestInOrder(siblings, siblings.indexOf(entry), survives) ??+ (entry.parentId !== null && next.byId.has(entry.parentId) ? entry.parentId : null) ??+ nearestInOrder(+ before.nodes,+ entry.order,+ (candidate) => candidate.stack === entry.stack && survives(candidate)+ ) ??+ nearestInOrder(before.nodes, entry.order, survives) ??+ next.nodes[0]?.node.id ??null);}- return layers[0]?.id ?? null;+ return next.nodes[0]?.node.id ?? null;};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.tsindex 9ba4a935d7..950f598b59 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts@@ -1,5 +1,5 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';@@ -17,7 +17,7 @@ import {renderableSourceOf,} from './sources';-const doc = { height: 200, width: 300 } as CanvasDocumentContractV2;+const doc = { height: 200, width: 300 } as CanvasDocumentContractV3;const inpaintMask = (bitmap: { imageName: string; width: number; height: number } | null,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.tsindex 8a80c85494..a33ff5a2f3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts@@ -13,7 +13,7 @@*/import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';@@ -110,7 +110,7 @@ export const isRenderableLayer = (layer: CanvasLayerContract): boolean => {** Throws for layers without a rasterizable source, so callers fail loudly.*/-export const getSourceContentRect = (layer: CanvasLayerContract, doc: CanvasDocumentContractV2): Rect => {+export const getSourceContentRect = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): Rect => {const source = renderableSourceOf(layer);if (!source) {throw new Error(`getSourceContentRect: layer type '${layer.type}' has no rasterizable source`);@@ -152,7 +152,7 @@ export const getSourceContentRect = (layer: CanvasLayerContract, doc: CanvasDocu* projected through the layer transform (rotation-aware). Used for culling and* fit-to-content. Throws for layers without a rasterizable source.*/-export const getSourceBounds = (layer: CanvasLayerContract, doc: CanvasDocumentContractV2): Rect => {+export const getSourceBounds = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): Rect => {const contentRect = getSourceContentRect(layer, doc);const { transform } = layer;const matrix = fromTRS({ x: transform.x, y: transform.y }, transform.rotation, transform.scaleX, transform.scaleY);@@ -162,7 +162,7 @@ export const getSourceBounds = (layer: CanvasLayerContract, doc: CanvasDocumentC/** The native (unscaled) pixel size of a layer's raster cache surface. */export const getSourcePixelSize = (layer: CanvasLayerContract,- doc: CanvasDocumentContractV2+ doc: CanvasDocumentContractV3): { width: number; height: number } => {const rect = getSourceContentRect(layer, doc);return { height: rect.height, width: rect.width };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.tsindex e61bdec71a..7c5d4116ab 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts@@ -1,9 +1,10 @@-import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { BitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import { PixelEditController } from '@workbench/canvas-engine/controllers/controlPixelController';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import { createHistory } from '@workbench/canvas-engine/history/history';import { createAdjustedSurfaceCache } from '@workbench/canvas-engine/render/adjustedSurfaceCache';@@ -63,13 +64,13 @@ const setup = (entry.surface.ctx.putImageData(new ImageData(new Uint8ClampedArray([0, 0, 0, 255, 255, 255, 255, 255]), 2, 1), 0, 0);layers.publishPixels(initialLayer.id);let layer = initialLayer;- const document: CanvasDocumentContractV2 = {+ let document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 4, width: 8, x: 0, y: 0 },height: 4,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: layer.id,- version: 2,+ version: 3,width: 8,};const history = createHistory();@@ -84,7 +85,7 @@ const setup = (throw new Error('expected raster replacement');}layer = replacement;- document.layers = [replacement];+ document = { ...document, stacks: stacksFrom([replacement]) };resources.onReplacement?.(replacement);},endBurst: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.tsindex 35297cb086..12ea95a4f1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts@@ -1,5 +1,7 @@import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import { documentFrom, groupContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';import { createTestStubRasterBackend, type StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it } from 'vitest';@@ -7,7 +9,7 @@ import {bakePixelEditSurface,buildMaterializedPixelLayer,decidePixelEdit,- isLayerPixelEditEligible,+ isLeafPixelEditEligible,} from './controlPixelEdit';const control = (overrides: Partial<CanvasControlLayerContract> = {}): CanvasControlLayerContract => ({@@ -96,7 +98,7 @@ describe('decidePixelEdit', () => {});});-describe('isLayerPixelEditEligible', () => {+describe('isLeafPixelEditEligible', () => {const rasterPaint: CanvasLayerContract = {blendMode: 'normal',id: 'raster',@@ -149,7 +151,14 @@ describe('isLayerPixelEditEligible', () => {['disabled control', control({ isEnabled: false }), false],['missing layer', undefined, false],] as const)('returns %s eligibility for %s', (_scenario, layer, expected) => {- expect(isLayerPixelEditEligible(layer)).toBe(expected);+ expect(isLeafPixelEditEligible(layer ? compileDocumentLeaves(documentFrom([layer]))[0] : null)).toBe(expected);+ });++ it('refuses a leaf whose ancestor is disabled or locked', () => {+ const gated = compileDocumentLeaves(documentFrom([groupContract('g', [control()], { isEnabled: false })]));+ expect(isLeafPixelEditEligible(gated[0])).toBe(false);+ const locked = compileDocumentLeaves(documentFrom([groupContract('g', [control()], { isLocked: true })]));+ expect(isLeafPixelEditEligible(locked[0])).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.tsindex c3d2dd2dd1..b5285a9aaa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts@@ -1,14 +1,11 @@/** Policy and pure transforms shared by control and raster-image pixel editing. */-import type {- CanvasControlLayerContract,- CanvasLayerContract,- CanvasRasterLayerContractV2,-} from '@workbench/canvas-engine/contracts';+import type { CanvasControlLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { bakeMatrix, IDENTITY_TRANSFORM, type LayerTransform } from '@workbench/canvas-engine/transform/transformMath';@@ -24,6 +21,9 @@ export interface DecidePixelEditInput {layer: PixelEditableLayer;hasSourceContent: boolean;isCacheReady: boolean;+ /** Ancestor-effective state; the leaf's own flags are always applied. */+ contributionEnabled?: boolean;+ effectiveLocked?: boolean;}const isIdentity = (transform: LayerTransform): boolean =>@@ -38,16 +38,23 @@ const isRasterizable = (layer: PixelEditableLayer): boolean =>? layer.source.type === 'image' || layer.source.type === 'paint': layer.source.type !== 'shape' || layer.source.kind !== 'polygon';-export const isLayerPixelEditEligible = (layer: CanvasLayerContract | undefined): boolean =>- !!layer &&- isLayerEditable(layer) &&- ((layer.type === 'raster' && layer.source.type === 'paint') || (layer.type === 'control' && isRasterizable(layer)));+/** Whether the leaf, with its ancestors applied, can take a direct pixel edit. */+export const isLeafPixelEditEligible = (leaf: SemanticLeaf | null | undefined): boolean =>+ isLeafEditable(leaf) &&+ ((leaf.layer.type === 'raster' && leaf.layer.source.type === 'paint') ||+ (leaf.layer.type === 'control' && isRasterizable(leaf.layer)));-export const decidePixelEdit = ({ hasSourceContent, isCacheReady, layer }: DecidePixelEditInput): PixelEditDecision => {- if (layer.isLocked) {+export const decidePixelEdit = ({+ contributionEnabled = true,+ effectiveLocked = false,+ hasSourceContent,+ isCacheReady,+ layer,+}: DecidePixelEditInput): PixelEditDecision => {+ if (layer.isLocked || effectiveLocked) {return { reason: 'locked', status: 'rejected' };}- if (!layer.isEnabled) {+ if (!layer.isEnabled || !contributionEnabled) {return { reason: 'disabled', status: 'rejected' };}if (!isRasterizable(layer)) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.tsindex d0e80b906b..8de8f9140f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts@@ -7,7 +7,11 @@* engine test suite.*/-import type { CanvasDocumentContractV2, CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';+import type {+ CanvasDocumentContractV3,+ CanvasLayerContract,+ CanvasStateContractV3,+} from '@workbench/canvas-engine/contracts';import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import type { Project, WorkbenchState } from '@workbench/projectContracts';@@ -21,6 +25,8 @@ import {type EngineTestAction = WorkbenchAction | CanvasProjectMutation;+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import {createCanvasEngine as createApplicationCanvasEngine,@@ -68,7 +74,7 @@ vi.mock('@workbench/canvas-operations/backend/canvasImages', () => ({uploadCanvasImage: vi.fn(() => Promise.resolve({ height: 64, imageName: 'mask-img', width: 64 })),}));-const makeCanvas = (document: CanvasDocumentContractV2, documentRevision = 0): CanvasStateContractV2 =>+const makeCanvas = (document: CanvasDocumentContractV3, documentRevision = 0): CanvasStateContractV3 =>({document,documentRevision,@@ -81,14 +87,14 @@ const makeCanvas = (document: CanvasDocumentContractV2, documentRevision = 0): CpendingImages: [],selectedImageIndex: 0,},- version: 2,- }) as CanvasStateContractV2;+ version: 3,+ }) as CanvasStateContractV3;-const maskDoc = (): CanvasDocumentContractV2 => ({+const maskDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [+ stacks: stacksFrom([{blendMode: 'normal',id: 'mask1',@@ -100,13 +106,13 @@ const maskDoc = (): CanvasDocumentContractV2 => ({transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'inpaint_mask',},- ],+ ]),selectedLayerId: 'mask1',- version: 2,+ version: 3,width: 100,});-const createReactiveStore = (document: CanvasDocumentContractV2) => {+const createReactiveStore = (document: CanvasDocumentContractV3) => {let state = {activeProjectId: 'p1',projects: [{ canvas: makeCanvas(document), id: 'p1' }],@@ -126,7 +132,7 @@ const createReactiveStore = (document: CanvasDocumentContractV2) => {});return {dispatch,- setDocument: (next: CanvasDocumentContractV2, revision = 0) => {+ setDocument: (next: CanvasDocumentContractV3, revision = 0) => {state = {activeProjectId: 'p1',projects: [{ canvas: makeCanvas(next, revision), id: 'p1' }],@@ -146,7 +152,7 @@ const createReactiveStore = (document: CanvasDocumentContractV2) => {};};-const createReducerBackedStore = (document: CanvasDocumentContractV2) => {+const createReducerBackedStore = (document: CanvasDocumentContractV3) => {let state = createInitialWorkbenchState();const projectId = state.activeProjectId;state = workbenchReducer(state, {@@ -244,7 +250,7 @@ const pointerAt = (x: number, y: number, buttons = 1): Partial<PointerEvent> =>* `readbackAlpha` overrides the stub's opaque readback when a test needs to model* transparent pixels explicitly. See `StubRasterBackendOptions`.*/-const setupEngine = (doc: CanvasDocumentContractV2, options: { readbackAlpha?: number } = {}) => {+const setupEngine = (doc: CanvasDocumentContractV3, options: { readbackAlpha?: number } = {}) => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -318,7 +324,7 @@ describe('inpaint mask painting', () => {it('does not paint into a locked mask', () => {const doc = maskDoc();- doc.layers[0]!.isLocked = true;+ getDocumentLeaves(doc)[0]!.isLocked = true;const { dispatch, engine, overlay, strokes } = setupEngine(doc);engine.tools.setTool('brush');overlay.fire('pointerdown', pointerAt(20, 20));@@ -378,7 +384,7 @@ describe('mask invert', () => {it('returns false for a missing layer, a non-mask layer, or a locked mask', () => {const lockedDoc = maskDoc();- lockedDoc.layers[0]!.isLocked = true;+ getDocumentLeaves(lockedDoc)[0]!.isLocked = true;const { engine } = setupEngine(lockedDoc);expect(engine.layers.invertMask('nope')).toBe(false);expect(engine.layers.invertMask('mask1')).toBe(false); // locked@@ -476,7 +482,7 @@ describe('mask invert', () => {});const doc = maskDoc();- doc.layers.push({+ doc.stacks.raster.push({blendMode: 'normal',id: 'raster1',isEnabled: true,@@ -536,7 +542,7 @@ describe('mask clear', () => {it('clears a regional-guidance mask', () => {const doc = maskDoc();- doc.layers[0] = {+ doc.stacks.inpaint_mask[0] = {autoNegative: false,blendMode: 'normal',id: 'mask1',@@ -563,7 +569,7 @@ describe('mask clear', () => {it('clears a cold hidden persisted mask and restores its bitmap reference on undo', () => {const doc = maskDoc();- const mask = doc.layers[0]!;+ const mask = getDocumentLeaves(doc)[0]!;if (mask.type !== 'inpaint_mask') {throw new Error('Expected inpaint mask fixture');}@@ -595,7 +601,7 @@ describe('mask clear', () => {it('refuses missing, non-mask, locked, and empty layers', () => {const locked = maskDoc();- locked.layers[0]!.isLocked = true;+ (locked.stacks.inpaint_mask[0] as CanvasLayerContract).isLocked = true;const { engine } = setupEngine(locked);expect(engine.layers.clearMask('missing')).toBe(false);@@ -603,7 +609,8 @@ describe('mask clear', () => {engine.lifecycle.dispose();const raster = maskDoc();- raster.layers[0] = {+ raster.stacks.inpaint_mask.length = 0;+ raster.stacks.raster[0] = {blendMode: 'normal',id: 'mask1',isEnabled: true,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 86dc29a9b8..0fae49d987 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -1,12 +1,12 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasLayerSourceContract,CanvasRasterLayerContractV2,CanvasStagingCandidateContract,- CanvasStateContractV2,+ CanvasStateContractV3,} from '@workbench/canvas-engine/contracts';import type * as ImagePatchModule from '@workbench/canvas-engine/history/imagePatch';import type * as LayerSnapshotModule from '@workbench/canvas-engine/history/layerSnapshot';@@ -30,8 +30,10 @@ import {type EngineTestAction = WorkbenchAction | CanvasProjectMutation;+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';-import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';+import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';import { DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/render/compositor';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';@@ -214,17 +216,17 @@ const rasterLayer = (id: string, opts: { imageName?: string; opacity?: number }type: 'raster',});-const makeDoc = (): CanvasDocumentContractV2 => ({+const makeDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [rasterLayer('a')],+ stacks: stacksFrom([rasterLayer('a')]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,});-const makeCanvas = (document: CanvasDocumentContractV2, documentRevision = 0): CanvasStateContractV2 => ({+const makeCanvas = (document: CanvasDocumentContractV3, documentRevision = 0): CanvasStateContractV3 => ({document,documentRevision,snapshots: [],@@ -236,11 +238,11 @@ const makeCanvas = (document: CanvasDocumentContractV2, documentRevision = 0): CpendingImages: [],selectedImageIndex: 0,},- version: 2,+ version: 3,});const createFakeStore = (- document: CanvasDocumentContractV2+ document: CanvasDocumentContractV3): { store: EngineStore; unsubscribe: ReturnType<typeof vi.fn> } => {const state = {activeProjectId: 'p1',@@ -280,11 +282,11 @@ const createEngine = () => {/** A reactive fake store: `setDocument` notifies subscribers, unlike `createFakeStore` above. */const createReactiveStore = (- document: CanvasDocumentContractV2+ document: CanvasDocumentContractV3): {listenerCount: () => number;setActiveProjectId: (projectId: string) => void;- setDocument: (next: CanvasDocumentContractV2, documentRevision?: number) => void;+ setDocument: (next: CanvasDocumentContractV3, documentRevision?: number) => void;store: EngineStore;} => {let revision = 0;@@ -662,7 +664,7 @@ describe('createCanvasEngine', () => {const capture = engine.exports.captureRasterSnapshot(documentSnapshot!, ['a']);setDocument({...document,- layers: [{ ...document.layers[0]!, opacity: 0.5 }],+ stacks: stacksFrom([{ ...getDocumentLeaves(document)[0]!, opacity: 0.5 }]),});pending.resolve(new Blob(['pixels']));@@ -687,7 +689,7 @@ describe('createCanvasEngine', () => {...rasterLayer('a'),source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' as const },};- const document = { ...makeDoc(), layers: [layer], selectedLayerId: layer.id };+ const document = { ...makeDoc(), stacks: stacksFrom([layer]), selectedLayerId: layer.id };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -782,10 +784,10 @@ describe('createCanvasEngine', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',};- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {...makeDoc(),height: imageSize,- layers: [largeLayer],+ stacks: stacksFrom([largeLayer]),width: imageSize,};const { requests, resolver } = createAbortableImageResolver();@@ -857,7 +859,7 @@ describe('createCanvasEngine', () => {it('captures valid pixels while identifying a genuinely empty paint layer for callers to skip', async () => {const blank = { ...rasterLayer('blank'), source: { bitmap: null, type: 'paint' } as const };- const { store } = createFakeStore({ ...makeDoc(), layers: [rasterLayer('valid'), blank] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([rasterLayer('valid'), blank]) });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob(['valid'])),@@ -880,7 +882,7 @@ describe('createCanvasEngine', () => {it('returns a successful empty raster snapshot for a blank-only document', async () => {const blank = { ...rasterLayer('blank'), source: { bitmap: null, type: 'paint' } as const };- const { store } = createFakeStore({ ...makeDoc(), layers: [blank] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([blank]) });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -1181,7 +1183,7 @@ describe('createCanvasEngine', () => {it('exportLayerPixels refuses hidden layers unless includeDisabled is set', async () => {const hidden = { ...rasterLayer('hidden'), isEnabled: false };- const { store } = createFakeStore({ ...makeDoc(), layers: [hidden] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([hidden]) });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -1207,7 +1209,7 @@ describe('createCanvasEngine', () => {},transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 5, y: 6 },};- const { store } = createFakeStore({ ...makeDoc(), layers: [layer] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([layer]) });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -1280,12 +1282,12 @@ describe('createCanvasEngine', () => {const backend = createRecordingRasterBackend();backend.createImageBitmap = vi.fn((blob) => Promise.resolve(blob === blobA ? bitmapA : bitmapB));const imageResolver = vi.fn((imageName: string) => (imageName === 'A' ? first.promise : second.promise));- const document = { ...makeDoc(), layers: [rasterLayer('L', { imageName: 'A' })] };+ const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('L', { imageName: 'A' })]) };const { setDocument, store } = createReactiveStore(document);const engine = createCanvasEngine({ backend, imageResolver, projectId: 'p1', store });const exportA = engine.exports.exportLayerPixels('L');- setDocument({ ...document, layers: [rasterLayer('L', { imageName: 'B' })] });+ setDocument({ ...document, stacks: stacksFrom([rasterLayer('L', { imageName: 'B' })]) });const exportB = engine.exports.exportLayerPixels('L');second.resolve(blobB);@@ -1312,12 +1314,12 @@ describe('createCanvasEngine', () => {Promise.resolve(blob === blobA ? recordingBitmap('document-A') : recordingBitmap('document-B')));const imageResolver = vi.fn((imageName: string) => (imageName === 'A' ? first.promise : second.promise));- const document = { ...makeDoc(), layers: [rasterLayer('L', { imageName: 'A' })] };+ const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('L', { imageName: 'A' })]) };const { setDocument, store } = createReactiveStore(document);const engine = createCanvasEngine({ backend, imageResolver, projectId: 'p1', store });const oldExport = engine.exports.exportLayerPixels('L');- setDocument({ ...document, layers: [rasterLayer('L', { imageName: 'B' })] }, 1);+ setDocument({ ...document, stacks: stacksFrom([rasterLayer('L', { imageName: 'B' })]) }, 1);const newExport = engine.exports.exportLayerPixels('L');second.resolve(blobB);@@ -1337,7 +1339,7 @@ describe('createCanvasEngine', () => {it('shares one rasterization between concurrent exports of the same version', async () => {const blob = new Blob(['shared']);const imageResolver = vi.fn(() => Promise.resolve(blob));- const { store } = createFakeStore({ ...makeDoc(), layers: [rasterLayer('L')] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([rasterLayer('L')]) });const engine = createCanvasEngine({backend: createRecordingRasterBackend(),imageResolver,@@ -1356,7 +1358,7 @@ describe('createCanvasEngine', () => {it('does not return a default export when the layer becomes disabled during rasterization', async () => {const pending = createDeferred<Blob>();const layer = rasterLayer('L');- const document = { ...makeDoc(), layers: [layer] };+ const document = { ...makeDoc(), stacks: stacksFrom([layer]) };const { setDocument, store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -1366,7 +1368,7 @@ describe('createCanvasEngine', () => {});const exported = engine.exports.exportLayerPixels('L');- setDocument({ ...document, layers: [{ ...layer, isEnabled: false }] });+ setDocument({ ...document, stacks: stacksFrom([{ ...layer, isEnabled: false }]) });pending.resolve(new Blob());expect(await exported).toEqual({ status: 'disabled' });@@ -1378,7 +1380,7 @@ describe('createCanvasEngine', () => {vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);const empty = { ...rasterLayer('empty'), source: { bitmap: null, type: 'paint' } as const };- const { store } = createReactiveStore({ ...makeDoc(), layers: [empty] });+ const { store } = createReactiveStore({ ...makeDoc(), stacks: stacksFrom([empty]) });const base = createTestStubRasterBackend();const surfaces: StubRasterSurface[] = [];const engine = createCanvasEngine({@@ -1426,7 +1428,7 @@ describe('createCanvasEngine', () => {width: 10,};const layer = { ...rasterLayer('shape'), source: shape };- const { store } = createFakeStore({ ...makeDoc(), layers: [layer] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([layer]) });const base = createTestStubRasterBackend();let shouldThrow = true;const engine = createCanvasEngine({@@ -1467,7 +1469,7 @@ describe('createCanvasEngine', () => {...rasterLayer('a'),transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 5, y: 6 },};- const { store } = createFakeStore({ ...makeDoc(), layers: [layer] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([layer]) });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -1498,7 +1500,7 @@ describe('createCanvasEngine', () => {...rasterLayer('a'),adjustments: { brightness: 0.25, contrast: 0, saturation: 0 },};- const { store } = createFakeStore({ ...makeDoc(), layers: [layer] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([layer]) });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -1529,7 +1531,7 @@ describe('createCanvasEngine', () => {...rasterLayer('a'),adjustments: { brightness: 0.25, contrast: 0, saturation: 0 },};- const { store } = createFakeStore({ ...makeDoc(), layers: [layer] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([layer]) });const base = createTestStubRasterBackend();const surfaces: StubRasterSurface[] = [];const engine = createCanvasEngine({@@ -1582,7 +1584,7 @@ describe('createCanvasEngine', () => {throw new Error('expected successful exports');}for (const result of [local, baked, blob]) {- expect(result.guard).toMatchObject({ layer: doc.layers[0], layerId: 'a', projectId: 'p1' });+ expect(result.guard).toMatchObject({ layer: getDocumentLeaves(doc)[0], layerId: 'a', projectId: 'p1' });expect(engine.exports.isLayerExportGuardCurrent(result.guard)).toBe(true);}engine.lifecycle.dispose();@@ -1622,7 +1624,7 @@ describe('createCanvasEngine', () => {identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },});- setDocument({ ...document, layers: [{ ...document.layers[0]!, opacity: 0.5 }] });+ setDocument({ ...document, stacks: stacksFrom([{ ...getDocumentLeaves(document)[0]!, opacity: 0.5 }]) });expect(engine.exports.isLayerExportGuardCurrent(exported.guard)).toBe(false);expect(cleanupPreview).toHaveBeenCalledOnce();@@ -1634,7 +1636,7 @@ describe('createCanvasEngine', () => {for (const nextLayers of [[{- ...makeDoc().layers[0]!,+ ...getDocumentLeaves(makeDoc())[0]!,source: { image: { height: 10, imageName: 'replacement', width: 10 }, type: 'image' as const },},],@@ -1659,7 +1661,7 @@ describe('createCanvasEngine', () => {identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },});- setDocument({ ...document, layers: nextLayers });+ setDocument({ ...document, stacks: stacksFrom(nextLayers) });expect(cleanupPreview).toHaveBeenCalledOnce();expect(getCanvasOperations(engine).controller.getSnapshot()).toEqual({ status: 'idle' });@@ -1688,7 +1690,7 @@ describe('createCanvasEngine', () => {identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },});- setDocument({ ...document, layers: document.layers }, 1);+ setDocument({ ...document, stacks: stacksFrom(getDocumentLeaves(document)) }, 1);expect(engine.exports.isLayerExportGuardCurrent(exported.guard)).toBe(false);expect(cleanupPreview).toHaveBeenCalledOnce();@@ -1766,7 +1768,7 @@ describe('createCanvasEngine', () => {const pending = engine.exports.exportBakedLayerBlob('a');await vi.waitFor(() => expect(encodeSurface).toHaveBeenCalledOnce());- setDocument({ ...document, layers: [{ ...document.layers[0]!, opacity: 0.5 }] });+ setDocument({ ...document, stacks: stacksFrom([{ ...getDocumentLeaves(document)[0]!, opacity: 0.5 }]) });encoded.resolve(new Blob(['stale'], { type: 'image/png' }));expect(await pending).toEqual({ status: 'not-ready' });@@ -1787,18 +1789,18 @@ describe('createCanvasEngine', () => {});const document = paintDoc();- const layer = document.layers[0];+ const layer = getDocumentLeaves(document)[0];if (!layer || layer.type !== 'raster') {throw new Error('expected paint layer');}- const persisted: CanvasDocumentContractV2 = {+ const persisted: CanvasDocumentContractV3 = {...document,- layers: [+ stacks: stacksFrom([{...layer,source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' },},- ],+ ]),};const { projectId, store } = createReducerBackedStore(persisted);const engine = createCanvasEngine({@@ -1835,7 +1837,7 @@ describe('createCanvasEngine', () => {adjustments: { brightness: 0.2, contrast: -0.1, saturation: 0.3 },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 5, y: 5 },};- const document = { ...makeDoc(), bbox: { height: 8, width: 10, x: 8, y: 2 }, layers: [layer] };+ const document = { ...makeDoc(), bbox: { height: 8, width: 10, x: 8, y: 2 }, stacks: stacksFrom([layer]) };const { projectId, store } = createReducerBackedStore(document);const backend = createRecordingRasterBackend();const bitmapStore = createSpyBitmapStore();@@ -1846,7 +1848,7 @@ describe('createCanvasEngine', () => {projectId,store,});- const beforeContract = structuredClone(engine.document.getDocument()!.layers[0]!);+ const beforeContract = structuredClone(getDocumentLeaves(engine.document.getDocument()!)[0]!);const beforeExport = await engine.exports.exportLayerPixels('a');expect(beforeExport.status).toBe('ok');if (beforeExport.status !== 'ok') {@@ -1858,7 +1860,7 @@ describe('createCanvasEngine', () => {expect(await engine.layers.cropLayerToBbox('a')).toEqual({ status: 'cropped' });- const afterContract = engine.document.getDocument()!.layers[0]!;+ const afterContract = getDocumentLeaves(engine.document.getDocument()!)[0]!;expect(afterContract).toEqual({blendMode: 'normal',id: 'a',@@ -1882,7 +1884,7 @@ describe('createCanvasEngine', () => {const forwardSources = backend.drawSourcesFor(forwardExport.surface as StubRasterSurface);engine.history.undo();- expect(engine.document.getDocument()!.layers[0]).toEqual(beforeContract);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(beforeContract);expect(bitmapStore.markLayerDirty).toHaveBeenCalledTimes(2);expect(thumbnailListener).toHaveBeenCalledTimes(2);const undoExport = await engine.exports.exportLayerPixels('a');@@ -1898,7 +1900,7 @@ describe('createCanvasEngine', () => {);engine.history.redo();- expect(engine.document.getDocument()!.layers[0]).toEqual(afterContract);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(afterContract);expect(bitmapStore.markLayerDirty).toHaveBeenCalledTimes(3);expect(thumbnailListener).toHaveBeenCalledTimes(3);const redoExport = await engine.exports.exportLayerPixels('a');@@ -1931,7 +1933,7 @@ describe('createCanvasEngine', () => {type: 'control',withTransparencyEffect: true,};- const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, layers: [control] };+ const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, stacks: stacksFrom([control]) };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -1942,7 +1944,7 @@ describe('createCanvasEngine', () => {});expect(await engine.layers.cropLayerToBbox('control')).toEqual({ status: 'cropped' });- const cropped = engine.document.getDocument()!.layers[0];+ const cropped = getDocumentLeaves(engine.document.getDocument()!)[0];expect(cropped).toMatchObject({adapter: control.adapter,source: { bitmap: null, offset: { x: 2, y: 3 }, type: 'paint' },@@ -1964,7 +1966,7 @@ describe('createCanvasEngine', () => {},noiseLevel: 0.25,};- const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, layers: [layer] };+ const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, stacks: stacksFrom([layer]) };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -1975,7 +1977,7 @@ describe('createCanvasEngine', () => {});expect(await engine.layers.cropLayerToBbox('mask')).toEqual({ status: 'cropped' });- expect(engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toMatchObject({denoiseLimit: 0.45,mask: { bitmap: null, fill: layer.mask.fill, offset: { x: 2, y: 3 } },noiseLevel: 0.25,@@ -2010,7 +2012,7 @@ describe('createCanvasEngine', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'regional_guidance',};- const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, layers: [layer] };+ const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, stacks: stacksFrom([layer]) };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -2021,7 +2023,7 @@ describe('createCanvasEngine', () => {});expect(await engine.layers.cropLayerToBbox('region')).toEqual({ status: 'cropped' });- expect(engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toMatchObject({autoNegative: false,mask: { bitmap: null, fill: layer.mask.fill, offset: { x: 2, y: 3 } },negativePrompt: 'negative',@@ -2072,7 +2074,7 @@ describe('createCanvasEngine', () => {{ ...rasterLayer('polygon'), source: polygon },rasterLayer('pending'),];- const document = { ...makeDoc(), layers };+ const document = { ...makeDoc(), stacks: stacksFrom(layers) };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -2090,7 +2092,7 @@ describe('createCanvasEngine', () => {it('cropLayerToBbox returns not-ready without mutation when the source changes during rasterization', async () => {const pending = createDeferred<Blob>();- const document = { ...makeDoc(), layers: [rasterLayer('a', { imageName: 'A' })] };+ const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('a', { imageName: 'A' })]) };const { setDocument, store } = createReactiveStore(document);const bitmapStore = createSpyBitmapStore();const engine = createCanvasEngine({@@ -2102,7 +2104,7 @@ describe('createCanvasEngine', () => {});const crop = engine.layers.cropLayerToBbox('a');- setDocument({ ...document, layers: [rasterLayer('a', { imageName: 'B' })] });+ setDocument({ ...document, stacks: stacksFrom([rasterLayer('a', { imageName: 'B' })]) });pending.resolve(new Blob());expect(await crop).toEqual({ status: 'not-ready' });@@ -2113,7 +2115,7 @@ describe('createCanvasEngine', () => {it('cropLayerToBbox aborts when an operation starts during its deferred export', async () => {const pending = createDeferred<Blob>();- const document = { ...makeDoc(), layers: [rasterLayer('operation'), rasterLayer('a')] };+ const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('operation'), rasterLayer('a')]) };const { projectId, store } = createReducerBackedStore(document);const bitmapStore = createSpyBitmapStore();const resolver = vi.fn((imageName: string) => (imageName === 'a' ? pending.promise : Promise.resolve(new Blob())));@@ -2171,7 +2173,11 @@ describe('createCanvasEngine', () => {...rasterLayer('paint'),source: { bitmap: { height: 10, imageName: 'paint', width: 10 }, type: 'paint' as const },};- const busyHarness = createReducerBackedStore({ ...makeDoc(), layers: [paint], selectedLayerId: 'paint' });+ const busyHarness = createReducerBackedStore({+ ...makeDoc(),+ stacks: stacksFrom([paint]),+ selectedLayerId: 'paint',+ });const busyEngine = createCanvasEngine({backend: createTestStubRasterBackend(),bitmapStore: createSpyBitmapStore(),@@ -2240,7 +2246,7 @@ describe('createCanvasEngine', () => {});it('copyLayerToRaster adds a baked paint copy directly above the source layer', async () => {- const doc = { ...makeDoc(), layers: [rasterLayer('top'), rasterLayer('a')] };+ const doc = { ...makeDoc(), stacks: stacksFrom([rasterLayer('top'), rasterLayer('a')]) };const { projectId, store } = createReducerBackedStore(doc);const dispatch = store.dispatch as Mock;const base = createTestStubRasterBackend();@@ -2267,7 +2273,7 @@ describe('createCanvasEngine', () => {.find((action) => action.type === 'applyCanvasLayerStackMutation');expect(mutation).toBeDefined();const added = mutation?.type === 'applyCanvasLayerStackMutation' ? mutation.add?.[0] : undefined;- const addedLayer = added?.layers[0];+ const addedLayer = added?.nodes[0];if (added && addedLayer?.type === 'raster') {expect(added.anchor).toMatchObject({ beforeId: 'a', projectId, stack: 'raster' });expect(addedLayer.id).toBe(newId);@@ -2288,7 +2294,7 @@ describe('createCanvasEngine', () => {it('copyLayerToRaster returns null for empty layers', async () => {const empty = { ...rasterLayer('empty'), source: { bitmap: null, type: 'paint' } as const };- const { store } = createFakeStore({ ...makeDoc(), layers: [empty] });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([empty]) });const dispatch = store.dispatch as Mock;const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -2310,7 +2316,7 @@ describe('createCanvasEngine', () => {fill: { color: '#e07575', style: 'diagonal' },},};- const { projectId, store } = createReducerBackedStore({ ...makeDoc(), layers: [mask] });+ const { projectId, store } = createReducerBackedStore({ ...makeDoc(), stacks: stacksFrom([mask]) });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -2319,12 +2325,12 @@ describe('createCanvasEngine', () => {});const newId = await engine.layers.copyLayerToRaster('mask');- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === newId)).toBe(true);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === newId)).toBe(true);engine.history.undo();- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === newId)).toBe(false);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === newId)).toBe(false);engine.history.redo();- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === newId)).toBe(true);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === newId)).toBe(true);engine.lifecycle.dispose();});@@ -2351,22 +2357,22 @@ describe('createCanvasEngine', () => {const newId = await engine.layers.copyLayerToRaster('a');expect(newId).not.toBeNull();engine.history.undo();- expect(engine.document.getDocument()!.layers.filter((layer) => layer.id === newId)).toHaveLength(0);+ expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id === newId)).toHaveLength(0);failNextAllocation = true;expect(() => engine.history.redo()).toThrow('copy replay allocation failed');- expect(engine.document.getDocument()!.layers.filter((layer) => layer.id === newId)).toHaveLength(0);+ expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id === newId)).toHaveLength(0);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);engine.history.redo();- expect(engine.document.getDocument()!.layers.filter((layer) => layer.id === newId)).toHaveLength(1);+ expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id === newId)).toHaveLength(1);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);engine.history.undo();- expect(engine.document.getDocument()!.layers.filter((layer) => layer.id === newId)).toHaveLength(0);+ expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id === newId)).toHaveLength(0);engine.lifecycle.dispose();});@@ -2457,13 +2463,13 @@ describe('document mirror wiring: layer reorder', () => {const a = rasterLayer('a', { opacity: 0.25 });const b = rasterLayer('b', { opacity: 0.75 });- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [a, b],+ stacks: stacksFrom([a, b]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,};const { setDocument, store } = createReactiveStore(doc);@@ -2490,7 +2496,7 @@ describe('document mirror wiring: layer reorder', () => {screen.surface.callLog.length = 0;// Pure reorder: new array reference, same layer object references, swapped order.- setDocument({ ...doc, layers: [b, a] });+ setDocument({ ...doc, stacks: stacksFrom([b, a]) });raf.flush();// No layer content changed, so nothing should be re-rasterized.@@ -2515,13 +2521,13 @@ describe('layer removal: adjusted-surface cache cleanup', () => {adjustedSurfaceCacheDeletes.length = 0;- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [rasterLayer('a'), rasterLayer('b')],+ stacks: stacksFrom([rasterLayer('a'), rasterLayer('b')]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,};const { setDocument, store } = createReactiveStore(doc);@@ -2540,7 +2546,7 @@ describe('layer removal: adjusted-surface cache cleanup', () => {expect(adjustedSurfaceCacheDeletes).not.toContain('a');// Remove layer 'a' via an ordinary layer-array edit (onLayersChanged → dropLayer).- setDocument({ ...doc, layers: [rasterLayer('b')] });+ setDocument({ ...doc, stacks: stacksFrom([rasterLayer('b')]) });raf.flush();// The removed layer's adjusted-surface slot is dropped alongside its layer cache.@@ -2700,7 +2706,7 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {expect(resolver).toHaveBeenNthCalledWith(1, 'a', expect.any(AbortSignal));// An edit lands mid-flight: same layer id, new object reference, new source.- setDocument({ ...doc, layers: [rasterLayer('a', { imageName: 'a-v2' })] });+ setDocument({ ...doc, stacks: stacksFrom([rasterLayer('a', { imageName: 'a-v2' })]) });// A frame runs while the first rasterize is still in flight. The source no// longer matches that job, so a fresh isolated job starts immediately.@@ -2740,11 +2746,11 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {// cache surface AND re-mark the layer dirty for persistence, and the canUndo /// canRedo stores track the stacks.-const paintDoc = (): CanvasDocumentContractV2 => ({+const paintDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [+ stacks: stacksFrom([{blendMode: 'normal',id: 'paint1',@@ -2756,9 +2762,9 @@ const paintDoc = (): CanvasDocumentContractV2 => ({transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',},- ],+ ]),selectedLayerId: 'paint1',- version: 2,+ version: 3,width: 100,});@@ -2792,13 +2798,13 @@ const createPixelEditHarness = (});- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: layer.id,- version: 2,+ version: 3,width: 100,};const { projectId, store } = createReducerBackedStore(document);@@ -2958,10 +2964,9 @@ const createRealControlPersistenceHarness = async (dispatch: createTestMutationPort(store, projectId).dispatch,encodeSurface,getLayerSource: (layerId) => {- const layer = store- .getState()- .projects.find((project) => project.id === projectId)- ?.canvas.document.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLeaves(+ store.getState().projects.find((project) => project.id === projectId)?.canvas.document+ ).find((candidate) => candidate.id === layerId);return layer?.type === 'control' ? layer.source : null;},getLayerSurface: () => placed,@@ -3059,15 +3064,15 @@ describe('engine-owned pixel editing', () => {it('materializes an image layer plus eraser stroke as one reversible edit', async () => {const h = createRasterImageEraserHarness();await h.publishInitialCache();- const before = structuredClone(h.engine.document.getDocument()!.layers[0]);+ const before = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);h.engine.tools.setTool('eraser');h.overlay.fire('pointerdown', pointerAt(20, 20));h.overlay.fire('pointermove', pointerAt(25, 25));h.overlay.fire('pointerup', pointerAt(25, 25, { buttons: 0 }));- const after = structuredClone(h.engine.document.getDocument()!.layers[0]);- expect(h.engine.document.getDocument()!.layers).toHaveLength(1);+ const after = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);expect(after).toMatchObject({id: 'image',source: { type: 'paint' },@@ -3082,11 +3087,11 @@ describe('engine-owned pixel editing', () => {expect(h.engine.stores.canUndo.get()).toBe(true);h.engine.history.undo();- expect(h.engine.document.getDocument()!.layers[0]).toEqual(before);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(before);expect(h.engine.stores.canRedo.get()).toBe(true);h.engine.history.redo();- expect(h.engine.document.getDocument()!.layers[0]).toEqual(after);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(after);h.engine.lifecycle.dispose();});@@ -3102,7 +3107,10 @@ describe('engine-owned pixel editing', () => {h.overlay.fire('pointermove', pointerAt(25, 25));expect(() => h.overlay.fire('pointerup', pointerAt(25, 25, { buttons: 0 }))).not.toThrow();- expect(h.engine.document.getDocument()!.layers[0]).toMatchObject({ source: { type: 'paint' }, type: 'raster' });+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toMatchObject({+ source: { type: 'paint' },+ type: 'raster',+ });expect(h.bitmapStore.markLayerDirty).toHaveBeenCalledWith('image');expect(h.bitmapStore.markLayerDirty.mock.invocationCallOrder[0]).toBeLessThan(h.bitmapStore.releaseSuspendedLayer.mock.invocationCallOrder[0]!@@ -3176,7 +3184,7 @@ describe('engine-owned pixel editing', () => {h.overlay.fire('pointerup', pointerAt(20, 20, { buttons: 0 }));expect(h.engine.document.getDocument()).toEqual(before);- expect(h.engine.document.getDocument()!.layers).toHaveLength(1);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);expect(h.strokes).toHaveLength(0);expect(h.bitmapStore.suspendLayer).not.toHaveBeenCalled();expect(h.engine.stores.canUndo.get()).toBe(false);@@ -3210,8 +3218,8 @@ describe('engine-owned pixel editing', () => {h.overlay.fire('pointermove', pointerAt(40, 40));h.overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));- expect(h.engine.document.getDocument()!.layers).toHaveLength(1);- expect(h.engine.document.getDocument()!.layers[0]).toMatchObject({ id: 'control', type: 'control' });+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toMatchObject({ id: 'control', type: 'control' });expect(h.strokes).toHaveLength(1);expect(h.strokes[0]!.layerId).toBe('control');expect(h.bitmapStore.markLayerDirty).toHaveBeenCalledWith('control');@@ -3453,14 +3461,14 @@ describe('engine-owned pixel editing', () => {transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 7, y: 11 },});await h.publishInitialCache();- const before = structuredClone(h.engine.document.getDocument()!.layers[0]);+ const before = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);h.engine.tools.setTool('brush');h.overlay.fire('pointerdown', pointerAt(20, 20));h.overlay.fire('pointermove', pointerAt(25, 25));h.overlay.fire('pointerup', pointerAt(25, 25, { buttons: 0 }));- const after = structuredClone(h.engine.document.getDocument()!.layers[0]);+ const after = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);expect(after).toMatchObject({adapter: before && 'adapter' in before ? before.adapter : undefined,filter: before && 'filter' in before ? before.filter : undefined,@@ -3478,12 +3486,12 @@ describe('engine-owned pixel editing', () => {);h.engine.history.undo();- expect(h.engine.document.getDocument()!.layers[0]).toEqual(before);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(before);expect(h.engine.stores.canUndo.get()).toBe(false);expect(h.engine.stores.canRedo.get()).toBe(true);h.engine.history.redo();- expect(h.engine.document.getDocument()!.layers[0]).toEqual(after);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(after);h.engine.lifecycle.dispose();});@@ -3593,14 +3601,14 @@ describe('engine-owned pixel editing', () => {h.engine.tools.setTool('brush');h.overlay.fire('pointerdown', pointerAt(35, 45));h.overlay.fire('pointerup', pointerAt(35, 45, { buttons: 0 }));- expect(h.engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toMatchObject({id: 'control',source: { type: 'paint' },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'control',});h.engine.history.undo();- expect(h.engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toMatchObject({transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 30, y: 40 },});h.engine.lifecycle.dispose();@@ -3618,7 +3626,7 @@ describe('engine-owned pixel editing', () => {h.overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));expect(h.engine.document.getDocument()).toEqual(before);- expect(h.engine.document.getDocument()!.layers).toHaveLength(1);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);expect(h.strokes).toHaveLength(0);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(h.bitmapStore.discardLayer).not.toHaveBeenCalled();@@ -3666,7 +3674,7 @@ describe('engine-owned pixel editing', () => {'adjusted surface cache delete failed');- expect(h.engine.document.getDocument()!.layers).toHaveLength(0);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(0);expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();expect(h.bitmapStore.discardLayer).toHaveBeenCalledWith('control');expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();@@ -3994,13 +4002,13 @@ describe('engine-owned history: stroke → undo → redo', () => {vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- const docV1: CanvasDocumentContractV2 = {+ const docV1: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [rasterLayer('a', { imageName: 'src-v1' })],+ stacks: stacksFrom([rasterLayer('a', { imageName: 'src-v1' })]),selectedLayerId: 'a',- version: 2,+ version: 3,width: 100,};const { setDocument, store } = createReactiveStore(docV1);@@ -4030,7 +4038,7 @@ describe('engine-owned history: stroke → undo → redo', () => {// reference diff alone could not tell from an ordinary edit. The engine must// invalidate the surviving cache entry so it re-rasterizes the new source// (a stale cache entry would keep rendering the v1 pixels).- setDocument({ ...docV1, layers: [rasterLayer('a', { imageName: 'src-v2' })] }, 1);+ setDocument({ ...docV1, stacks: stacksFrom([rasterLayer('a', { imageName: 'src-v2' })]) }, 1);// Persistence bookkeeping for the outgoing document was dropped so a reused// layer id can't have its next legit persistence dispatch suppressed.@@ -4165,7 +4173,11 @@ describe('commitStructural', () => {it('reports a reducer refusal as dispatch-rejected with no history entry', () => {const layer = rasterLayer('L');- const { projectId, store } = createReducerBackedStore({ ...makeDoc(), layers: [layer], selectedLayerId: 'L' });+ const { projectId, store } = createReducerBackedStore({+ ...makeDoc(),+ stacks: stacksFrom([layer]),+ selectedLayerId: 'L',+ });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -4182,7 +4194,11 @@ describe('commitStructural', () => {it('reverts an accepted edit that fails its postcondition and records nothing', () => {const layer = rasterLayer('L');- const { projectId, store } = createReducerBackedStore({ ...makeDoc(), layers: [layer], selectedLayerId: 'L' });+ const { projectId, store } = createReducerBackedStore({+ ...makeDoc(),+ stacks: stacksFrom([layer]),+ selectedLayerId: 'L',+ });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -4198,7 +4214,7 @@ describe('commitStructural', () => {{ verify: () => false })).toEqual({ recovered: 'reverted', status: 'postcondition-failed' });- expect(engine.document.getDocument()?.layers[0]?.name).toBe('L');+ expect(getDocumentLeaves(engine.document.getDocument())[0]?.name).toBe('L');expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();});@@ -4207,7 +4223,7 @@ describe('commitStructural', () => {const layer = rasterLayer('L');const { dispatch, projectId, store } = createReducerBackedStore({...makeDoc(),- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: 'L',});const reportError = vi.fn();@@ -4408,7 +4424,7 @@ describe('drawLayerThumbnail', () => {} as CanvasRasterLayerContractV2;const backend = createSeededThumbnailBackend([10, 20, 30, 255]);const createSurface = vi.spyOn(backend, 'createSurface');- const { store } = createReactiveStore({ ...makeDoc(), layers: [layer] });+ const { store } = createReactiveStore({ ...makeDoc(), stacks: stacksFrom([layer]) });const engine = createCanvasEngine({backend,imageResolver: () => Promise.resolve(new Blob()),@@ -4447,7 +4463,7 @@ describe('drawLayerThumbnail', () => {? createSeededThumbnailBackend([100, 50, 200, 255]): createTestStubRasterBackend();const createSurface = vi.spyOn(backend, 'createSurface');- const { store } = createReactiveStore({ ...makeDoc(), layers: [layer as CanvasLayerContract] });+ const { store } = createReactiveStore({ ...makeDoc(), stacks: stacksFrom([layer as CanvasLayerContract]) });const engine = createCanvasEngine({backend,imageResolver: () => Promise.resolve(new Blob()),@@ -4498,7 +4514,7 @@ describe('drawLayerThumbnail', () => {const layer = largeThumbnailLayer(kind);const backend = createTestStubRasterBackend();const createSurface = vi.spyOn(backend, 'createSurface');- const { store } = createReactiveStore({ ...makeDoc(), layers: [layer] });+ const { store } = createReactiveStore({ ...makeDoc(), stacks: stacksFrom([layer]) });const engine = createCanvasEngine({backend,imageResolver: () => Promise.resolve(new Blob()),@@ -4566,7 +4582,7 @@ describe('drawLayerThumbnail', () => {])('invalidates the keyed thumbnail version when %s changes without changing the source',async (_name, layer, edit) => {- const doc = { ...makeDoc(), layers: [layer as CanvasLayerContract] };+ const doc = { ...makeDoc(), stacks: stacksFrom([layer as CanvasLayerContract]) };const { setDocument, store } = createReactiveStore(doc);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -4578,7 +4594,7 @@ describe('drawLayerThumbnail', () => {const listener = vi.fn();const unsubscribe = engine.stores.thumbnailVersion.subscribeKey('a', listener);- setDocument({ ...doc, layers: [edit(layer as CanvasLayerContract) as CanvasLayerContract] });+ setDocument({ ...doc, stacks: stacksFrom([edit(layer as CanvasLayerContract) as CanvasLayerContract]) });expect(listener).toHaveBeenCalledTimes(1);unsubscribe();@@ -4588,7 +4604,7 @@ describe('drawLayerThumbnail', () => {it('does not let display invalidation suppress the next cache-version publication', async () => {const layer = rasterLayer('a');- const doc = { ...makeDoc(), layers: [layer] };+ const doc = { ...makeDoc(), stacks: stacksFrom([layer]) };const { setDocument, store } = createReactiveStore(doc);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -4604,8 +4620,8 @@ describe('drawLayerThumbnail', () => {...layer,adjustments: { brightness: 0.25, contrast: 0, saturation: 0 },} as CanvasLayerContract;- setDocument({ ...doc, layers: [adjusted] });- setDocument({ ...doc, layers: [rasterLayer('a', { imageName: 'a-v2' })] });+ setDocument({ ...doc, stacks: stacksFrom([adjusted]) });+ setDocument({ ...doc, stacks: stacksFrom([rasterLayer('a', { imageName: 'a-v2' })]) });await engine.previews.requestLayerThumbnail('a');expect(listener).toHaveBeenCalledTimes(2);@@ -4669,9 +4685,9 @@ describe('requestLayerThumbnail', () => {});it('rasterizes disabled layers on explicit request', async () => {- const layer = { ...makeDoc().layers[0]!, isEnabled: false };+ const layer = { ...getDocumentLeaves(makeDoc())[0]!, isEnabled: false };const resolver = vi.fn(() => Promise.resolve(new Blob()));- const { store } = createReactiveStore({ ...makeDoc(), layers: [layer] });+ const { store } = createReactiveStore({ ...makeDoc(), stacks: stacksFrom([layer]) });const engine = createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: resolver,@@ -4688,7 +4704,7 @@ describe('requestLayerThumbnail', () => {const bitmap = recordingBitmap('detached-replaced');const backend = createTestStubRasterBackend();backend.createImageBitmap = vi.fn(() => Promise.resolve(bitmap));- const doc = { ...makeDoc(), layers: [rasterLayer('a', { imageName: 'old' })] };+ const doc = { ...makeDoc(), stacks: stacksFrom([rasterLayer('a', { imageName: 'old' })]) };const { setDocument, store } = createReactiveStore(doc);const engine = createCanvasEngine({backend,@@ -4698,7 +4714,7 @@ describe('requestLayerThumbnail', () => {});expect(await engine.previews.requestLayerThumbnail('a')).toBe('ready');- setDocument({ ...doc, layers: [rasterLayer('a', { imageName: 'new' })] });+ setDocument({ ...doc, stacks: stacksFrom([rasterLayer('a', { imageName: 'new' })]) });expect(bitmap.close).toHaveBeenCalledTimes(1);engine.lifecycle.dispose();@@ -4708,7 +4724,7 @@ describe('requestLayerThumbnail', () => {const bitmap = recordingBitmap('detached-deleted');const backend = createTestStubRasterBackend();backend.createImageBitmap = vi.fn(() => Promise.resolve(bitmap));- const doc = { ...makeDoc(), layers: [rasterLayer('a', { imageName: 'old' })] };+ const doc = { ...makeDoc(), stacks: stacksFrom([rasterLayer('a', { imageName: 'old' })]) };const { setDocument, store } = createReactiveStore(doc);const engine = createCanvasEngine({backend,@@ -4718,7 +4734,7 @@ describe('requestLayerThumbnail', () => {});expect(await engine.previews.requestLayerThumbnail('a')).toBe('ready');- setDocument({ ...doc, layers: [] });+ setDocument({ ...doc, stacks: stacksFrom([]) });expect(bitmap.close).toHaveBeenCalledTimes(1);engine.lifecycle.dispose();@@ -4730,7 +4746,7 @@ describe('requestLayerThumbnail', () => {backend.createImageBitmap = vi.fn(() => Promise.resolve(bitmap));const first = rasterLayer('a', { imageName: 'shared' });const second = rasterLayer('b', { imageName: 'shared' });- const doc = { ...makeDoc(), layers: [first, second] };+ const doc = { ...makeDoc(), stacks: stacksFrom([first, second]) };const { setDocument, store } = createReactiveStore(doc);const engine = createCanvasEngine({backend,@@ -4742,8 +4758,8 @@ describe('requestLayerThumbnail', () => {expect(await engine.previews.requestLayerThumbnail('b')).toBe('ready');expect(bitmap.close).toHaveBeenCalledTimes(2);- setDocument({ ...doc, layers: [second] });- setDocument({ ...doc, layers: [] });+ setDocument({ ...doc, stacks: stacksFrom([second]) });+ setDocument({ ...doc, stacks: stacksFrom([]) });expect(bitmap.close).toHaveBeenCalledTimes(2);engine.lifecycle.dispose();@@ -4755,7 +4771,7 @@ describe('requestLayerThumbnail', () => {backend.createImageBitmap = vi.fn(() => Promise.resolve(bitmap));const first = rasterLayer('a', { imageName: 'shared' });const second = rasterLayer('b', { imageName: 'shared' });- const doc = { ...makeDoc(), layers: [first, second] };+ const doc = { ...makeDoc(), stacks: stacksFrom([first, second]) };const { setDocument, store } = createReactiveStore(doc);const engine = createCanvasEngine({backend,@@ -4768,8 +4784,8 @@ describe('requestLayerThumbnail', () => {expect(bitmap.close).toHaveBeenCalledTimes(2);const firstChanged = rasterLayer('a', { imageName: 'first-new' });- setDocument({ ...doc, layers: [firstChanged, second] });- setDocument({ ...doc, layers: [firstChanged, rasterLayer('b', { imageName: 'second-new' })] });+ setDocument({ ...doc, stacks: stacksFrom([firstChanged, second]) });+ setDocument({ ...doc, stacks: stacksFrom([firstChanged, rasterLayer('b', { imageName: 'second-new' })]) });expect(bitmap.close).toHaveBeenCalledTimes(2);engine.lifecycle.dispose();@@ -4778,10 +4794,10 @@ describe('requestLayerThumbnail', () => {it('releases a decoded bitmap when invalidation lands after cache insertion but before publication', async () => {const bitmap = recordingBitmap('stale-before-publication');const original = rasterLayer('a', { imageName: 'old' });- const doc = { ...makeDoc(), layers: [original] };+ const doc = { ...makeDoc(), stacks: stacksFrom([original]) };const { setDocument, store } = createReactiveStore(doc);const backend = createInvalidateDuringBitmapDrawBackend(bitmap, () => {- setDocument({ ...doc, layers: [rasterLayer('a', { imageName: 'new' })] });+ setDocument({ ...doc, stacks: stacksFrom([rasterLayer('a', { imageName: 'new' })]) });});const engine = createCanvasEngine({backend,@@ -4799,10 +4815,10 @@ describe('requestLayerThumbnail', () => {const bitmap = recordingBitmap('stale-shared-before-publication');const first = rasterLayer('a', { imageName: 'shared' });const second = rasterLayer('b', { imageName: 'shared' });- const doc = { ...makeDoc(), layers: [first, second] };+ const doc = { ...makeDoc(), stacks: stacksFrom([first, second]) };const { setDocument, store } = createReactiveStore(doc);const backend = createInvalidateDuringBitmapDrawBackend(bitmap, () => {- setDocument({ ...doc, layers: [rasterLayer('a', { imageName: 'new' }), second] });+ setDocument({ ...doc, stacks: stacksFrom([rasterLayer('a', { imageName: 'new' }), second]) });});const engine = createCanvasEngine({backend,@@ -4813,7 +4829,7 @@ describe('requestLayerThumbnail', () => {expect(await engine.previews.requestLayerThumbnail('a')).toBe('stale');expect(bitmap.close).toHaveBeenCalledTimes(1);- setDocument({ ...doc, layers: [rasterLayer('a', { imageName: 'new' })] });+ setDocument({ ...doc, stacks: stacksFrom([rasterLayer('a', { imageName: 'new' })]) });expect(bitmap.close).toHaveBeenCalledTimes(1);engine.lifecycle.dispose();});@@ -4825,10 +4841,10 @@ describe('requestLayerThumbnail', () => {...(rasterLayer('b') as CanvasRasterLayerContractV2),source: { bitmap: { height: 10, imageName: 'shared', width: 10 }, type: 'paint' },};- const doc = { ...makeDoc(), layers: [first, second] };+ const doc = { ...makeDoc(), stacks: stacksFrom([first, second]) };const { setDocument, store } = createReactiveStore(doc);const backend = createInvalidateDuringBitmapDrawBackend(bitmap, () => {- setDocument({ ...doc, layers: [second] });+ setDocument({ ...doc, stacks: stacksFrom([second]) });});const engine = createCanvasEngine({backend,@@ -4841,7 +4857,9 @@ describe('requestLayerThumbnail', () => {expect(bitmap.close).toHaveBeenCalledTimes(1);setDocument({...doc,- layers: [{ ...second, source: { bitmap: { height: 10, imageName: 'new', width: 10 }, type: 'paint' } }],+ stacks: stacksFrom([+ { ...second, source: { bitmap: { height: 10, imageName: 'new', width: 10 }, type: 'paint' } },+ ]),});expect(bitmap.close).toHaveBeenCalledTimes(1);engine.lifecycle.dispose();@@ -4857,10 +4875,10 @@ describe('requestLayerThumbnail', () => {bitmap: { height: 10, imageName: 'shared', width: 10 },},};- const doc = { ...makeDoc(), layers: [first, second] };+ const doc = { ...makeDoc(), stacks: stacksFrom([first, second]) };const { setDocument, store } = createReactiveStore(doc);const backend = createInvalidateDuringBitmapDrawBackend(bitmap, () => {- setDocument({ ...doc, layers: [second] });+ setDocument({ ...doc, stacks: stacksFrom([second]) });});const engine = createCanvasEngine({backend,@@ -4873,12 +4891,12 @@ describe('requestLayerThumbnail', () => {expect(bitmap.close).toHaveBeenCalledTimes(1);setDocument({...doc,- layers: [+ stacks: stacksFrom([{...second,mask: { ...second.mask, bitmap: { height: 10, imageName: 'new', width: 10 } },},- ],+ ]),});expect(bitmap.close).toHaveBeenCalledTimes(1);engine.lifecycle.dispose();@@ -4894,12 +4912,15 @@ describe('requestLayerThumbnail', () => {});const first = rasterLayer('a', { imageName: 'shared' });const second = rasterLayer('b', { imageName: 'shared' });- const doc = { ...makeDoc(), layers: [first, second] };+ const doc = { ...makeDoc(), stacks: stacksFrom([first, second]) };const { setDocument, store } = createReactiveStore(doc);const backend = createInvalidateDuringBitmapDrawBackend(bitmap, () => {setDocument({...doc,- layers: [rasterLayer('a', { imageName: 'first-new' }), rasterLayer('b', { imageName: 'second-new' })],+ stacks: stacksFrom([+ rasterLayer('a', { imageName: 'first-new' }),+ rasterLayer('b', { imageName: 'second-new' }),+ ]),});});const engine = createCanvasEngine({ backend, imageResolver: resolver, projectId: 'p1', store });@@ -4947,7 +4968,7 @@ describe('requestLayerThumbnail', () => {});const oldRequest = engine.previews.requestLayerThumbnail('a');- setDocument({ ...doc, layers: [rasterLayer('a', { imageName: 'a-v2' })] });+ setDocument({ ...doc, stacks: stacksFrom([rasterLayer('a', { imageName: 'a-v2' })]) });expect(requests.get('a')?.signal?.aborted).toBe(true);const newRequest = engine.previews.requestLayerThumbnail('a');@@ -5004,7 +5025,7 @@ describe('requestLayerThumbnail', () => {const request = engine.previews.requestLayerThumbnail('a');expect(engine.stores.thumbnailStatus.get('a')).toBe('loading');- setDocument({ ...doc, layers: [] });+ setDocument({ ...doc, stacks: stacksFrom([]) });expect(requests.get('a')?.signal?.aborted).toBe(true);expect(engine.stores.thumbnailStatus.get('a')).toBeUndefined();@@ -5083,11 +5104,11 @@ describe('requestLayerThumbnail', () => {// ---- mergeLayerDown: composites the upper cache into the below local space -----const twoPaintDoc = (): CanvasDocumentContractV2 => ({+const twoPaintDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [+ stacks: stacksFrom([{blendMode: 'multiply',id: 'upper',@@ -5114,9 +5135,9 @@ const twoPaintDoc = (): CanvasDocumentContractV2 => ({transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 20 },type: 'raster',},- ],+ ]),selectedLayerId: 'upper',- version: 2,+ version: 3,width: 100,});@@ -5266,7 +5287,9 @@ describe('mergeLayerDown', () => {const doc = twoPaintDoc();const locked = {...doc,- layers: doc.layers.map((layer) => (layer.id === lockedId ? { ...layer, isLocked: true } : layer)),+ stacks: stacksFrom(+ getDocumentLeaves(doc).map((layer) => (layer.id === lockedId ? { ...layer, isLocked: true } : layer))+ ),};const { store } = createReactiveStore(locked);const dispatch = store.dispatch as Mock;@@ -5294,12 +5317,14 @@ describe('mergeLayerDown', () => {// cache surface). Merging must NOT `drawImage` the zero-dimension operand (which// throws in browsers) but must still dispatch the collapse and composite the// non-empty operand.- const oneEmptyPaintDoc = (emptyId: 'upper' | 'below'): CanvasDocumentContractV2 => {+ const oneEmptyPaintDoc = (emptyId: 'upper' | 'below'): CanvasDocumentContractV3 => {const doc = twoPaintDoc();return {...doc,- layers: doc.layers.map((layer) =>- layer.id === emptyId ? { ...layer, source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' } } : layer+ stacks: stacksFrom(+ getDocumentLeaves(doc).map((layer) =>+ layer.id === emptyId ? { ...layer, source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' } } : layer+ )),};};@@ -5373,12 +5398,14 @@ describe('mergeLayerDown', () => {vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);const base = twoPaintDoc();- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {...base,- layers: base.layers.map((layer) => ({- ...layer,- source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' as const },- })),+ stacks: stacksFrom(+ getDocumentLeaves(base).map((layer) => ({+ ...layer,+ source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' as const },+ }))+ ),};const { store } = createReactiveStore(doc);const dispatch = store.dispatch as Mock;@@ -5435,9 +5462,9 @@ describe('mergeLayerDown', () => {vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);const base = twoPaintDoc();- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {...base,- layers: base.layers.map((layer) => (layer.id === maskId ? maskLayer(maskId) : layer)),+ stacks: stacksFrom(getDocumentLeaves(base).map((layer) => (layer.id === maskId ? maskLayer(maskId) : layer))),};const { store } = createReactiveStore(doc);const dispatch = store.dispatch as Mock;@@ -5458,7 +5485,9 @@ describe('mergeLayerDown', () => {);// Document unchanged: still two layers, each with its original type — no// mask was blitted into, and no mask was clobbered into a raster layer.- expect(engine.document.getDocument()!.layers.map((l) => l.type)).toEqual(doc.layers.map((l) => l.type));+ expect(getDocumentLeaves(engine.document.getDocument()!).map((l) => l.type)).toEqual(+ getDocumentLeaves(doc).map((l) => l.type)+ );engine.lifecycle.dispose();});@@ -5469,9 +5498,9 @@ describe('mergeLayerDown', () => {vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);const base = twoPaintDoc();- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {...base,- layers: [maskLayer('upper'), maskLayer('below')],+ stacks: stacksFrom([maskLayer('upper'), maskLayer('below')]),};const { store } = createReactiveStore(doc);const dispatch = store.dispatch as Mock;@@ -5490,7 +5519,10 @@ describe('mergeLayerDown', () => {expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(false);- expect(engine.document.getDocument()!.layers.map((l) => l.type)).toEqual(['inpaint_mask', 'inpaint_mask']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((l) => l.type)).toEqual([+ 'inpaint_mask',+ 'inpaint_mask',+ ]);engine.lifecycle.dispose();});@@ -5546,24 +5578,24 @@ describe('boolean raster operations', () => {expect(resultSurface!.callLog.filter((entry) => entry.op === 'drawImage')).toHaveLength(2);const merged = engine.document.getDocument()!;- const result = merged.layers.find((layer) => layer.id !== 'upper' && layer.id !== 'below');+ const result = getDocumentLeaves(merged).find((layer) => layer.id !== 'upper' && layer.id !== 'below');expect(result).toMatchObject({isEnabled: true,source: { bitmap: null, offset: { x: 10, y: 20 }, type: 'paint' },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',});- expect(merged.layers.find((layer) => layer.id === 'upper')?.isEnabled).toBe(false);- expect(merged.layers.find((layer) => layer.id === 'below')?.isEnabled).toBe(false);+ expect(getDocumentLeaves(merged).find((layer) => layer.id === 'upper')?.isEnabled).toBe(false);+ expect(getDocumentLeaves(merged).find((layer) => layer.id === 'below')?.isEnabled).toBe(false);engine.history.undo();- expect(engine.document.getDocument()!.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => [layer.id, layer.isEnabled])).toEqual([['upper', true],['below', true],]);engine.history.redo();- expect(engine.document.getDocument()!.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => [layer.id, layer.isEnabled])).toEqual([[result!.id, true],['upper', false],['below', false],@@ -5603,13 +5635,12 @@ describe('boolean raster operations', () => {raf.flush();expect(await engine.layers.booleanMergeRasterLayers('upper', 'intersect')).toBe('not-ready');- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(['upper', 'below']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['upper', 'below']);engine.lifecycle.dispose();});it('rejects unsupported and missing layer pairs without modifying the document', async () => {- const doc = twoPaintDoc();- doc.layers[1] = maskLayer('below');+ const doc = { ...twoPaintDoc(), stacks: stacksFrom([twoPaintDoc().stacks.raster[0]!, maskLayer('below')]) };const { projectId, store } = createReducerBackedStore(doc);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -5618,9 +5649,9 @@ describe('boolean raster operations', () => {store,});- expect(await engine.layers.booleanMergeRasterLayers('upper', 'exclude')).toBe('unsupported');+ expect(await engine.layers.booleanMergeRasterLayers('upper', 'exclude')).toBe('missing');expect(await engine.layers.booleanMergeRasterLayers('missing', 'exclude')).toBe('missing');- expect(engine.document.getDocument()!.layers).toEqual(doc.layers);+ expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual(getDocumentLeaves(doc));engine.lifecycle.dispose();});@@ -5650,7 +5681,7 @@ describe('boolean raster operations', () => {});const upper = emptyPaint('upper');const below = emptyPaint('below');- const doc = { ...makeDoc(), layers: [upper, below], selectedLayerId: 'upper' };+ const doc = { ...makeDoc(), stacks: stacksFrom([upper, below]), selectedLayerId: 'upper' };const { projectId, store } = createReducerBackedStore(doc);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -5681,11 +5712,11 @@ describe('boolean raster operations', () => {});describe('extract masked canvas area', () => {- const maskedDoc = (): CanvasDocumentContractV2 => {+ const maskedDoc = (): CanvasDocumentContractV3 => {const doc = twoPaintDoc();return {...doc,- layers: [+ stacks: stacksFrom([{...maskLayer('mask'),mask: {@@ -5694,8 +5725,8 @@ describe('extract masked canvas area', () => {offset: { x: 15, y: 25 },},},- ...doc.layers,- ],+ ...getDocumentLeaves(doc),+ ]),selectedLayerId: 'mask',};};@@ -5748,21 +5779,27 @@ describe('extract masked canvas area', () => {expect(extractedPixels).toMatchObject({ height: 20, width: 20 });expect(extractedPixels!.callLog.filter((entry) => entry.op === 'drawImage').length).toBeGreaterThanOrEqual(3);- const extracted = engine.document.getDocument()!.layers.find((layer) => layer.id === result.layerId);+ const extracted = getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === result.layerId);expect(extracted).toMatchObject({isEnabled: true,source: { bitmap: null, offset: { x: 15, y: 25 }, type: 'paint' },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',});- expect(engine.document.getDocument()!.layers.find((layer) => layer.id === 'mask')).toEqual(maskedDoc().layers[0]);- expect(engine.document.getDocument()!.layers.find((layer) => layer.id === 'upper')?.isEnabled).toBe(true);- expect(engine.document.getDocument()!.layers.find((layer) => layer.id === 'below')?.isEnabled).toBe(true);+ expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === 'mask')).toEqual(+ getDocumentLeaves(maskedDoc())[0]+ );+ expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === 'upper')?.isEnabled).toBe(+ true+ );+ expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === 'below')?.isEnabled).toBe(+ true+ );engine.history.undo();- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(false);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(false);engine.history.redo();- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(true);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(true);engine.lifecycle.dispose();});@@ -5791,7 +5828,7 @@ describe('extract masked canvas area', () => {bitmap: { height: 10, imageName: 'mask', width: 10 },},};- const document = { ...makeDoc(), layers: [mask, raster, control], selectedLayerId: 'mask' };+ const document = { ...makeDoc(), stacks: stacksFrom([mask, raster, control]), selectedLayerId: 'mask' };const { projectId, store } = createReducerBackedStore(document);const base = createTestStubRasterBackend();const surfaces: StubRasterSurface[] = [];@@ -5854,7 +5891,7 @@ describe('extract masked canvas area', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',};- document.layers.splice(2, 0, blank);+ document.stacks.raster.splice(2, 0, blank);const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -5896,17 +5933,19 @@ describe('extract masked canvas area', () => {const extraction = engine.exports.extractMaskedArea('mask');setDocument({...document,- layers: document.layers.map((layer) =>- layer.id === 'upper' && layer.type === 'raster'- ? {- ...layer,- source: {- bitmap: { height: 40, imageName: 'upper-v2', width: 40 },- offset: { x: 0, y: 0 },- type: 'paint',- },- }- : layer+ stacks: stacksFrom(+ getDocumentLeaves(document).map((layer) =>+ layer.id === 'upper' && layer.type === 'raster'+ ? {+ ...layer,+ source: {+ bitmap: { height: 40, imageName: 'upper-v2', width: 40 },+ offset: { x: 0, y: 0 },+ type: 'paint',+ },+ }+ : layer+ )),});@@ -5917,7 +5956,7 @@ describe('extract masked canvas area', () => {it('refuses extraction from a locked mask', async () => {const document = maskedDoc();- document.layers[0] = { ...document.layers[0]!, isLocked: true };+ document.stacks.inpaint_mask[0] = { ...(document.stacks.inpaint_mask[0] as CanvasLayerContract), isLocked: true };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -5935,7 +5974,11 @@ describe('extract masked canvas area', () => {raf.flush();expect(await engine.exports.extractMaskedArea('mask')).toEqual({ status: 'not-ready' });- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(['mask', 'upper', 'below']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([+ 'mask',+ 'upper',+ 'below',+ ]);engine.lifecycle.dispose();});@@ -5952,11 +5995,11 @@ describe('extract masked canvas area', () => {expect(await engine.exports.extractMaskedArea('missing')).toEqual({ status: 'missing' });expect(await engine.exports.extractMaskedArea('upper')).toEqual({ status: 'unsupported' });expect(await engine.exports.extractMaskedArea('mask')).toEqual({ status: 'not-ready' });- expect(engine.document.getDocument()!.layers).toEqual(doc.layers);+ expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual(getDocumentLeaves(doc));engine.lifecycle.dispose();const emptyDoc = maskedDoc();- emptyDoc.layers[0] = maskLayer('mask');+ emptyDoc.stacks.inpaint_mask[0] = maskLayer('mask');const emptyHarness = createReducerBackedStore(emptyDoc);const emptyEngine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -5977,7 +6020,7 @@ describe('extract masked canvas area', () => {* no-op mock store cannot exercise that transaction.*/const createReducerBackedStore = (- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,mainBase?: string): { dispatch: Mock<(action: EngineTestAction) => void>; projectId: string; store: EngineStore } => {let state = createInitialWorkbenchState();@@ -6059,7 +6102,7 @@ describe('staged result acceptance', () => {throw new Error('expected commit');}const projectAfterCommit = reducer.store.getState().projects[0]!;- const acceptedLayer = projectAfterCommit.canvas.document.layers[0]!;+ const acceptedLayer = getDocumentLeaves(projectAfterCommit.canvas.document)[0]!;const acceptedEvent = projectAfterCommit.events[0]!;expect(acceptedLayer).toMatchObject({id: result.layerId,@@ -6072,13 +6115,15 @@ describe('staged result acceptance', () => {engine.history.undo();const projectAfterUndo = reducer.store.getState().projects[0]!;- expect(projectAfterUndo.canvas.document.layers).not.toContainEqual(expect.objectContaining({ id: result.layerId }));+ expect(getDocumentLeaves(projectAfterUndo.canvas.document)).not.toContainEqual(+ expect.objectContaining({ id: result.layerId })+ );expect(projectAfterUndo.canvas.document.selectedLayerId).toBe('a');expect(projectAfterUndo.canvas.stagingArea.pendingImages).toEqual([]);engine.history.redo();const projectAfterRedo = reducer.store.getState().projects[0]!;- expect(projectAfterRedo.canvas.document.layers[0]).toBe(acceptedLayer);+ expect(getDocumentLeaves(projectAfterRedo.canvas.document)[0]).toBe(acceptedLayer);expect(projectAfterRedo.canvas.stagingArea.pendingImages).toEqual([]);expect(projectAfterRedo.events).toContain(acceptedEvent);expect(projectAfterRedo.events.filter((event) => event.id === acceptedEvent.id)).toHaveLength(1);@@ -6231,7 +6276,11 @@ describe('staged result acceptance', () => {}reducerCanvas = {...canvas,- document: { ...document, layers: [mutation.layer, ...document.layers], selectedLayerId: mutation.layer.id },+ document: {+ ...document,+ stacks: stacksFrom([mutation.layer, ...getDocumentLeaves(document)]),+ selectedLayerId: mutation.layer.id,+ },stagingArea: { ...canvas.stagingArea, pendingImageIds: [], pendingImages: [] },};committed = true;@@ -6307,7 +6356,7 @@ describe('structural raster publication failure atomicity', () => {isEnabled: false,});- const createFaultHarness = (document: CanvasDocumentContractV2) => {+ const createFaultHarness = (document: CanvasDocumentContractV3) => {const faults = createStructuralFaultBackend();const bitmapStore = createSpyBitmapStore();const reducer = createReducerBackedStore(document);@@ -6338,7 +6387,7 @@ describe('structural raster publication failure atomicity', () => {const expectInitialFailureExact = (harness: ReturnType<typeof createFaultHarness>,- expectedDocument: CanvasDocumentContractV2+ expectedDocument: CanvasDocumentContractV3): void => {expect(harness.engine.document.getDocument()).toBe(expectedDocument);expect(harness.engine.document.getDocument()).toEqual(expectedDocument);@@ -6354,10 +6403,10 @@ describe('structural raster publication failure atomicity', () => {'crop keeps document, cache, selection, and history exact when final cache %s fails',async (failure) => {const source = rasterLayer('crop-source');- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {...makeDoc(),bbox: { height: 7, width: 6, x: 2, y: 3 },- layers: [source, sentinelLayer()],+ stacks: stacksFrom([source, sentinelLayer()]),selectedLayerId: 'selection-sentinel',};const harness = createFaultHarness(document);@@ -6382,7 +6431,11 @@ describe('structural raster publication failure atomicity', () => {'commitLayerCopy keeps document, cache, selection, and history exact when final cache %s fails',async (failure) => {const source = rasterLayer('copy-source');- const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };+ const document = {+ ...makeDoc(),+ stacks: stacksFrom([source, sentinelLayer()]),+ selectedLayerId: 'selection-sentinel',+ };const harness = createFaultHarness(document);const sourceCache = await snapshotLayerCache(harness.engine, source.id);const expectedDocument = harness.engine.document.getDocument()!;@@ -6401,7 +6454,9 @@ describe('structural raster publication failure atomicity', () => {).toThrow(structuralFaultMessage(failure));expectInitialFailureExact(harness, expectedDocument);- expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === copy.id)).toBe(false);+ expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === copy.id)).toBe(+ false+ );await expectLayerCacheExact(harness.engine, source.id, sourceCache);harness.engine.lifecycle.dispose();}@@ -6411,11 +6466,15 @@ describe('structural raster publication failure atomicity', () => {'commitLayerConversion keeps document, cache, selection, and history exact when final cache %s fails',async (failure) => {const source = rasterLayer('conversion-source');- const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };+ const document = {+ ...makeDoc(),+ stacks: stacksFrom([source, sentinelLayer()]),+ selectedLayerId: 'selection-sentinel',+ };const harness = createFaultHarness(document);const sourceCache = await snapshotLayerCache(harness.engine, source.id);const expectedDocument = harness.engine.document.getDocument()!;- const live = harness.engine.document.getDocument()!.layers.find((layer) => layer.id === source.id)!;+ const live = getDocumentLeaves(harness.engine.document.getDocument()!).find((layer) => layer.id === source.id)!;if (live.type !== 'raster') {throw new Error('expected a raster conversion source');}@@ -6443,7 +6502,11 @@ describe('structural raster publication failure atomicity', () => {'copyLayerToRaster keeps document, cache, selection, and history exact when final cache %s fails',async (failure) => {const source = rasterLayer('raster-copy-source');- const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };+ const document = {+ ...makeDoc(),+ stacks: stacksFrom([source, sentinelLayer()]),+ selectedLayerId: 'selection-sentinel',+ };const harness = createFaultHarness(document);const sourceCache = await snapshotLayerCache(harness.engine, source.id);const expectedDocument = harness.engine.document.getDocument()!;@@ -6465,7 +6528,7 @@ describe('structural raster publication failure atomicity', () => {const pair = twoPaintDoc();const document = {...pair,- layers: [...pair.layers, sentinelLayer()],+ stacks: stacksFrom([...getDocumentLeaves(pair), sentinelLayer()]),selectedLayerId: 'selection-sentinel',};const harness = createFaultHarness(document);@@ -6501,7 +6564,7 @@ describe('structural raster publication failure atomicity', () => {};const document = {...pair,- layers: [mask, ...pair.layers, sentinelLayer()],+ stacks: stacksFrom([mask, ...getDocumentLeaves(pair), sentinelLayer()]),selectedLayerId: 'selection-sentinel',};const harness = createFaultHarness(document);@@ -6525,10 +6588,10 @@ describe('structural raster publication failure atomicity', () => {const createCropReplayHarness = async () => {const source = rasterLayer('crop-replay-source');- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {...makeDoc(),bbox: { height: 7, width: 6, x: 2, y: 3 },- layers: [source, sentinelLayer()],+ stacks: stacksFrom([source, sentinelLayer()]),selectedLayerId: 'selection-sentinel',};const harness = createFaultHarness(document);@@ -6584,7 +6647,11 @@ describe('structural raster publication failure atomicity', () => {it('commitLayerCopy redo cache-draw failure leaves the restored state exact and retryable', async () => {const source = rasterLayer('copy-replay-source');const copy = { ...structuredClone(source), id: 'copy-replay-result', name: 'Copy replay result' };- const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };+ const document = {+ ...makeDoc(),+ stacks: stacksFrom([source, sentinelLayer()]),+ selectedLayerId: 'selection-sentinel',+ };const harness = createFaultHarness(document);const originalCache = await snapshotLayerCache(harness.engine, source.id);const originalDocument = harness.engine.document.getDocument()!;@@ -6605,23 +6672,29 @@ describe('structural raster publication failure atomicity', () => {expect(harness.engine.document.getDocument()).toBe(restoredDocument);expect(harness.engine.document.getDocument()).toEqual(originalDocument);- expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === copy.id)).toBe(false);+ expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === copy.id)).toBe(false);expect(harness.engine.stores.canUndo.get()).toBe(false);expect(harness.engine.stores.canRedo.get()).toBe(true);await expectLayerCacheExact(harness.engine, source.id, originalCache);harness.engine.history.redo();expect(harness.engine.document.getDocument()).toEqual(committedDocument);- expect(harness.engine.document.getDocument()!.layers.filter((layer) => layer.id === copy.id)).toHaveLength(1);+ expect(+ getDocumentLeaves(harness.engine.document.getDocument()!).filter((layer) => layer.id === copy.id)+ ).toHaveLength(1);harness.engine.lifecycle.dispose();});it('commitLayerConversion keeps failed undo and redo cache preparation exact and retryable', async () => {const source = rasterLayer('conversion-replay-source');- const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };+ const document = {+ ...makeDoc(),+ stacks: stacksFrom([source, sentinelLayer()]),+ selectedLayerId: 'selection-sentinel',+ };const harness = createFaultHarness(document);await snapshotLayerCache(harness.engine, source.id);const originalDocument = harness.engine.document.getDocument()!;- const live = originalDocument.layers.find((layer) => layer.id === source.id)!;+ const live = getDocumentLeaves(originalDocument).find((layer) => layer.id === source.id)!;if (live.type !== 'raster') {throw new Error('expected a raster conversion source');}@@ -6664,7 +6737,7 @@ describe('structural raster publication failure atomicity', () => {const pair = twoPaintDoc();const document = {...pair,- layers: [...pair.layers, sentinelLayer()],+ stacks: stacksFrom([...getDocumentLeaves(pair), sentinelLayer()]),selectedLayerId: 'selection-sentinel',};const harness = createFaultHarness(document);@@ -6682,7 +6755,9 @@ describe('structural raster publication failure atomicity', () => {expect(harness.engine.document.getDocument()).toBe(restoredDocument);expect(harness.engine.document.getDocument()).toEqual(originalDocument);- expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === resultId)).toBe(false);+ expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === resultId)).toBe(+ false+ );expect(harness.engine.stores.canUndo.get()).toBe(false);expect(harness.engine.stores.canRedo.get()).toBe(true);await expectLayerCacheExact(harness.engine, 'upper', upperCache);@@ -6704,7 +6779,7 @@ describe('structural raster publication failure atomicity', () => {};const document = {...pair,- layers: [mask, ...pair.layers, sentinelLayer()],+ stacks: stacksFrom([mask, ...getDocumentLeaves(pair), sentinelLayer()]),selectedLayerId: 'selection-sentinel',};const harness = createFaultHarness(document);@@ -6726,7 +6801,9 @@ describe('structural raster publication failure atomicity', () => {expect(harness.engine.document.getDocument()).toBe(restoredDocument);expect(harness.engine.document.getDocument()).toEqual(originalDocument);- expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === extracted.layerId)).toBe(false);+ expect(+ getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === extracted.layerId)+ ).toBe(false);expect(harness.engine.stores.canUndo.get()).toBe(false);expect(harness.engine.stores.canRedo.get()).toBe(true);await expectLayerCacheExact(harness.engine, mask.id, maskCache);@@ -6739,7 +6816,11 @@ describe('structural raster publication failure atomicity', () => {it('copyLayerToRaster undo restores the exact prior selection', async () => {const source = rasterLayer('selection-copy-source');- const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };+ const document = {+ ...makeDoc(),+ stacks: stacksFrom([source, sentinelLayer()]),+ selectedLayerId: 'selection-sentinel',+ };const harness = createFaultHarness(document);const originalDocument = harness.engine.document.getDocument()!;const copiedId = await harness.engine.layers.copyLayerToRaster(source.id);@@ -6757,16 +6838,16 @@ describe('structural raster publication failure atomicity', () => {it('keeps a reducer-rejected copy undo retryable until its prior selection exists again', async () => {const source = rasterLayer('rejected-undo-source');const sentinel = sentinelLayer();- const document = { ...makeDoc(), layers: [source, sentinel], selectedLayerId: sentinel.id };+ const document = { ...makeDoc(), stacks: stacksFrom([source, sentinel]), selectedLayerId: sentinel.id };const harness = createFaultHarness(document);const copiedId = await harness.engine.layers.copyLayerToRaster(source.id);expect(copiedId).not.toBeNull();harness.store.dispatch({ ids: [sentinel.id], type: 'removeCanvasLayers' });- expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === copiedId)).toBe(true);+ expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === copiedId)).toBe(true);expect(() => harness.engine.history.undo()).toThrow('Canvas document mutation was rejected');- expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === copiedId)).toBe(true);+ expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === copiedId)).toBe(true);expect(harness.engine.stores.canUndo.get()).toBe(true);expect(harness.engine.stores.canRedo.get()).toBe(false);@@ -6776,7 +6857,9 @@ describe('structural raster publication failure atomicity', () => {type: 'addCanvasLayer',});expect(() => harness.engine.history.undo()).not.toThrow();- expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === copiedId)).toBe(false);+ expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === copiedId)).toBe(+ false+ );expect(harness.engine.document.getDocument()!.selectedLayerId).toBe(sentinel.id);expect(harness.engine.stores.canUndo.get()).toBe(false);expect(harness.engine.stores.canRedo.get()).toBe(true);@@ -6785,9 +6868,9 @@ describe('structural raster publication failure atomicity', () => {it('publishes a prepared structural mutation to its bound project while another project is active', () => {const source = rasterLayer('inactive-source');- const document = { ...makeDoc(), layers: [source], selectedLayerId: source.id };+ const document = { ...makeDoc(), stacks: stacksFrom([source]), selectedLayerId: source.id };const harness = createFaultHarness(document);- const liveSource = harness.engine.document.getDocument()!.layers[0]!;+ const liveSource = getDocumentLeaves(harness.engine.document.getDocument()!)[0]!;const copy = { ...structuredClone(source), id: 'inactive-copy' };harness.store.dispatch({ type: 'createProject' });const otherProjectId = harness.store.getState().activeProjectId;@@ -6811,7 +6894,7 @@ describe('structural raster publication failure atomicity', () => {expect(harness.store.getState().projects.find((project) => project.id === otherProjectId)!.canvas.document).toEqual(otherBefore);- expect(harness.engine.document.getDocument()?.layers[0]?.id).toBe(copy.id);+ expect(getDocumentLeaves(harness.engine.document.getDocument())[0]?.id).toBe(copy.id);expect(harness.engine.stores.canUndo.get()).toBe(true);harness.engine.lifecycle.dispose();});@@ -6825,10 +6908,10 @@ describe('structural raster publication failure atomicity', () => {type: 'paint',},};- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {...makeDoc(),bbox: { height: 7, width: 6, x: 2, y: 3 },- layers: [source, sentinelLayer()],+ stacks: stacksFrom([source, sentinelLayer()]),selectedLayerId: 'selection-sentinel',};const reducer = createReducerBackedStore(document);@@ -6847,10 +6930,9 @@ describe('structural raster publication failure atomicity', () => {encodeSurface: (surface) =>Promise.resolve(new Blob([`${surface.width}x${surface.height}`], { type: 'image/png' })),getLayerSource: (layerId) => {- const layer = reducer.store- .getState()- .projects.find((project) => project.id === reducer.projectId)- ?.canvas.document.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLeaves(+ reducer.store.getState().projects.find((project) => project.id === reducer.projectId)?.canvas.document+ ).find((candidate) => candidate.id === layerId);return layer?.type === 'raster' || layer?.type === 'control' ? layer.source : null;},getLayerSurface: () => placed,@@ -6904,7 +6986,7 @@ describe('structural raster publication failure atomicity', () => {},});expect(engine.document.getDocument()!.selectedLayerId).toBe('selection-sentinel');- expect(engine.document.getDocument()!.layers.find((layer) => layer.id === source.id)).toMatchObject({+ expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === source.id)).toMatchObject({source: {bitmap: { height: 7, imageName: 'cropped-paint', width: 6 },offset: { x: 2, y: 3 },@@ -6918,23 +7000,27 @@ describe('structural raster publication failure atomicity', () => {});describe('mergeVisibleRasterLayers', () => {- /** [upper raster, mask, lower raster] — the interleaved case round 1 no-oped. */- const interleavedDoc = (): CanvasDocumentContractV2 => {+ /** Two adjacent rasters with a mask in another stack. */+ const interleavedDoc = (): CanvasDocumentContractV3 => {const base = twoPaintDoc();- const [upper, below] = base.layers as [CanvasLayerContract, CanvasLayerContract];- return { ...base, layers: [upper, maskLayer('mid-mask'), below] };+ const [upper, below] = getDocumentLeaves(base) as [CanvasLayerContract, CanvasLayerContract];+ return { ...base, stacks: stacksFrom([upper, maskLayer('mid-mask'), below]) };};- const selectedMergeDoc = (): CanvasDocumentContractV2 => {+ const selectedMergeDoc = (): CanvasDocumentContractV3 => {const doc = interleavedDoc();return {...doc,- layers: doc.layers.map((layer) => (layer.id === 'upper' ? { ...layer, blendMode: 'normal' as const } : layer)),+ stacks: stacksFrom(+ getDocumentLeaves(doc).map((layer) =>+ layer.id === 'upper' ? { ...layer, blendMode: 'normal' as const } : layer+ )+ ),};};const setup = (- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,pendingClearIds: ReadonlySet<string> = new Set(),pendingWorkIds: ReadonlySet<string> = new Set()) => {@@ -7009,10 +7095,10 @@ describe('mergeVisibleRasterLayers', () => {throw new Error(`unexpected duplicate result: ${result.status}`);}const [upperCopyId, belowCopyId] = result.duplicateIds;- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([+ 'mid-mask',upperCopyId,'upper',- 'mid-mask',belowCopyId,'below',]);@@ -7022,15 +7108,19 @@ describe('mergeVisibleRasterLayers', () => {expect(engine.exports.hasExportableLayerContent(belowCopyId!)).toBe(true);engine.history.undo();- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(['upper', 'mid-mask', 'below']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([+ 'mid-mask',+ 'upper',+ 'below',+ ]);expect(engine.document.getDocument()!.selectedLayerId).toBe('upper');expect(getPanelSelectedIds()).toEqual(['upper', 'below']);engine.history.redo();- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([+ 'mid-mask',upperCopyId,'upper',- 'mid-mask',belowCopyId,'below',]);@@ -7134,7 +7224,9 @@ describe('mergeVisibleRasterLayers', () => {if (result.status !== 'duplicated') {throw new Error(`unexpected duplicate result: ${result.status}`);}- const duplicate = engine.document.getDocument()!.layers.find((layer) => layer.id === result.duplicateIds[0]);+ const duplicate = getDocumentLeaves(engine.document.getDocument()!).find(+ (layer) => layer.id === result.duplicateIds[0]+ );expect(duplicate).toMatchObject({ source: { bitmap: null, type: 'paint' }, type: 'raster' });engine.lifecycle.dispose();});@@ -7146,7 +7238,7 @@ describe('mergeVisibleRasterLayers', () => {bitmap: { height: 20, imageName: 'stale-mask', width: 20 },offset: { x: 4, y: 5 },};- const doc = { ...twoPaintDoc(), layers: [mask], selectedLayerId: mask.id };+ const doc = { ...twoPaintDoc(), stacks: stacksFrom([mask]), selectedLayerId: mask.id };const { engine } = setup(doc, new Set([mask.id]));const result = await engine.layers.duplicateLayers([mask.id]);@@ -7155,7 +7247,9 @@ describe('mergeVisibleRasterLayers', () => {if (result.status !== 'duplicated') {throw new Error(`unexpected duplicate result: ${result.status}`);}- const duplicate = engine.document.getDocument()!.layers.find((layer) => layer.id === result.duplicateIds[0]);+ const duplicate = getDocumentLeaves(engine.document.getDocument()!).find(+ (layer) => layer.id === result.duplicateIds[0]+ );expect(duplicate).toMatchObject({mask: { bitmap: null, fill: mask.mask.fill, offset: { x: 0, y: 0 } },type: 'inpaint_mask',@@ -7164,8 +7258,13 @@ describe('mergeVisibleRasterLayers', () => {});it('duplicates a disabled persisted layer without waiting for a cache it cannot receive', async () => {- const doc = twoPaintDoc();- doc.layers = doc.layers.map((layer) => (layer.id === 'upper' ? { ...layer, isEnabled: false } : layer));+ const base = twoPaintDoc();+ const doc = {+ ...base,+ stacks: stacksFrom(+ getDocumentLeaves(base).map((layer) => (layer.id === 'upper' ? { ...layer, isEnabled: false } : layer))+ ),+ };const { engine, surfaces } = setup(doc);const result = await engine.layers.duplicateLayers(['upper']);@@ -7175,16 +7274,18 @@ describe('mergeVisibleRasterLayers', () => {throw new Error(`unexpected duplicate result: ${result.status}`);}expect(surfaces).toHaveLength(0);- const original = doc.layers.find((layer) => layer.id === 'upper');+ const original = getDocumentLeaves(doc).find((layer) => layer.id === 'upper');if (original?.type !== 'raster') {throw new Error('expected a raster source');}- const duplicate = engine.document.getDocument()!.layers.find((layer) => layer.id === result.duplicateIds[0]);+ const duplicate = getDocumentLeaves(engine.document.getDocument()!).find(+ (layer) => layer.id === result.duplicateIds[0]+ );expect(duplicate).toMatchObject({ isEnabled: false, source: original.source, type: 'raster' });engine.lifecycle.dispose();});- it('merges rasters separated only by another layer group and restores them on undo', async () => {+ it('merges the selected adjacent rasters, leaves other stacks alone, and restores them on undo', async () => {const { engine, getPanelSelectedIds, raf, setPanelSelectedIds } = setup(selectedMergeDoc());raf.flush();await flushMicrotasks();@@ -7193,25 +7294,27 @@ describe('mergeVisibleRasterLayers', () => {const before = engine.document.getDocument()!;expect(await engine.layers.mergeSelectedRasterLayers(['upper', 'below'])).toBe('merged');- const merged = engine.document.getDocument()!.layers[0]!;- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([merged.id, 'mid-mask']);+ const merged = engine.document.getDocument()!.stacks.raster[0]!;+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['mid-mask', merged.id]);expect(merged).toMatchObject({ name: 'upper merged', type: 'raster' });expect(engine.document.getDocument()!.selectedLayerId).toBe(merged.id);expect(getPanelSelectedIds()).toEqual([merged.id]);engine.history.undo();const restored = engine.document.getDocument()!;- expect(haveSameStackOrders(restored.layers, before.layers)).toBe(true);- expect(restored.layers.map((layer) => before.layers.find((candidate) => candidate.id === layer.id))).toEqual(- restored.layers- );+ expect(haveSameStructure(restored.stacks, before.stacks)).toBe(true);+ expect(+ getDocumentLeaves(restored).map((layer) =>+ getDocumentLeaves(before).find((candidate) => candidate.id === layer.id)+ )+ ).toEqual(getDocumentLeaves(restored));expect(restored.selectedLayerId).toBe(before.selectedLayerId);expect(engine.exports.hasExportableLayerContent('upper')).toBe(true);expect(engine.exports.hasExportableLayerContent('below')).toBe(true);expect(getPanelSelectedIds()).toEqual(['upper', 'below']);engine.history.redo();- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([merged.id, 'mid-mask']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['mid-mask', merged.id]);expect(engine.exports.hasExportableLayerContent(merged.id)).toBe(true);expect(getPanelSelectedIds()).toEqual([merged.id]);engine.lifecycle.dispose();@@ -7260,21 +7363,21 @@ describe('mergeVisibleRasterLayers', () => {it('refuses to merge across an unselected raster because that would reorder the composite', async () => {const doc = selectedMergeDoc();const middle: CanvasRasterLayerContractV2 = {- ...(doc.layers.find((layer) => layer.id === 'below') as CanvasRasterLayerContractV2),+ ...(getDocumentLeaves(doc).find((layer) => layer.id === 'below') as CanvasRasterLayerContractV2),id: 'middle-raster',name: 'middle-raster',source: { bitmap: { height: 50, imageName: 'middle-bmp', width: 50 }, type: 'paint' },};- const upper = doc.layers.find((layer) => layer.id === 'upper')!;- const below = doc.layers.find((layer) => layer.id === 'below')!;- const withRasterGap = { ...doc, layers: [upper, middle, below] };+ const upper = getDocumentLeaves(doc).find((layer) => layer.id === 'upper')!;+ const below = getDocumentLeaves(doc).find((layer) => layer.id === 'below')!;+ const withRasterGap = { ...doc, stacks: stacksFrom([upper, middle, below]) };const { engine, raf } = setup(withRasterGap);raf.flush();await flushMicrotasks();raf.flush();expect(await engine.layers.mergeSelectedRasterLayers(['upper', 'below'])).toBe('nothing');- expect(engine.document.getDocument()!.layers).toEqual(withRasterGap.layers);+ expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual(getDocumentLeaves(withRasterGap));expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();});@@ -7287,7 +7390,7 @@ describe('mergeVisibleRasterLayers', () => {raf.flush();expect(await engine.layers.mergeSelectedRasterLayers(['upper', 'below'])).toBe('nothing');- expect(engine.document.getDocument()!.layers).toEqual(doc.layers);+ expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual(getDocumentLeaves(doc));expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();});@@ -7305,10 +7408,10 @@ describe('mergeVisibleRasterLayers', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',}));- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {...twoPaintDoc(),height: size,- layers,+ stacks: stacksFrom(layers),selectedLayerId: 'top',width: size,};@@ -7322,7 +7425,7 @@ describe('mergeVisibleRasterLayers', () => {// Each first-use source allocates one cache and one rasterization scratch;// the transaction then allocates exactly one immediately-live copy.expect(surfaces).toHaveLength(layers.length * 3);- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(layers.flatMap((layer, index) => [result.duplicateIds[index], layer.id]));const afterDuplicate = surfaces.length;@@ -7362,10 +7465,10 @@ describe('mergeVisibleRasterLayers', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10_000, y: 10_000 },type: 'raster',}));- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {...twoPaintDoc(),height: size,- layers,+ stacks: stacksFrom(layers),selectedLayerId: 'top',width: size,};@@ -7383,7 +7486,7 @@ describe('mergeVisibleRasterLayers', () => {engine.history.redo();await flushMicrotasks();- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(layers.flatMap((layer, index) => [result.duplicateIds[index], layer.id]));// Redo warms each offscreen reference sequentially: one cache plus one@@ -7428,10 +7531,10 @@ describe('mergeVisibleRasterLayers', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',}));- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {...twoPaintDoc(),height: size,- layers,+ stacks: stacksFrom(layers),selectedLayerId: 'top',width: size,};@@ -7444,7 +7547,7 @@ describe('mergeVisibleRasterLayers', () => {expect(await engine.layers.duplicateLayers(layers.map((layer) => layer.id))).toEqual({ status: 'over-budget' });expect(surfaces).toHaveLength(afterRasterization);expect(await engine.layers.mergeSelectedRasterLayers(layers.map((layer) => layer.id))).toBe('over-budget');- expect(engine.document.getDocument()!.layers).toEqual(layers);+ expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual(layers);expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();});@@ -7452,18 +7555,23 @@ describe('mergeVisibleRasterLayers', () => {it('waits for contributor rasterization before applying one atomic insertion', async () => {const { engine, raf } = setup(interleavedDoc());const pending = engine.layers.mergeVisibleRasterLayers();- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(['upper', 'mid-mask', 'below']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([+ 'mid-mask',+ 'upper',+ 'below',+ ]);raf.flush();await flushMicrotasks();raf.flush();expect(await pending).toBe('merged');- expect(- engine.document- .getDocument()!- .layers.slice(1)- .map((layer) => layer.id)- ).toEqual(['upper', 'mid-mask', 'below']);+ const mergedId = engine.document.getDocument()!.stacks.raster[0]!.id;+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([+ 'mid-mask',+ mergedId,+ 'upper',+ 'below',+ ]);engine.lifecycle.dispose();});@@ -7476,9 +7584,10 @@ describe('mergeVisibleRasterLayers', () => {expect(await engine.layers.mergeVisibleRasterLayers()).toBe('merged');- const layers = engine.document.getDocument()!.layers;+ const layers = getDocumentLeaves(engine.document.getDocument()!);+ const merged = engine.document.getDocument()!.stacks.raster[0]!;expect(layers).toHaveLength(4);- expect(layers[0]).toMatchObject({+ expect(merged).toMatchObject({blendMode: 'normal',isEnabled: true,isLocked: false,@@ -7487,8 +7596,12 @@ describe('mergeVisibleRasterLayers', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',});- expect(layers.slice(1).map((layer) => layer.id)).toEqual(['upper', 'mid-mask', 'below']);- expect(engine.document.getDocument()!.selectedLayerId).toBe(layers[0]!.id);+ expect(layers.filter((layer) => layer.id !== merged.id).map((layer) => layer.id)).toEqual([+ 'mid-mask',+ 'upper',+ 'below',+ ]);+ expect(engine.document.getDocument()!.selectedLayerId).toBe(merged.id);engine.lifecycle.dispose();});@@ -7496,11 +7609,11 @@ describe('mergeVisibleRasterLayers', () => {it('includes locked parametric rasters, excludes hidden rasters, and composites bottom-to-top', async () => {const doc = twoPaintDoc();const upper: CanvasRasterLayerContractV2 = {- ...(doc.layers[0] as CanvasRasterLayerContractV2),+ ...(getDocumentLeaves(doc)[0] as CanvasRasterLayerContractV2),isLocked: true,};const below: CanvasRasterLayerContractV2 = {- ...(doc.layers[1] as CanvasRasterLayerContractV2),+ ...(getDocumentLeaves(doc)[1] as CanvasRasterLayerContractV2),source: {angle: 0,height: 60,@@ -7514,7 +7627,7 @@ describe('mergeVisibleRasterLayers', () => {},};const hidden: CanvasRasterLayerContractV2 = {- ...(doc.layers[1] as CanvasRasterLayerContractV2),+ ...(getDocumentLeaves(doc)[1] as CanvasRasterLayerContractV2),id: 'hidden',isEnabled: false,name: 'hidden',@@ -7522,15 +7635,18 @@ describe('mergeVisibleRasterLayers', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: -1000, y: -1000 },};const sourceLayers = [upper, maskLayer('mid-mask'), hidden, below];- const { engine, raf, surfaces } = setup({ ...doc, layers: sourceLayers });+ const sourceDoc = { ...doc, stacks: stacksFrom(sourceLayers) };+ const { engine, raf, surfaces } = setup(sourceDoc);raf.flush();await flushMicrotasks();raf.flush();expect(await engine.layers.mergeVisibleRasterLayers()).toBe('merged');- const merged = engine.document.getDocument()!.layers[0]!;+ const merged = engine.document.getDocument()!.stacks.raster[0]!;expect(merged).toMatchObject({ source: { offset: { x: 10, y: 20 }, type: 'paint' }, type: 'raster' });- expect(engine.document.getDocument()!.layers.slice(1)).toEqual(sourceLayers);+ expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id !== merged.id)).toEqual(+ getDocumentLeaves(sourceDoc)+ );const composite = surfaces.find((surface) =>@@ -7562,13 +7678,13 @@ describe('mergeVisibleRasterLayers', () => {raf.flush();expect(await engine.layers.mergeVisibleRasterLayers()).toBe('merged');- const firstId = engine.document.getDocument()!.layers[0]!.id;+ const firstId = engine.document.getDocument()!.stacks.raster[0]!.id;expect(await engine.layers.mergeVisibleRasterLayers()).toBe('merged');- const layers = engine.document.getDocument()!.layers;- expect(layers).toHaveLength(5);- expect(layers[0]!.id).not.toBe(firstId);- expect(layers[1]!.id).toBe(firstId);- expect(layers.slice(2).map((layer) => layer.id)).toEqual(['upper', 'mid-mask', 'below']);+ const rasters = engine.document.getDocument()!.stacks.raster;+ expect(getDocumentLeaves(engine.document.getDocument()!)).toHaveLength(5);+ expect(rasters[0]!.id).not.toBe(firstId);+ expect(rasters[1]!.id).toBe(firstId);+ expect(rasters.slice(2).map((layer) => layer.id)).toEqual(['upper', 'below']);engine.lifecycle.dispose();});@@ -7581,15 +7697,17 @@ describe('mergeVisibleRasterLayers', () => {const before = engine.document.getDocument()!;expect(await engine.layers.mergeVisibleRasterLayers()).toBe('merged');- const merged = engine.document.getDocument()!.layers[0]!;+ const merged = engine.document.getDocument()!.stacks.raster[0]!;engine.history.undo();- expect(engine.document.getDocument()!.layers).toEqual(before.layers);+ expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual(getDocumentLeaves(before));expect(engine.document.getDocument()!.selectedLayerId).toBe(before.selectedLayerId);engine.history.redo();- expect(engine.document.getDocument()!.layers[0]).toEqual(merged);- expect(engine.document.getDocument()!.layers.slice(1)).toEqual(before.layers);+ expect(engine.document.getDocument()!.stacks.raster[0]).toEqual(merged);+ expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id !== merged.id)).toEqual(+ getDocumentLeaves(before)+ );expect(engine.document.getDocument()!.selectedLayerId).toBe(merged.id);engine.lifecycle.dispose();@@ -7611,7 +7729,11 @@ describe('mergeVisibleRasterLayers', () => {});expect(await engine.layers.mergeVisibleRasterLayers()).toBe('busy');- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(['upper', 'mid-mask', 'below']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([+ 'mid-mask',+ 'upper',+ 'below',+ ]);expect(getCanvasOperations(engine).controller.getSnapshot()).toMatchObject({identity: { kind: 'filter' },status: 'active',@@ -7624,21 +7746,23 @@ describe('mergeVisibleRasterLayers', () => {it('returns nothing for empty raster layers and preserves them', async () => {const base = twoPaintDoc();- const doc: CanvasDocumentContractV2 = {+ const doc: CanvasDocumentContractV3 = {...base,- layers: base.layers.map((layer) => ({- ...layer,- source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' as const },- })),+ stacks: stacksFrom(+ getDocumentLeaves(base).map((layer) => ({+ ...layer,+ source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' as const },+ }))+ ),};const { engine, raf } = setup(doc);raf.flush();await flushMicrotasks();raf.flush();- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(['upper', 'below']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['upper', 'below']);expect(await engine.layers.mergeVisibleRasterLayers()).toBe('nothing');- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(['upper', 'below']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['upper', 'below']);engine.lifecycle.dispose();});@@ -7646,11 +7770,11 @@ describe('mergeVisibleRasterLayers', () => {// ---- rasterizeLayer: parametric → paint, undoable via param re-convert -----const shapeLayerDoc = (over: { isLocked?: boolean } = {}): CanvasDocumentContractV2 => ({+const shapeLayerDoc = (over: { isLocked?: boolean } = {}): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [+ stacks: stacksFrom([{blendMode: 'normal',id: 'shape1',@@ -7662,14 +7786,14 @@ const shapeLayerDoc = (over: { isLocked?: boolean } = {}): CanvasDocumentContractransform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 20 },type: 'raster',},- ],+ ]),selectedLayerId: 'shape1',- version: 2,+ version: 3,width: 100,});describe('rasterizeLayer (parametric → paint)', () => {- const setup = (doc: CanvasDocumentContractV2) => {+ const setup = (doc: CanvasDocumentContractV3) => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -7794,8 +7918,8 @@ describe('rasterizeLayer (parametric → paint)', () => {it('rasterizes a gradient layer', () => {const doc = shapeLayerDoc();- doc.layers[0] = {- ...doc.layers[0],+ doc.stacks.raster[0] = {+ ...(doc.stacks.raster[0] as CanvasLayerContract),source: { angle: 45, kind: 'linear', stops: [{ color: '#000', offset: 0 }], type: 'gradient' },} as CanvasLayerContract;const { dispatch, engine } = setup(doc);@@ -7812,7 +7936,10 @@ describe('rasterizeLayer (parametric → paint)', () => {engine.lifecycle.dispose();const paintDoc = shapeLayerDoc();- paintDoc.layers[0] = { ...paintDoc.layers[0], source: { bitmap: null, type: 'paint' } } as CanvasLayerContract;+ paintDoc.stacks.raster[0] = {+ ...paintDoc.stacks.raster[0],+ source: { bitmap: null, type: 'paint' },+ } as CanvasLayerContract;const paint = setup(paintDoc);expect(paint.engine.layers.rasterizeLayer('shape1')).toBe(false);paint.engine.lifecycle.dispose();@@ -7840,7 +7967,7 @@ describe('rasterizeLayer (parametric → paint)', () => {vi.useRealTimers();});- const setupWithRealBitmapStore = (doc: CanvasDocumentContractV2) => {+ const setupWithRealBitmapStore = (doc: CanvasDocumentContractV3) => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -7861,7 +7988,7 @@ describe('rasterizeLayer (parametric → paint)', () => {dispatch: createTestMutationPort(store, 'p1').dispatch,encodeSurface,getLayerSource: (layerId) => {- const layer = engine.document.getDocument()?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLeaves(engine.document.getDocument()).find((candidate) => candidate.id === layerId);return layer && (layer.type === 'raster' || layer.type === 'control') ? layer.source : null;},getLayerSurface: () => ({ offset: { x: 0, y: 0 }, surface: fakeSurface }),@@ -7891,13 +8018,16 @@ describe('rasterizeLayer (parametric → paint)', () => {* `doc`, simulating what the real reducer would do — `createReactiveStore`'s* `dispatch` is a bare spy and does not mutate state on its own.*/- const applyLastConvert = (doc: CanvasDocumentContractV2, dispatch: Mock): CanvasDocumentContractV2 => {+ const applyLastConvert = (doc: CanvasDocumentContractV3, dispatch: Mock): CanvasDocumentContractV3 => {const converts = convertCalls(dispatch);const last = converts.at(-1);if (last?.type !== 'convertCanvasLayer') {throw new Error('expected a convertCanvasLayer dispatch');}- return { ...doc, layers: doc.layers.map((layer) => (layer.id === last.id ? last.layer : layer)) };+ return {+ ...doc,+ stacks: stacksFrom(getDocumentLeaves(doc).map((layer) => (layer.id === last.id ? last.layer : layer))),+ };};/**@@ -7943,7 +8073,7 @@ describe('rasterizeLayer (parametric → paint)', () => {// The guard drops the flush before it ever encodes/uploads.expect(uploadImage).not.toHaveBeenCalled();expect(paintSourceDispatches(dispatch)).toHaveLength(0);- const layer = engine.document.getDocument()!.layers[0] as CanvasRasterLayerContractV2;+ const layer = getDocumentLeaves(engine.document.getDocument()!)[0] as CanvasRasterLayerContractV2;expect(layer.source.type).toBe('shape');engine.lifecycle.dispose();@@ -7956,7 +8086,7 @@ describe('rasterizeLayer (parametric → paint)', () => {expect(uploadImage).not.toHaveBeenCalled();expect(paintSourceDispatches(dispatch)).toHaveLength(0);- const layer = engine.document.getDocument()!.layers[0] as CanvasRasterLayerContractV2;+ const layer = getDocumentLeaves(engine.document.getDocument()!)[0] as CanvasRasterLayerContractV2;expect(layer.source.type).toBe('shape');engine.lifecycle.dispose();@@ -7993,8 +8123,10 @@ describe('rasterizeLayer (parametric → paint)', () => {// would — the document now genuinely points at img-x, not `bitmap: null`.doc = {...doc,- layers: doc.layers.map((layer) =>- layer.id === firstPersist?.id ? { ...layer, source: firstPersist.source } : layer+ stacks: stacksFrom(+ getDocumentLeaves(doc).map((layer) =>+ layer.id === firstPersist?.id ? { ...layer, source: firstPersist.source } : layer+ )),};setDocument(doc);@@ -8012,7 +8144,7 @@ describe('rasterizeLayer (parametric → paint)', () => {doc = applyLastConvert(doc, dispatch);setDocument(doc);raf.flush();- const layerAfterRedo = engine.document.getDocument()!.layers[0] as CanvasRasterLayerContractV2;+ const layerAfterRedo = getDocumentLeaves(engine.document.getDocument()!)[0] as CanvasRasterLayerContractV2;expect(layerAfterRedo.source).toEqual({ bitmap: null, offset: { x: 10, y: 20 }, type: 'paint' });// Flush again: the re-baked pixels are identical, so the content hash@@ -8032,12 +8164,14 @@ describe('rasterizeLayer (parametric → paint)', () => {// Applying it restores the document's bitmap ref — no longer null.doc = {...doc,- layers: doc.layers.map((layer) =>- layer.id === secondPersist?.id ? { ...layer, source: secondPersist.source } : layer+ stacks: stacksFrom(+ getDocumentLeaves(doc).map((layer) =>+ layer.id === secondPersist?.id ? { ...layer, source: secondPersist.source } : layer+ )),};setDocument(doc);- const layerFinal = engine.document.getDocument()!.layers[0] as CanvasRasterLayerContractV2;+ const layerFinal = getDocumentLeaves(engine.document.getDocument()!)[0] as CanvasRasterLayerContractV2;expect(layerFinal.source.type).toBe('paint');if (layerFinal.source.type === 'paint') {expect(layerFinal.source.bitmap).not.toBeNull();@@ -8073,18 +8207,18 @@ describe('rasterizeLayer (parametric → paint)', () => {const selectedImageDoc = (overrides: { isLocked?: boolean; isEnabled?: boolean } = {},selectedLayerId: string | null = 'a'-): CanvasDocumentContractV2 => ({+): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [{ ...rasterLayer('a'), ...overrides }],+ stacks: stacksFrom([{ ...rasterLayer('a'), ...overrides }]),selectedLayerId,- version: 2,+ version: 3,width: 100,});describe('nudgeSelectedLayer', () => {- const setup = (doc: CanvasDocumentContractV2, selectedLayerIds?: readonly string[]) => {+ const setup = (doc: CanvasDocumentContractV3, selectedLayerIds?: readonly string[]) => {const { store } = createFakeStore(doc);const dispatch = store.dispatch as Mock;const engine = createCanvasEngine({@@ -8125,18 +8259,16 @@ describe('nudgeSelectedLayer', () => {engine.layers.nudgeSelectedLayer(3, -2);expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenNthCalledWith(1, {- id: 'a',- patch: { transform: { x: 3, y: -2 } },- type: 'updateCanvasLayer',+ type: 'setCanvasLayerPositions',+ updates: [{ id: 'a', x: 3, y: -2 }],});expect(engine.stores.canUndo.get()).toBe(true);// Undo dispatches the inverse (back to the original position).engine.history.undo();expect(dispatch).toHaveBeenNthCalledWith(2, {- id: 'a',- patch: { transform: { x: 0, y: 0 } },- type: 'updateCanvasLayer',+ type: 'setCanvasLayerPositions',+ updates: [{ id: 'a', x: 0, y: 0 }],});engine.lifecycle.dispose();});@@ -8144,7 +8276,10 @@ describe('nudgeSelectedLayer', () => {it('nudges every selected layer together and undoes the batch atomically', () => {const doc = selectedImageDoc();const second = { ...rasterLayer('b'), transform: { ...rasterLayer('b').transform, x: 10, y: 20 } };- const { dispatch, engine } = setup({ ...doc, layers: [doc.layers[0]!, second] }, ['a', 'b']);+ const { dispatch, engine } = setup({ ...doc, stacks: stacksFrom([getDocumentLeaves(doc)[0]!, second]) }, [+ 'a',+ 'b',+ ]);engine.layers.nudgeSelectedLayer(3, -2);expect(dispatch).toHaveBeenNthCalledWith(1, {@@ -8267,15 +8402,15 @@ describe('move tool: drag through the pipeline', () => {// ---- ride-along: composed auto-create + stroke history entry -------------const imageSelectedDoc = (): CanvasDocumentContractV2 => ({+const imageSelectedDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,// Selected layer is an image (not paintable) → a brush stroke auto-creates a// fresh paint layer for the gesture.- layers: [rasterLayer('img')],+ stacks: stacksFrom([rasterLayer('img')]),selectedLayerId: 'img',- version: 2,+ version: 3,width: 100,});@@ -8368,13 +8503,13 @@ describe('engine-owned history: composed auto-create + stroke entry', () => {});describe('setStagedPreview', () => {- const emptyDoc = (bbox = { height: 100, width: 100, x: 0, y: 0 }): CanvasDocumentContractV2 => ({+ const emptyDoc = (bbox = { height: 100, width: 100, x: 0, y: 0 }): CanvasDocumentContractV3 => ({background: 'transparent',bbox,height: 100,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,});@@ -8634,13 +8769,13 @@ describe('commitRasterFilterResult', () => {type: 'raster',});- const filterDoc = (layers: CanvasLayerContract[] = [filterLayer()]): CanvasDocumentContractV2 => ({+ const filterDoc = (layers: CanvasLayerContract[] = [filterLayer()]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: layers[0]?.id ?? null,- version: 2,+ version: 3,width: 100,});@@ -8656,7 +8791,7 @@ describe('commitRasterFilterResult', () => {projectId,store,});- const before = structuredClone(engine.document.getDocument()!.layers[0]!);+ const before = structuredClone(getDocumentLeaves(engine.document.getDocument()!)[0]!);const exported = await engine.exports.exportLayerPixels(layer.id);if (exported.status !== 'ok') {throw new Error('expected a filterable export');@@ -8670,7 +8805,7 @@ describe('commitRasterFilterResult', () => {expect(result).toEqual({ layerId: layer.id, status: 'committed' });expect(getCanvasOperations(engine).controller.getSnapshot()).toEqual({ status: 'idle' });- const after = engine.document.getDocument()!.layers[0]!;+ const after = getDocumentLeaves(engine.document.getDocument()!)[0]!;const { adjustments: _adjustments, ...beforeWithoutAdjustments } = before as CanvasRasterLayerContractV2;expect(after).toEqual({...beforeWithoutAdjustments,@@ -8687,7 +8822,7 @@ describe('commitRasterFilterResult', () => {const forwardSources = backend.drawSourcesFor(forwardExport.surface as StubRasterSurface);engine.history.undo();- expect(engine.document.getDocument()!.layers[0]).toEqual(before);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(before);expect(engine.stores.canUndo.get()).toBe(false);const undoExport = await engine.exports.exportLayerPixels(layer.id);expect(undoExport.status).toBe('ok');@@ -8701,7 +8836,7 @@ describe('commitRasterFilterResult', () => {}engine.history.redo();- expect(engine.document.getDocument()!.layers[0]).toEqual(after);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(after);expect(engine.stores.canRedo.get()).toBe(false);const redoExport = await engine.exports.exportLayerPixels(layer.id);expect(redoExport.status).toBe('ok');@@ -8742,13 +8877,15 @@ describe('commitRasterFilterResult', () => {if (result.status !== 'committed') {throw new Error('expected a committed copy');}- expect(engine.document.getDocument()!.layers.map((candidate) => candidate.id)).toEqual([+ expect(getDocumentLeaves(engine.document.getDocument()!).map((candidate) => candidate.id)).toEqual([result.layerId,'source','below',]);- expect(engine.document.getDocument()!.layers.find((candidate) => candidate.id === 'source')).toEqual(sourceBefore);- const copy = engine.document.getDocument()!.layers[0]!;+ expect(getDocumentLeaves(engine.document.getDocument()!).find((candidate) => candidate.id === 'source')).toEqual(+ sourceBefore+ );+ const copy = getDocumentLeaves(engine.document.getDocument()!)[0]!;expect(copy).toMatchObject({blendMode: source.blendMode,isEnabled: source.isEnabled,@@ -8762,17 +8899,20 @@ describe('commitRasterFilterResult', () => {expect((await engine.exports.exportLayerPixels(result.layerId)).status).toBe('ok');engine.history.undo();- expect(engine.document.getDocument()!.layers.map((candidate) => candidate.id)).toEqual(['source', 'below']);+ expect(getDocumentLeaves(engine.document.getDocument()!).map((candidate) => candidate.id)).toEqual([+ 'source',+ 'below',+ ]);expect(engine.document.getDocument()!.selectedLayerId).toBe(below.id);expect(engine.stores.canUndo.get()).toBe(false);engine.history.redo();- expect(engine.document.getDocument()!.layers.map((candidate) => candidate.id)).toEqual([+ expect(getDocumentLeaves(engine.document.getDocument()!).map((candidate) => candidate.id)).toEqual([result.layerId,'source','below',]);expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);- expect(engine.document.getDocument()!.layers[0]).toEqual(copy);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(copy);expect(engine.stores.canRedo.get()).toBe(false);engine.lifecycle.dispose();});@@ -8816,7 +8956,7 @@ describe('commitRasterFilterResult', () => {});expect(result).toEqual({ layerId: source.id, status: 'committed' });- const after = engine.document.getDocument()!.layers[0]!;+ const after = getDocumentLeaves(engine.document.getDocument()!)[0]!;expect(after).toMatchObject({filter: { settings: { radius: 8 }, type: 'content_shuffle' },source: { bitmap: durableImage, offset: { x: 7, y: -3 }, type: 'paint' },@@ -8824,9 +8964,9 @@ describe('commitRasterFilterResult', () => {type: 'control',});engine.history.undo();- expect(engine.document.getDocument()!.layers[0]).toEqual(before);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(before);engine.history.redo();- expect(engine.document.getDocument()!.layers[0]).toEqual(after);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(after);engine.lifecycle.dispose();});@@ -8869,8 +9009,11 @@ describe('commitRasterFilterResult', () => {});expect(result.status).toBe('committed');- expect(engine.document.getDocument()!.layers.map((layer) => layer.type)).toEqual([target, 'control']);- expect(engine.document.getDocument()!.layers[0]).toMatchObject({+ const saved = engine.document.getDocument()!.stacks[target][0]!;+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(+ target === 'control' ? [saved.id, 'control'] : ['control', saved.id]+ );+ expect(saved).toMatchObject({filter: { settings: {}, type: 'canny_edge_detection' },source: { offset: { x: 7, y: -3 }, type: 'paint' },transform: source.transform,@@ -8904,7 +9047,7 @@ describe('commitRasterFilterResult', () => {});expect(result.status).toBe('committed');- expect(engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toMatchObject({source: { offset: { x: -4, y: 7 }, type: 'paint' },transform: source.transform,type: 'control',@@ -8942,7 +9085,7 @@ describe('commitRasterFilterResult', () => {});expect(result.status).toBe('committed');- const created = engine.document.getDocument()!.layers[0];+ const created = getDocumentLeaves(engine.document.getDocument()!)[0];expect(created?.type === 'control' ? created.adapter.kind : null).toBe(expectedKind);engine.lifecycle.dispose();}@@ -9005,7 +9148,7 @@ describe('commitRasterFilterResult', () => {}engine.history.undo();- expect(engine.document.getDocument()!.layers[0]).toEqual(source);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(source);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);unsubscribeThumbnail();@@ -9112,7 +9255,7 @@ describe('commitRasterFilterResult', () => {expect(bitmapStore.discardLayer).toHaveBeenCalledTimes(2);expect(bitmapStore.markLayerDirty).not.toHaveBeenCalled();- const redone = engine.document.getDocument()!.layers[0];+ const redone = getDocumentLeaves(engine.document.getDocument()!)[0];expect(redone).toMatchObject({ source: { bitmap: durableImage, type: 'paint' } });if (redone?.type === 'raster' && redone.source.type === 'paint') {expect(redone.source.bitmap).toEqual(durableImage);@@ -9166,10 +9309,9 @@ describe('commitRasterFilterResult', () => {dispatch: createTestMutationPort(store, projectId).dispatch,encodeSurface: () => Promise.resolve(new Blob(['unpersisted-paint'], { type: 'image/png' })),getLayerSource: (layerId) => {- const layer = store- .getState()- .projects.find((project) => project.id === projectId)- ?.canvas.document.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLeaves(+ store.getState().projects.find((project) => project.id === projectId)?.canvas.document+ ).find((candidate) => candidate.id === layerId);return layer?.type === 'raster' || layer?.type === 'control' ? layer.source : null;},getLayerSurface: () => placed,@@ -9235,7 +9377,7 @@ describe('commitRasterFilterResult', () => {expect(uploadImage).not.toHaveBeenCalled();expect(bitmapUpdateActions(harness.store)).toHaveLength(0);expect(harness.engine.document.getDocument()).toEqual(committed);- expect(harness.engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(harness.engine.document.getDocument()!)[0]).toMatchObject({source: { bitmap: durableImage, type: 'paint' },});const cache = await harness.engine.exports.exportLayerPixels(harness.source.id);@@ -9329,7 +9471,7 @@ describe('commitRasterFilterResult', () => {expect(harness.engine.document.getDocument()).toEqual(committed);expect(harness.engine.stores.canUndo.get()).toBe(true);expect(harness.engine.stores.canRedo.get()).toBe(false);- const redone = harness.engine.document.getDocument()!.layers[0];+ const redone = getDocumentLeaves(harness.engine.document.getDocument()!)[0];expect(redone).toMatchObject({ source: { bitmap: durableImage, type: 'paint' } });harness.engine.lifecycle.dispose();});@@ -9352,7 +9494,7 @@ describe('commitRasterFilterResult', () => {throw new Error('expected a committed filtered copy');}const durableCopy = structuredClone(- harness.engine.document.getDocument()!.layers.find((layer) => layer.id === copied.layerId)!+ getDocumentLeaves(harness.engine.document.getDocument()!).find((layer) => layer.id === copied.layerId)!);harness.engine.selection.selectAll();@@ -9369,9 +9511,9 @@ describe('commitRasterFilterResult', () => {harness.engine.history.undo();expect((await harness.engine.exports.exportLayerPixels(copied.layerId)).status).toBe('missing');harness.engine.history.redo();- expect(harness.engine.document.getDocument()!.layers.find((layer) => layer.id === copied.layerId)).toEqual(- durableCopy- );+ expect(+ getDocumentLeaves(harness.engine.document.getDocument()!).find((layer) => layer.id === copied.layerId)+ ).toEqual(durableCopy);uploaded.resolve({ height: 10, imageName: 'stale-copy-paint', width: 10 });await barrier;@@ -9382,9 +9524,9 @@ describe('commitRasterFilterResult', () => {.filter((action) => action.type === 'updateCanvasLayerSource' && action.id === copied.layerId);expect(staleUpdates).toHaveLength(0);expect(harness.discardLayer).toHaveBeenCalledWith(copied.layerId);- expect(harness.engine.document.getDocument()!.layers.find((layer) => layer.id === copied.layerId)).toEqual(- durableCopy- );+ expect(+ getDocumentLeaves(harness.engine.document.getDocument()!).find((layer) => layer.id === copied.layerId)+ ).toEqual(durableCopy);expect(harness.engine.stores.canUndo.get()).toBe(true);const cache = await harness.engine.exports.exportLayerPixels(copied.layerId);expect(cache.status).toBe('ok');@@ -9426,7 +9568,7 @@ describe('commitRasterFilterResult', () => {if (result.status !== 'committed') {throw new Error('expected a committed copy');}- const copy = structuredClone(engine.document.getDocument()!.layers[0]!);+ const copy = structuredClone(getDocumentLeaves(engine.document.getDocument()!)[0]!);engine.history.undo();expect(engine.document.getDocument()).toEqual(beforeDocument);const adjustedDeletesBefore = adjustedSurfaceCacheDeletes.length;@@ -9449,7 +9591,7 @@ describe('commitRasterFilterResult', () => {expect(adjustedSurfaceCacheDeletes).toHaveLength(adjustedDeletesBefore);engine.history.redo();- expect(engine.document.getDocument()!.layers[0]).toEqual(copy);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(copy);expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect((await engine.exports.exportLayerPixels(result.layerId)).status).toBe('ok');expect(engine.stores.canUndo.get()).toBe(true);@@ -9597,7 +9739,7 @@ describe('commitRasterFilterResult', () => {it('returns missing without mutation when the source is deleted', async () => {const harness = await createPendingGuardHarness();- harness.setDocument({ ...harness.document, layers: [] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([]) });harness.decoded.resolve(new Blob());await expect(harness.pending).resolves.toEqual({ status: 'missing' });@@ -9608,7 +9750,7 @@ describe('commitRasterFilterResult', () => {it('returns stale without mutation when the source contract changes', async () => {const harness = await createPendingGuardHarness();- harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, opacity: 0.2 }] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([{ ...harness.layer, opacity: 0.2 }]) });harness.decoded.resolve(new Blob());await expect(harness.pending).resolves.toEqual({ status: 'stale' });@@ -9619,7 +9761,7 @@ describe('commitRasterFilterResult', () => {it('returns locked without mutation when the source becomes locked', async () => {const harness = await createPendingGuardHarness();- harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, isLocked: true }] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([{ ...harness.layer, isLocked: true }]) });harness.decoded.resolve(new Blob());await expect(harness.pending).resolves.toEqual({ status: 'locked' });@@ -9637,7 +9779,7 @@ describe('commitRasterFilterResult', () => {type: 'control',withTransparencyEffect: false,};- harness.setDocument({ ...harness.document, layers: [control] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([control]) });harness.decoded.resolve(new Blob());await expect(harness.pending).resolves.toEqual({ status: 'stale' });@@ -10024,7 +10166,7 @@ describe('commitRasterFilterResult', () => {expect(result).toEqual({ layerId: source.id, status: 'committed' });const reducerDocument = store.getState().projects.find((project) => project.id === projectId)!.canvas.document;- expect(reducerDocument.layers[0]).toMatchObject({+ expect(getDocumentLeaves(reducerDocument)[0]).toMatchObject({source: { bitmap: durableImage, type: 'paint' },});expect(engine.document.getDocument()).toBe(reducerDocument);@@ -10069,7 +10211,7 @@ describe('commitRasterFilterResult', () => {if (result.status !== 'committed') {throw new Error('expected a committed copy');}- const copy = structuredClone(engine.document.getDocument()!.layers[0]!);+ const copy = structuredClone(getDocumentLeaves(engine.document.getDocument()!)[0]!);const unsubscribeFault = store.subscribe(() => {throw new Error('copy undo observer failed');});@@ -10084,7 +10226,7 @@ describe('commitRasterFilterResult', () => {unsubscribeFault();engine.history.redo();- expect(engine.document.getDocument()!.layers[0]).toEqual(copy);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(copy);expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);@@ -10131,7 +10273,7 @@ describe('commitRasterFilterResult', () => {expect(() => engine.history.undo()).toThrow('copy removal failed');- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(true);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(true);expect(engine.document.getDocument()!.selectedLayerId).toBe(selected.id);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);@@ -10216,13 +10358,13 @@ describe('commitGeneratedImageResult', () => {withTransparencyEffect: true,});- const workflowDocument = (layers: CanvasLayerContract[] = [workflowRaster()]): CanvasDocumentContractV2 => ({+ const workflowDocument = (layers: CanvasLayerContract[] = [workflowRaster()]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: layers.at(-1)?.id ?? null,- version: 2,+ version: 3,width: 100,});@@ -10319,7 +10461,7 @@ describe('commitGeneratedImageResult', () => {if (result.status !== 'committed') {throw new Error('expected a committed control copy');}- const created = engine.document.getDocument()!.layers.find((layer) => layer.id === result.layerId);+ const created = getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === result.layerId);expect(created?.type === 'control' ? created.adapter.kind : null).toBe(expectedKind);// Without a getDefaultControlModel option the layer starts model-less.expect(created?.type === 'control' ? created.adapter.model : 'wrong-type').toBeNull();@@ -10356,7 +10498,7 @@ describe('commitGeneratedImageResult', () => {throw new Error('expected a committed control copy');}expect(getDefaultControlModel).toHaveBeenCalledWith('sd-1');- const created = engine.document.getDocument()!.layers.find((layer) => layer.id === result.layerId);+ const created = getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === result.layerId);expect(created?.type === 'control' ? created.adapter.model : null).toBe('sd1-union');engine.lifecycle.dispose();});@@ -10388,7 +10530,7 @@ describe('commitGeneratedImageResult', () => {});expect(result).toEqual({ layerId: source.id, status: 'committed' });- const after = engine.document.getDocument()!.layers[0]!;+ const after = getDocumentLeaves(engine.document.getDocument()!)[0]!;expect(after).toEqual({blendMode: source.blendMode,id: source.id,@@ -10412,12 +10554,12 @@ describe('commitGeneratedImageResult', () => {expect(engine.stores.canUndo.get()).toBe(true);engine.history.undo();- expect(engine.document.getDocument()!.layers[0]).toEqual(before);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(before);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);engine.history.redo();- expect(engine.document.getDocument()!.layers[0]).toEqual(after);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(after);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);expect(bitmapStore.discardLayer).toHaveBeenCalledTimes(2);@@ -10448,15 +10590,15 @@ describe('commitGeneratedImageResult', () => {})).resolves.toEqual({ layerId: source.id, status: 'committed' });- expect(engine.document.getDocument()!.layers[0]).toEqual({+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual({...source,source: { bitmap: generatedImage, offset: generatedOrigin, type: 'paint' },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },});engine.history.undo();- expect(engine.document.getDocument()!.layers[0]).toEqual(source);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(source);engine.history.redo();- expect(engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toMatchObject({adapter: source.type === 'control' ? source.adapter : undefined,filter: source.type === 'control' ? source.filter : undefined,withTransparencyEffect: true,@@ -10492,14 +10634,14 @@ describe('commitGeneratedImageResult', () => {throw new Error(`expected a committed copy, received ${JSON.stringify(result)}`);}- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([+ source.id,result.layerId,above.id,- source.id,selected.id,]);- expect(engine.document.getDocument()!.layers[2]).toEqual(source);- expect(engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(source);+ expect(engine.document.getDocument()!.stacks.raster[0]).toMatchObject({id: result.layerId,isEnabled: true,isLocked: false,@@ -10514,7 +10656,7 @@ describe('commitGeneratedImageResult', () => {expect(engine.document.getDocument()).toEqual(document);expect(engine.stores.canUndo.get()).toBe(false);engine.history.redo();- expect(engine.document.getDocument()!.layers[0]?.id).toBe(result.layerId);+ expect(engine.document.getDocument()!.stacks.raster[0]?.id).toBe(result.layerId);expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect(engine.stores.canRedo.get()).toBe(false);engine.lifecycle.dispose();@@ -10583,7 +10725,7 @@ describe('commitGeneratedImageResult', () => {it('returns missing after decode when the source was deleted', async () => {const harness = await createPendingGuardHarness();- harness.setDocument({ ...harness.document, layers: [] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([]) });harness.decoded.resolve(new Blob());await expect(harness.pending).resolves.toEqual({ status: 'missing' });expect(harness.store.dispatch).not.toHaveBeenCalled();@@ -10592,7 +10734,7 @@ describe('commitGeneratedImageResult', () => {it('returns locked after decode when the source became locked', async () => {const harness = await createPendingGuardHarness();- harness.setDocument({ ...harness.document, layers: [{ ...harness.source, isLocked: true }] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([{ ...harness.source, isLocked: true }]) });harness.decoded.resolve(new Blob());await expect(harness.pending).resolves.toEqual({ status: 'locked' });expect(harness.store.dispatch).not.toHaveBeenCalled();@@ -10601,7 +10743,7 @@ describe('commitGeneratedImageResult', () => {it('returns unsupported after decode when the source became a mask', async () => {const harness = await createPendingGuardHarness();- harness.setDocument({ ...harness.document, layers: [maskLayer(harness.source.id)] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([maskLayer(harness.source.id)]) });harness.decoded.resolve(new Blob());await expect(harness.pending).resolves.toEqual({ status: 'unsupported' });expect(harness.store.dispatch).not.toHaveBeenCalled();@@ -10610,7 +10752,7 @@ describe('commitGeneratedImageResult', () => {it('returns stale after decode when the immutable source contract changed', async () => {const harness = await createPendingGuardHarness();- harness.setDocument({ ...harness.document, layers: [{ ...harness.source, opacity: 0.1 }] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([{ ...harness.source, opacity: 0.1 }]) });harness.decoded.resolve(new Blob());await expect(harness.pending).resolves.toEqual({ status: 'stale' });expect(harness.store.dispatch).not.toHaveBeenCalled();@@ -10809,7 +10951,9 @@ describe('commitGeneratedImageResult', () => {await expect(pending).resolves.toEqual({ status: 'stale' });expect(engine.document.getDocument()).toEqual(afterPaintEdit);- expect(engine.document.getDocument()!.layers[0]).not.toMatchObject({ source: { bitmap: generatedImage } });+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).not.toMatchObject({+ source: { bitmap: generatedImage },+ });expect(engine.stores.canUndo.get()).toBe(true);engine.lifecycle.dispose();});@@ -10984,7 +11128,7 @@ describe('commitGeneratedImageResult', () => {}(reactive.store.dispatch as Mock).mockClear();faults.armCreateHook(successfulCreates, () => {- reactive.setDocument({ ...document, layers: [{ ...source, opacity: 0.2 }] });+ reactive.setDocument({ ...document, stacks: stacksFrom([{ ...source, opacity: 0.2 }]) });});await expect(@@ -11084,7 +11228,7 @@ describe('commitGeneratedImageResult', () => {expect(() => engine.history.redo()).toThrow('generated cache allocation failed');expect(engine.document.getDocument()).toEqual(document);expect(engine.document.getDocument()!.selectedLayerId).toBe(selected.id);- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(false);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(false);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);@@ -11152,13 +11296,13 @@ describe('replaceSelectionFromImage', () => {type: 'raster',});- const sourceDocument = (layer: CanvasLayerContract = sourceLayer()): CanvasDocumentContractV2 => ({+ const sourceDocument = (layer: CanvasLayerContract = sourceLayer()): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: layer.id,- version: 2,+ version: 3,width: 100,});@@ -11396,19 +11540,19 @@ describe('replaceSelectionFromImage', () => {expected: 'missing',label: 'source deletion',mutate: (harness: Awaited<ReturnType<typeof createHarness>>) =>- harness.setDocument({ ...harness.document, layers: [] }),+ harness.setDocument({ ...harness.document, stacks: stacksFrom([]) }),},{expected: 'stale',label: 'source contract edit',mutate: (harness: Awaited<ReturnType<typeof createHarness>>) =>- harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, opacity: 0.5 }] }),+ harness.setDocument({ ...harness.document, stacks: stacksFrom([{ ...harness.layer, opacity: 0.5 }]) }),},{expected: 'locked',label: 'source lock',mutate: (harness: Awaited<ReturnType<typeof createHarness>>) =>- harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, isLocked: true }] }),+ harness.setDocument({ ...harness.document, stacks: stacksFrom([{ ...harness.layer, isLocked: true }]) }),},{expected: 'unsupported',@@ -11420,7 +11564,7 @@ describe('replaceSelectionFromImage', () => {mask: { bitmap: null, fill: { color: '#fff', style: 'solid' } },type: 'inpaint_mask',};- harness.setDocument({ ...harness.document, layers: [mask] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([mask]) });},},{@@ -11553,16 +11697,16 @@ describe('commitMaskImageResult', () => {type: 'regional_guidance',});- const docFor = (target: 'inpaint_mask' | 'regional_guidance'): CanvasDocumentContractV2 => {+ const docFor = (target: 'inpaint_mask' | 'regional_guidance'): CanvasDocumentContractV3 => {const layer = source();const below = { ...source(), id: 'below', name: 'Below' };return {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [target === 'inpaint_mask' ? existingInpaint() : existingRegional(), layer, below],+ stacks: stacksFrom([target === 'inpaint_mask' ? existingInpaint() : existingRegional(), layer, below]),selectedLayerId: below.id,- version: 2,+ version: 3,width: 100,};};@@ -11636,11 +11780,11 @@ describe('commitMaskImageResult', () => {if (result.status !== 'committed') {throw new Error('expected a committed mask');}- const created = engine.document.getDocument()!.layers.find((layer) => layer.id === result.layerId)!;+ const created = getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === result.layerId)!;expect(created).toEqual({ ...expected, id: result.layerId });- expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual([result.layerId,- document.layers[0]!.id,+ getDocumentLeaves(document)[0]!.id,'source','below',]);@@ -11656,7 +11800,9 @@ describe('commitMaskImageResult', () => {expect(engine.stores.canRedo.get()).toBe(true);engine.history.redo();- expect(engine.document.getDocument()!.layers.find((layer) => layer.id === result.layerId)).toEqual(created);+ expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === result.layerId)).toEqual(+ created+ );expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);@@ -11697,7 +11843,7 @@ describe('commitMaskImageResult', () => {expect(engine.document.getDocument()).toBe(store.getState().projects.find((project) => project.id === projectId)!.canvas.document);- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(true);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(true);expect(engine.stores.canUndo.get()).toBe(true);engine.history.undo();@@ -11830,7 +11976,7 @@ describe('commitMaskImageResult', () => {expect(() => engine.history.undo()).toThrow('mask removal failed');- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(true);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(true);expect(engine.document.getDocument()!.selectedLayerId).toBe('below');expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);@@ -11844,7 +11990,7 @@ describe('commitMaskImageResult', () => {const guardHarness = async () => {const layer = source();- const document: CanvasDocumentContractV2 = { ...docFor('inpaint_mask'), layers: [layer] };+ const document: CanvasDocumentContractV3 = { ...docFor('inpaint_mask'), stacks: stacksFrom([layer]) };const reactive = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -11885,19 +12031,19 @@ describe('commitMaskImageResult', () => {expected: 'missing',label: 'source deletion',mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) =>- harness.setDocument({ ...harness.document, layers: [] }),+ harness.setDocument({ ...harness.document, stacks: stacksFrom([]) }),},{expected: 'stale',label: 'source contract edit',mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) =>- harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, opacity: 0.4 }] }),+ harness.setDocument({ ...harness.document, stacks: stacksFrom([{ ...harness.layer, opacity: 0.4 }]) }),},{expected: 'locked',label: 'source lock',mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) =>- harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, isLocked: true }] }),+ harness.setDocument({ ...harness.document, stacks: stacksFrom([{ ...harness.layer, isLocked: true }]) }),},{expected: 'unsupported',@@ -11909,7 +12055,7 @@ describe('commitMaskImageResult', () => {mask: { bitmap: null, fill: { color: '#fff', style: 'solid' } },type: 'inpaint_mask',};- harness.setDocument({ ...harness.document, layers: [mask] });+ harness.setDocument({ ...harness.document, stacks: stacksFrom([mask]) });},},{@@ -11972,13 +12118,13 @@ describe('guarded filter previews', () => {name: 'Upscaler',type: 'spandrel_image_to_image',};- const emptyDoc = (): CanvasDocumentContractV2 => ({+ const emptyDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 100,});@@ -12013,7 +12159,7 @@ describe('guarded filter previews', () => {it('auto-processes a debounced preview after a filter draft update', async () => {const layer = guardableLayer('auto-filter');- const { store } = createReactiveStore({ ...emptyDoc(), layers: [layer] });+ const { store } = createReactiveStore({ ...emptyDoc(), stacks: stacksFrom([layer]) });const runGraph = vi.fn(() =>Promise.resolve({ height: 10, imageName: 'auto.png', origin: 'test', output: {}, width: 10 }));@@ -12050,7 +12196,7 @@ describe('guarded filter previews', () => {it('setFilterOperationAutoProcess toggles the session and stops auto-runs', async () => {const layer = guardableLayer('auto-filter-toggle');- const { store } = createReactiveStore({ ...emptyDoc(), layers: [layer] });+ const { store } = createReactiveStore({ ...emptyDoc(), stacks: stacksFrom([layer]) });const runGraph = vi.fn(() =>Promise.resolve({ height: 10, imageName: 'auto.png', origin: 'test', output: {}, width: 10 }));@@ -12085,7 +12231,7 @@ describe('guarded filter previews', () => {it('clears the session and ends the operation after a committed filter commit', async () => {const source = guardableLayer('commit-clear');- const document = { ...emptyDoc(), layers: [source], selectedLayerId: source.id };+ const document = { ...emptyDoc(), stacks: stacksFrom([source]), selectedLayerId: source.id };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: filterBitmapBackend(),@@ -12116,7 +12262,7 @@ describe('guarded filter previews', () => {'rejects a decoded dimension mismatch for canny %s without scaling, then retries successfully',async (target) => {const source = guardableLayer('dimension-source');- const document = { ...emptyDoc(), layers: [source], selectedLayerId: source.id };+ const document = { ...emptyDoc(), stacks: stacksFrom([source]), selectedLayerId: source.id };const { projectId, store } = createReducerBackedStore(document);const base = createTestStubRasterBackend();const decodedDimensions = [@@ -12189,14 +12335,14 @@ describe('guarded filter previews', () => {);expect(bitmapDraws.length).toBeGreaterThan(0);expect(bitmapDraws.every((entry) => entry.args.length === 3)).toBe(true);- expect(engine.document.getDocument()?.layers).toHaveLength(target === 'apply' ? 1 : 2);+ expect(getDocumentLeaves(engine.document.getDocument())).toHaveLength(target === 'apply' ? 1 : 2);engine.lifecycle.dispose();});it('interaction lock blocks Filter and Select Object launches without creating sessions', async () => {const layer = guardableLayer('locked-launch');- const { store } = createReactiveStore({ ...emptyDoc(), layers: [layer] });+ const { store } = createReactiveStore({ ...emptyDoc(), stacks: stacksFrom([layer]) });const engine = createCanvasEngine({backend: filterBitmapBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -12217,7 +12363,7 @@ describe('guarded filter previews', () => {it('keeps an active Select Object operation available to cancel while interaction is locked', async () => {const layer = guardableLayer('active-before-lock');- const { store } = createReactiveStore({ ...emptyDoc(), layers: [layer] });+ const { store } = createReactiveStore({ ...emptyDoc(), stacks: stacksFrom([layer]) });const engine = createCanvasEngine({backend: filterBitmapBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -12266,7 +12412,7 @@ describe('guarded filter previews', () => {it('publishes a guarded filter preview while the exported layer snapshot remains current', async () => {const bitmaps = createDeferredBitmapBackend();- const document = { ...emptyDoc(), layers: [guardableLayer('L')] };+ const document = { ...emptyDoc(), stacks: stacksFrom([guardableLayer('L')]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: bitmaps.backend,@@ -12293,7 +12439,7 @@ describe('guarded filter previews', () => {it('owns a guarded filter session independently of the launching view', async () => {const layer = { ...guardableLayer('L'), filter: { settings: { radius: 2 }, type: 'content_shuffle' } };- const document = { ...emptyDoc(), layers: [layer] };+ const document = { ...emptyDoc(), stacks: stacksFrom([layer]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: filterBitmapBackend(),@@ -12337,7 +12483,7 @@ describe('guarded filter previews', () => {...guardableLayer('manual'),filter: { settings: { coarse: true }, type: 'lineart_edge_detection' },};- const document = { ...emptyDoc(), layers: [unfiltered, manual] };+ const document = { ...emptyDoc(), stacks: stacksFrom([unfiltered, manual]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12364,7 +12510,7 @@ describe('guarded filter previews', () => {it('does not replace another layer filter session with a recommendation', async () => {const first = guardableLayer('first');const second = guardableLayer('second');- const document = { ...emptyDoc(), layers: [first, second] };+ const document = { ...emptyDoc(), stacks: stacksFrom([first, second]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12385,7 +12531,7 @@ describe('guarded filter previews', () => {it('does not overwrite a same-layer draft or preview on rapid recommendations', async () => {const layer = guardableLayer('recommended');- const document = { ...emptyDoc(), layers: [layer] };+ const document = { ...emptyDoc(), stacks: stacksFrom([layer]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12413,7 +12559,7 @@ describe('guarded filter previews', () => {it('does not replace a different active canvas operation with a recommendation', async () => {const first = guardableLayer('first');const second = guardableLayer('second');- const document = { ...emptyDoc(), layers: [first, second] };+ const document = { ...emptyDoc(), stacks: stacksFrom([first, second]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12467,7 +12613,7 @@ describe('guarded filter previews', () => {const createFilterFlowHarness = async (sourceType: 'raster' | 'control') => {const source = filterFlowLayer(sourceType);- const document = { ...emptyDoc(), layers: [source], selectedLayerId: source.id };+ const document = { ...emptyDoc(), stacks: stacksFrom([source]), selectedLayerId: source.id };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: filterBitmapBackend(),@@ -12542,7 +12688,7 @@ describe('guarded filter previews', () => {const source = filterFlowLayer('raster');const { projectId, store } = createReducerBackedStore({...emptyDoc(),- layers: [source],+ stacks: stacksFrom([source]),selectedLayerId: source.id,});const graph = createDeferred<{ height: number; imageName: string; origin: string; output: {}; width: number }>();@@ -12606,7 +12752,7 @@ describe('guarded filter previews', () => {'preserves $type/$target output geometry through preview, commit, and one-entry undo/redo',async ({ expectedRect, output, settings, target, type }) => {const source = filterFlowLayer('raster');- const document = { ...emptyDoc(), layers: [source], selectedLayerId: source.id };+ const document = { ...emptyDoc(), stacks: stacksFrom([source]), selectedLayerId: source.id };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: filterBitmapBackend(output.width, output.height),@@ -12629,8 +12775,8 @@ describe('guarded filter previews', () => {expect(getCanvasOperations(engine).stores.filterSession.get()?.preview?.rect).toEqual(expectedRect);await getCanvasOperations(engine).commitFilterOperation(target, () => Promise.resolve());- const committedId = target === 'apply' ? source.id : engine.document.getDocument()!.layers[0]!.id;- const committed = engine.document.getDocument()!.layers.find((layer) => layer.id === committedId)!;+ const committedId = target === 'apply' ? source.id : getDocumentLeaves(engine.document.getDocument()!)[0]!.id;+ const committed = getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === committedId)!;expect(committed.transform).toEqual(source.transform);if (!('source' in committed)) {throw new Error('expected a raster or control filter result');@@ -12648,7 +12794,7 @@ describe('guarded filter previews', () => {expect(engine.document.getDocument()).toEqual(document);expect(engine.stores.canUndo.get()).toBe(false);engine.history.redo();- const redone = engine.document.getDocument()!.layers.find((layer) => layer.id === committedId)!;+ const redone = getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === committedId)!;expect(redone).toEqual(committed);expect(engine.stores.canRedo.get()).toBe(false);engine.lifecycle.dispose();@@ -12679,7 +12825,7 @@ describe('guarded filter previews', () => {expect(makeDurable).toHaveBeenCalledTimes(2);expect(getCanvasOperations(engine).stores.filterSession.get()).toBeNull();expect(getCanvasOperations(engine).controller.getSnapshot()).toEqual({ status: 'idle' });- expect(engine.document.getDocument()!.layers[0]).toMatchObject({+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toMatchObject({filter: source.filter,opacity: source.opacity,blendMode: source.blendMode,@@ -12703,8 +12849,11 @@ describe('guarded filter previews', () => {await getCanvasOperations(engine).commitFilterOperation(target, () => Promise.resolve());expect(getCanvasOperations(engine).stores.filterSession.get()).toBeNull();- expect(engine.document.getDocument()!.layers.map((layer) => layer.type)).toEqual([target, 'control']);- expect(engine.document.getDocument()!.layers[0]).toMatchObject({+ const saved = engine.document.getDocument()!.stacks[target][0]!;+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(+ target === 'control' ? [saved.id, source.id] : [source.id, saved.id]+ );+ expect(saved).toMatchObject({blendMode: source.blendMode,opacity: source.opacity,source: { offset: { x: 7, y: -3 }, type: 'paint' },@@ -12712,7 +12861,7 @@ describe('guarded filter previews', () => {});expect(engine.stores.canUndo.get()).toBe(true);engine.history.undo();- expect(engine.document.getDocument()!.layers).toEqual([source]);+ expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual([source]);expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();}@@ -12731,7 +12880,7 @@ describe('guarded filter previews', () => {resolvePromotion();await pending;- expect(engine.document.getDocument()!.layers[0]).toEqual(source);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(source);expect(getCanvasOperations(engine).stores.filterSession.get()).toBeNull();expect(getCanvasOperations(engine).controller.getSnapshot()).toMatchObject({identity: { kind: 'select-object' },@@ -12743,7 +12892,7 @@ describe('guarded filter previews', () => {it('aborts an in-flight upload when a newer Process request wins', async () => {const source = filterFlowLayer('raster');- const document = { ...emptyDoc(), layers: [source], selectedLayerId: source.id };+ const document = { ...emptyDoc(), stacks: stacksFrom([source]), selectedLayerId: source.id };const { projectId, store } = createReducerBackedStore(document);const uploadSignals: AbortSignal[] = [];let uploadCount = 0;@@ -12791,7 +12940,7 @@ describe('guarded filter previews', () => {});it('makes filter and Select Object operations mutually exclusive', async () => {- const document = { ...emptyDoc(), layers: [guardableLayer('L')] };+ const document = { ...emptyDoc(), stacks: stacksFrom([guardableLayer('L')]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12814,7 +12963,7 @@ describe('guarded filter previews', () => {});it('refuses ordinary structural editing while a filter operation is active', async () => {- const document = { ...emptyDoc(), layers: [guardableLayer('L')] };+ const document = { ...emptyDoc(), stacks: stacksFrom([guardableLayer('L')]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12843,7 +12992,7 @@ describe('guarded filter previews', () => {'centrally blocks edits and undo during %s, then restores them after cancel',async (kind) => {const layer = guardableLayer('L');- const document = { ...emptyDoc(), layers: [layer], selectedLayerId: layer.id };+ const document = { ...emptyDoc(), stacks: stacksFrom([layer]), selectedLayerId: layer.id };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12894,7 +13043,10 @@ describe('guarded filter previews', () => {})).resolves.toEqual({ status: 'busy' });- expect(engine.document.getDocument()!.layers[0]).toMatchObject({ name: 'Renamed', transform: { x: 0 } });+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toMatchObject({+ name: 'Renamed',+ transform: { x: 0 },+ });expect(getCanvasOperations(engine).controller.getSnapshot()).toMatchObject({identity: { kind },status: 'active',@@ -12908,14 +13060,14 @@ describe('guarded filter previews', () => {expect(engine.stores.documentEditingLocked.get()).toBe(false);expect(engine.stores.documentEditingLayerId.get()).toBeNull();engine.history.undo();- expect(engine.document.getDocument()!.layers[0]?.name).toBe('L');+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]?.name).toBe('L');engine.lifecycle.dispose();});it('does not clear history while document editing is locked', async () => {const layer = guardableLayer('L');- const document = { ...emptyDoc(), layers: [layer] };+ const document = { ...emptyDoc(), stacks: stacksFrom([layer]) };const { projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12954,7 +13106,7 @@ describe('guarded filter previews', () => {it('invalidates the owned filter session when its guarded source changes', async () => {const layer = guardableLayer('L');- const document = { ...emptyDoc(), layers: [layer] };+ const document = { ...emptyDoc(), stacks: stacksFrom([layer]) };const { setDocument, store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -12969,7 +13121,7 @@ describe('guarded filter previews', () => {initialFilter: null,});- setDocument({ ...document, layers: [{ ...layer, opacity: 0.5 }] });+ setDocument({ ...document, stacks: stacksFrom([{ ...layer, opacity: 0.5 }]) });expect(getCanvasOperations(engine).controller.getSnapshot()).toEqual({ status: 'idle' });expect(getCanvasOperations(engine).stores.filterSession.get()).toBeNull();@@ -12979,7 +13131,7 @@ describe('guarded filter previews', () => {it('rejects a guarded filter preview when its source changes during decode', async () => {const bitmaps = createDeferredBitmapBackend();const layer = guardableLayer('L');- const document = { ...emptyDoc(), layers: [layer] };+ const document = { ...emptyDoc(), stacks: stacksFrom([layer]) };const { setDocument, store } = createReactiveStore(document);const engine = createCanvasEngine({backend: bitmaps.backend,@@ -13000,7 +13152,7 @@ describe('guarded filter previews', () => {await flushMicrotasks();setDocument({...document,- layers: [{ ...layer, source: { ...layer.source, fill: '#000' } } as CanvasLayerContract],+ stacks: stacksFrom([{ ...layer, source: { ...layer.source, fill: '#000' } } as CanvasLayerContract]),});bitmaps.resolveBitmap(0);@@ -13011,7 +13163,7 @@ describe('guarded filter previews', () => {it('rejects a guarded filter preview when raster adjustments change during decode', async () => {const bitmaps = createDeferredBitmapBackend();const layer = guardableLayer('L');- const document = { ...emptyDoc(), layers: [layer] };+ const document = { ...emptyDoc(), stacks: stacksFrom([layer]) };const { setDocument, store } = createReactiveStore(document);const engine = createCanvasEngine({backend: bitmaps.backend,@@ -13032,7 +13184,7 @@ describe('guarded filter previews', () => {await flushMicrotasks();setDocument({...document,- layers: [{ ...layer, adjustments: { brightness: 0.2, contrast: 0, saturation: 0 } }],+ stacks: stacksFrom([{ ...layer, adjustments: { brightness: 0.2, contrast: 0, saturation: 0 } }]),});bitmaps.resolveBitmap(0);@@ -13042,7 +13194,7 @@ describe('guarded filter previews', () => {it('rejects a guarded filter preview when the paint cache version changes during decode', async () => {const bitmaps = createDeferredBitmapBackend();- const document = { ...emptyDoc(), layers: [guardableLayer('L')] };+ const document = { ...emptyDoc(), stacks: stacksFrom([guardableLayer('L')]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: bitmaps.backend,@@ -13071,7 +13223,7 @@ describe('guarded filter previews', () => {it('returns missing when the guarded preview layer is deleted during decode', async () => {const bitmaps = createDeferredBitmapBackend();- const document = { ...emptyDoc(), layers: [guardableLayer('L')] };+ const document = { ...emptyDoc(), stacks: stacksFrom([guardableLayer('L')]) };const { setDocument, store } = createReactiveStore(document);const engine = createCanvasEngine({backend: bitmaps.backend,@@ -13090,7 +13242,7 @@ describe('guarded filter previews', () => {exported.guard);await flushMicrotasks();- setDocument({ ...document, layers: [] });+ setDocument({ ...document, stacks: stacksFrom([]) });bitmaps.resolveBitmap(0);await expect(pending).resolves.toBe('missing');@@ -13099,7 +13251,7 @@ describe('guarded filter previews', () => {it('rejects a guarded filter preview after document replacement reuses the layer id', async () => {const bitmaps = createDeferredBitmapBackend();- const document = { ...emptyDoc(), layers: [guardableLayer('L')] };+ const document = { ...emptyDoc(), stacks: stacksFrom([guardableLayer('L')]) };const { setDocument, store } = createReactiveStore(document);const engine = createCanvasEngine({backend: bitmaps.backend,@@ -13127,7 +13279,7 @@ describe('guarded filter previews', () => {it('lets only the newest guarded filter preview publish', async () => {const bitmaps = createDeferredBitmapBackend();- const document = { ...emptyDoc(), layers: [guardableLayer('L')] };+ const document = { ...emptyDoc(), stacks: stacksFrom([guardableLayer('L')]) };const { store } = createReactiveStore(document);const engine = createCanvasEngine({backend: bitmaps.backend,@@ -13180,7 +13332,7 @@ describe('guarded filter previews', () => {backend.createImageBitmap = vi.fn(() =>Promise.resolve(recordingBitmap(sourceNeedsBitmap && bitmapCall++ === 0 ? 'layer-source' : 'guarded-preview')));- const document = { ...emptyDoc(), layers: [layer], selectedLayerId: layer.id };+ const document = { ...emptyDoc(), stacks: stacksFrom([layer]), selectedLayerId: layer.id };const reactive = createReactiveStore(document);const engine = createCanvasEngine({backend,@@ -13224,7 +13376,7 @@ describe('guarded filter previews', () => {it('publishes an in-flight guarded preview across an active-project away/back transition', async () => {const bitmaps = createDeferredBitmapBackend();- const document = { ...emptyDoc(), layers: [guardableLayer('L')] };+ const document = { ...emptyDoc(), stacks: stacksFrom([guardableLayer('L')]) };const reactive = createReactiveStore(document);const engine = createCanvasEngine({backend: bitmaps.backend,@@ -13269,7 +13421,9 @@ describe('guarded filter previews', () => {const harness = await createPublishedGuardedPreview();harness.setDocument({...harness.document,- layers: [{ ...harness.layer, source: { ...harness.layer.source, fill: '#000' } } as CanvasLayerContract],+ stacks: stacksFrom([+ { ...harness.layer, source: { ...harness.layer.source, fill: '#000' } } as CanvasLayerContract,+ ]),});harness.raf.flush();@@ -13281,7 +13435,7 @@ describe('guarded filter previews', () => {const harness = await createPublishedGuardedPreview();harness.setDocument({...harness.document,- layers: [{ ...harness.layer, adjustments: { brightness: 0.3, contrast: 0, saturation: 0 } }],+ stacks: stacksFrom([{ ...harness.layer, adjustments: { brightness: 0.3, contrast: 0, saturation: 0 } }]),});harness.raf.flush();@@ -13487,10 +13641,9 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',await expect(engine.lifecycle.flushPendingUploads()).resolves.toBeUndefined();await expect(engine.lifecycle.flushPendingUploads()).resolves.toBeUndefined();- const authoritativeLayer = reducer.store- .getState()- .projects.find((project) => project.id === reducer.projectId)- ?.canvas.document.layers.find((layer) => layer.id === 'paint1');+ const authoritativeLayer = getDocumentLeaves(+ reducer.store.getState().projects.find((project) => project.id === reducer.projectId)?.canvas.document+ ).find((layer) => layer.id === 'paint1');expect(uploadImage).toHaveBeenCalledOnce();const bitmapUpdates = reducer.dispatch.mock.calls.map(([action]) => action)@@ -13622,10 +13775,10 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',// A prop-only edit that PRESERVES the source reference (exactly as the reducer// does — it spreads `...layer`): opacity + a transform nudge.const doc = engine.document.getDocument()!;- const layer = doc.layers[0]!;+ const layer = getDocumentLeaves(doc)[0]!;setDocument({...doc,- layers: [{ ...layer, opacity: 0.5, transform: { ...layer.transform, x: 12, y: -4 } }],+ stacks: stacksFrom([{ ...layer, opacity: 0.5, transform: { ...layer.transform, x: 12, y: -4 } }]),});raf.flush();await flushMicrotasks();@@ -13636,7 +13789,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',expect(fullClearCount(paintCache)).toBe(clearsBefore);// No resolve/rasterize was even attempted for the paint layer.expect(resolver).not.toHaveBeenCalled();- expect(engine.document.getDocument()!.layers[0]!.opacity).toBe(0.5);+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]!.opacity).toBe(0.5);engine.lifecycle.dispose();});@@ -13657,7 +13810,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',it('preserves live pixels through contract copy and conversion history', async () => {const engine = await paintOneStrokeWithReducer();- const raster = engine.document.getDocument()!.layers[0]!;+ const raster = getDocumentLeaves(engine.document.getDocument()!)[0]!;if (raster.type !== 'raster') {throw new Error('expected raster source');}@@ -13685,15 +13838,19 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',).toBe(true);expect((await engine.exports.exportLayerPixels(copy.id)).status).toBe('ok');engine.history.undo();- expect(engine.document.getDocument()!.layers.some((layer) => layer.id === copy.id)).toBe(false);+ expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === copy.id)).toBe(false);engine.history.redo();expect((await engine.exports.exportLayerPixels(copy.id)).status).toBe('ok');expect(engine.layers.commitLayerConversion('Convert layer', raster, control)).toBe(true);- expect(engine.document.getDocument()!.layers.find((layer) => layer.id === raster.id)?.type).toBe('control');+ expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === raster.id)?.type).toBe(+ 'control'+ );expect((await engine.exports.exportLayerPixels(raster.id)).status).toBe('ok');engine.history.undo();- expect(engine.document.getDocument()!.layers.find((layer) => layer.id === raster.id)?.type).toBe('raster');+ expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === raster.id)?.type).toBe(+ 'raster'+ );expect((await engine.exports.exportLayerPixels(raster.id)).status).toBe('ok');engine.lifecycle.dispose();});@@ -13707,7 +13864,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',store,});expect((await engine.exports.exportLayerPixels('a')).status).toBe('ok');- const live = engine.document.getDocument()!.layers[0]!;+ const live = getDocumentLeaves(engine.document.getDocument()!)[0]!;if (live.type !== 'raster') {throw new Error('expected raster layer');}@@ -13721,7 +13878,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',expect(engine.layers.commitLayerConversion('Convert', structuredClone(live), converted)).toBe(false);expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'convertCanvasLayer' }));- expect(engine.document.getDocument()!.layers[0]!.type).toBe('raster');+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]!.type).toBe('raster');engine.lifecycle.dispose();});@@ -13734,7 +13891,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',store,});expect((await engine.exports.exportLayerPixels('a')).status).toBe('ok');- const expectedUnlocked = engine.document.getDocument()!.layers[0]!;+ const expectedUnlocked = getDocumentLeaves(engine.document.getDocument()!)[0]!;if (expectedUnlocked.type !== 'raster') {throw new Error('expected raster layer');}@@ -13749,7 +13906,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',expect(engine.layers.commitLayerConversion('Convert', expectedUnlocked, converted)).toBe(false);expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'convertCanvasLayer' }));- expect(engine.document.getDocument()!.layers[0]).toMatchObject({ isLocked: true, type: 'raster' });+ expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toMatchObject({ isLocked: true, type: 'raster' });engine.lifecycle.dispose();});@@ -13758,8 +13915,8 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',const clearsBefore = fullClearCount(paintCache);const doc = engine.document.getDocument()!;- const layer = doc.layers[0]!;- setDocument({ ...doc, layers: [{ ...layer, opacity: 0.25 }] });+ const layer = getDocumentLeaves(doc)[0]!;+ setDocument({ ...doc, stacks: stacksFrom([{ ...layer, opacity: 0.25 }]) });raf.flush();await flushMicrotasks();raf.flush();@@ -13784,15 +13941,15 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',// persisted bitmap). isSelfEcho is false in the spy store, so this must// invalidate and re-rasterize — which decodes the persisted image.const doc = engine.document.getDocument()!;- const layer = doc.layers[0] as CanvasRasterLayerContractV2;+ const layer = getDocumentLeaves(doc)[0] as CanvasRasterLayerContractV2;setDocument({...doc,- layers: [+ stacks: stacksFrom([{...layer,source: { bitmap: { contentHash: 'h', height: 100, imageName: 'persisted', width: 100 }, type: 'paint' },},- ],+ ]),});raf.flush();await flushMicrotasks();@@ -13828,7 +13985,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',// Prop-only edit (opacity), source reference preserved: no re-rasterize.const doc = engine.document.getDocument()!;- setDocument({ ...doc, layers: [{ ...doc.layers[0]!, opacity: 0.3 }] });+ setDocument({ ...doc, stacks: stacksFrom([{ ...getDocumentLeaves(doc)[0]!, opacity: 0.3 }]) });raf.flush();await flushMicrotasks();raf.flush();@@ -13836,10 +13993,12 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',// Source swap (new image name → new source object): re-rasterizes the new source.const doc2 = engine.document.getDocument()!;- const imgLayer = doc2.layers[0] as CanvasRasterLayerContractV2;+ const imgLayer = getDocumentLeaves(doc2)[0] as CanvasRasterLayerContractV2;setDocument({...doc2,- layers: [{ ...imgLayer, source: { image: { height: 10, imageName: 'a-v2', width: 10 }, type: 'image' } }],+ stacks: stacksFrom([+ { ...imgLayer, source: { image: { height: 10, imageName: 'a-v2', width: 10 }, type: 'image' } },+ ]),});raf.flush();await flushMicrotasks();@@ -13865,7 +14024,7 @@ describe('hasExportableLayerContent', () => {});const createContentEngine = (layers: CanvasLayerContract[]) => {- const { store } = createFakeStore({ ...makeDoc(), layers });+ const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom(layers) });return createCanvasEngine({backend: createTestStubRasterBackend(),imageResolver: () => Promise.resolve(new Blob()),@@ -13890,7 +14049,7 @@ describe('hasExportableLayerContent', () => {const { setDocument, store } = createReactiveStore({...makeDoc(),- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: layer.id,});const engine = createCanvasEngine({@@ -14057,7 +14216,7 @@ describe('hasExportableLayerContent', () => {expect(engine.exports.hasExportableLayerContent('stale-paint')).toBe(true);const doc = engine.document.getDocument()!;- const layer = doc.layers[0];+ const layer = getDocumentLeaves(doc)[0];if (!layer || layer.type !== 'raster') {throw new Error('expected raster paint layer');}@@ -14065,7 +14224,7 @@ describe('hasExportableLayerContent', () => {// cache synchronously. Do not run the scheduled frame that would rebuild it.setDocument({...doc,- layers: [{ ...layer, source: { bitmap: null, type: 'paint' } }],+ stacks: stacksFrom([{ ...layer, source: { bitmap: null, type: 'paint' } }]),});const { target } = createThumbnailTarget();expect(engine.previews.drawLayerThumbnail('stale-paint', target, 96)).toBe(true);@@ -14123,14 +14282,14 @@ describe('gesture guard: nudge / commitStructural mid-stroke', () => {engine.layers.nudgeSelectedLayer(1, 0);// No structural transform dispatch, no history entry.- expect(dispatch.mock.calls.filter((call) => call[0].type === 'updateCanvasLayer')).toHaveLength(0);+ expect(dispatch.mock.calls.filter((call) => call[0].type === 'setCanvasLayerPositions')).toHaveLength(0);expect(engine.stores.canUndo.get()).toBe(false);// After the gesture ends, the nudge lands.overlay.fire('pointerup', pointerAt(30, 30, { buttons: 0 }));engine.layers.nudgeSelectedLayer(1, 0);expect(dispatch.mock.calls.length).toBeGreaterThan(before);- expect(dispatch.mock.calls.some((call) => call[0].type === 'updateCanvasLayer')).toBe(true);+ expect(dispatch.mock.calls.some((call) => call[0].type === 'setCanvasLayerPositions')).toBe(true);engine.lifecycle.dispose();});@@ -14651,13 +14810,13 @@ describe('checker colors: fed-token tile rebuild', () => {// ---- fitToView: content ∪ bbox (document rect retired as world bounds) -------const noLayerDoc = (overrides: Partial<CanvasDocumentContractV2> = {}): CanvasDocumentContractV2 => ({+const noLayerDoc = (overrides: Partial<CanvasDocumentContractV3> = {}): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 1000,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 1000,...overrides,});@@ -14696,7 +14855,7 @@ describe('fitToView: content ∪ bbox', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 900, y: 900 },type: 'raster',};- const { store } = createReactiveStore(noLayerDoc({ layers: [layer] }));+ const { store } = createReactiveStore(noLayerDoc({ stacks: stacksFrom([layer]) }));const engine = createCanvasEngine({backend: createTestStubRasterBackend(),bitmapStore: createSpyBitmapStore(),@@ -14796,11 +14955,11 @@ describe('transform session', () => {// Regression: parametric layers (shape/gradient/text) could not be transformed// — `applyTransform` only handled image sources. Phase 5 "param for parametric":// the transform commits as a param edit and the source stays editable-forever.- const textLayerDoc: CanvasDocumentContractV2 = {+ const textLayerDoc: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [+ stacks: stacksFrom([{blendMode: 'normal',id: 't',@@ -14821,9 +14980,9 @@ describe('transform session', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',},- ],+ ]),selectedLayerId: 't',- version: 2,+ version: 3,width: 100,};const { store } = createReactiveStore(textLayerDoc);@@ -14943,7 +15102,7 @@ describe('transform session', () => {// persisted bitmap so its cache is non-empty (an empty paint layer is not// transformable).const movedPaint = paintDoc();- const movedLayer = movedPaint.layers[0] as CanvasRasterLayerContractV2;+ const movedLayer = getDocumentLeaves(movedPaint)[0] as CanvasRasterLayerContractV2;movedLayer.source = {bitmap: { height: 50, imageName: 'paint1-bmp', width: 50 },offset: { x: 0, y: 0 },@@ -15095,7 +15254,7 @@ describe('transform session', () => {// Delete the session's layer via an ordinary layer-array edit (same dims,// same revision) — NOT a wholesale replace, so this exercises the// `onLayersChanged` teardown rather than `onDocumentReplaced`'s.- setDocument({ ...doc, layers: [] });+ setDocument({ ...doc, stacks: stacksFrom([]) });expect(engine.stores.transformSession.get()).toBeNull();@@ -15208,7 +15367,7 @@ describe('transform session', () => {// The session's layer is deleted while temp-switched away (e.g. via the// layers panel) — the layer-change teardown cancels the session// immediately, regardless of which tool is active.- setDocument({ ...doc, layers: [] });+ setDocument({ ...doc, stacks: stacksFrom([]) });expect(engine.stores.transformSession.get()).toBeNull();setTool('transform', { temporary: true }); // space up: resume@@ -15223,11 +15382,11 @@ describe('transform session', () => {// ---- Selection subsystem -------------------------------------------------const lockedPaintDoc = (): CanvasDocumentContractV2 => ({+const lockedPaintDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [+ stacks: stacksFrom([{blendMode: 'normal',id: 'paint1',@@ -15239,9 +15398,9 @@ const lockedPaintDoc = (): CanvasDocumentContractV2 => ({transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',},- ],+ ]),selectedLayerId: 'paint1',- version: 2,+ version: 3,width: 100,});@@ -15297,7 +15456,7 @@ describe('engine selection: select all / deselect / invert + hasSelection store'});describe('engine selection: fill / erase', () => {- const makeEngine = (doc: CanvasDocumentContractV2) => {+ const makeEngine = (doc: CanvasDocumentContractV3) => {vi.stubGlobal('Path2D',class FakePath2D {@@ -15323,8 +15482,8 @@ describe('engine selection: fill / erase', () => {const h = createControlSelectionHarness({ source: { bitmap: null, type: 'paint' } });h.engine.selection.selectAll();h.engine.selection.fillSelection();- expect(h.engine.document.getDocument()!.layers).toHaveLength(1);- expect(h.engine.document.getDocument()!.layers[0]).toMatchObject({ id: 'control', type: 'control' });+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toMatchObject({ id: 'control', type: 'control' });expect(h.engine.stores.canUndo.get()).toBe(true);h.engine.lifecycle.dispose();});@@ -15336,8 +15495,8 @@ describe('engine selection: fill / erase', () => {await h.publishInitialCache();h.engine.selection.selectAll();h.engine.selection.eraseSelection();- expect(h.engine.document.getDocument()!.layers).toHaveLength(1);- expect(h.engine.document.getDocument()!.layers[0]).toMatchObject({ id: 'control', type: 'control' });+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toMatchObject({ id: 'control', type: 'control' });expect(h.engine.stores.canUndo.get()).toBe(true);h.engine.lifecycle.dispose();});@@ -15348,19 +15507,19 @@ describe('engine selection: fill / erase', () => {transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 5, y: 6 },});await h.publishInitialCache();- const before = structuredClone(h.engine.document.getDocument()!.layers[0]);+ const before = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);h.engine.selection.selectAll();if (kind === 'fill') {h.engine.selection.fillSelection();} else {h.engine.selection.eraseSelection();}- const after = structuredClone(h.engine.document.getDocument()!.layers[0]);+ const after = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);expect(after).toMatchObject({ id: 'control', source: { type: 'paint' }, type: 'control' });h.engine.history.undo();- expect(h.engine.document.getDocument()!.layers[0]).toEqual(before);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(before);h.engine.history.redo();- expect(h.engine.document.getDocument()!.layers[0]).toEqual(after);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(after);h.engine.lifecycle.dispose();});@@ -15799,7 +15958,7 @@ describe('engine selection: fill / erase', () => {it('fillSelection is a no-op on a transparency-locked EMPTY layer (source-atop clamps to existing pixels)', () => {const doc = paintDoc();- const target = doc.layers[0];+ const target = getDocumentLeaves(doc)[0];if (target?.type === 'raster') {target.isTransparencyLocked = true;}@@ -16012,11 +16171,11 @@ describe('text edit session', () => {...over,});- const textDoc = (over: Partial<CanvasDocumentContractV2> = {}): CanvasDocumentContractV2 => ({+ const textDoc = (over: Partial<CanvasDocumentContractV3> = {}): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [+ stacks: stacksFrom([{blendMode: 'normal',id: 'txt1',@@ -16028,14 +16187,14 @@ describe('text edit session', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 5, y: 6 },type: 'raster',},- ],+ ]),selectedLayerId: 'txt1',- version: 2,+ version: 3,width: 100,...over,});- const makeEngine = (doc: CanvasDocumentContractV2) => {+ const makeEngine = (doc: CanvasDocumentContractV3) => {const { setDocument, store } = createReactiveStore(doc);const dispatch = store.dispatch as Mock;const engine = createCanvasEngine({@@ -16164,7 +16323,7 @@ describe('text edit session', () => {it('does not open an edit session on a locked text layer', () => {const { engine } = makeEngine(textDoc({- layers: [+ stacks: stacksFrom([{blendMode: 'normal',id: 'txt1',@@ -16176,7 +16335,7 @@ describe('text edit session', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',},- ],+ ]),}));engine.tools.setTool('text');@@ -16316,17 +16475,17 @@ describe('text edit session', () => {describe('canTargetLayerFromContextMenu (canvas right-click target)', () => {// The menu acts on the document's SELECTED layer — the canvas never hit-tests// to pick one, so this only reports whether an in-progress edit suppresses it.- const doc = (): CanvasDocumentContractV2 => ({+ const doc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [rasterLayer('raster')],+ stacks: stacksFrom([rasterLayer('raster')]),selectedLayerId: 'raster',- version: 2,+ version: 3,width: 100,});- const makeEngine = (document: CanvasDocumentContractV2) => {+ const makeEngine = (document: CanvasDocumentContractV3) => {const { store } = createFakeStore(document);return createCanvasEngine({backend: createTestStubRasterBackend(),@@ -16374,7 +16533,7 @@ describe('Select Object canvas engine integration', () => {});/** A raster layer whose baked world rect exactly covers `rect`. */- const samRectLayer = (id: string, rect: CanvasDocumentContractV2['bbox']): CanvasRasterLayerContractV2 => ({+ const samRectLayer = (id: string, rect: CanvasDocumentContractV3['bbox']): CanvasRasterLayerContractV2 => ({...samLayer(id),source: {fill: '#fff',@@ -16388,13 +16547,13 @@ describe('Select Object canvas engine integration', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: rect.x, y: rect.y },});- const samDocument = (layers: CanvasLayerContract[] = [samLayer('source')]): CanvasDocumentContractV2 => ({+ const samDocument = (layers: CanvasLayerContract[] = [samLayer('source')]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: layers[0]?.id ?? null,- version: 2,+ version: 3,width: 100,});@@ -16448,7 +16607,7 @@ describe('Select Object canvas engine integration', () => {const createSamHarness = async (options: {backend?: StubRasterBackend;- bbox?: CanvasDocumentContractV2['bbox'];+ bbox?: CanvasDocumentContractV3['bbox'];imageResolver?: (imageName: string, signal?: AbortSignal) => Promise<Blob>;layers?: CanvasLayerContract[];runGraph?: NonNullable<CanvasEngineOptions['selectObjectDeps']>['runGraph'];@@ -16583,7 +16742,7 @@ describe('Select Object canvas engine integration', () => {const createCommittingSamHarness = async (imageResolver: (imageName: string, signal?: AbortSignal) => Promise<Blob> = () => Promise.resolve(new Blob()),backend: StubRasterBackend = createTestStubRasterBackend(),- bbox: CanvasDocumentContractV2['bbox'] = { height: 100, width: 100, x: 0, y: 0 }+ bbox: CanvasDocumentContractV3['bbox'] = { height: 100, width: 100, x: 0, y: 0 }) => {const document = { ...samDocument([samRectLayer('source', bbox)]), bbox };const reactive = createReducerBackedStore(document);@@ -16959,7 +17118,7 @@ describe('Select Object canvas engine integration', () => {expect(makeDurable).toHaveBeenCalledOnce();expect(makeDurable).toHaveBeenCalledWith('sam-mask.png');- const replaced = h.engine.document.getDocument()!.layers.find((layer) => layer.id === 'source')!;+ const replaced = getDocumentLeaves(h.engine.document.getDocument()!).find((layer) => layer.id === 'source')!;expect(replaced).toMatchObject({source: {bitmap: { height: 100, imageName: 'sam-mask.png', width: 100 },@@ -16969,7 +17128,7 @@ describe('Select Object canvas engine integration', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',});- expect(h.engine.document.getDocument()!.layers).toHaveLength(1);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);expect(getCanvasOperations(h.engine).stores.samSession.get()).toBeNull();expect(getCanvasOperations(h.engine).controller.getSnapshot()).toEqual({ status: 'idle' });expect(h.engine.stores.activeTool.get()).toBe('view');@@ -16979,7 +17138,9 @@ describe('Select Object canvas engine integration', () => {expect(h.engine.document.getDocument()).toEqual(h.document);expect(h.engine.stores.canUndo.get()).toBe(false);h.engine.history.redo();- expect(h.engine.document.getDocument()!.layers.find((layer) => layer.id === 'source')).toEqual(replaced);+ expect(getDocumentLeaves(h.engine.document.getDocument()!).find((layer) => layer.id === 'source')).toEqual(+ replaced+ );h.engine.lifecycle.dispose();});@@ -17108,7 +17269,7 @@ describe('Select Object canvas engine integration', () => {durable.resolve();await expect(pending).resolves.toMatchObject({ status: 'committed' });- expect(h.engine.document.getDocument()?.layers[0]?.type).toBe('inpaint_mask');+ expect(getDocumentLeaves(h.engine.document.getDocument())[0]?.type).toBe('inpaint_mask');h.engine.lifecycle.dispose();});@@ -17147,9 +17308,9 @@ describe('Select Object canvas engine integration', () => {expect(result.status).toBe('committed');expect(calls[0]).toBe('durable');- expect(h.engine.document.getDocument()?.layers[0]?.type).toBe(target);- expect(h.engine.document.getDocument()?.layers[1]?.id).toBe('source');- const created = h.engine.document.getDocument()?.layers[0];+ expect(getDocumentLeaves(h.engine.document.getDocument())[0]?.type).toBe(target);+ expect(getDocumentLeaves(h.engine.document.getDocument())[1]?.id).toBe('source');+ const created = getDocumentLeaves(h.engine.document.getDocument())[0];if (!created) {throw new Error('expected a saved object layer');}@@ -17172,9 +17333,9 @@ describe('Select Object canvas engine integration', () => {expect(h.engine.stores.canUndo.get()).toBe(true);h.engine.history.undo();- expect(h.engine.document.getDocument()?.layers.map((layer) => layer.id)).toEqual(['source']);+ expect(getDocumentLeaves(h.engine.document.getDocument()).map((layer) => layer.id)).toEqual(['source']);h.engine.history.redo();- expect(h.engine.document.getDocument()?.layers[0]?.type).toBe(target);+ expect(getDocumentLeaves(h.engine.document.getDocument())[0]?.type).toBe(target);h.engine.lifecycle.dispose();});@@ -17195,12 +17356,12 @@ describe('Select Object canvas engine integration', () => {status: 'committed',});- expect(h.engine.document.getDocument()?.layers.map((layer) => layer.name)).toEqual([+ expect(getDocumentLeaves(h.engine.document.getDocument()).map((layer) => layer.name)).toEqual(['Segmented Object','Segmented Object','source',]);- expect(h.engine.document.getDocument()?.layers[2]).toEqual(h.document.layers[0]);+ expect(getDocumentLeaves(h.engine.document.getDocument())[2]).toEqual(getDocumentLeaves(h.document)[0]);expect(getCanvasOperations(h.engine).stores.samSession.get()).toMatchObject({ hasPreview: true, status: 'ready' });expect(h.engine.stores.activeTool.get()).toBe('sam');h.engine.lifecycle.dispose();@@ -17213,7 +17374,7 @@ describe('Select Object canvas engine integration', () => {const result = await getCanvasOperations(h.engine).saveSelectObjectSession('raster', () => Promise.resolve());expect(result.status).toBe('committed');- const created = h.engine.document.getDocument()?.layers[0];+ const created = getDocumentLeaves(h.engine.document.getDocument())[0];expect(created?.type).toBe('raster');if (created?.type === 'raster') {expect(created.source).toMatchObject({@@ -17467,7 +17628,7 @@ describe('Select Object canvas engine integration', () => {durable.resolve();await expect(pending).resolves.toEqual({ status: 'stale' });- expect(h.engine.document.getDocument()?.layers).toHaveLength(1);+ expect(getDocumentLeaves(h.engine.document.getDocument())).toHaveLength(1);expect(h.engine.stores.canUndo.get()).toBe(false);h.engine.lifecycle.dispose();});@@ -17480,7 +17641,7 @@ describe('Select Object canvas engine integration', () => {let sessionDuringReentry: ReturnType<ReturnType<typeof getCanvasOperations>['stores']['samSession']['get']> = null;reducer.store.subscribe(() => {const current = reducer.store.getState().projects[0]?.canvas.document;- if (!reentered && current?.layers.length === 2) {+ if (!reentered && getDocumentLeaves(current).length === 2) {reentered = true;reducer.store.dispatch({ id: 'source', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' });sessionDuringReentry = getCanvasOperations(engine).stores.samSession.get();@@ -17513,7 +17674,7 @@ describe('Select Object canvas engine integration', () => {expect(reentered).toBe(true);expect(sessionDuringReentry).toBeNull();expect(getCanvasOperations(engine).controller.getSnapshot()).toEqual({ status: 'idle' });- expect(engine.document.getDocument()?.layers.find((layer) => layer.id === 'source')?.opacity).toBe(0.5);+ expect(getDocumentLeaves(engine.document.getDocument()).find((layer) => layer.id === 'source')?.opacity).toBe(0.5);engine.lifecycle.dispose();});@@ -17529,7 +17690,7 @@ describe('Select Object canvas engine integration', () => {const document = h.engine.document.getDocument()!;if (kind === 'source') {- h.setDocument({ ...document, layers: [{ ...document.layers[0]!, opacity: 0.5 }] });+ h.setDocument({ ...document, stacks: stacksFrom([{ ...getDocumentLeaves(document)[0]!, opacity: 0.5 }]) });} else if (kind === 'project') {h.setActiveProjectId('p2');} else {@@ -17641,13 +17802,15 @@ describe('Select Object canvas engine integration', () => {expect(getCanvasOperations(h.engine).stores.samSession.get()).not.toBeNull();const reordered = h.engine.document.getDocument()!;- h.setDocument({ ...reordered, layers: [...reordered.layers].reverse() });+ h.setDocument({ ...reordered, stacks: stacksFrom([...getDocumentLeaves(reordered)].reverse()) });expect(getCanvasOperations(h.engine).stores.samSession.get()).not.toBeNull();const withOtherEdited = h.engine.document.getDocument()!;h.setDocument({...withOtherEdited,- layers: withOtherEdited.layers.map((layer) => (layer.id === 'other' ? { ...layer, opacity: 0.5 } : layer)),+ stacks: stacksFrom(+ getDocumentLeaves(withOtherEdited).map((layer) => (layer.id === 'other' ? { ...layer, opacity: 0.5 } : layer))+ ),});expect(getCanvasOperations(h.engine).stores.samSession.get()).not.toBeNull();expect(getCanvasOperations(h.engine).controller.getSnapshot()).toMatchObject({@@ -17658,7 +17821,11 @@ describe('Select Object canvas engine integration', () => {const withSourceEdited = h.engine.document.getDocument()!;h.setDocument({...withSourceEdited,- layers: withSourceEdited.layers.map((layer) => (layer.id === 'source' ? { ...layer, opacity: 0.25 } : layer)),+ stacks: stacksFrom(+ getDocumentLeaves(withSourceEdited).map((layer) =>+ layer.id === 'source' ? { ...layer, opacity: 0.25 } : layer+ )+ ),});expect(getCanvasOperations(h.engine).stores.samSession.get()).toBeNull();expect(getCanvasOperations(h.engine).controller.getSnapshot()).toEqual({ status: 'idle' });@@ -17685,12 +17852,12 @@ describe('Select Object canvas engine integration', () => {const document = h.engine.document.getDocument()!;h.setDocument({...document,- layers: [+ stacks: stacksFrom([{...outside,source: { image: { height: 10, imageName: 'inside.png', width: 10 }, type: 'image' },},- ],+ ]),});expect(getCanvasOperations(h.engine).startSelectObject('moving-source')).toBe('not-ready');@@ -17816,7 +17983,7 @@ describe('Select Object canvas engine integration', () => {{ args: [], op: 'clip' },]));- expect(h.engine.document.getDocument()!.layers.every((layer) => layer.isEnabled)).toBe(true);+ expect(getDocumentLeaves(h.engine.document.getDocument()!).every((layer) => layer.isEnabled)).toBe(true);h.engine.lifecycle.dispose();});@@ -17975,7 +18142,7 @@ describe('Select Object canvas engine integration', () => {h.setDocument({...h.engine.document.getDocument()!,- layers: [{ ...h.engine.document.getDocument()!.layers[0]!, opacity: 0.5 }],+ stacks: stacksFrom([{ ...getDocumentLeaves(h.engine.document.getDocument()!)[0]!, opacity: 0.5 }]),});expect(getCanvasOperations(h.engine).stores.samSession.get()).toBeNull();@@ -18057,7 +18224,7 @@ describe('Select Object canvas engine integration', () => {h.setDocument({...h.engine.document.getDocument()!,- layers: [{ ...h.engine.document.getDocument()!.layers[0]!, opacity: 0.5 }],+ stacks: stacksFrom([{ ...getDocumentLeaves(h.engine.document.getDocument()!)[0]!, opacity: 0.5 }]),});h.fireKey('keyup', 'Space', ' ');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 4397e0c6a6..975c4555f8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -67,7 +67,7 @@ export type {import type { CanvasApplicationHost } from '@workbench/canvas-engine/applicationHost';import type {CanvasImageRef,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';@@ -110,9 +110,11 @@ import { StagedResultController } from '@workbench/canvas-engine/controllers/staimport { StructuralLayerController } from '@workbench/canvas-engine/controllers/structuralLayerController';import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import {- createFlatDocumentModel,- type FlatCanvasDocumentModel,-} from '@workbench/canvas-engine/document-model/flatDocumentModel';+ compileDocumentLeaves,+ createDocumentModel,+ type CanvasDocumentModel,+} from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import {createEngineStores,type EngineStores,@@ -549,7 +551,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC*/const getLayerSourceById = (layerId: string): CanvasLayerSourceContract | null => {const doc = mirror.getDocument();- const layer = doc?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(doc, layerId);// Masks expose their alpha bitmap as a synthetic `paint` source so the bitmap// store's source-type/redundant-dispatch guards and the mirror's self-echo// check work uniformly across paint layers and masks.@@ -557,7 +559,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};const getAuthoritativeLayerSourceById = (layerId: string): CanvasLayerSourceContract | null => {- const layer = mutationPort.getCanvasState()?.document.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(mutationPort.getCanvasState()?.document, layerId);return layer ? renderableSourceOf(layer) : null;};@@ -571,7 +573,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC*/const dispatchLayerBitmap = (layerId: string, bitmap: CanvasImageRef, offset: { x: number; y: number }): boolean => {const doc = mirror.getDocument();- const layer = doc?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(doc, layerId);if (!layer) {return false;}@@ -605,7 +607,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC*/const clearLayerBitmap = (layerId: string): boolean => {const doc = mirror.getDocument();- const layer = doc?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(doc, layerId);if (!layer) {return false;}@@ -650,7 +652,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCif (pixelEditController?.isOpenFor([layerId])) {return true;}- const layer = mirror.getDocument()?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(mirror.getDocument(), layerId);return !!layer && isCurrentRasterizationJob(layer);};@@ -717,13 +719,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// Direct pixel writes do not replace the reducer canvas object. Snapshot// freshness therefore also binds to this engine-local content epoch.let rasterContentEpoch = 0;- const resolveSelectedLayerIds = (document: CanvasDocumentContractV2): readonly string[] => {+ const resolveSelectedLayerIds = (document: CanvasDocumentContractV3): readonly string[] => {const primaryId = document.selectedLayerId;if (!primaryId) {return [];}const requested = new Set(opts.getSelectedLayerIds?.() ?? [primaryId]);- const reconciled = document.layers.filter((layer) => requested.has(layer.id)).map((layer) => layer.id);+ const reconciled = getDocumentLeaves(document)+ .filter((layer) => requested.has(layer.id))+ .map((layer) => layer.id);return requested.has(primaryId) && reconciled.length === requested.size ? reconciled : [primaryId];};const cancelOpenPixelEdit = (): void => {@@ -1028,7 +1032,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},commitStructural: (label, forward, inverse) => commitStructural(label, forward, inverse),documentDeltaToLayerLocal: (layerId, delta) => {- const layer = mirror.getDocument()?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(mirror.getDocument(), layerId);return layer ? documentDeltaToLocal(layerMatrix(layer.transform), delta) : delta;},getFloatingSelection: () => floatingSelection.get(),@@ -1126,7 +1130,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// ---- Rasterization orchestration ---------------------------------------- const rasterizeDeps = (doc: CanvasDocumentContractV2, signal?: AbortSignal): RasterizeDeps => ({+ const rasterizeDeps = (doc: CanvasDocumentContractV3, signal?: AbortSignal): RasterizeDeps => ({backend,bitmapPool: rasterController.bitmaps,documentSize: { height: doc.height, width: doc.width },@@ -1264,7 +1268,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC): Promise<StructuralExportLayerPixelsResult> => normalizeStructuralExport(rasterizeLayerPixels(layerId, options));const rasterizeLayerForThumbnail = async (layer: CanvasLayerContract,- document: CanvasDocumentContractV2+ document: CanvasDocumentContractV3): Promise<'published' | 'stale' | 'error'> => {const result = await getOrStartLayerRasterization(layer, document);return result === 'aborted' ? 'stale' : result;@@ -1490,10 +1494,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => stores.lassoPreview.set(null));cleanup.run(() => stores.marqueePreview.set(null));const doc = mirror.getDocument();- const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);+ const present = new Set(doc ? getDocumentLeaves(doc).map((layer) => layer.id) : []);rasterController.clearMirroredImages();rasterController.clearThumbnailKeys();- for (const layer of doc?.layers ?? []) {+ for (const layer of getDocumentLeaves(doc)) {rasterController.setThumbnailKey(layer.id, getLayerThumbnailDisplayKey(layer));const imageName = layerImageName(layer);if (imageName) {@@ -1553,7 +1557,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst sourceChanged = new Set(sourceChangedIds);const previousImageNames = new Map(ids.map((id) => [id, rasterController.getMirroredImage(id)]));for (const id of ids) {- const layer = doc?.layers.find((candidate) => candidate.id === id);+ const layer = getDocumentLayer(doc, id);const imageName = layer ? layerImageName(layer) : null;if (imageName) {rasterController.setMirroredImage(id, imageName);@@ -1577,7 +1581,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreChasTextEditSession: textSession?.layerId === id,hasTransformSession: session?.layerId === id,isSelfEcho: () => bitmapStore.isSelfEcho(id, getLayerSourceById(id)),- layer: doc?.layers.find((candidate) => candidate.id === id),+ layer: getDocumentLayer(doc, id) ?? undefined,previousImageName: previousImageNames.get(id),sourceChanged: sourceChanged.has(id),});@@ -1657,7 +1661,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreConStagingChanged: () => scheduler.invalidate({ overlay: true }),});- for (const layer of mirror.getDocument()?.layers ?? []) {+ for (const layer of getDocumentLeaves(mirror.getDocument())) {rasterController.setThumbnailKey(layer.id, getLayerThumbnailDisplayKey(layer));const imageName = layerImageName(layer);if (imageName) {@@ -2029,9 +2033,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// bbox (generation frame) is the primary anchor, so an empty canvas fits it;// any renderable layer beyond the bbox is unioned in so it lands in view.let bounds: Rect = { ...doc.bbox };- for (const layer of doc.layers) {- if (isRenderableLayer(layer)) {- bounds = union(bounds, getSourceBounds(layer, doc));+ for (const leaf of compileDocumentLeaves(doc)) {+ if (leaf.contributionEnabled && isRenderableLayer(leaf.layer)) {+ bounds = union(bounds, getSourceBounds(leaf.layer, doc));}}viewport.fitToView(bounds, viewport.getViewportSize());@@ -2057,7 +2061,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCfitToView();};- const isLayerCacheReadyForOp = (layer: CanvasLayerContract, doc: CanvasDocumentContractV2): boolean => {+ const isLayerCacheReadyForOp = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): boolean => {if (isEmpty(getSourceContentRect(layer, doc))) {return true;}@@ -2100,7 +2104,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}};- const getReducerDocument = (): CanvasDocumentContractV2 | null => mutationPort.getCanvasState()?.document ?? null;+ const getReducerDocument = (): CanvasDocumentContractV3 | null => mutationPort.getCanvasState()?.document ?? null;const getMainModelBase = (): string | null => {return opts.getMainModelBase?.() ?? null;};@@ -2112,10 +2116,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC/** Conversion reducers clone contracts, so their publication postcondition compares by value. */const documentHasLayerContract = (- document: CanvasDocumentContractV2 | null,+ document: CanvasDocumentContractV3 | null,expected: CanvasLayerContract): boolean => {- const current = document?.layers.find((candidate) => candidate.id === expected.id);+ const current = getDocumentLayer(document, expected.id);return current !== undefined && areJsonValuesStructurallyEqual(current, expected);};@@ -2162,7 +2166,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst captureLayerCache = (layer: CanvasLayerContract,- doc: CanvasDocumentContractV2+ doc: CanvasDocumentContractV3): { pixels: RasterSurface; rect: Rect } | null | 'not-ready' => {const entry = layerCache.get(layer.id);if (!entry || isEmpty(entry.rect)) {@@ -2178,7 +2182,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst getDuplicateRasterPlan = (layer: CanvasLayerContract,- doc: CanvasDocumentContractV2+ doc: CanvasDocumentContractV3): DuplicateLayerRasterPlan => {const source = renderableSourceOf(layer);if (!source) {@@ -2244,6 +2248,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst layerMutationController = new LayerMutationController({captureInsertionAnchor,+ captureRestoreAnchor: (nodeId) => mutationContext.captureRestoreAnchor(nodeId),captureCache: captureLayerCache,createLayerId,concurrency: mutationContext,@@ -2468,7 +2473,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst exportSelectionBlob = (): Promise<Blob | null> => {floatingSelection.commit();const doc = mirror.getDocument();- const layer = doc?.layers.find((candidate) => candidate.id === doc.selectedLayerId);+ const layer = getDocumentLayer(doc, doc?.selectedLayerId);const mask = selection.mask();const entry = layer ? layerCache.get(layer.id) : undefined;if (!doc || !layer || !mask || !entry || isEmpty(entry.rect)) {@@ -2577,7 +2582,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst doc = mirror.getDocument();// Invalidate (mark stale → re-rasterize) every live layer cache and drop its// memoized adjusted surface; the next composite rebuilds them from source.- for (const layer of doc?.layers ?? []) {+ for (const layer of getDocumentLeaves(doc)) {invalidateLayerCache(layer.id);deleteDerivedSurfaces(layer.id);}@@ -2597,7 +2602,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbbox: doc?.bbox ?? null,canRedo: history.canRedo(),canUndo: history.canUndo(),- document: doc ? { height: doc.height, layers: doc.layers.length, width: doc.width } : null,+ document: doc ? { height: doc.height, layers: getDocumentLeaves(doc).length, width: doc.width } : null,hasSelection: selection.hasSelection(),projectId,selectedLayerId: doc?.selectedLayerId ?? null,@@ -2869,14 +2874,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreChasExportableLayerContent,isLayerExportGuardCurrent,};- let documentModel: FlatCanvasDocumentModel | null = null;- const currentDocumentModel = (): FlatCanvasDocumentModel | null => {+ let documentModel: CanvasDocumentModel | null = null;+ const currentDocumentModel = (): CanvasDocumentModel | null => {const document = mutationPort.getCanvasState()?.document ?? null;if (!document) {return null;}if (documentModel?.document !== document) {- documentModel = createFlatDocumentModel(document, {+ documentModel = createDocumentModel(document, {editRevision: mutationContext.getEditRevision(),projectId,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.tsindex 0f6e32aef0..87e1dc597d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts@@ -1,8 +1,9 @@-import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';@@ -46,17 +47,17 @@ const controlLayer = (id: string): CanvasLayerContract => ({withTransparencyEffect: false,});-const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 128, width: 128, x: 0, y: 0 },height: 128,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 128,});-const makeDeps = (document: CanvasDocumentContractV2) => {+const makeDeps = (document: CanvasDocumentContractV3) => {const stub = createTestStubRasterBackend();const snapshot: RasterCompositeExportSnapshot = {contentEpoch: 1,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.tsindex beb37b560f..87cfb11750 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';@@ -18,7 +18,7 @@ export type RasterCompositeExportResult =export interface RasterCompositeExportSnapshot {contentEpoch: number;- document: CanvasDocumentContractV2 | null;+ document: CanvasDocumentContractV3 | null;documentGeneration: number;lifecycleGeneration: number;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.test.tsindex ed0b99f9fc..2a6ddac012 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.test.ts@@ -1,11 +1,12 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { beforeEach, describe, expect, it } from 'vitest';import {@@ -46,7 +47,7 @@ let canvasState: boolean;const build = (overrides: Partial<CreateLayerExportGuardsDeps> = {}): LayerExportGuards =>createLayerExportGuards({- getDocument: () => ({ height: 64, layers: [layer], width: 64 }) as CanvasDocumentContractV2,+ getDocument: () => ({ height: 64, stacks: stacksFrom([layer]), width: 64 }) as CanvasDocumentContractV3,getDocumentGeneration: () => generation,getRasterizationJob: () => job,hasCanvasState: () => canvasState,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.tsindex 9e5e163cd5..6059659517 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts@@ -1,6 +1,6 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';@@ -8,6 +8,7 @@ import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rastimport type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { areJsonValuesStructurallyEqual } from '@platform/core/json';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { isEmpty } from '@workbench/canvas-engine/math/rect';@@ -29,7 +30,7 @@ export interface CreateLayerExportGuardsDeps {readonly isDisposed: () => boolean;readonly hasCanvasState: () => boolean;readonly getDocumentGeneration: () => number;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getRasterizationJob: (layerId: string) => RasterizationJob | undefined;}@@ -90,7 +91,7 @@ export const createLayerExportGuards = (deps: CreateLayerExportGuardsDeps): Layereturn false;}const document = deps.getDocument();- const liveLayer = document?.layers.find((candidate) => candidate.id === guard.layerId);+ const liveLayer = getDocumentLayer(document, guard.layerId);const entry = layerCache.get(guard.layerId);return !!entry && liveLayer === guard.layer && entry.version === guard.cacheVersion;};@@ -98,7 +99,7 @@ export const createLayerExportGuards = (deps: CreateLayerExportGuardsDeps): Layereturn {captureCurrentLayerExportGuard: (layerId) => {const document = deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(document, layerId);const source = layer ? renderableSourceOf(layer) : null;const entry = layerCache.get(layerId);if (@@ -120,7 +121,7 @@ export const createLayerExportGuards = (deps: CreateLayerExportGuardsDeps): LayehasExportableLayerContent: (layerId) => {const doc = deps.getDocument();- const layer = doc?.layers.find((candidate) => candidate.id === layerId);+ const layer = getDocumentLayer(doc, layerId);if (!doc || !layer) {return false;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.tsindex e63092e63a..377fceb8c9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts@@ -1,8 +1,9 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { beforeEach, describe, expect, it, vi } from 'vitest';import { createLayerRasterizer, type CreateLayerRasterizerDeps } from './layerRasterizer';@@ -42,15 +43,15 @@ const textLayer = (): CanvasLayerContract =>},});-const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 =>- ({ height: 64, layers, width: 64 }) as unknown as CanvasDocumentContractV2;+const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 =>+ ({ height: 64, stacks: stacksFrom(layers), width: 64 }) as unknown as CanvasDocumentContractV3;interface Harness {deps: CreateLayerRasterizerDeps;entry: LayerCacheEntry;installed: Map<string, RasterizationJob>;documentGeneration: { value: number };- document: { value: CanvasDocumentContractV2 };+ document: { value: CanvasDocumentContractV3 };state: { disposed: boolean; hasCanvas: boolean };rasterize: ReturnType<typeof vi.fn>;fontReady: (() => void) | null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.tsindex 69c74d9d12..a09fd5aa7e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts@@ -1,5 +1,5 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';@@ -9,6 +9,7 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { RasterizeResult } from '@workbench/canvas-engine/render/rasterizers';import { areJsonValuesStructurallyEqual } from '@platform/core/json';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';import { isEmpty } from '@workbench/canvas-engine/math/rect';@@ -48,11 +49,11 @@ export interface CreateLayerRasterizerDeps {readonly createSurface: (width: number, height: number) => RasterSurface;readonly rasterize: (source: CanvasLayerSourceContract,- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,scratch: RasterSurface,signal: AbortSignal) => Promise<RasterizeResult>;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly hasCanvasState: () => boolean;readonly isDisposed: () => boolean;readonly invalidateLayerCache: (layerId: string) => void;@@ -70,7 +71,7 @@ export interface LayerRasterizer {*/getOrStartLayerRasterization(layer: CanvasLayerContract,- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,signal?: AbortSignal): Promise<LayerRasterizationOutcome>;}@@ -102,7 +103,7 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRasconst getOrStartLayerRasterization = (layer: CanvasLayerContract,- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,signal?: AbortSignal): Promise<LayerRasterizationOutcome> => {if (signal?.aborted) {@@ -144,7 +145,7 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRasif (source.type === 'text') {deps.fontLoader.ensure(textFontString(source), () => {- const currentLayer = deps.getDocument()?.layers.find((candidate) => candidate.id === layer.id);+ const currentLayer = getDocumentLayer(deps.getDocument(), layer.id);if (deps.isDisposed() ||!deps.hasCanvasState() ||@@ -177,7 +178,7 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRasvoid (async () => {try {const result = await deps.rasterize(source, document, scratch, controller.signal);- const currentLayer = deps.getDocument()?.layers.find((candidate) => candidate.id === layer.id);+ const currentLayer = getDocumentLayer(deps.getDocument(), layer.id);const currentEntry = layerCache.get(layer.id);if (deps.isDisposed() ||@@ -216,7 +217,7 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRasif (job.abortedByCaller) {return 'aborted';}- const currentLayer = deps.getDocument()?.layers.find((candidate) => candidate.id === layer.id);+ const currentLayer = getDocumentLayer(deps.getDocument(), layer.id);if (deps.isDisposed() ||!deps.hasCanvasState() ||diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.tsindex f8abf40829..bd5b8a8ca3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts@@ -1,16 +1,7 @@/**- * The canvas document mutation vocabulary.- *- * These types live inside `canvas-engine` because the engine and its controllers- * are their heaviest consumers — 21 engine files import `CanvasProjectMutation`,- * and every one of them wants only the type, never the reducer. Keeping the- * declaration in `workbench/canvasProjectMutations.ts` made the engine's own- * public surface (`capabilities.ts`) import upward from the workbench root,- * which is the edge that closed the 16-module import cycle.- *- * The reducer that interprets these mutations stays in- * `workbench/canvasProjectMutations.ts` and re-exports these types, so callers- * outside canvas are unaffected.+ * The canvas document mutation vocabulary. Declared inside `canvas-engine` because the engine and+ * its controllers are its heaviest consumers; the reducer that interprets it lives in+ * `workbench/canvasProjectMutations.ts` and re-exports these types.*/import type { ProjectEvent } from '@workbench/projectEventContracts';@@ -19,7 +10,7 @@ import type {CanvasAdjustmentsContract,CanvasControlAdapterContract,CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerBaseContract,CanvasLayerContract,CanvasLayerSourceContract,@@ -28,13 +19,17 @@ import type {CanvasRegionalGuidanceLayerContract,CanvasStagingAreaContractV2,} from './contracts';-import type { FlatLayerInsertion, FlatLayerInsertionAnchor } from './document/insertionAnchors';-import type { ReorderFlatStackCommand } from './document/layerStacks';+import type { CanvasNodeInsertion, CanvasNodeInsertionAnchor, CanvasNodeMove } from './document/insertionAnchors';+import type { ReorderSiblingsCommand } from './document/layerStacks';+/** Base fields a node accepts; a group takes only `name`, `isEnabled` and `isLocked`. */export type CanvasLayerBasePatch = Partial<Pick<CanvasLayerBaseContract, 'name' | 'isEnabled' | 'isLocked' | 'opacity' | 'blendMode'>> & { transform?: Partial<CanvasLayerBaseContract['transform']> };+/** The base fields a group carries; anything else in a patch does not apply to it. */+export const GROUP_PATCH_KEYS: readonly (keyof CanvasLayerBasePatch)[] = ['name', 'isEnabled', 'isLocked'];+export type CanvasLayerConfigPatch =| {layerType: 'raster';@@ -61,7 +56,7 @@ export type CanvasLayerConfigPatch =export type CanvasProjectMutation =| {type: 'commitStagedImage';- anchor: FlatLayerInsertionAnchor;+ anchor: CanvasNodeInsertionAnchor;candidateFingerprint: string;continueStaging: boolean;event: ProjectEvent;@@ -83,20 +78,25 @@ export type CanvasProjectMutation =| { type: 'toggleCanvasStagingVisibility' }| { type: 'toggleCanvasStagingThumbnailsVisibility' }| { type: 'clearCanvasStaging' }- | { type: 'addCanvasLayer'; layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor }+ | { type: 'addCanvasLayer'; layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor }| {+ /**+ * One atomic restructuring, applied as `add`, then `move`, then `removeIds`, then the flag+ * and selection updates, so an anchor may name a node a later step moves or removes. The+ * whole mutation is refused when any step is invalid or the result exceeds the depth or+ * node limits.+ */type: 'applyCanvasLayerStackMutation';- /** Applied in order against the document before `removeIds`, so an anchor may name a removed layer. */- add?: readonly FlatLayerInsertion[];+ add?: readonly CanvasNodeInsertion[];+ move?: readonly CanvasNodeMove[];removeIds?: readonly string[];enabledUpdates: readonly { id: string; isEnabled: boolean }[];lockedUpdates?: readonly { id: string; isLocked: boolean }[];- /** Omit to preserve the current selection, repairing it if that layer is removed. */+ /** Omit to preserve the current selection, repairing it if that node is removed. */selectedLayerId?: string | null;}| { type: 'removeCanvasLayers'; ids: string[] }- | { type: 'duplicateCanvasLayer'; sourceId: string; newId: string }- | { type: 'reorderCanvasLayerStacks'; stacks: readonly ReorderFlatStackCommand[] }+ | { type: 'reorderCanvasSiblings'; orders: readonly ReorderSiblingsCommand[] }| { type: 'updateCanvasLayer'; id: string; patch: CanvasLayerBasePatch }| { type: 'replaceCanvasLayer'; layerId: string; layer: CanvasLayerContract }| { type: 'setCanvasLayersEnabled'; updates: readonly { id: string; isEnabled: boolean }[] }@@ -104,16 +104,23 @@ export type CanvasProjectMutation =| { type: 'setCanvasLayersHidden'; updates: readonly { id: string; isHidden: boolean }[] }| { type: 'updateCanvasLayerSource'; id: string; source: CanvasLayerSourceContract }| { type: 'updateCanvasLayerConfig'; id: string; config: CanvasLayerConfigPatch }- | { type: 'convertCanvasLayer'; id: string; targetType: CanvasLayerContract['type']; layer: CanvasLayerContract }+ | {+ type: 'convertCanvasLayer';+ id: string;+ targetType: CanvasLayerContract['type'];+ layer: CanvasLayerContract;+ /** Where a leaf changing stacks lands; the top of its new stack when absent. */+ anchor?: CanvasNodeInsertionAnchor;+ }| {type: 'mergeCanvasLayersDown';upperLayerId: string;source: Extract<CanvasLayerSourceContract, { type: 'paint' }>;}- | { type: 'setCanvasBbox'; bbox: CanvasDocumentContractV2['bbox'] }+ | { type: 'setCanvasBbox'; bbox: CanvasDocumentContractV3['bbox'] }| { type: 'setCanvasSelectedLayer'; id: string | null }| { type: 'resizeCanvasDocument'; width: number; height: number; offsetX?: number; offsetY?: number }- | { type: 'replaceCanvasDocument'; document: CanvasDocumentContractV2 }+ | { type: 'replaceCanvasDocument'; document: CanvasDocumentContractV3 }| { type: 'saveCanvasSnapshot'; id: string; name: string; createdAt: string }| { type: 'restoreCanvasSnapshot'; snapshotId: string }| { type: 'deleteCanvasSnapshot'; snapshotId: string }diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.test.tsindex 287b963235..c0801b7ca2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.test.ts@@ -1,7 +1,8 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';@@ -13,8 +14,10 @@ const surface = (): RasterSurface => ({}) as RasterSurface;const guardFor = (layerId: string): LayerExportGuard =>({ cacheVersion: 1, documentGeneration: 1, layerId, projectId: 'p' }) as LayerExportGuard;-const documentWith = (...layerIds: string[]): CanvasDocumentContractV2 =>- ({ layers: layerIds.map((id) => ({ id })) }) as CanvasDocumentContractV2;+const documentWith = (...layerIds: string[]): CanvasDocumentContractV3 =>+ ({+ stacks: stacksFrom(layerIds.map((id) => ({ id, type: 'raster' }) as CanvasLayerContract)),+ }) as CanvasDocumentContractV3;/** The real state controller — it has no collaborators, so faking it would only weaken the assertions. */let previews: PreviewStateController;@@ -22,7 +25,7 @@ let invalidateAll: Mock<() => void>;let invalidateLayer: Mock<(layerId: string) => void>;let decodeBlob: Mock<CreatePreviewPublisherDeps['decodeBlob']>;let resolveImage: Mock<(imageName: string) => Promise<Blob>>;-let getDocument: () => CanvasDocumentContractV2 | null;+let getDocument: () => CanvasDocumentContractV3 | null;let isGuardCurrent: Mock<(guard: LayerExportGuard) => boolean>;const build = (overrides: Partial<CreatePreviewPublisherDeps> = {}): PreviewPublisher =>diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.tsindex 6f72d9527e..ed2a0c8d0a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts@@ -4,11 +4,12 @@ import type {StagedPreviewInput,StagedPreviewPlacement,} from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { PreviewStateController } from '@workbench/canvas-engine/controllers/previewStateController';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { ImageResolver } from '@workbench/canvas-engine/render/rasterizers';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';import { createStagedPreviewBlobCache } from './stagedPreviewBlobCache';@@ -32,7 +33,7 @@ export interface CreatePreviewPublisherDeps {) => Promise<{ surface: RasterSurface; decodedWidth: number; decodedHeight: number }>;readonly invalidateAll: () => void;readonly invalidateLayer: (layerId: string) => void;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;}@@ -234,7 +235,7 @@ export const createPreviewPublisher = (deps: CreatePreviewPublisherDeps): PreviesetGuardedFilterPreview: (layerId, input, guard) => {const validate = (): FilterPreviewOutcome => {- const liveLayer = deps.getDocument()?.layers.find((candidate) => candidate.id === layerId);+ const liveLayer = getDocumentLayer(deps.getDocument(), layerId);if (!liveLayer) {return 'missing';}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.tsindex 8cab99fa4b..7acfd097a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts@@ -1,9 +1,11 @@import type { CanvasDocumentSnapshot, LayerExportGuard } from '@workbench/canvas-engine/capabilities';-import type { CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasStateContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { ExportLayerPixelsResult } from '@workbench/canvas-engine/controllers/rasterExportController';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { beforeEach, describe, expect, it, vi } from 'vitest';import { createRasterSnapshotCapture, type CreateRasterSnapshotCaptureDeps } from './rasterSnapshotCapture';@@ -26,8 +28,10 @@ const imageLayer = (id: string, size = 4) => ({type: 'raster',});-const canvasState = (layerIds: readonly string[] = ['a']): CanvasStateContractV2 =>- ({ document: { layers: layerIds.map((id) => imageLayer(id)) } }) as unknown as CanvasStateContractV2;+const canvasState = (layerIds: readonly string[] = ['a']): CanvasStateContractV3 =>+ ({+ document: { stacks: stacksFrom(layerIds.map((id) => imageLayer(id) as unknown as CanvasLayerContract)) },+ }) as unknown as CanvasStateContractV3;const guard = (layerId: string): LayerExportGuard => ({ layerId }) as LayerExportGuard;@@ -43,7 +47,7 @@ const okPixels = (layerId: string, size = 4): ExportLayerPixelsResult => ({interface Harness {deps: CreateRasterSnapshotCaptureDeps;state: {- canvas: CanvasStateContractV2 | null;+ canvas: CanvasStateContractV3 | null;contentEpoch: number;disposed: boolean;documentGeneration: number;@@ -57,7 +61,7 @@ let harness: Harness;const makeHarness = (overrides: Partial<CreateRasterSnapshotCaptureDeps> = {}): Harness => {const state = {- canvas: canvasState() as CanvasStateContractV2 | null,+ canvas: canvasState() as CanvasStateContractV3 | null,contentEpoch: 0,disposed: false,documentGeneration: 1,@@ -93,7 +97,7 @@ describe('captureDocumentSnapshot', () => {it('clones the canvas rather than aliasing it', () => {const snapshot = createRasterSnapshotCapture(harness.deps).captureDocumentSnapshot();expect(snapshot?.canvas).not.toBe(harness.state.canvas);- expect(snapshot?.canvas.document.layers[0]?.id).toBe('a');+ expect(getDocumentLeaves(snapshot?.canvas.document)[0]?.id).toBe('a');});it('refuses once disposed, and when there is no canvas', () => {@@ -241,8 +245,12 @@ describe('captureRasterSnapshot', () => {it('refuses a layer whose source cannot be exported', async () => {harness.state.canvas = {- document: { layers: [{ ...imageLayer('a'), source: { kind: 'polygon', type: 'shape' } }] },- } as unknown as CanvasStateContractV2;+ document: {+ stacks: stacksFrom([+ { ...imageLayer('a'), source: { kind: 'polygon', type: 'shape' } } as unknown as CanvasLayerContract,+ ]),+ },+ } as unknown as CanvasStateContractV3;const capture = createRasterSnapshotCapture(harness.deps);const snapshot = capture.captureDocumentSnapshot()!;expect((await capture.captureRasterSnapshot(snapshot, ['a'])).status).toBe('not-ready');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.tsindex 2b2edc00b8..4ba6fa39b0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts@@ -1,8 +1,8 @@import type { CanvasDocumentSnapshot, LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,- CanvasStateContractV2,+ CanvasStateContractV3,} from '@workbench/canvas-engine/contracts';import type { ExportLayerPixelsResult } from '@workbench/canvas-engine/controllers/rasterExportController';import type { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';@@ -10,7 +10,7 @@ import type { CanvasRasterSnapshot, CaptureRasterSnapshotResult } from '@workbenimport 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 { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/documentModel';import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';@@ -21,7 +21,7 @@ const BYTES_PER_PIXEL = 4;* from a raster pass. Reserved up front so a capture that cannot fit is refused* before any work is done; the real cost is topped up per layer afterwards.*/-const estimatedLayerBytes = (layer: CanvasLayerContract, document: CanvasDocumentContractV2): number => {+const estimatedLayerBytes = (layer: CanvasLayerContract, document: CanvasDocumentContractV3): number => {const source = renderableSourceOf(layer);if (source?.type === 'image') {return source.image.width * source.image.height * BYTES_PER_PIXEL;@@ -38,7 +38,7 @@ export interface CreateRasterSnapshotCaptureDeps {/** Re-reads the live cache sizes into the budget before a reservation decision. */readonly syncMemoryBaselines: () => void;readonly createSurface: (width: number, height: number) => RasterSurface;- readonly getCanvasState: () => CanvasStateContractV2 | null;+ readonly getCanvasState: () => CanvasStateContractV3 | null;readonly getDocumentGeneration: () => number;readonly getContentEpoch: () => number;readonly getLifecycleGeneration: () => number;@@ -94,7 +94,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDepconst activeSnapshots = new Set<CanvasRasterSnapshot>();const snapshotSources = new WeakMap<CanvasDocumentSnapshot,- { canvas: CanvasStateContractV2; contentEpoch: number; lifecycleGeneration: number }+ { canvas: CanvasStateContractV3; contentEpoch: number; lifecycleGeneration: number }>();const isDocumentSnapshotCurrent = (snapshot: CanvasDocumentSnapshot): boolean => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.tsindex 4577e2f08b..d550356a92 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts@@ -1,4 +1,4 @@-import type { CanvasStateContractV2 } from './contracts';+import type { CanvasStateContractV3 } from './contracts';import type { RasterSurface } from './render/raster';import type { Rect } from './types';@@ -8,7 +8,7 @@ export interface CanvasDetachedLayerSurface {}export interface CanvasRasterSnapshot {- readonly canvas: CanvasStateContractV2;+ readonly canvas: CanvasStateContractV3;readonly documentGeneration: number;readonly emptyLayerIds: ReadonlySet<string>;readonly layerSurfaces: ReadonlyMap<string, CanvasDetachedLayerSurface>;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.tsindex 9985fd6ca9..16fe2845b8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts@@ -1,5 +1,6 @@-import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';import { describe, expect, it } from 'vitest';@@ -23,13 +24,13 @@ const layer = (x: number): CanvasRasterLayerContractV2 => ({type: 'raster',});-const documentWith = (rasterLayer: CanvasRasterLayerContractV2, width = 8): CanvasDocumentContractV2 => ({+const documentWith = (rasterLayer: CanvasRasterLayerContractV2, width = 8): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 8, width, x: 0, y: 0 },height: 8,- layers: [rasterLayer],+ stacks: stacksFrom([rasterLayer]),selectedLayerId: rasterLayer.id,- version: 2,+ version: 3,width,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.tsindex 0149fb0d19..d3c0c3d47f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts@@ -1,9 +1,10 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';import type { RasterBackend, RasterSurface } from './raster';@@ -86,13 +87,13 @@ const rasterLayer = (id: string, overrides: Partial<CanvasRasterLayerContractV2>...overrides,});-const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 100,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.tsindex cc5abd7000..47407e9958 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts@@ -13,7 +13,7 @@* Zero React, zero import-time side effects.*/-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';import type { LayerCacheStore } from './layerCache';@@ -37,7 +37,7 @@ export interface RgbaSample {* with non-zero alpha.*/export const sampleDocumentColor = (- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,layers: LayerCacheStore,backend: RasterBackend,docPoint: Vec2diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.tsindex e8d0579c15..a8aebdc342 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { SamPreviewState } from '@workbench/canvas-engine/controllers/previewStateController';import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';@@ -6,6 +6,8 @@ import type { Mat2d } from '@workbench/canvas-engine/types';import { PreviewStateController } from '@workbench/canvas-engine/controllers/previewStateController';import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import * as compositor from '@workbench/canvas-engine/render/compositor';import * as surfaceBudget from '@workbench/canvas-engine/render/surfaceBudget';@@ -36,13 +38,13 @@ const layer = (id: string, overrides: Record<string, unknown> = {}): CanvasLayer...overrides,}) as unknown as CanvasLayerContract;-const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 =>+const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 =>({bbox: { height: 32, width: 32, x: 4, y: 6 },height: 64,- layers,+ stacks: stacksFrom(layers),width: 64,- }) as unknown as CanvasDocumentContractV2;+ }) as unknown as CanvasDocumentContractV3;interface Harness {deps: CreateCompositeFrameDeps;@@ -152,8 +154,8 @@ describe('SAM isolation', () => {it('isolates the layer through the composition plan', () => {draw(documentOf([layer('a'), layer('b')]), null, isolated());- const doc = composite.mock.calls.at(-1)?.[1] as CanvasDocumentContractV2;- expect(doc.layers.map((entry) => entry.id)).toEqual(['a', 'b']);+ const doc = composite.mock.calls.at(-1)?.[1] as CanvasDocumentContractV3;+ expect(getDocumentLeaves(doc).map((entry) => entry.id)).toEqual(['a', 'b']);expect(lastCompositeOptions().isolationLayerId).toBe('a');});@@ -185,8 +187,8 @@ describe('SAM isolation', () => {it('draws the whole document when the SAM preview is not isolated', () => {const sam = { ...isolated(), isolated: false } as SamPreviewState;draw(documentOf([layer('a'), layer('b')]), null, sam);- const doc = composite.mock.calls.at(-1)?.[1] as CanvasDocumentContractV2;- expect(doc.layers.map((entry) => entry.id)).toEqual(['a', 'b']);+ const doc = composite.mock.calls.at(-1)?.[1] as CanvasDocumentContractV3;+ expect(getDocumentLeaves(doc).map((entry) => entry.id)).toEqual(['a', 'b']);expect(lastCompositeOptions().clipRect).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex efa610777a..bfa289fd92 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type {PreviewStateController,SamPreviewState,@@ -12,6 +12,7 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rendimport type { LayerDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';import { getSourceContentRect, isRenderableLayer, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { compositeDocument, shouldSmoothAtZoom } from '@workbench/canvas-engine/render/compositor';@@ -35,7 +36,7 @@ export interface CreateCompositeFrameDeps {readonly getMaskPatternTile: (style: string, color: string) => RasterSurface | null;readonly getCheckerboardTile: () => RasterSurface;/** Starts (or joins) the rasterization of a layer whose cache is stale. */- readonly rasterizeLayer: (layer: CanvasLayerContract, doc: CanvasDocumentContractV2) => void;+ readonly rasterizeLayer: (layer: CanvasLayerContract, doc: CanvasDocumentContractV3) => void;readonly syncMemoryBaselines: () => void;readonly deleteDerivedSurfaces: (layerId: string) => void;}@@ -44,7 +45,7 @@ export interface CompositeFrame {/** Composites the document onto the screen surface and enforces the surface budget. */draw(screen: RasterSurface,- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,view: Mat2d,floatFrame: FloatingSelectionFrame | null,samPreview: SamPreviewState | null,@@ -87,8 +88,8 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF* shrinking it back to the contract size here would destroy those pixels. The* rasterizer owns sizing the surface and placing its content rect.*/- const ensureLayerCaches = (doc: CanvasDocumentContractV2, activeFrameLayerIds: ReadonlySet<string>): void => {- for (const layer of doc.layers) {+ const ensureLayerCaches = (doc: CanvasDocumentContractV3, activeFrameLayerIds: ReadonlySet<string>): void => {+ for (const layer of getDocumentLeaves(doc)) {// The layer's rasterizable source: a raster/control `source`, or a mask// layer's alpha bitmap viewed as a paint source (colorized at composite).if (!isLayerContributing(layer) || !renderableSourceOf(layer) || !activeFrameLayerIds.has(layer.id)) {@@ -159,7 +160,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFconst isolatedIds = isolatedGuard ? new Set([isolatedGuard.layerId]) : null;const liveCacheRects = new Map<string, Rect>();- for (const layer of doc.layers) {+ for (const layer of getDocumentLeaves(doc)) {const rect = layerCache.peek(layer.id)?.rect;if (rect) {liveCacheRects.set(layer.id, rect);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.tsindex 2ff7c9c38b..db889a6cc7 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@@ -1,6 +1,6 @@import type {CanvasBlendMode,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,CanvasRasterLayerContractV2,@@ -9,6 +9,7 @@ import type {import type { Mat2d } from '@workbench/canvas-engine/types';import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { identity } from '@workbench/canvas-engine/math/mat2d';import { describe, expect, it } from 'vitest';@@ -80,14 +81,14 @@ const inpaintMaskLayer = (id: string): CanvasLayerContract => ({const makeDoc = (layers: CanvasLayerContract[],- overrides: Partial<CanvasDocumentContractV2> = {}-): CanvasDocumentContractV2 => ({+ overrides: Partial<CanvasDocumentContractV3> = {}+): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 100,...overrides,});@@ -488,8 +489,7 @@ describe('compositeDocument', () => {const widthToId: Record<number, string> = { 10: 'raster', 11: 'control', 12: 'regional', 13: 'inpaint' };const target = backend.createSurface(200, 200) as StubRasterSurface;- // Deliberately SCRAMBLED array order (index 0 = top-most): a raster created- // above a control layer, masks interleaved below. Group order must win.+ // Each stack draws in LAYER_STACK_ORDER whatever order the fixture lists them in.const doc = makeDoc([rasterLayer('raster'),inpaintMaskLayer('inpaint'),@@ -503,7 +503,7 @@ describe('compositeDocument', () => {.map((e) => widthToId[(e.args[0] as { width: number }).width]).filter((id): id is string => id !== undefined);- // Raster (bottom) first, then control, then the masks — regardless of array index.+ // Raster (bottom) first, then control, then the masks.expect(order.indexOf('raster')).toBeLessThan(order.indexOf('control'));expect(order.indexOf('control')).toBeLessThan(order.indexOf('regional'));expect(order.indexOf('regional')).toBeLessThan(order.indexOf('inpaint'));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 762ba7057a..e6e37ec9b0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -15,14 +15,14 @@import type {CanvasBlendMode,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,} from '@workbench/canvas-engine/contracts';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';-import type { SemanticLeafV2 } from '@workbench/canvas-engine/document-model/semanticLeaf';+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';import type { LayerDamage, Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';-import { compileDocumentLeaves, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/flatDocumentModel';+import { compileDocumentLeaves, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import {ALL_OVERLAY_STACKS_SHOWN,planScreenComposition,@@ -208,7 +208,7 @@ const identityTransform = (ctx: Ctx): void => {ctx.setTransform(1, 0, 0, 1, 0, 0);};-const getEffectiveLayerMatrix = (leaf: SemanticLeafV2, opts: CompositeOptions): Mat2d => {+const getEffectiveLayerMatrix = (leaf: SemanticLeaf, opts: CompositeOptions): Mat2d => {const override = opts.transformOverrides?.get(leaf.id);if (!override) {return leaf.worldTransform;@@ -223,7 +223,7 @@ const getEffectiveLayerMatrix = (leaf: SemanticLeafV2, opts: CompositeOptions):};const isDefinitelyOffscreen = (- leaf: SemanticLeafV2,+ leaf: SemanticLeaf,entry: LayerCacheEntry,view: Mat2d,target: RasterSurface,@@ -301,7 +301,7 @@ const drawBackground = (ctx: Ctx, tile: RasterSurface | null, bounds: Rect): voi* of the previous frame behind.*/const resolveDamage = (- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,view: Mat2d,target: RasterSurface,opts: CompositeOptions@@ -396,7 +396,7 @@ const drawMaskLayer = (*/const drawCachedLayer = (ctx: Ctx,- leaf: SemanticLeafV2,+ leaf: SemanticLeaf,entry: LayerCacheEntry,view: Mat2d,opts: CompositeOptions@@ -476,7 +476,7 @@ const drawCachedLayer = (*/const drawFloatingSelection = (ctx: Ctx,- leaf: SemanticLeafV2,+ leaf: SemanticLeaf,view: Mat2d,opts: CompositeOptions,float: NonNullable<CompositeOptions['floatingSelection']>@@ -496,7 +496,7 @@ const drawFloatingSelection = (*/export const compositeDocument = (target: RasterSurface,- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,caches: LayerCacheStore,view: Mat2d,opts: CompositeOptions = {}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.tsindex a22d5ccb10..cd17f9119b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts@@ -10,12 +10,13 @@*/import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';import type { LayerDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { fromTRS, identity } from '@workbench/canvas-engine/math/mat2d';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';@@ -92,7 +93,7 @@ describe('damage-clipped compositing matches a full repaint', () => {* clipped on top of the previous frame. Returns both screens' pixels.*/const run = (- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,caches: ReturnType<typeof createLayerCacheStore>,backend: ReturnType<typeof createDomRasterBackend>,view: Mat2d,@@ -122,7 +123,7 @@ describe('damage-clipped compositing matches a full repaint', () => {const layers = [rasterLayer('a')];const rects = { a: { height: 200, width: 300, x: 40, y: 30 } };const { backend, caches } = scene(layers, rects, { a: '#3b82f6' });- const doc = { layers } as unknown as CanvasDocumentContractV2;+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;const steps = Array.from({ length: 6 },(_, i) => () => repaint(caches, 'a', { height: 30, width: 40, x: 60 + i * 30, y: 60 + i * 20 }, '#ef4444')@@ -137,7 +138,7 @@ describe('damage-clipped compositing matches a full repaint', () => {const layers = [rasterLayer('a', { transform: { rotation: 0, scaleX: 1.7, scaleY: 1.3, x: 55, y: 25 } })];const rects = { a: { height: 160, width: 220, x: 0, y: 0 } };const { backend, caches } = scene(layers, rects, { a: '#22c55e' });- const doc = { layers } as unknown as CanvasDocumentContractV2;+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;const steps = [() => repaint(caches, 'a', { height: 40, width: 50, x: 20, y: 20 }, '#eab308'),() => repaint(caches, 'a', { height: 25, width: 25, x: 120, y: 90 }, '#a855f7'),@@ -150,7 +151,7 @@ describe('damage-clipped compositing matches a full repaint', () => {const layers = [rasterLayer('a', { transform: { rotation: 0.4, scaleX: 1, scaleY: 1, x: 90, y: 60 } })];const rects = { a: { height: 150, width: 200, x: 0, y: 0 } };const { backend, caches } = scene(layers, rects, { a: '#06b6d4' });- const doc = { layers } as unknown as CanvasDocumentContractV2;+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;const steps = [() => repaint(caches, 'a', { height: 40, width: 60, x: 30, y: 40 }, '#f97316')];const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, true);expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });@@ -165,7 +166,7 @@ describe('damage-clipped compositing matches a full repaint', () => {top: { height: 140, width: 180, x: 90, y: 70 },};const { backend, caches } = scene(layers, rects, { bottom: '#3b82f6', top: '#f43f5e' });- const doc = { layers } as unknown as CanvasDocumentContractV2;+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;const steps = [() => repaint(caches, 'bottom', { height: 60, width: 60, x: 100, y: 80 }, '#facc15'),() => repaint(caches, 'bottom', { height: 40, width: 200, x: 40, y: 200 }, '#14b8a6'),@@ -178,7 +179,7 @@ describe('damage-clipped compositing matches a full repaint', () => {const layers = [rasterLayer('a')];const rects = { a: { height: 180, width: 240, x: 10, y: 10 } };const { backend, caches } = scene(layers, rects, { a: '#8b5cf6' });- const doc = { layers } as unknown as CanvasDocumentContractV2;+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;for (const view of [fromTRS({ x: -120, y: -80 }, 0, 3, 3), fromTRS({ x: 40, y: 30 }, 0, 0.6, 0.6)]) {const steps = [() => repaint(caches, 'a', { height: 30, width: 30, x: 50, y: 45 }, '#fb7185')];const { clipped, full } = run(doc, caches, backend, view, steps, true);@@ -191,7 +192,7 @@ describe('damage-clipped compositing matches a full repaint', () => {const layers = [rasterLayer('a')];const rects = { a: { height: 200, width: 300, x: 40, y: 30 } };const { backend, caches } = scene(layers, rects, { a: '#3b82f6' });- const doc = { layers } as unknown as CanvasDocumentContractV2;+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;const steps = [() => {repaint(caches, 'a', { height: 80, width: 90, x: 60, y: 60 }, '#ef4444');@@ -206,7 +207,7 @@ describe('damage-clipped compositing matches a full repaint', () => {const layers = [rasterLayer('a')];const rects = { a: { height: 200, width: 300, x: 40, y: 30 } };const { backend, caches } = scene(layers, rects, { a: '#3b82f6' });- const doc = { layers } as unknown as CanvasDocumentContractV2;+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;const steps = [() => repaint(caches, 'a', { height: 50, width: 50, x: 70, y: 70 }, '#ef4444')];const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, false);expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.test.tsindex 913d8e47c1..eb7f860fb7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.test.ts@@ -1,7 +1,8 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';import { floatingSelectionFrame } from './floatingSelectionFrame';@@ -17,14 +18,19 @@ const float = (overrides: Partial<FloatingSelection> = {}): FloatingSelection =>...overrides,}) as unknown as FloatingSelection;-const documentOf = (layerIds: readonly string[]): CanvasDocumentContractV2 =>+const documentOf = (layerIds: readonly string[]): CanvasDocumentContractV3 =>({- layers: layerIds.map((id) => ({- id,- type: 'raster',- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 20 },- })),- }) as unknown as CanvasDocumentContractV2;+ stacks: stacksFrom(+ layerIds.map(+ (id) =>+ ({+ id,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 20 },+ type: 'raster',+ }) as unknown as CanvasLayerContract+ )+ ),+ }) as unknown as CanvasDocumentContractV3;describe('floatingSelectionFrame', () => {it('describes the composite and the ants together', () => {@@ -64,8 +70,14 @@ describe('floatingSelectionFrame', () => {it('reports nothing when the layer transform cannot be inverted', () => {const collapsed = {- layers: [{ id: 'layer-1', type: 'raster', transform: { rotation: 0, scaleX: 0, scaleY: 0, x: 0, y: 0 } }],- } as unknown as CanvasDocumentContractV2;+ stacks: stacksFrom([+ {+ id: 'layer-1',+ transform: { rotation: 0, scaleX: 0, scaleY: 0, x: 0, y: 0 },+ type: 'raster',+ } as unknown as CanvasLayerContract,+ ]),+ } as unknown as CanvasDocumentContractV3;expect(floatingSelectionFrame(float(), collapsed)).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.tsindex ebbae90950..924b0a4ecd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts@@ -1,8 +1,8 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';import type { Mat2d } from '@workbench/canvas-engine/types';-import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/flatDocumentModel';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { floatDocumentMatrix } from '@workbench/canvas-engine/selection/floatingSelection';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';@@ -27,7 +27,7 @@ export interface FloatingSelectionFrame {*/export const floatingSelectionFrame = (float: FloatingSelection | null,- doc: CanvasDocumentContractV2 | null+ doc: CanvasDocumentContractV3 | null): FloatingSelectionFrame | null => {const leaf = float && doc ? lookupDocumentLeaf(doc, float.layerId) : null;if (!float || !leaf) {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.tsindex 4fab010036..a000ddfaf6 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@@ -1,10 +1,11 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';import { calculateActiveFrameLayerIds } from './frameDemand';@@ -36,13 +37,13 @@ const hiddenControl = (id: string): CanvasControlLayerContract => ({withTransparencyEffect: false,});-const document = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const document = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 1_000,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 1_000,});@@ -125,3 +126,19 @@ describe('calculateActiveFrameLayerIds', () => {).toEqual(new Set(['rotated']));});});++describe('calculateActiveFrameLayerIds — group gating', () => {+ it('does not demand a layer hidden or disabled by a group above it', () => {+ const doc = {+ ...document([layer('base', 0, 0)]),+ stacks: stacksFrom([+ { ...groupContract('hidden', [{ ...hiddenControl('c'), isHidden: false }]), isHidden: true },+ groupContract('off', [layer('r', 0, 0)], { isEnabled: false }),+ layer('base', 0, 0),+ ]),+ };+ expect(calculateActiveFrameLayerIds({ document: doc, viewport: { height: 200, width: 200, x: 0, y: 0 } })).toEqual(+ new Set(['base'])+ );+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.tsindex 41acb0dbe9..512fd2f2b8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts@@ -1,14 +1,14 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';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';export interface FrameDemandInput {- readonly document: CanvasDocumentContractV2;+ readonly document: CanvasDocumentContractV3;readonly isolationLayerIds?: ReadonlySet<string>;readonly liveCacheRects?: ReadonlyMap<string, Rect>;readonly transformOverrides?: ReadonlyMap<diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemandBudget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemandBudget.test.tsindex 201aa2b235..fd7135d4e6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemandBudget.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemandBudget.test.ts@@ -1,5 +1,6 @@-import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it, vi } from 'vitest';import { calculateActiveFrameLayerIds } from './frameDemand';@@ -23,13 +24,13 @@ describe('frame demand cache allocation', () => {const stub = createTestStubRasterBackend();const createSurface = vi.fn(stub.createSurface);const caches = createLayerCacheStore({ ...stub, createSurface });- const document: CanvasDocumentContractV2 = {+ const document: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 1_000,- layers: [layer('left', 0), layer('right', 500)],+ stacks: stacksFrom([layer('left', 0), layer('right', 500)]),selectedLayerId: null,- version: 2,+ version: 3,width: 1_000,};const allocateDemand = (x: number): Set<string> => {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.tsindex 6f6e60702e..b585533b07 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@@ -1,7 +1,7 @@import type {CanvasBlendMode,CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasMaskFillContract,@@ -9,6 +9,7 @@ import type {} from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { identity } from '@workbench/canvas-engine/math/mat2d';import {compositeDocument,@@ -77,13 +78,13 @@ const inpaintMask = (id: string, fill: CanvasMaskFillContract): CanvasInpaintMastype: 'inpaint_mask',});-const doc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const doc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: BBOX,height: HEIGHT,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: WIDTH,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.tsindex f4890a2ea5..ba33e0d6ab 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts@@ -1,8 +1,9 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { SamPreviewState } from '@workbench/canvas-engine/controllers/previewStateController';import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';import type { Mat2d, ToolId } from '@workbench/canvas-engine/types';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -26,11 +27,11 @@ const documentOf = (layerIds: readonly string[] = ['a'], overrides: Record<strin({bbox: { height: 32, width: 32, x: 0, y: 0 },height: 64,- layers: layerIds.map((id) => layer(id)),+ stacks: stacksFrom(layerIds.map((id) => layer(id) as unknown as CanvasLayerContract)),selectedLayerId: layerIds[0] ?? null,width: 64,...overrides,- }) as unknown as CanvasDocumentContractV2;+ }) as unknown as CanvasDocumentContractV3;interface Harness {deps: CreateOverlayFrameDeps;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.tsindex 0f39c02874..018bd1452a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { SamPreviewState } from '@workbench/canvas-engine/controllers/previewStateController';import type { EngineStores } from '@workbench/canvas-engine/engineStores';import type {@@ -14,7 +14,7 @@ import {compileDocumentLeaves,lookupDocumentLayer,lookupDocumentLeaf,-} from '@workbench/canvas-engine/document-model/flatDocumentModel';+} from '@workbench/canvas-engine/document-model/documentModel';import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';import { hittableLayerRect, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';import { transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';@@ -42,7 +42,7 @@ export interface CreateOverlayFrameDeps {export interface OverlayFrame {/** Everything the overlay renderer draws this frame, gathered from live state. */describe(- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,view: Mat2d,floatFrame: FloatingSelectionFrame | null,samPreview: SamPreviewState | null@@ -67,7 +67,7 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =* (carrying a live override) wins over the committed selection so the marquee* tracks the preview rather than lagging a frame behind it.*/- const moveOutlineCorners = (doc: CanvasDocumentContractV2): readonly Vec2[] | null => {+ const moveOutlineCorners = (doc: CanvasDocumentContractV3): readonly Vec2[] | null => {if (getActiveToolId() !== 'move') {return null;}@@ -80,7 +80,7 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =};/** The transform-tool frame (rotated bounds + handles + rotation nub), or `null`. */- const transformFrame = (doc: CanvasDocumentContractV2): TransformFrameOverlay | null => {+ const transformFrame = (doc: CanvasDocumentContractV3): TransformFrameOverlay | null => {if (getActiveToolId() !== 'transform') {return null;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.tsindex f861835738..17f0ba96f2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts@@ -1,15 +1,15 @@import type {CanvasAdjustmentsContract,CanvasBlendMode,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerSourceContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';-import type { SemanticLeafV2 } from '@workbench/canvas-engine/document-model/semanticLeaf';+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d, Rect } from '@workbench/canvas-engine/types';-import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';import { roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { adjustmentsKey, applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';@@ -57,7 +57,7 @@ const defaultWriteImageData = (surface: RasterSurface, imageData: ImageData, x:surface.ctx.putImageData(imageData, x, y);/** True when a leaf is a contributing raster layer with rasterizable, non-empty pixels. */-const isBaseRasterLeaf = (leaf: SemanticLeafV2): leaf is SemanticLeafV2 & { layer: CanvasRasterLayerContractV2 } => {+const isBaseRasterLeaf = (leaf: SemanticLeaf): leaf is SemanticLeaf & { layer: CanvasRasterLayerContractV2 } => {const { layer } = leaf;if (!leaf.contributionEnabled || layer.type !== 'raster') {return false;@@ -81,7 +81,7 @@ const sourceRefOf = (source: CanvasLayerSourceContract): string => {};/** The native (unscaled) content rect of a base-raster layer's source (layer-local). */-const contentRectOf = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentContractV2): Rect => {+const contentRectOf = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentContractV3): Rect => {const { source } = layer;if (source.type === 'image') {return { height: source.image.height, width: source.image.width, x: 0, y: 0 };@@ -94,7 +94,7 @@ const contentRectOf = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentCo};/** Projects a document layer into its frozen composite contribution. */-const toLayerRef = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentContractV2): CompositeLayerRef => {+const toLayerRef = (layer: CanvasRasterLayerContractV2, doc: CanvasDocumentContractV3): CompositeLayerRef => {const rect = contentRectOf(layer, doc);const hasAdjustments = !isIdentityAdjustments(layer.adjustments);return {@@ -153,7 +153,7 @@ export const getCompositeLayerBounds = (layers: readonly CompositeLayerRef[]): R};/** Plans the enabled base-raster layers over an exact document-space rectangle. */-export const planBaseRasterComposite = (document: CanvasDocumentContractV2, rect: Rect): BaseRasterCompositeEntry => {+export const planBaseRasterComposite = (document: CanvasDocumentContractV3, rect: Rect): BaseRasterCompositeEntry => {const layers = compileDocumentLeaves(document).filter(isBaseRasterLeaf).map((leaf) => toLayerRef(leaf.layer, document));@@ -166,7 +166,7 @@ export const planBaseRasterComposite = (document: CanvasDocumentContractV2, rect};/** Tight outward-rounded bounds of all enabled raster content in the document. */-export const getBaseRasterContentBounds = (document: CanvasDocumentContractV2): Rect | null => {+export const getBaseRasterContentBounds = (document: CanvasDocumentContractV3): Rect | null => {const bounds = getCompositeLayerBounds(planBaseRasterComposite(document, document.bbox).layers);return bounds === null ? null : roundOut(bounds);};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.test.tsindex 8274946993..d27751a5f5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.test.ts@@ -1,6 +1,7 @@-import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it, vi } from 'vitest';import { createSelectObjectBridge, type CreateSelectObjectBridgeDeps } from './selectObjectBridge';@@ -16,7 +17,8 @@ const layer = (overrides: Record<string, unknown> = {}) =>...overrides,}) as never;-const documentOf = (layers: unknown[]): CanvasDocumentContractV2 => ({ layers }) as CanvasDocumentContractV2;+const documentOf = (layers: unknown[]): CanvasDocumentContractV3 =>+ ({ stacks: stacksFrom(layers as CanvasLayerContract[]) }) as CanvasDocumentContractV3;const surface = () => {const ctx = { fillRect: vi.fn(), fillStyle: '', globalCompositeOperation: '' };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.tsindex b76d6381db..2bf607abd2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.ts@@ -1,11 +1,12 @@import type { SelectObjectStartContext } from '@workbench/canvas-engine/applicationHost';import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';@@ -14,7 +15,7 @@ const SELECT_OBJECT_PREVIEW_TINT = '#38bdf8';export interface CreateSelectObjectBridgeDeps {readonly layerCache: LayerCacheStore;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getDocument: () => CanvasDocumentContractV3 | null;readonly captureGuard: (layerId: string) => LayerExportGuard | null;readonly decodeImage: (image: CanvasImageRef,@@ -78,17 +79,18 @@ export const createSelectObjectBridge = (deps: CreateSelectObjectBridgeDeps): SeprepareSelectObjectStart: (layerId) => {const document = deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);- if (!document || !layer) {+ const leaf = lookupDocumentLeaf(document, layerId);+ const layer = leaf?.layer;+ if (!document || !leaf || !layer) {return { status: 'missing' };}if (layer.type !== 'raster' && layer.type !== 'control') {return { status: 'unsupported' };}- if (!layer.isEnabled) {+ if (!leaf.contributionEnabled) {return { status: 'disabled' };}- if (layer.isLocked) {+ if (leaf.effectiveLocked) {return { status: 'locked' };}const guard = deps.captureGuard(layer.id);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.tsindex d243cbb553..ed80c0312a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts@@ -1,5 +1,5 @@import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { History, HistoryEntry } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';@@ -38,7 +38,7 @@ export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit =const { applyImagePatch, dispatchCanvasMutation, history, layerCache } = deps;const createComposedPaintEntry = (- created: { layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor },+ created: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor },event: StrokeCommittedEvent,label: string): HistoryEntry => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.tsindex a42155d02f..e99cc5348a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts@@ -1,9 +1,10 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';@@ -13,13 +14,13 @@ import { createBboxTool } from './bboxTool';// Grid-aligned start frame (grid 8) so a zero-net-move gesture is a true no-op.const bbox = { height: 96, width: 96, x: 16, y: 16 };-const makeDoc = (): CanvasDocumentContractV2 => ({+const makeDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { ...bbox },height: 512,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 512,});@@ -58,10 +59,10 @@ interface Harness {ctx: ToolContext;dispatched: CanvasProjectMutation[];commits: StructuralCommit[];- previewOf: () => CanvasDocumentContractV2['bbox'] | null;+ previewOf: () => CanvasDocumentContractV3['bbox'] | null;}-const createHarness = (doc: CanvasDocumentContractV2): Harness => {+const createHarness = (doc: CanvasDocumentContractV3): Harness => {const dispatched: CanvasProjectMutation[] = [];const commits: StructuralCommit[] = [];const stores = createEngineStores();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.tsindex 5213e112dc..8d88b59948 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts@@ -1,9 +1,10 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { createLayerCacheStore, type LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -54,13 +55,13 @@ const paintLayer = (id: string, x = 0): CanvasLayerContract => ({type: 'raster',});-const makeDoc = (layerX = 0): CanvasDocumentContractV2 => ({+const makeDoc = (layerX = 0): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [paintLayer('paint1', layerX)],+ stacks: stacksFrom([paintLayer('paint1', layerX)]),selectedLayerId: 'paint1',- version: 2,+ version: 3,width: 100,});@@ -83,7 +84,7 @@ interface Harness {overlayCursors: unknown[];}-const createHarness = (doc: CanvasDocumentContractV2 | null): Harness => {+const createHarness = (doc: CanvasDocumentContractV3 | null): Harness => {const pixel: MutablePixel = { current: [10, 20, 30, 255] };const backend = createFixedPixelBackend(pixel);const layers = createLayerCacheStore(backend);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.tsindex 4c422411a6..e705bbb3df 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts@@ -1,9 +1,10 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';@@ -32,13 +33,13 @@ const gradientLayer = (over: Partial<CanvasLayerContract> = {}): CanvasLayerCont...over,}) as CanvasLayerContract;-const makeDoc = (over: Partial<CanvasDocumentContractV2> = {}): CanvasDocumentContractV2 => ({+const makeDoc = (over: Partial<CanvasDocumentContractV3> = {}): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 96, width: 96, x: 0, y: 0 },height: 512,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 512,...over,});@@ -63,7 +64,7 @@ interface StructuralCommit {inverse: CanvasProjectMutation;}-const createHarness = (doc: CanvasDocumentContractV2) => {+const createHarness = (doc: CanvasDocumentContractV3) => {const dispatched: CanvasProjectMutation[] = [];const commits: StructuralCommit[] = [];const stores = createEngineStores();@@ -137,7 +138,7 @@ describe('gradient tool: create when no gradient selected', () => {describe('gradient tool: edit selected gradient layer', () => {it('commits ONE updateCanvasLayerSource with the new angle (kind/stops preserved)', () => {const layer = gradientLayer();- const doc = makeDoc({ layers: [layer], selectedLayerId: 'grad-existing' });+ const doc = makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'grad-existing' });const h = createHarness(doc);const tool = createGradientTool();@@ -167,7 +168,7 @@ describe('gradient tool: edit selected gradient layer', () => {it('is a no-op when the selected gradient layer is locked', () => {const layer = gradientLayer({ isLocked: true });- const doc = makeDoc({ layers: [layer], selectedLayerId: 'grad-existing' });+ const doc = makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'grad-existing' });const h = createHarness(doc);const tool = createGradientTool();@@ -192,7 +193,7 @@ describe('gradient tool: edit selected gradient layer', () => {type: 'gradient',},} as Partial<CanvasLayerContract>);- const doc = makeDoc({ layers: [layer], selectedLayerId: 'grad-existing' });+ const doc = makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'grad-existing' });const h = createHarness(doc);const tool = createGradientTool();@@ -213,7 +214,7 @@ describe('gradient tool: edit selected gradient layer', () => {id: 'paint-1',source: { bitmap: null, type: 'paint' },} as Partial<CanvasLayerContract>);- const doc = makeDoc({ layers: [paint], selectedLayerId: 'paint-1' });+ const doc = makeDoc({ stacks: stacksFrom([paint]), selectedLayerId: 'paint-1' });const h = createHarness(doc);const tool = createGradientTool();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.tsindex 911215942b..8ee8b8bdd4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts@@ -27,7 +27,9 @@ import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@woimport type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { Vec2 } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import type { Tool, ToolContext } from './tool';@@ -115,11 +117,12 @@ export const createGradientTool = (): Tool => {return;}const angle = angleFromDrag(current.startDoc, input.documentPoint);- const selected = doc.selectedLayerId ? doc.layers.find((layer) => layer.id === doc.selectedLayerId) : undefined;+ const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;+ const selected = leaf?.layer;- if (selected && selected.type === 'raster' && selected.source.type === 'gradient') {+ if (leaf && selected && selected.type === 'raster' && selected.source.type === 'gradient') {// Edit the selected gradient layer — unless it's locked/disabled (no-op).- if (!isLayerEditable(selected)) {+ if (!isLeafEditable(leaf)) {clearPreview(ctx);return;}@@ -161,7 +164,7 @@ export const createGradientTool = (): Tool => {id: layerId,isEnabled: true,isLocked: false,- name: `Gradient ${doc.layers.length + 1}`,+ name: `Gradient ${getDocumentLeaves(doc).length + 1}`,opacity: 1,source,transform: { rotation: 0, scaleX: 1, scaleY: 1, x: doc.bbox.x, y: doc.bbox.y },diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.tsindex 3c9534f498..f2b27b6fe8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts@@ -1,5 +1,6 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { estimateTextExtent } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';import { describe, expect, it } from 'vitest';@@ -121,13 +122,13 @@ const maskLayer = (type: 'inpaint_mask',});-const doc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const doc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 100,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.tsindex bff319356d..39f0610f82 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts@@ -25,7 +25,7 @@*/import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerBaseContract,CanvasLayerContract,} from '@workbench/canvas-engine/contracts';@@ -48,7 +48,7 @@ type LayerTransform = CanvasLayerBaseContract['transform'];*/export const hittableLayerRect = (layer: CanvasLayerContract,- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,liveRect?: Rect): Rect | null => {if (!renderableSourceOf(layer)) {@@ -74,7 +74,7 @@ export const hittableLayerRect = (*/export const hittableLayerSize = (layer: CanvasLayerContract,- doc: CanvasDocumentContractV2+ doc: CanvasDocumentContractV3): { width: number; height: number } | null => {const rect = hittableLayerRect(layer, doc);return rect ? { height: rect.height, width: rect.width } : null;@@ -90,7 +90,7 @@ export const layerMatrix = (transform: LayerTransform) =>*/export const hitTestLayer = (layer: CanvasLayerContract,- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,point: Vec2,liveRect?: Rect): boolean => {@@ -115,7 +115,7 @@ export const hitTestLayer = (*/export const layerOutlineCorners = (layer: CanvasLayerContract,- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,override?: { x: number; y: number; scaleX?: number; scaleY?: number; rotation?: number } | null): Vec2[] | null => {const rect = hittableLayerRect(layer, doc);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.tsindex b2e045aaff..1930ae92bf 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts@@ -1,10 +1,11 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -51,13 +52,13 @@ const shapeLayer = (type: 'raster',});-const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId,- version: 2,+ version: 3,width: 100,});@@ -118,7 +119,7 @@ const IDENTITY: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0const fakeFloat = (layerId: string): FloatingSelection =>({ layerId, transform: { ...IDENTITY } }) as FloatingSelection;-const createHarness = (doc: CanvasDocumentContractV2, options: HarnessOptions = {}): Harness => {+const createHarness = (doc: CanvasDocumentContractV3, options: HarnessOptions = {}): Harness => {const dispatched: CanvasProjectMutation[] = [];const commits: StructuralCommit[] = [];const overrides: { layerId: string; override: { x: number; y: number } | null }[] = [];diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.tsindex a267cfe33b..3e36d99edb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts@@ -39,7 +39,9 @@ import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { snapMovedPoint } from '@workbench/canvas-engine/math/snapping';import type { Tool, ToolContext } from './tool';@@ -96,17 +98,29 @@ export const createMoveTool = (): Tool => {* The drag target is the document's selected layer, and nothing else — the* press point plays no part in choosing it.*/- const selectedDraggableLayers = (ctx: ToolContext): readonly CanvasLayerContract[] => {+ const selectedDraggableLayers = (+ ctx: ToolContext+ ): { layers: readonly CanvasLayerContract[]; primaryId: string | null } => {const doc = ctx.getDocument();const selectedId = doc?.selectedLayerId;if (!doc || !selectedId) {- return [];+ return { layers: [], primaryId: null };}const requested = new Set(ctx.getSelectedLayerIds?.() ?? [selectedId]);- const selected = doc.layers.filter((layer) => requested.has(layer.id));- return requested.has(selectedId) && selected.length === requested.size && selected.every(isLayerEditable)- ? selected- : [];+ requested.add(selectedId);+ const index = getDocumentIndex(doc);+ if ([...requested].some((id) => !index.byId.has(id))) {+ return { layers: [], primaryId: null };+ }+ // A selected group drags every leaf beneath it; a locked node anywhere in the set refuses the drag.+ const leaves = compileDocumentLeaves(doc).filter(+ (leaf) => requested.has(leaf.id) || leaf.parentIds.some((ancestor) => requested.has(ancestor))+ );+ if (leaves.length === 0 || !leaves.every(isLeafEditable)) {+ return { layers: [], primaryId: null };+ }+ const primary = leaves.find((leaf) => leaf.id === selectedId || leaf.parentIds.includes(selectedId));+ return { layers: leaves.map((leaf) => leaf.layer), primaryId: primary?.id ?? null };};/**@@ -118,8 +132,8 @@ export const createMoveTool = (): Tool => {if (existing) {return { kind: 'float', layerId: existing.layerId, origin: { ...existing.transform } };}- const layers = selectedDraggableLayers(ctx);- const primary = layers.find((layer) => layer.id === ctx.getDocument()?.selectedLayerId);+ const { layers, primaryId } = selectedDraggableLayers(ctx);+ const primary = layers.find((layer) => layer.id === primaryId);if (!primary) {return { kind: 'none' };}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.tsindex 95f7b9c77b..b5a5a5ed47 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts@@ -1,6 +1,6 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,} from '@workbench/canvas-engine/contracts';import type { StubRasterBackend, StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';@@ -13,6 +13,7 @@ import type {import type { PointerInput } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { isEmpty } from '@workbench/canvas-engine/math/rect';@@ -88,13 +89,13 @@ const controlTransaction = (layerId = 'control'): PixelEditTransaction => ({layerId,});-const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId,- version: 2,+ version: 3,width: 100,});@@ -128,7 +129,7 @@ interface Harness {}const createHarness = (- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,transaction: PixelEditTransaction | null | undefined = undefined): Harness => {const backend = createTestStubRasterBackend();@@ -579,7 +580,7 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves no* The auto-create dispatch happens at pointer-DOWN, outside history, so a gesture* producing no dirty rect must roll the layer back itself or strand it un-undoably.*/- const clipped = (doc: CanvasDocumentContractV2) => {+ const clipped = (doc: CanvasDocumentContractV3) => {const h = createHarness(doc);// Clip-to-bbox on with the stroke outside the frame, so `commit()` returns null.const ctx: ToolContext = { ...h.ctx, getStrokeClipRect: () => ({ height: 10, width: 10, x: 0, y: 0 }) };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex 5f5d2df242..8ed9352867 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -15,10 +15,12 @@*/import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { PointerInput } from '@workbench/canvas-engine/types';-import { isLayerPaintable, isLayerTransparencyLocked } from '@workbench/canvas-engine/document/layerEligibility';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafPaintable, isLayerTransparencyLocked } from '@workbench/canvas-engine/document/layerEligibility';import { isMaskLayer } from '@workbench/canvas-engine/document/sources';import type { StrokeCommittedEvent, Tool, ToolContext } from './tool';@@ -53,7 +55,7 @@ interface PaintTarget {commit(event: StrokeCommittedEvent): void;cancel(): void;/** When the gesture auto-created its layer, the created contract + its anchor (for history). */- createdLayer?: { layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor };+ createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor };/*** Overrides the brush colour for this gesture (mask targets paint an opaque* stencil — the stored RGB is irrelevant, the compositor colorizes by alpha).@@ -81,12 +83,13 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetif (!doc) {return null;}- const selected = doc.selectedLayerId ? doc.layers.find((layer) => layer.id === doc.selectedLayerId) : undefined;+ const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;+ const selected = leaf?.layer;- if (selected && selected.type === 'raster' && selected.source.type === 'paint') {+ if (leaf && selected && selected.type === 'raster' && selected.source.type === 'paint') {// The selection is a paint layer: paint into it, unless it's locked/disabled// (a no-op — don't silently spawn a new layer over the user's locked target).- if (!isLayerPaintable(selected)) {+ if (!isLeafPaintable(leaf)) {return null;}if (selected.source.bitmap) {@@ -109,11 +112,11 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget};}- if (selected?.type === 'raster' && selected.source.type === 'image' && tool === 'eraser') {+ if (leaf && selected?.type === 'raster' && selected.source.type === 'image' && tool === 'eraser') {// Erasing is a destructive pixel edit, so materialize the image into an// undoable paint layer in place. A locked/disabled/unready image refuses the// transaction; never spawn a new layer over the selected image.- if (!isLayerPaintable(selected) || isLayerTransparencyLocked(selected)) {+ if (!isLeafPaintable(leaf) || isLayerTransparencyLocked(selected)) {return null;}const transaction = ctx.beginPixelEdit?.(selected.id) ?? null;@@ -127,12 +130,12 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget};}- if (selected && isMaskLayer(selected)) {+ if (leaf && selected && isMaskLayer(selected)) {// The selection is a mask: paint the stroke into its alpha stencil cache// (brush adds coverage, eraser removes — the shared stroke session handles// both via its composite op). Never auto-create a paint layer here. A// locked/disabled mask refuses the stroke (a no-op, not a spawn).- if (!isLayerPaintable(selected)) {+ if (!isLeafPaintable(leaf)) {return null;}if (selected.mask.bitmap) {@@ -173,7 +176,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetid: layerId,isEnabled: true,isLocked: false,- name: `Layer ${doc.layers.length + 1}`,+ name: `Layer ${getDocumentLeaves(doc).length + 1}`,opacity: 1,source: { bitmap: null, type: 'paint' },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.tsindex d8154abd51..a53248b242 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts@@ -1,22 +1,23 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';import { createShapeTool, rectFromDrag } from './shapeTool';-const makeDoc = (): CanvasDocumentContractV2 => ({+const makeDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 96, width: 96, x: 0, y: 0 },height: 512,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 512,});@@ -40,7 +41,7 @@ interface StructuralCommit {inverse: CanvasProjectMutation;}-const createHarness = (doc: CanvasDocumentContractV2) => {+const createHarness = (doc: CanvasDocumentContractV3) => {const dispatched: CanvasProjectMutation[] = [];const commits: StructuralCommit[] = [];const stores = createEngineStores();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.tsindex ecaab22b24..b51e3cadb9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts@@ -24,6 +24,8 @@ import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contrimport type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { Rect, Vec2 } from '@workbench/canvas-engine/types';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import type { Tool, ToolContext } from './tool';/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */@@ -135,7 +137,7 @@ export const createShapeTool = (): Tool => {id: layerId,isEnabled: true,isLocked: false,- name: `Shape ${doc.layers.length + 1}`,+ name: `Shape ${getDocumentLeaves(doc).length + 1}`,opacity: 1,source: {fill: options.fill,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 9682b94028..991c422ea0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -38,7 +38,7 @@*/import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { PlacedSurface, PointerInput, Rect, Vec2 } from '@workbench/canvas-engine/types';@@ -75,7 +75,7 @@ export interface StrokeSessionConfig {composite: 'source-over' | 'destination-out' | 'source-atop';tool: 'brush' | 'eraser';/** Set only when this gesture auto-created its paint layer (for the composed history entry). */- createdLayer?: { layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor } | null;+ createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor } | null;/*** The bounded selection mask to clip the stroke to (resolved once by the tool* on pointer-down when a selection exists), as a placed surface in documentdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.tsindex ecae165733..1b959c31d7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts@@ -1,7 +1,8 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';@@ -30,13 +31,13 @@ const textLayer = (over: Partial<CanvasLayerContract> = {}): CanvasLayerContract...over,}) as CanvasLayerContract;-const makeDoc = (over: Partial<CanvasDocumentContractV2> = {}): CanvasDocumentContractV2 => ({+const makeDoc = (over: Partial<CanvasDocumentContractV3> = {}): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 96, width: 96, x: 0, y: 0 },height: 512,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 512,...over,});@@ -51,7 +52,7 @@ const pointer = (x: number, y: number, buttons = 1): PointerInput => ({timeStamp: 0,});-const createHarness = (doc: CanvasDocumentContractV2) => {+const createHarness = (doc: CanvasDocumentContractV3) => {const stores = createEngineStores();const openTextCreate = vi.fn<(point: Vec2) => void>();const openTextEdit = vi.fn<(layerId: string) => void>();@@ -84,7 +85,7 @@ describe('text tool: click behaviour', () => {});it('opens an edit-mode session when the click hits an existing text layer', () => {- const doc = makeDoc({ layers: [textLayer()] });+ const doc = makeDoc({ stacks: stacksFrom([textLayer()]) });const h = createHarness(doc);const tool = createTextTool();@@ -97,7 +98,7 @@ describe('text tool: click behaviour', () => {});it('creates rather than edits when the click misses the text block', () => {- const doc = makeDoc({ layers: [textLayer()] });+ const doc = makeDoc({ stacks: stacksFrom([textLayer()]) });const h = createHarness(doc);const tool = createTextTool();@@ -108,7 +109,7 @@ describe('text tool: click behaviour', () => {});it('does not edit a locked text layer (falls through to create)', () => {- const doc = makeDoc({ layers: [textLayer({ isLocked: true })] });+ const doc = makeDoc({ stacks: stacksFrom([textLayer({ isLocked: true })]) });const h = createHarness(doc);const tool = createTextTool();@@ -119,7 +120,7 @@ describe('text tool: click behaviour', () => {});it('does not edit a hidden (disabled) text layer', () => {- const doc = makeDoc({ layers: [textLayer({ isEnabled: false })] });+ const doc = makeDoc({ stacks: stacksFrom([textLayer({ isEnabled: false })]) });const h = createHarness(doc);const tool = createTextTool();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.tsindex 7695cad152..5cc63761c2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts@@ -33,13 +33,14 @@*/import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';import type { Vec2 } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { applyToPoint, invert } from '@workbench/canvas-engine/math/mat2d';import { estimateTextExtent } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';@@ -54,9 +55,8 @@ type TextSource = Extract<CanvasLayerSourceContract, { type: 'text' }>;/** A text-sourced raster layer. */type TextLayer = Extract<CanvasLayerContract, { type: 'raster' }> & { source: TextSource };-/** True when `layer` is an enabled, unlocked text layer (an edit-session candidate). */-const isEditableTextLayer = (layer: CanvasLayerContract): layer is TextLayer =>- layer.type === 'raster' && layer.source.type === 'text' && isLayerEditable(layer);+const isTextLayer = (layer: CanvasLayerContract): layer is TextLayer =>+ layer.type === 'raster' && layer.source.type === 'text';/*** The rendered text-block size for hit-testing: the live cache surface size when@@ -72,9 +72,10 @@ const textLayerSize = (layer: TextLayer, ctx: ToolContext): { width: number; hei};/** The top-most editable text layer whose rendered block contains `point` (document space), or `null`. */-const topTextLayerAt = (doc: CanvasDocumentContractV2, point: Vec2, ctx: ToolContext): TextLayer | null => {- for (const layer of doc.layers) {- if (!isEditableTextLayer(layer)) {+const topTextLayerAt = (doc: CanvasDocumentContractV3, point: Vec2, ctx: ToolContext): TextLayer | null => {+ for (const leaf of compileDocumentLeaves(doc)) {+ const layer = leaf.layer;+ if (!isTextLayer(layer) || !isLeafEditable(leaf)) {continue;}const inverse = invert(layerMatrix(layer.transform));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex cc88527df1..cd4ff53ed6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -14,8 +14,8 @@*/import type { StructuralCommitResult } 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 { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { EngineStores } from '@workbench/canvas-engine/engineStores';import type { CreatePath2D } from '@workbench/canvas-engine/freehand';@@ -55,7 +55,7 @@ export interface StrokeCommittedEvent {* now-empty auto-created layer (and a redo re-adds the layer + stroke).* Absent for strokes painted into a pre-existing layer.*/- createdLayer?: { layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor };+ createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor };}export interface PixelEditPatch {@@ -90,7 +90,7 @@ export interface ToolContext {/** The pan/zoom viewport. */viewport: Viewport;/** The current mirrored document, or `null` when none is available. */- getDocument(): CanvasDocumentContractV2 | null;+ getDocument(): CanvasDocumentContractV3 | null;/** Selected layer ids from the Layers panel, including the document's primary layer. */getSelectedLayerIds?(): readonly string[];/** Requests a re-render for the given flags. */@@ -98,7 +98,7 @@ export interface ToolContext {/** Reducer bridge. Painting tools use it for the single gesture-start `addCanvasLayer`. */dispatch(action: CanvasProjectMutation): void;/** Where a layer the tool creates lands: above `aboveId` when it belongs to `stack`, else the stack top. */- captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor;+ captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): CanvasNodeInsertionAnchor;/*** Records a structural document edit on the engine-owned canvas history:* dispatches `forward` now, and an undo dispatches `inverse` / a redodiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.tsindex 4cf886dadc..84067fad59 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts@@ -1,9 +1,11 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';@@ -31,13 +33,13 @@ const imageLayer = (type: 'raster',});-const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 200, width: 200, x: 0, y: 0 },height: 200,- layers,+ stacks: stacksFrom(layers),selectedLayerId,- version: 2,+ version: 3,width: 200,});@@ -110,7 +112,7 @@ interface Harness {* Grid snapping starts OFF so the gesture-math tests assert raw pointer deltas;* the snapping tests re-enable it on `h.ctx.stores`. (The product default is on.)*/-const createHarness = (doc: CanvasDocumentContractV2, zoom = 1, float?: FloatingSelection | null): Harness => {+const createHarness = (doc: CanvasDocumentContractV3, zoom = 1, float?: FloatingSelection | null): Harness => {const stores = createEngineStores();stores.snapToGrid.set(false);const overrides: { layerId: string; override: unknown }[] = [];@@ -119,7 +121,7 @@ const createHarness = (doc: CanvasDocumentContractV2, zoom = 1, float?: Floatingconst floatTransforms: LayerTransform[] = [];const beginTransformSession = (layerId: string): void => {- const layer = doc.layers.find((entry) => entry.id === layerId);+ const layer = getDocumentLeaves(doc).find((entry) => entry.id === layerId);if (!layer) {return;}@@ -624,8 +626,9 @@ describe('transform tool: floating selections', () => {it('maps the pointer through the layer matrix, so a scaled layer drags true', () => {// On a 2× layer, dragging 40 document px must move the float 20 layer-local px.const h = createHarness(doc({ height: 100, width: 100 }), 1, makeFloat('a'));- (h.ctx.getDocument() as CanvasDocumentContractV2).layers[0]!.transform.scaleX = 2;- (h.ctx.getDocument() as CanvasDocumentContractV2).layers[0]!.transform.scaleY = 2;+ const scaled = getDocumentLeaves(h.ctx.getDocument())[0]!;+ scaled.transform.scaleX = 2;+ scaled.transform.scaleY = 2;const tool = createTransformTool();down(tool, h.ctx, pointer(50, 50));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.tsindex 3372e4b231..135194e4b3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts@@ -39,7 +39,9 @@ import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { LayerTransform, TransformRect, TransformTarget } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';-import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { applyToPoint, invert } from '@workbench/canvas-engine/math/mat2d';import {applyMove,@@ -119,7 +121,7 @@ export const createTransformTool = (): Tool => {// Masks are MOVE-able (legacy parity) but not transform-able in this phase:// `applyTransform` has no mask bake path, so a transform session on a mask// would preview then no-op on Apply. Exclude them until that lands (Phase 7+).- isLayerEditable(layer) &&+ isLeafEditable(lookupDocumentLeaf(doc, layer.id)) &&layer.type !== 'inpaint_mask' &&layer.type !== 'regional_guidance' &&hittableLayerRect(layer, doc) !== null;@@ -136,7 +138,7 @@ export const createTransformTool = (): Tool => {}const float = ctx.getFloatingSelection?.() ?? null;if (float) {- const layer = doc.layers.find((candidate) => candidate.id === float.layerId);+ const layer = getDocumentLayer(doc, float.layerId);if (!layer) {return null;}@@ -155,7 +157,7 @@ export const createTransformTool = (): Tool => {};}const session = ctx.stores.transformSession.get();- const layer = session ? doc.layers.find((candidate) => candidate.id === session.layerId) : undefined;+ const layer = session ? getDocumentLayer(doc, session.layerId) : undefined;const rect = session && layer ? hittableLayerRect(layer, doc) : null;if (!session || !rect) {return null;@@ -260,7 +262,7 @@ export const createTransformTool = (): Tool => {// Entering the tool on an eligible selected layer opens a session on it.const doc = ctx.getDocument();const selectedId = doc?.selectedLayerId;- const selected = selectedId ? doc?.layers.find((layer) => layer.id === selectedId) : undefined;+ const selected = selectedId ? getDocumentLayer(doc, selectedId) : undefined;if (doc && selected && isEligible(selected, doc)) {ctx.beginTransformSession?.(selected.id);}@@ -358,7 +360,7 @@ export const createTransformTool = (): Tool => {// panel is the sole authority on which layer is active — a press never// re-targets it) and start a move gesture.const selectedId = doc.selectedLayerId;- const selected = selectedId ? doc.layers.find((layer) => layer.id === selectedId) : undefined;+ const selected = selectedId ? getDocumentLayer(doc, selectedId) : undefined;if (!selected || !isEligible(selected, doc)) {return;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.test.tsindex 9dd828b795..5b6b962581 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.test.ts@@ -1,11 +1,14 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import type { FilterOperationSession } from '@workbench/canvas-operations/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it, vi } from 'vitest';import { createFilterOperationCoordinator } from './FilterOperationCoordinator';import { createCanvasOperationStores } from './operationStores';const layer = {+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },filter: null,id: 'layer-1',isEnabled: true,@@ -40,7 +43,10 @@ const createHarness = () => {subscribe: vi.fn(() => () => undefined),},createSession: vi.fn(() => session),- getDocument: vi.fn<() => any>(() => ({ layers: [layer], selectedLayerId: null })),+ getDocument: vi.fn<() => any>(() => ({+ stacks: stacksFrom([layer as unknown as CanvasLayerContract]),+ selectedLayerId: null,+ })),getInitialDraft: vi.fn(() => ({ settings: {}, type: 'canny' })),getSessionDeps: vi.fn(() => ({})),isInteractionLocked: vi.fn(() => false),@@ -85,11 +91,20 @@ describe('FilterOperationCoordinator', () => {const { coordinator, deps } = createHarness();deps.getDocument.mockReturnValueOnce(null);expect(coordinator.start(layer.id)).toBe('missing');- deps.getDocument.mockReturnValueOnce({ layers: [{ ...layer, type: 'inpaint_mask' }], selectedLayerId: null });+ deps.getDocument.mockReturnValueOnce({+ stacks: stacksFrom([{ ...layer, type: 'inpaint_mask' } as unknown as CanvasLayerContract]),+ selectedLayerId: null,+ });expect(coordinator.start(layer.id)).toBe('unsupported');- deps.getDocument.mockReturnValueOnce({ layers: [{ ...layer, isEnabled: false }], selectedLayerId: null });+ deps.getDocument.mockReturnValueOnce({+ stacks: stacksFrom([{ ...layer, isEnabled: false } as unknown as CanvasLayerContract]),+ selectedLayerId: null,+ });expect(coordinator.start(layer.id)).toBe('disabled');- deps.getDocument.mockReturnValueOnce({ layers: [{ ...layer, isLocked: true }], selectedLayerId: null });+ deps.getDocument.mockReturnValueOnce({+ stacks: stacksFrom([{ ...layer, isLocked: true } as unknown as CanvasLayerContract]),+ selectedLayerId: null,+ });expect(coordinator.start(layer.id)).toBe('locked');deps.isInteractionLocked.mockReturnValueOnce(true);expect(coordinator.start(layer.id)).toBe('locked');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.tsindex 577f398ac8..4186c4ebef 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/FilterOperationCoordinator.ts@@ -1,5 +1,5 @@import type { LayerExportGuard } from '@workbench/canvas-engine/api';-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type {CanvasOperationActionResult,@@ -17,6 +17,7 @@ import type {import type { FilterCommitTarget, LayerFilterSettings } from '@workbench/canvas-operations/operationTypes';import type { BackendGraphContract } from '@workbench/graphContracts';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';import {buildFilterDefaults,DEFAULT_CONTROL_FILTER_TYPE,@@ -31,7 +32,7 @@ export interface FilterOperationCoordinatorDeps {readonly stores: CanvasApplicationOperationStores;readonly controller: CanvasOperationController;isInteractionLocked(): boolean;- getDocument(): CanvasDocumentContractV2 | null;+ getDocument(): CanvasDocumentContractV3 | null;captureGuard(layerId: string): LayerExportGuard | null;selectLayer(layerId: string): void;clearOtherOperation(): void;@@ -96,8 +97,9 @@ export const createFilterOperationCoordinator = (deps: FilterOperationCoordinatoreturn 'not-ready';}const document = deps.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);- if (!document || !layer) {+ const leaf = lookupDocumentLeaf(document, layerId);+ const layer = leaf?.layer;+ if (!document || !leaf || !layer) {return 'missing';}if (layer.type !== 'raster' && layer.type !== 'control') {@@ -106,10 +108,10 @@ export const createFilterOperationCoordinator = (deps: FilterOperationCoordinatoif (recommendedFilterType && layer.filter) {return 'not-ready';}- if (!layer.isEnabled) {+ if (!leaf.contributionEnabled) {return 'disabled';}- if (layer.isLocked) {+ if (leaf.effectiveLocked) {return 'locked';}const guard = deps.captureGuard(layer.id);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.tsindex 7ae3dd2633..6b4ffbf452 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.test.ts@@ -1,6 +1,6 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,CanvasRasterLayerContractV2,@@ -10,6 +10,7 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import type { Rect } from '@workbench/canvas-operations/generationContracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { planComposites, planControlComposites } from '@workbench/canvas-operations/generationCompositePlan';import { describe, expect, it, vi } from 'vitest';@@ -57,13 +58,13 @@ const controlLayer = (id: string, overrides: Partial<CanvasControlLayerContract>...overrides,});-const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 100,});@@ -321,7 +322,7 @@ const inpaintMask = (type: 'inpaint_mask',});-const maskEntryOf = (doc: CanvasDocumentContractV2) =>+const maskEntryOf = (doc: CanvasDocumentContractV3) =>planComposites(doc, BBOX).entries.find((e) => e.kind === 'inpaint-mask')!;/** A grayscale ImageData that is uniformly white or has a single dark pixel. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.tsindex cce66e9fc8..ef7b4224aa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts@@ -3,7 +3,7 @@ import type {LayerExportGuard,ReplaceSelectionFromImageResult,} from '@workbench/canvas-engine/api';-import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { CommitRasterFilterResult } from '@workbench/canvas-engine/controllers/filterResultController';import type {CommitMaskImageResult,@@ -142,7 +142,7 @@ export interface CanvasFilterCoordinatorDeps {readonly stores: CanvasApplicationOperationStores;readonly controller: CanvasOperationController;isInteractionLocked(): boolean;- getDocument(): CanvasDocumentContractV2 | null;+ getDocument(): CanvasDocumentContractV3 | null;captureGuard(layerId: string): LayerExportGuard | null;selectLayer(layerId: string): void;clearOtherOperation(): void;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.tsindex a96748e4f4..cc926ef42c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts@@ -1,11 +1,12 @@import type { GalleryImage } from '@features/gallery';-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-engine/engine';import type { RasterCompositeExportResult } from '@workbench/canvas-engine/exportRasterComposite';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { Project, WorkbenchState } from '@workbench/projectContracts';import { accountLifecycle } from '@platform/state/accountLifecycle';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';import { createInitialWorkbenchState } from '@workbench/workbenchState';@@ -47,7 +48,7 @@ const withProject = (): { project: Project; state: WorkbenchState } => {const document = {...current.canvas.document,bbox,- layers: [createEmptyPaintLayer('Existing', 'previous')],+ stacks: stacksFrom([createEmptyPaintLayer('Existing', 'previous')]),selectedLayerId: 'previous',};const project = { ...current, canvas: { ...current.canvas, document } };@@ -84,7 +85,7 @@ const createHarness = (});const getDocument = vi.fn(() => {order.push('document');- return project.canvas.document as unknown as CanvasDocumentContractV2;+ return project.canvas.document as unknown as CanvasDocumentContractV3;});const exportRasterComposite = vi.fn<CanvasEngine['exports']['exportRasterComposite']>(() => {order.push('export');@@ -146,7 +147,7 @@ const getCommittedLayers = (harness: ReturnType<typeof createHarness>): readonlyif (forward?.type !== 'applyCanvasLayerStackMutation' || !forward.add) {throw new Error('Expected add stack mutation');}- return forward.add.flatMap((insertion) => insertion.layers);+ return forward.add.flatMap((insertion) => insertion.nodes as CanvasLayerContract[]);};describe('createFromBbox', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.tsindex 02b24c6e5d..16c5bae8aa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts@@ -1,10 +1,12 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasRegionalGuidanceLayerContract,} from '@workbench/canvas-engine/contracts';import { accountLifecycle } from '@platform/state/accountLifecycle';+import { getDocumentLeaves } from '@workbench/canvas-engine/api';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';@@ -17,7 +19,7 @@ import {planControlComposites,planRegionalMaskComposites,} from '@workbench/canvas-operations/generationCompositePlan';-import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';@@ -105,13 +107,13 @@ const regionalLayer = (id: string): CanvasRegionalGuidanceLayerContract => ({type: 'regional_guidance',});-const invocationDocument = (): CanvasDocumentContractV2 => ({+const invocationDocument = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 64, width: 64, x: 0, y: 0 },height: 64,- layers: [controlLayer('control-a'), regionalLayer('regional-a')],+ stacks: stacksFrom([controlLayer('control-a'), regionalLayer('regional-a')]),selectedLayerId: 'control-a',- version: 2,+ version: 3,width: 64,});@@ -344,7 +346,7 @@ describe('createEngineRegistry', () => {const registry = createEngineRegistry({ timers: fakeTimers.timers });let project = createInitialWorkbenchState().projects[0]!;project = applyCanvasProjectMutation(project, {- document: createEmptyCanvasDocumentV2(),+ document: createEmptyCanvasDocument(),type: 'replaceCanvasDocument',});project = applyCanvasProjectMutation(project, {@@ -387,7 +389,7 @@ describe('createEngineRegistry', () => {dispatch: mutationPort.dispatch,encodeSurface: () => Promise.resolve(new Blob(['pending-pixels'], { type: 'image/png' })),getLayerSource: () => {- const layer = project.canvas.document.layers.find((candidate) => candidate.id === 'pending-layer');+ const layer = getDocumentLeaves(project.canvas.document).find((candidate) => candidate.id === 'pending-layer');return layer?.type === 'raster' && layer.source.type === 'paint' ? layer.source : null;},getLayerSurface: () => ({ offset: { x: 0, y: 0 }, surface }),@@ -415,7 +417,7 @@ describe('createEngineRegistry', () => {uploaded.resolve({ height: 8, imageName: 'persisted-after-reacquire.png', width: 8 });await bitmapStore.flushPendingUploads();- const layer = project.canvas.document.layers.find((candidate) => candidate.id === 'pending-layer');+ const layer = getDocumentLeaves(project.canvas.document).find((candidate) => candidate.id === 'pending-layer');expect(layer?.type === 'raster' && layer.source.type === 'paint' ? layer.source.bitmap?.imageName : null).toBe('persisted-after-reacquire.png');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.tsindex a4364b6cd3..023d15bbae 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-engine/engine';import type { RasterCompositeExportResult } from '@workbench/canvas-engine/exportRasterComposite';import type { Rect } from '@workbench/canvas-engine/types';@@ -10,11 +10,11 @@ import { exportCanvasComposite } from './exportCanvasComposite';const defaultRect: Rect = { height: 456, width: 123, x: -4, y: 8 };const defaultBlob = new Blob(['pixels'], { type: 'image/png' });-const createDocument = (bbox: Rect): CanvasDocumentContractV2 => ({ bbox }) as unknown as CanvasDocumentContractV2;+const createDocument = (bbox: Rect): CanvasDocumentContractV3 => ({ bbox }) as unknown as CanvasDocumentContractV3;const createHarness = (options: {- document?: CanvasDocumentContractV2 | null;+ document?: CanvasDocumentContractV3 | null;exportResult?: RasterCompositeExportResult;onFlush?: () => void;} = {}@@ -45,7 +45,7 @@ const createHarness = (engine,exportRasterComposite,order,- setDocument: (next: CanvasDocumentContractV2 | null) => {+ setDocument: (next: CanvasDocumentContractV3 | null) => {document = next;},};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.tsindex 9479eb7eb5..b352686113 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts@@ -1,14 +1,16 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasRasterLayerContractV2,- CanvasStateContractV2,+ CanvasStateContractV3,} from '@workbench/canvas-engine/contracts';import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { getDocumentLeaves } from '@workbench/canvas-engine/api';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';@@ -72,17 +74,17 @@ const inpaintMaskLayer = (id: string, noiseLevel?: number): CanvasLayerContracttype: 'inpaint_mask',});-const makeDoc = (layers: CanvasLayerContract[], size = 64): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasLayerContract[], size = 64): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: size, width: size, x: 0, y: 0 },height: size,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: size,});-const makeCanvas = (document: CanvasDocumentContractV2): CanvasStateContractV2 => ({+const makeCanvas = (document: CanvasDocumentContractV3): CanvasStateContractV3 => ({document: structuredClone(document),documentRevision: 0,snapshots: [],@@ -94,7 +96,7 @@ const makeCanvas = (document: CanvasDocumentContractV2): CanvasStateContractV2 =pendingImages: [],selectedImageIndex: 0,},- version: 2,+ version: 3,});/** Uniform-alpha ImageData (255 = fully opaque → bboxFullyCovered true). */@@ -127,7 +129,7 @@ interface HostOptions {* release, and a per-call-unique hash so every distinct composite entry uploads* (plan-key dedupe still reuses across calls).*/-const makeHost = (document: CanvasDocumentContractV2, options: HostOptions = {}): HostHarness => {+const makeHost = (document: CanvasDocumentContractV3, options: HostOptions = {}): HostHarness => {const stub = createTestStubRasterBackend();const events: string[] = [];const surfaceIds: string[] = [];@@ -316,7 +318,7 @@ describe('composeForGeneration', () => {}expect(result.composites.mode).toBe('img2img');expect(result.composites.baseImageName).toBe('composite-1.png');- expect(result.composites.canvas.document.layers[0]?.id).toBe('base');+ expect(getDocumentLeaves(result.composites.canvas.document)[0]?.id).toBe('base');expect(result.composites.bbox).toEqual({ height: 64, width: 64, x: 0, y: 0 });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.tsindex 55be115797..d068aed634 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts@@ -33,7 +33,7 @@ import type {CanvasControlLayerContract,CanvasDocumentSnapshot,CanvasRegionalGuidanceLayerContract,- CanvasStateContractV2,+ CanvasStateContractV3,} from '@workbench/canvas-engine/api';import type { CaptureRasterSnapshotResult } from '@workbench/canvas-engine/rasterTransactions';import type { Rect } from '@workbench/canvas-engine/types';@@ -42,7 +42,7 @@ import type {ExecuteCompositePlanDeps,} from '@workbench/canvas-operations/compositeForGeneration';-import { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/flatDocumentModel';+import { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/documentModel';import { intersect } from '@workbench/canvas-engine/math/rect';import {computeCompositeContentBounds,@@ -133,7 +133,7 @@ export interface GenerationCompositeDedupeCommit {/** Everything a canvas invoke needs from the composite pipeline. */export interface GenerationComposites {/** The frozen canvas state the composites were built from (for the enqueue snapshot). */- canvas: CanvasStateContractV2;+ canvas: CanvasStateContractV3;/** The generation bounding box of the frozen document. */bbox: Rect;/** The resolved generation mode. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.tsindex 1c2fcc5b55..100acd32b4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.test.ts@@ -1,12 +1,13 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,} from '@workbench/canvas-engine/contracts';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';import type { Rect } from './generationContracts';@@ -56,19 +57,19 @@ const BBOX: Rect = { height: 200, width: 200, x: 0, y: 0 };const makeDoc = (layers: CanvasLayerContract[],- overrides: Partial<CanvasDocumentContractV2> = {}-): CanvasDocumentContractV2 => ({+ overrides: Partial<CanvasDocumentContractV3> = {}+): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 200, width: 200, x: 0, y: 0 },height: 300,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 400,...overrides,});-const keyOf = (doc: CanvasDocumentContractV2, bbox: Rect = BBOX): string => planComposites(doc, bbox).entries[0]!.key;+const keyOf = (doc: CanvasDocumentContractV3, bbox: Rect = BBOX): string => planComposites(doc, bbox).entries[0]!.key;describe('planComposites — plan shape', () => {it('emits a single base-raster entry scoped to the bbox', () => {@@ -243,7 +244,7 @@ const inpaintMask = (type: 'inpaint_mask',});-const entryOfKind = (doc: CanvasDocumentContractV2, kind: string) =>+const entryOfKind = (doc: CanvasDocumentContractV3, kind: string) =>planComposites(doc, BBOX).entries.find((e) => e.kind === kind);describe('planComposites — inpaint-mask entries', () => {@@ -315,7 +316,7 @@ describe('planComposites — noise-mask entries', () => {});describe('planComposites — mask entry keys', () => {- const maskKeyOf = (doc: CanvasDocumentContractV2, kind: string): string | undefined => entryOfKind(doc, kind)?.key;+ const maskKeyOf = (doc: CanvasDocumentContractV3, kind: string): string | undefined => entryOfKind(doc, kind)?.key;it('is stable for identical documents', () => {const a = makeDoc([inpaintMask('m1', { denoiseLimit: 0.5 })]);@@ -529,3 +530,14 @@ describe('planComposites — raster adjustments in the base key', () => {});const plan0 = (layer: CanvasLayerContract): string => planComposites(makeDoc([layer]), BBOX).entries[0]!.key;++describe('planComposites — group gating', () => {+ it('excludes a raster leaf whose group is disabled', () => {+ const doc = {+ ...makeDoc([]),+ stacks: stacksFrom([groupContract('g', [rasterLayer('inner')], { isEnabled: false }), rasterLayer('root')]),+ };+ expect(planComposites(doc, BBOX).entries[0]!.layers.map((layer) => layer.id)).toEqual(['root']);+ expect(getBaseRasterContentBounds(doc)).toEqual({ height: 48, width: 64, x: 0, y: 0 });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.tsindex bab806ff26..3c37c2d80e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts@@ -1,6 +1,6 @@import type {CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasLayerSourceContract,@@ -13,7 +13,7 @@ import {getCompositeLayerBounds,planBaseRasterComposite,} from '@workbench/canvas-engine/api';-import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';import { hasControlLayerContent, hasRegionalGuidanceMaskContent } from '@workbench/canvasLayerContent';import type {@@ -65,7 +65,7 @@ export { getBaseRasterContentBounds, getCompositeLayerBounds, planBaseRasterComp/** The contributing layers, in flat order, narrowed to the ones that satisfy `hasContent`. */const contributingLayers = <T extends CanvasLayerContract>(- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,hasContent: (layer: CanvasLayerContract) => layer is T): T[] =>compileDocumentLeaves(document)@@ -134,7 +134,7 @@ const deriveMaskKey = (kind: string, bbox: Rect, layers: CompositeMaskLayerRef[]* (masks with an undefined `noiseLevel` are excluded, mirroring legacy — they* must NOT be treated as noise 0).*/-export const planComposites = (document: CanvasDocumentContractV2, bbox: Rect): CompositePlan => {+export const planComposites = (document: CanvasDocumentContractV3, bbox: Rect): CompositePlan => {const entries: CompositeEntry[] = [planBaseRasterComposite(document, bbox)];const maskLayers = contributingLayers(document, isInpaintMaskWithContent);@@ -172,7 +172,7 @@ export const planComposites = (document: CanvasDocumentContractV2, bbox: Rect):/** The native (unscaled) content rect of a control layer's source (layer-local). */const controlContentRect = (layer: CanvasControlLayerContract,- doc: CanvasDocumentContractV2+ doc: CanvasDocumentContractV3): { width: number; height: number; x: number; y: number } => {const { source } = layer;if (source.type === 'image') {@@ -192,7 +192,7 @@ const controlContentRect = (* rasterizes control at opacity 1, no filters), so display tweaks don't churn the* entry key.*/-const toControlLayerRef = (layer: CanvasControlLayerContract, doc: CanvasDocumentContractV2): CompositeLayerRef => {+const toControlLayerRef = (layer: CanvasControlLayerContract, doc: CanvasDocumentContractV3): CompositeLayerRef => {const rect = controlContentRect(layer, doc);return {blendMode: 'normal',@@ -225,7 +225,7 @@ export interface ControlCompositeEntry {* Control layers never contribute to the `base-raster` composite, so they never* paint into the img2img/inpaint source.*/-export const planControlComposites = (document: CanvasDocumentContractV2, bbox: Rect): ControlCompositeEntry[] =>+export const planControlComposites = (document: CanvasDocumentContractV3, bbox: Rect): ControlCompositeEntry[] =>contributingLayers(document, isControlLayerWithContent).map((layer) => {const ref = toControlLayerRef(layer, document);return {@@ -292,7 +292,7 @@ export interface RegionalMaskCompositeEntry {* "no region" reason). Regional layers never contribute to `base-raster`.*/export const planRegionalMaskComposites = (- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,bbox: Rect): RegionalMaskCompositeEntry[] =>contributingLayers(document, isRegionalGuidanceWithMask).map((layer) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex 4ae98692d7..e53d6bc05c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -7,6 +7,7 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { Project, WorkbenchState } from '@workbench/projectContracts';import { accountLifecycle } from '@platform/state/accountLifecycle';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import {createControlLayer,@@ -47,7 +48,7 @@ const withProject = (mutate?: (project: Project) => Project): { project: Projectconst document = {...current.canvas.document,bbox: { height: 512, width: 768, x: 31, y: 47 },- layers: [createEmptyPaintLayer('Existing', 'previous')],+ stacks: stacksFrom([createEmptyPaintLayer('Existing', 'previous')]),selectedLayerId: 'previous',};const base = { ...current, canvas: { ...current.canvas, document } };@@ -158,7 +159,7 @@ const getForwardLayers = (action: WorkbenchAction | CanvasProjectMutation): readif (mutation.type !== 'applyCanvasLayerStackMutation' || !mutation.add) {throw new Error('Expected add stack mutation');}- return mutation.add.flatMap((insertion) => insertion.layers);+ return mutation.add.flatMap((insertion) => insertion.nodes as CanvasLayerContract[]);};const expectedLayer = (diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.tsindex e63dd3ec73..266408b440 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts@@ -17,7 +17,7 @@ import {captureAccountScope,registerAccountOwnedResource,} from '@platform/state/accountLifecycle';-import { captureInsertionAnchor } from '@workbench/canvas-engine/api';+import { captureInsertionAnchor, getDocumentLeaves } from '@workbench/canvas-engine/api';import { resolveDefaultControlModelForBase } from '@workbench/widgets/layers/controlModelOptions';import {createControlLayer,@@ -160,7 +160,7 @@ const buildLayers = (buildLayer(image, destination, {bbox: project.canvas.document.bbox,defaultControlModel,- existingLayers: [...project.canvas.document.layers, ...layers],+ existingLayers: [...getDocumentLeaves(project.canvas.document), ...layers],modelBase,}));@@ -289,7 +289,7 @@ export const importGalleryImagesToCanvas = async (options: {const anchorFor = (stack: LayerStackKind) =>matchingProjectEngine? matchingProjectEngine.document.captureInsertionAnchor(stack, null)- : captureInsertionAnchor(capturedDocument.layers, {+ : captureInsertionAnchor(capturedDocument.stacks, {aboveId: null,editRevision: project.canvas.documentRevision,projectId: project.id,@@ -298,7 +298,7 @@ export const importGalleryImagesToCanvas = async (options: {const forward: CanvasProjectMutation = {add: [...new Set(layers.map((layer) => layer.type))].map((stack) => ({anchor: anchorFor(stack),- layers: layers.filter((layer) => layer.type === stack),+ nodes: layers.filter((layer) => layer.type === stack),})),enabledUpdates: [],selectedLayerId: layers.at(-1)?.id ?? previousSelectedLayerId,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.tsindex 1b32350cba..5f4948f19e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts@@ -1,8 +1,9 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/contracts';-import { haveSameStackOrders } from '@workbench/canvas-engine/api';+import { getDocumentIndex, getDocumentLeaves, haveSameStructure } from '@workbench/canvas-engine/api';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';-import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import { createInpaintMaskLayer } from '@workbench/widgets/layers/layerOps';import { createWorkbenchStore } from '@workbench/workbenchStore';@@ -22,11 +23,11 @@ const raster = (id: string): CanvasLayerContract => ({type: 'raster',});-const setup = (layers: CanvasLayerContract[], selectedLayerId: string) => {+const setup = (layers: CanvasNodeContract[], selectedLayerId: string) => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;store.commands.canvas.apply(projectId, {- document: { ...createEmptyCanvasDocumentV2(), layers, selectedLayerId },+ document: { ...createEmptyCanvasDocument(), stacks: stacksFrom(layers), selectedLayerId },type: 'replaceCanvasDocument',});const engine = createCanvasEngine({@@ -49,19 +50,19 @@ describe('layer restore through history on an interleaved document', () => {const duplicated = await engine.layers.duplicateLayers(['r0']);expect(duplicated.status).toBe('duplicated');- const r0 = document().layers.find((layer) => layer.id === 'r0')!;+ const r0 = getDocumentLeaves(document()).find((layer) => layer.id === 'r0')!;const remove = engine.document.model()!.prepare({ ids: ['r0'], type: 'remove' });if (remove.status !== 'prepared') {throw new Error('expected a prepared removal');}expect(engine.layers.commitPrepared('Delete', remove.edit).status).toBe('committed');- expect(document().layers.some((layer) => layer.id === 'r0')).toBe(false);+ expect(getDocumentLeaves(document()).some((layer) => layer.id === 'r0')).toBe(false);engine.history.undo();- expect(document().layers.find((layer) => layer.id === 'r0')).toEqual(r0);+ expect(getDocumentLeaves(document()).find((layer) => layer.id === 'r0')).toEqual(r0);expect(() => engine.history.undo()).not.toThrow();- expect(haveSameStackOrders(document().layers, original.layers)).toBe(true);+ expect(haveSameStructure(document().stacks, original.stacks)).toBe(true);expect(document().selectedLayerId).toBe('r0');expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();@@ -83,18 +84,52 @@ describe('layer restore through history on an interleaved document', () => {throw new Error('expected a prepared removal');}expect(engine.layers.commitPrepared('Delete', remove.edit).status).toBe('committed');- expect(document().layers.map((layer) => layer.id)).toEqual(['m1', 'r1']);+ expect(getDocumentLeaves(document()).map((layer) => layer.id)).toEqual(['m1', 'r1']);engine.history.undo();expect(- document()- .layers.filter((layer) => layer.type === 'raster')+ getDocumentLeaves(document())+ .filter((layer) => layer.type === 'raster').map((layer) => layer.id)).toEqual([duplicateId, 'r0', 'r1']);expect(() => engine.history.undo()).not.toThrow();- expect(haveSameStackOrders(document().layers, original.layers)).toBe(true);+ expect(haveSameStructure(document().stacks, original.stacks)).toBe(true);expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();});++ it('duplicates a group as a whole subtree with fresh ids and removes it again on undo', async () => {+ const { document, engine, original } = setup(+ [raster('r0'), groupContract('g', [raster('r1'), groupContract('h', [raster('r2')])]), raster('r3')],+ 'g'+ );+ const outline = () =>+ getDocumentIndex(document()).nodes.map((entry) => `${' '.repeat(entry.path.length)}${entry.node.id}`);++ const duplicated = await engine.layers.duplicateLayers(['g', 'r2']);+ if (duplicated.status !== 'duplicated') {+ throw new Error(`expected a duplicate, got ${duplicated.status}`);+ }+ expect(duplicated.duplicateIds).toHaveLength(1);+ const [copyId] = duplicated.duplicateIds;+ expect(duplicated.selectedLayerId).toBe(copyId);+ expect(document().selectedLayerId).toBe(copyId);+ const copy = getDocumentIndex(document()).byId.get(copyId!)!;+ expect(copy).toMatchObject({ parentId: null, siblingIndex: 1 });+ expect(copy.node).toMatchObject({ name: 'g copy', type: 'group' });+ const copiedIds = getDocumentIndex(document())+ .nodes.filter((entry) => entry.path.includes(copyId!))+ .map((entry) => entry.node.id);+ expect(copiedIds).toHaveLength(3);+ expect(new Set([...copiedIds, ...getDocumentLeaves(original).map((layer) => layer.id)]).size).toBe(7);+ expect(outline()).toHaveLength(10);++ engine.history.undo();+ expect(haveSameStructure(document().stacks, original.stacks)).toBe(true);+ expect(document().selectedLayerId).toBe('g');+ engine.history.redo();+ expect(getDocumentIndex(document()).byId.get(copyId!)?.node).toMatchObject({ name: 'g copy' });+ engine.lifecycle.dispose();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.tsindex 21244f3781..1c9fd63d7d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts@@ -1,5 +1,5 @@import type { GenerateModelConfig, GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-engine/engine';import type { RasterCompositeExportResult } from '@workbench/canvas-engine/exportRasterComposite';import type { Rect } from '@workbench/canvas-engine/types';@@ -59,11 +59,11 @@ const createProject = (boardId = 'board-1', generateOverrides: Partial<GenerateWreturn project;};-const createDocument = (bbox: Rect): CanvasDocumentContractV2 => ({ bbox }) as unknown as CanvasDocumentContractV2;+const createDocument = (bbox: Rect): CanvasDocumentContractV3 => ({ bbox }) as unknown as CanvasDocumentContractV3;const createHarness = (options: {- document?: CanvasDocumentContractV2 | null;+ document?: CanvasDocumentContractV3 | null;exportResult?: RasterCompositeExportResult;onFlush?: () => void;} = {}@@ -100,7 +100,7 @@ const createHarness = (flushPendingUploads,getDocument,order,- setDocument: (next: CanvasDocumentContractV2 | null) => {+ setDocument: (next: CanvasDocumentContractV3 | null) => {document = next;},uploadImage,diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.tsindex 0f9e43571f..ba732b183a 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts@@ -32,7 +32,7 @@*/import type { AspectRatioId } from '@features/generation/contracts';-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/api';+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/api';import type { WorkbenchState } from '@workbench/projectContracts';import { clampDimension, deriveAspectRatioId } from '@features/generation/settings';@@ -42,7 +42,7 @@ import type { WorkbenchCommands } from './workbenchStore';import { gridSizeForModelBase } from './widgets/canvas/bboxGrid';import { getProjectWidgetValues } from './widgetState';-type Bbox = CanvasDocumentContractV2['bbox'];+type Bbox = CanvasDocumentContractV3['bbox'];/** The last-synced width/height on both sides, used to detect which side changed. */export interface CanvasDimsSnapshot {diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.tsindex c55bdf2669..46944231ea 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts@@ -1,16 +1,18 @@-import type { CanvasStateContractV2 } from '@workbench/canvas-engine/api';+import type { CanvasStateContractV3 } from '@workbench/canvas-engine/api';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';import type { CanvasLoadResult } from './canvasLoadContracts';import {- createEmptyCanvasDocumentV2,- createEmptyCanvasStateV2,- createNewCanvasStateV2,+ createEmptyCanvasDocument,+ createEmptyCanvasState,+ createNewCanvasState,DEFAULT_CANVAS_DOCUMENT_HEIGHT,DEFAULT_CANVAS_DOCUMENT_WIDTH,loadCanvasState,+ normalizeCanvasDocumentContract,placementToTransform,} from './canvasMigration';import {@@ -21,26 +23,27 @@ import {nextInpaintMaskName,} from './widgets/layers/layerOps';-const migrate = (raw: unknown): CanvasStateContractV2 => {+const load = (raw: unknown): CanvasStateContractV3 => {const result = loadCanvasState(raw);-if (result.status !== 'loaded') {throw new Error(`Expected canvas state to load, got ${JSON.stringify(result)}.`);}-return result.value;};-const refusal = (raw: unknown): Exclude<CanvasLoadResult<CanvasStateContractV2>, { status: 'loaded' }> => {+const refusal = (raw: unknown): Exclude<CanvasLoadResult<CanvasStateContractV3>, { status: 'loaded' }> => {const result = loadCanvasState(raw);-if (result.status === 'loaded') {throw new Error('Expected canvas state to be refused.');}-return result;};+const withNodes = (nodes: unknown[], stack: 'raster' | 'control' | 'regional_guidance' | 'inpaint_mask' = 'raster') => {+ const state = createEmptyCanvasState();+ return { ...state, document: { ...state.document, stacks: { ...state.document.stacks, [stack]: nodes } } };+};+describe('placementToTransform', () => {it('maps a placement rect to a scale-based transform relative to the source image size', () => {expect(placementToTransform({ height: 200, width: 400, x: 10, y: 20 }, 200, 100)).toEqual({@@ -72,56 +75,26 @@ describe('loadCanvasState', () => {{ beginEndStepPct: [0.2, 0.9], controlMode: null, kind: 'z_image_control', model: 'z-control', weight: 0.7 },] as const;const layers = adapters.map((adapter, index) => ({+ ...createControlLayer(`Control ${index}`, `control-${index}`),adapter,- blendMode: 'normal',- id: `control-${index}`,- isEnabled: true,- isLocked: false,- name: `Control ${index}`,- opacity: 1,- source: { bitmap: null, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'control',- withTransparencyEffect: true,}));- const state = {- ...createEmptyCanvasStateV2(),- document: { ...createEmptyCanvasStateV2().document, layers },- };- const migrated = migrate(state);+ const loaded = load(withNodes(layers, 'control'));- expect(migrated.document.layers.map((layer) => (layer.type === 'control' ? layer.adapter : null))).toEqual(+ expect(loaded.document.stacks.control.map((layer) => (layer.type === 'control' ? layer.adapter : null))).toEqual(adapters);});it('normalizes an incomplete persisted Z-Image control with backend defaults', () => {- const state = createEmptyCanvasStateV2();- const migrated = migrate({- ...state,- document: {- ...state.document,- layers: [- {- adapter: { kind: 'z_image_control', model: 'z-control' },- blendMode: 'normal',- id: 'z-control',- isEnabled: true,- isLocked: false,- name: 'Z Control',- opacity: 1,- source: { bitmap: null, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'control',- withTransparencyEffect: true,- },- ],- },- });- const layer = migrated.document.layers[0];+ const loaded = load(+ withNodes(+ [{ ...createControlLayer('Z Control', 'z-control'), adapter: { kind: 'z_image_control', model: 'z-control' } }],+ 'control'+ )+ );+ const layer = loaded.document.stacks.control[0];- expect(layer?.type).toBe('control');expect(layer?.type === 'control' ? layer.adapter : null).toEqual({beginEndStepPct: [0, 1],controlMode: null,@@ -132,43 +105,34 @@ describe('loadCanvasState', () => {});it('normalizes control adapters in both the live document and saved snapshots', () => {- const state = createEmptyCanvasStateV2();const invalidLayer = {+ ...createControlLayer('Z Control', 'z-control'),adapter: { beginEndStepPct: [0.8, 0.2], controlMode: null, kind: 'z_image_control', model: null, weight: -1 },- blendMode: 'normal',- id: 'z-control',- isEnabled: true,- isLocked: false,- name: 'Z Control',- opacity: 1,- source: { bitmap: null, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'control',- withTransparencyEffect: true,};- const document = { ...state.document, layers: [invalidLayer] };- const migrated = migrate({+ const state = withNodes([invalidLayer], 'control');+ const loaded = load({...state,- document,- snapshots: [{ createdAt: 'now', document, id: 'snapshot', name: 'Snapshot' }],+ snapshots: [{ createdAt: 'now', document: state.document, id: 'snapshot', name: 'Snapshot' }],});- const getAdapter = (doc: (typeof migrated)['document']) => {- const layer = doc.layers[0];+ const getAdapter = (doc: (typeof loaded)['document']) => {+ const layer = doc.stacks.control[0];return layer?.type === 'control' ? layer.adapter : null;};- expect(getAdapter(migrated.document)).toMatchObject({ beginEndStepPct: [0, 1], weight: 0.75 });- expect(getAdapter(migrated.snapshots[0]!.document)).toMatchObject({ beginEndStepPct: [0, 1], weight: 0.75 });+ expect(getAdapter(loaded.document)).toMatchObject({ beginEndStepPct: [0, 1], weight: 0.75 });+ expect(getAdapter(loaded.snapshots[0]!.document)).toMatchObject({ beginEndStepPct: [0, 1], weight: 0.75 });});it('refuses a state whose snapshot entries are malformed instead of discarding them', () => {- const state = createEmptyCanvasStateV2();- const liveLayer = createEmptyPaintLayer('Live', 'live');- const validDocument = { ...state.document, layers: [createControlLayer('Snapshot Control', 'snapshot-control')] };+ const state = createEmptyCanvasState();+ const validDocument = {+ ...state.document,+ stacks: stacksFrom([createControlLayer('Snapshot Control', 'snapshot-control')]),+ };const valid = { createdAt: 'now', document: validDocument, id: 'valid', name: 'Valid' };- const base = { ...state, document: { ...state.document, layers: [liveLayer] } };+ const base = withNodes([createEmptyPaintLayer('Live', 'live')]);- expect(migrate({ ...base, snapshots: [valid] }).snapshots).toEqual([valid]);+ expect(load({ ...base, snapshots: [valid] }).snapshots).toEqual([valid]);for (const malformed of [null,@@ -176,10 +140,14 @@ describe('loadCanvasState', () => {{},{ createdAt: 'now', id: 'missing-document', name: 'Missing document' },{ createdAt: 'now', document: null, id: 'null-document', name: 'Null document' },- { createdAt: 'now', document: { ...state.document, layers: { bad: true } }, id: 'bad-layers', name: 'Bad' },+ {+ createdAt: 'now',+ document: { ...state.document, stacks: { raster: { bad: true } } },+ id: 'bad-layers',+ name: 'Bad',+ },]) {const raw = { ...base, snapshots: [valid, malformed] };-expect(refusal(raw)).toMatchObject({ raw, scope: 'snapshot', status: 'invalid' });}});@@ -188,20 +156,17 @@ describe('loadCanvasState', () => {['missing discriminant and base fields', { id: 'broken' }],['unknown layer type', { ...createEmptyPaintLayer('Mystery', 'mystery'), type: 'mystery' }],['raster with invalid source', { ...createEmptyPaintLayer('Raster', 'raster'), source: null }],- ['control with invalid adapter', { ...createControlLayer('Control', 'control'), adapter: null }],- [- 'regional guidance with invalid mask',- { ...createRegionalGuidanceLayer('Region', 0, 'region'), mask: { bitmap: null, fill: null } },- ],- ['inpaint mask with invalid mask', { ...createInpaintMaskLayer('Mask', 'mask'), mask: null }],- ])('refuses a snapshot containing a malformed layer: %s', (_label, malformedLayer) => {- const state = createEmptyCanvasStateV2();+ ['a leaf of another stack', createControlLayer('Control', 'control')],+ ['a group without children', { ...groupContract('g'), children: null }],+ ['a group with a malformed child', groupContract('g', [{ ...createEmptyPaintLayer('Bad', 'bad'), opacity: 4 }])],+ ])('refuses a snapshot containing a malformed node: %s', (_label, malformedNode) => {+ const state = createEmptyCanvasState();const raw = {...state,snapshots: [{createdAt: 'now',- document: { ...state.document, layers: [createEmptyPaintLayer('Fine', 'fine'), malformedLayer] },+ document: { ...state.document, stacks: { raster: [createEmptyPaintLayer('Fine', 'fine'), malformedNode] } },id: 'malformed',name: 'Malformed',},@@ -209,508 +174,227 @@ describe('loadCanvasState', () => {};expect(refusal(raw)).toMatchObject({- diagnostics: [{ path: 'snapshots[0].document.layers[1]' }],+ diagnostics: [{ path: expect.stringContaining('snapshots[0].document.stacks.raster[1]') }],raw,scope: 'snapshot',status: 'invalid',});});- it('round-trips valid snapshots containing every layer type', () => {- const state = createEmptyCanvasStateV2();- const layers = [- createEmptyPaintLayer('Raster', 'raster'),- createControlLayer('Control', 'control'),- createRegionalGuidanceLayer('Region', 0, 'region'),- createInpaintMaskLayer('Mask', 'mask'),- ];+ it('round-trips valid snapshots containing every layer type and nested groups', () => {+ const state = createEmptyCanvasState();+ const stacks = {+ control: [groupContract('cg', [createControlLayer('Control', 'control')], { isHidden: true })],+ inpaint_mask: [createInpaintMaskLayer('Mask', 'mask')],+ raster: [groupContract('rg', [createEmptyPaintLayer('Raster', 'raster'), groupContract('inner', [])])],+ regional_guidance: [createRegionalGuidanceLayer('Region', 0, 'region')],+ };const snapshot = {createdAt: 'now',- document: { ...state.document, layers, selectedLayerId: 'control' },- id: 'valid-layers',- name: 'Valid layers',+ document: { ...state.document, selectedLayerId: 'rg', stacks },+ id: 'valid',+ name: 'Valid',};- const migrated = migrate({ ...state, snapshots: [snapshot] });+ const loaded = load({ ...state, document: snapshot.document, snapshots: [snapshot] });- expect(migrated.snapshots).toEqual([snapshot]);+ expect(loaded.document).toEqual(snapshot.document);+ expect(loaded.snapshots).toEqual([snapshot]);});- it('refuses a live document containing an unknown layer type instead of dropping it', () => {- const state = createEmptyCanvasStateV2();+ it('refuses a live document containing an unknown node type instead of dropping it', () => {const valid = createEmptyPaintLayer('Valid', 'valid');- const raw = {- ...state,- document: { ...state.document, layers: [valid, { ...valid, id: 'mystery', type: 'mystery' }] },- };+ const raw = withNodes([valid, { ...valid, id: 'mystery', type: 'mystery' }]);expect(refusal(raw)).toMatchObject({- diagnostics: [{ message: expect.stringContaining('mystery layer is invalid'), path: 'document.layers[1]' }],+ diagnostics: [{ message: expect.stringContaining('mystery node is invalid'), path: 'document.stacks.raster[1]' }],raw,scope: 'document',status: 'invalid',});});- it('refuses a live document containing a malformed layer with a diagnostic naming the field', () => {- const state = createEmptyCanvasStateV2();- const raw = {- ...state,- document: { ...state.document, layers: [{ ...createEmptyPaintLayer('Bad', 'bad'), opacity: 4 }] },- };-- expect(refusal(raw)).toMatchObject({- diagnostics: [{ message: expect.stringContaining('opacity'), path: 'document.layers[0]' }],+ it('refuses a live document containing a malformed leaf with a diagnostic naming the field', () => {+ expect(refusal(withNodes([{ ...createEmptyPaintLayer('Bad', 'bad'), opacity: 4 }]))).toMatchObject({+ diagnostics: [{ message: expect.stringContaining('opacity'), path: 'document.stacks.raster[0]' }],status: 'invalid',});});- it('refuses future outer canvas versions before any migration', () => {- const state = createEmptyCanvasStateV2();- const raw = { ...state, document: { ...state.document, version: 3, zones: [] }, version: 3 };-- expect(refusal(raw)).toEqual({ raw, scope: 'state', status: 'unsupported-version', version: 3 });- });-- it('refuses a version 2 state whose nested document is a future version', () => {- const state = createEmptyCanvasStateV2();- const raw = { ...state, document: { ...state.document, version: 3 } };-- expect(refusal(raw)).toEqual({ raw, scope: 'document', status: 'unsupported-version', version: 3 });+ it.each([+ [+ 'a duplicated id across stacks',+ { control: [createControlLayer('C', 'dup')], raster: [createEmptyPaintLayer('R', 'dup')] },+ 'document.stacks.control[0].id',+ ],+ [+ 'a duplicated id inside a group',+ { raster: [groupContract('g', [createEmptyPaintLayer('A', 'a'), createEmptyPaintLayer('B', 'a')])] },+ 'document.stacks.raster[0].children[1].id',+ ],+ [+ 'a display-hidden raster group',+ { raster: [groupContract('g', [], { isHidden: true })] },+ 'document.stacks.raster[0].isHidden',+ ],+ ['a leaf in the wrong stack', { raster: [createControlLayer('C', 'c')] }, 'document.stacks.raster[0]'],+ [+ 'a group nested past the depth limit',+ {+ raster: [+ Array.from({ length: 11 }).reduce<unknown>(+ (child, _, index) => groupContract(`g${index}`, child ? [child as never] : []),+ null+ ),+ ],+ },+ 'document.stacks.raster[0]',+ ],+ ])('refuses %s', (_label, stacks, path) => {+ const state = createEmptyCanvasState();+ const raw = { ...state, document: { ...state.document, stacks } };+ expect(refusal(raw)).toMatchObject({+ diagnostics: [{ path: expect.stringContaining(path) }],+ scope: 'document',+ status: 'invalid',+ });});- it('refuses a version 2 state holding a future-version snapshot', () => {- const state = createEmptyCanvasStateV2();- const raw = {- ...state,- snapshots: [{ createdAt: 'now', document: { ...state.document, version: 4 }, id: 'future', name: 'Future' }],- };-- expect(refusal(raw)).toEqual({ raw, scope: 'snapshot', status: 'unsupported-version', version: 4 });+ it('accepts a group nested exactly at the depth limit', () => {+ const nested = Array.from({ length: 10 }).reduce<unknown>(+ (child, _, index) => groupContract(`g${index}`, child ? [child as never] : []),+ null+ );+ expect(load(withNodes([nested])).document.stacks.raster[0]).toEqual(nested);});- it('refuses a legacy state whose nested document declares a future version', () => {- const raw = { document: { height: 1, layers: [], version: 3, width: 1 } };-- expect(refusal(raw)).toEqual({ raw, scope: 'document', status: 'unsupported-version', version: 3 });+ it.each([+ ['a future outer version', { ...createEmptyCanvasState(), version: 4 }, 'state', 4],+ ['an older outer version', { ...createEmptyCanvasState(), version: 2 }, 'state', 2],+ ['a legacy version', { ...createEmptyCanvasState(), version: 1 }, 'state', 1],+ [+ 'a nested document of another version',+ { ...createEmptyCanvasState(), document: { ...createEmptyCanvasDocument(), version: 2 } },+ 'document',+ 2,+ ],+ [+ 'a snapshot of another version',+ {+ ...createEmptyCanvasState(),+ snapshots: [{ createdAt: 'now', document: { ...createEmptyCanvasDocument(), version: 4 }, id: 'f', name: 'F' }],+ },+ 'snapshot',+ 4,+ ],+ ])('refuses %s before parsing anything', (_label, raw, scope, version) => {+ expect(refusal(raw)).toEqual({ raw, scope, status: 'unsupported-version', version });});it.each([- ['a string', '2'],+ ['a string', '3'],['a fraction', 2.5],['zero', 0],['a negative number', -1],['null', null],+ ['absent', undefined],])('treats a malformed declared version as invalid rather than guessing: %s', (_label, version) => {- const raw = { ...createEmptyCanvasStateV2(), version };-+ const raw = { ...createEmptyCanvasState(), version };expect(refusal(raw)).toMatchObject({ diagnostics: [{ path: 'version' }], raw, scope: 'state', status: 'invalid' });});- it('treats a version 2 document inside a legacy state as invalid', () => {- const state = createEmptyCanvasStateV2();- const raw = { document: state.document };-- expect(refusal(raw)).toMatchObject({- diagnostics: [{ path: 'document.version' }],- scope: 'document',- status: 'invalid',- });- });-- it('fills a missing document, layers, or snapshots with known defaults', () => {- const empty = createEmptyCanvasStateV2();-- expect(migrate({ version: 2 })).toEqual(empty);- expect(migrate({ document: { height: 1024, width: 1024 }, version: 2 }).document.layers).toEqual([]);- expect(migrate({ ...empty, snapshots: undefined }).snapshots).toEqual([]);+ it('treats absent state as empty, fills missing snapshots, and refuses a document without its stacks', () => {+ const empty = createEmptyCanvasState();++ expect(load(undefined)).toEqual(empty);+ expect(load(null)).toEqual(empty);+ expect(refusal({ version: 3 })).toMatchObject({ scope: 'document', status: 'invalid' });+ // A v2-shaped body under a v3 envelope must not load as an empty canvas and then be saved over.+ expect(+ refusal({+ document: { height: 1024, layers: [createEmptyPaintLayer('Raster', 'r')], version: 3, width: 1024 },+ version: 3,+ })+ ).toMatchObject({ diagnostics: [{ path: 'document.stacks' }], scope: 'document', status: 'invalid' });+ expect(load({ ...empty, snapshots: undefined }).snapshots).toEqual([]);expect(refusal({ ...empty, snapshots: null })).toMatchObject({ scope: 'state', status: 'invalid' });expect(refusal({ ...empty, document: null })).toMatchObject({ scope: 'document', status: 'invalid' });- });-- it('tolerates a version 2 state whose document omits its version', () => {- const state = createEmptyCanvasStateV2();- const { version: _version, ...document } = state.document;-- expect(migrate({ ...state, document }).document.version).toBe(2);- });-- it('reports the legacy migration as a diagnostic on a loaded result', () => {- expect(loadCanvasState({ document: { layers: [] } })).toMatchObject({- diagnostics: [{ path: 'version' }],- status: 'loaded',- });- expect(loadCanvasState(createEmptyCanvasStateV2())).toMatchObject({ diagnostics: [], status: 'loaded' });- });-- it('maps a v1 raster layer to a v2 raster layer positioned by transform', () => {- const v1Canvas = {- document: {- height: 768,- layers: [- {- acceptedAt: '2026-06-09T00:00:00.000Z',- height: 512,- id: 'layer-1',- imageName: 'candidate.png',- imageUrl: '/api/v1/images/i/candidate.png/full',- label: 'Layer 1',- placement: { height: 300, opacity: 0.8, width: 600, x: 12, y: 24 },- queuedAt: '2026-06-09T00:00:00.000Z',- sourceQueueItemId: 'queue-1',- thumbnailUrl: '/api/v1/images/i/candidate.png/thumbnail',- width: 1024,- },- ],- version: 1,- width: 1024,- },- stagingArea: {- areThumbnailsVisible: true,- isVisible: false,- pendingImageIds: [],- pendingImages: [],- selectedImageIndex: 0,- },- version: 1,- };-- const migrated = migrate(v1Canvas);-- expect(migrated.version).toBe(2);- expect(migrated.document.layers).toHaveLength(1);-- const layer = migrated.document.layers[0];-- expect(layer).toEqual({- blendMode: 'normal',- id: 'layer-1',- isEnabled: true,- isLocked: false,- name: 'Layer 1',- opacity: 0.8,- source: { image: { height: 512, imageName: 'candidate.png', width: 1024 }, type: 'image' },- transform: { rotation: 0, scaleX: 600 / 1024, scaleY: 300 / 512, x: 12, y: 24 },- type: 'raster',- });- });-- it('generates an id and positional name for a layer missing them, and defaults a missing placement', () => {- const migrated = migrate({- document: {- height: 512,- layers: [{ height: 256, imageName: 'no-id.png', width: 256 }],- width: 512,- },- version: 1,- });-- const layer = migrated.document.layers[0];-- expect(layer?.id).toBeTruthy();- expect(layer?.name).toBe('Layer 1');- expect(layer?.type).toBe('raster');-- if (layer?.type === 'raster' && layer.source.type === 'image') {- expect(layer.source.image).toEqual({ height: 256, imageName: 'no-id.png', width: 256 });- expect(layer.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });- expect(layer.opacity).toBe(1);- }- });-- it('migrates a bare imageName-string legacy layer', () => {- const migrated = migrate({- document: { height: 512, layers: ['legacy-image.png'], width: 512 },- version: 1,- });-- const layer = migrated.document.layers[0];-- expect(layer?.name).toBe('legacy-image.png');-- if (layer?.type === 'raster' && layer.source.type === 'image') {- expect(layer.source.image.imageName).toBe('legacy-image.png');- }- });-- it('supports the pre-`document` legacy shape with layers directly on the canvas', () => {- const migrated = migrate({- layers: ['ancient.png'],- version: 1,- });-- expect(migrated.document.width).toBe(DEFAULT_CANVAS_DOCUMENT_WIDTH);- expect(migrated.document.height).toBe(DEFAULT_CANVAS_DOCUMENT_HEIGHT);- expect(migrated.document.layers).toHaveLength(1);- });-- it('defaults bbox to the full document rect', () => {- const migrated = migrate({ document: { height: 600, layers: [], width: 800 }, version: 1 });-- expect(migrated.document.bbox).toEqual({ height: 600, width: 800, x: 0, y: 0 });- });-- it('defaults selectedLayerId to null (v1 had no selection concept)', () => {- const migrated = migrate({ document: { height: 512, layers: [], width: 512 }, version: 1 });-- expect(migrated.document.selectedLayerId).toBeNull();- });-- it('carries the staging area through unchanged and defaults autoSwitchMode to off', () => {- const pendingImages = [- {- height: 512,- imageName: 'staged.png',- imageUrl: '/api/v1/images/i/staged.png/full',- placement: { height: 512, opacity: 1, width: 512, x: 0, y: 0 },- queuedAt: '2026-06-09T00:00:00.000Z',- sourceQueueItemId: 'queue-1',- thumbnailUrl: '/api/v1/images/i/staged.png/thumbnail',- width: 512,- },- ];-- const migrated = migrate({- document: { height: 512, layers: [], width: 512 },- stagingArea: {- areThumbnailsVisible: false,- isVisible: true,- pendingImageIds: ['staged.png'],- pendingImages,- selectedImageIndex: 0,- selectedLayerId: 'layer-x',- sourceQueueItemId: 'queue-1',- },- version: 1,- });-- expect(migrated.stagingArea).toEqual({- areThumbnailsVisible: false,- autoSwitchMode: 'off',- isVisible: true,- pendingImageIds: ['staged.png'],- pendingImages,- selectedImageIndex: 0,- selectedLayerId: 'layer-x',- sourceQueueItemId: 'queue-1',+ expect(refusal({ ...empty, document: { ...empty.document, stacks: [] } })).toMatchObject({+ scope: 'document',+ status: 'invalid',});- // The candidate objects themselves are carried through by reference, not reshaped.- expect(migrated.stagingArea.pendingImages[0]).toBe(pendingImages[0]);});- it('starts with no snapshots', () => {- const migrated = migrate({ document: { height: 512, layers: [], width: 512 }, version: 1 });-- expect(migrated.snapshots).toEqual([]);- });-- it('passes already-v2 input through normalized rather than re-migrating it', () => {- const v2Canvas = {- document: {- background: 'transparent',- bbox: { height: 512, width: 512, x: 0, y: 0 },- height: 512,- layers: [- {- blendMode: 'multiply',- id: 'layer-1',- isEnabled: true,- isLocked: false,- name: 'Layer 1',- opacity: 0.5,- source: { image: { height: 100, imageName: 'v2.png', width: 100 }, type: 'image' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- },- ],- selectedLayerId: 'layer-1',- version: 2,- width: 512,- },- documentRevision: 0,- snapshots: [],- stagingArea: {- areThumbnailsVisible: true,- autoSwitchMode: 'latest',- isVisible: false,- pendingImageIds: [],- pendingImages: [],- selectedImageIndex: 0,- },- version: 2,+ it('passes a valid state through normalized, keeping every persisted field', () => {+ const canvas = {+ ...withNodes([+ {+ ...createEmptyPaintLayer('Layer 1', 'layer-1'),+ blendMode: 'multiply',+ opacity: 0.5,+ source: { image: { height: 100, imageName: 'v3.png', width: 100 }, type: 'image' },+ },+ ]),+ documentRevision: 4,+ stagingArea: { ...createEmptyCanvasState().stagingArea, autoSwitchMode: 'latest' },};+ canvas.document.selectedLayerId = 'layer-1';- const migrated = migrate(v2Canvas);-- expect(migrated).toEqual(v2Canvas);- // Not double-migrated: blendMode/opacity/selectedLayerId survive untouched, which a v1->v2- // re-derivation from a (nonexistent) placement would not preserve.- expect(migrated.document.layers[0]).toEqual(v2Canvas.document.layers[0]);- expect(migrated.stagingArea.autoSwitchMode).toBe('latest');+ expect(load(canvas)).toEqual(canvas);});- it('normalizes persisted bbox geometry to whole pixels in documents and snapshots', () => {- const state = createEmptyCanvasStateV2();+ it('normalizes persisted geometry to whole pixels in documents and snapshots', () => {+ const state = createEmptyCanvasState();const document = {...state.document,bbox: { height: 12.6, width: 12.4, x: -3.4, y: -3.6 },height: 511.6,width: 512.4,};-- const migrated = migrate({- ...state,- document,- snapshots: [{ createdAt: 'now', document, id: 'fractional-bbox', name: 'Fractional bbox' }],- });-- expect(migrated.document.bbox).toEqual({ height: 13, width: 12, x: -3, y: -4 });- expect({ height: migrated.document.height, width: migrated.document.width }).toEqual({ height: 512, width: 512 });- expect(migrated.snapshots[0]?.document.bbox).toEqual({ height: 13, width: 12, x: -3, y: -4 });+ const loaded = load({ ...state, document, snapshots: [{ createdAt: 'now', document, id: 's', name: 'S' }] });+ const expected = { bbox: { height: 13, width: 12, x: -3, y: -4 }, height: 512, width: 512 };+ expect(loaded.document).toMatchObject(expected);+ expect(loaded.snapshots[0]!.document).toMatchObject(expected);});- it('creates and migrates whole-pixel document dimensions', () => {- const created = createEmptyCanvasDocumentV2(512.4, 511.6);- const migrated = migrate({ height: 511.6, layers: [], width: 512.4 });-- expect(created).toMatchObject({ bbox: { height: 512, width: 512, x: 0, y: 0 }, height: 512, width: 512 });- expect(migrated.document).toMatchObject({- bbox: { height: 512, width: 512, x: 0, y: 0 },- height: 512,- width: 512,- });+ it('normalizes the removed oldest staging auto-switch mode to off and keeps progress', () => {+ const state = createEmptyCanvasState();+ expect(+ load({ ...state, stagingArea: { ...state.stagingArea, autoSwitchMode: 'oldest' } }).stagingArea.autoSwitchMode+ ).toBe('off');+ expect(+ load({ ...state, stagingArea: { ...state.stagingArea, autoSwitchMode: 'progress' } }).stagingArea.autoSwitchMode+ ).toBe('progress');});- it('preserves the progress canvas staging auto-switch mode', () => {- const migrated = migrate({- document: { height: 512, layers: [], width: 512 },- stagingArea: { autoSwitchMode: 'progress' },- version: 2,- });-- expect(migrated.stagingArea.autoSwitchMode).toBe('progress');- });-- it('normalizes the removed oldest canvas staging auto-switch mode to off', () => {- const migrated = migrate({- document: { height: 512, layers: [], width: 512 },- stagingArea: { autoSwitchMode: 'oldest' },- version: 2,- });-- expect(migrated.stagingArea.autoSwitchMode).toBe('off');- });-- it('round-trips content-sized fields (paint offset, gradient width/height) on an already-v2 doc unchanged', () => {- const paintOffset = { x: -30, y: 45 };- const gradientExtent = { height: 220, width: 180 };- const v2Canvas = {- document: {- background: 'transparent',- bbox: { height: 512, width: 512, x: 0, y: 0 },- height: 512,- layers: [- {- blendMode: 'normal',- id: 'paint-1',- isEnabled: true,- isLocked: false,- name: 'Paint 1',- opacity: 1,- // Content-sized paint bitmap placed off-origin.- source: { bitmap: { height: 40, imageName: 'paint.png', width: 40 }, offset: paintOffset, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- },- {- blendMode: 'normal',- id: 'gradient-1',- isEnabled: true,- isLocked: false,- name: 'Gradient 1',- opacity: 1,- // Gradient carrying an explicit content extent (not document-sized).- source: {- angle: 45,- height: gradientExtent.height,- kind: 'linear',- stops: [- { color: '#000000', offset: 0 },- { color: '#ffffff', offset: 1 },- ],- type: 'gradient',- width: gradientExtent.width,- },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- },- ],- selectedLayerId: 'paint-1',- version: 2,- width: 512,- },- documentRevision: 3,- snapshots: [],- stagingArea: {- areThumbnailsVisible: true,- autoSwitchMode: 'off',- isVisible: false,- pendingImageIds: [],- pendingImages: [],- selectedImageIndex: 0,- },- version: 2,- };-- const migrated = migrate(v2Canvas);-- // Whole-state round-trip: normalization must not drop or rewrite the- // content-sizing fields the current schema carries.- expect(migrated).toEqual(v2Canvas);- const paintLayer = migrated.document.layers[0];- const gradientLayer = migrated.document.layers[1];- if (paintLayer?.type !== 'raster' || gradientLayer?.type !== 'raster') {- throw new Error('expected two raster layers to survive normalization');+ it('refuses garbage input as invalid state and preserves the raw payload', () => {+ for (const garbage of [[], 'canvas', 42]) {+ expect(refusal(garbage)).toMatchObject({ raw: garbage, scope: 'state', status: 'invalid' });}- expect(paintLayer.source).toEqual({- bitmap: { height: 40, imageName: 'paint.png', width: 40 },- offset: paintOffset,- type: 'paint',- });- expect(gradientLayer.source).toMatchObject({- height: gradientExtent.height,- type: 'gradient',- width: gradientExtent.width,- });- });-- it.each([undefined, null, {}])('falls back to a fresh empty v2 state for absent input (%j)', (absent) => {- const migrated = migrate(absent);-- expect(migrated).toEqual(createEmptyCanvasStateV2());- expect(migrated.document.width).toBe(DEFAULT_CANVAS_DOCUMENT_WIDTH);- expect(migrated.document.height).toBe(DEFAULT_CANVAS_DOCUMENT_HEIGHT);- expect(migrated.document.layers).toEqual([]);- expect(migrated.stagingArea.autoSwitchMode).toBe('off');});+});- it.each(['garbage', 42, []])('refuses non-object canvas state (%j)', (garbage) => {- expect(refusal(garbage)).toMatchObject({ raw: garbage, scope: 'state', status: 'invalid' });+describe('normalizeCanvasDocumentContract', () => {+ it('re-validates an in-memory document and refuses one holding an invalid node', () => {+ const state = createEmptyCanvasState();+ const document = { ...state.document, stacks: stacksFrom([createEmptyPaintLayer('A', 'a')]) };+ expect(normalizeCanvasDocumentContract(document)).toEqual(document);+ expect(+ normalizeCanvasDocumentContract({ ...document, stacks: { ...document.stacks, raster: [{ id: 'x' } as never] } })+ ).toBeNull();});});-describe('createEmptyCanvasStateV2', () => {- it('creates a well-formed empty v2 canvas at the default document size', () => {- const state = createEmptyCanvasStateV2();-- expect(state).toEqual({+describe('createEmptyCanvasState', () => {+ it('creates a well-formed empty canvas at the default document size', () => {+ expect(createEmptyCanvasState()).toEqual({document: {background: 'transparent',bbox: { height: DEFAULT_CANVAS_DOCUMENT_HEIGHT, width: DEFAULT_CANVAS_DOCUMENT_WIDTH, x: 0, y: 0 },height: DEFAULT_CANVAS_DOCUMENT_HEIGHT,- layers: [],selectedLayerId: null,- version: 2,+ stacks: { control: [], inpaint_mask: [], raster: [], regional_guidance: [] },+ version: 3,width: DEFAULT_CANVAS_DOCUMENT_WIDTH,},documentRevision: 0,@@ -723,66 +407,85 @@ describe('createEmptyCanvasStateV2', () => {pendingImages: [],selectedImageIndex: 0,},- version: 2,+ version: 3,});});it('honors a custom document size', () => {- const state = createEmptyCanvasStateV2(800, 600);+ const state = createEmptyCanvasState(800, 600);+ expect(state.document).toMatchObject({ bbox: { height: 600, width: 800, x: 0, y: 0 }, height: 600, width: 800 });+ });+});++describe('createNewCanvasState', () => {+ it('seeds exactly one empty inpaint mask, selected, matching the layers-panel factory', () => {+ const state = createNewCanvasState();+ const mask = state.document.stacks.inpaint_mask[0];- expect(state.document.width).toBe(800);- expect(state.document.height).toBe(600);- expect(state.document.bbox).toEqual({ height: 600, width: 800, x: 0, y: 0 });+ expect(state.document.stacks.inpaint_mask).toHaveLength(1);+ expect(state.document.stacks.raster).toEqual([]);+ expect(mask).toEqual(createInpaintMaskLayer(nextInpaintMaskName([]), mask?.id ?? ''));+ expect(state.document.selectedLayerId).toBe(mask?.id);+ });++ it('honors a custom document size while staying otherwise identical to an empty canvas', () => {+ const state = createNewCanvasState(800, 600);+ expect({+ ...state,+ document: { ...state.document, selectedLayerId: null, stacks: createEmptyCanvasState().document.stacks },+ }).toEqual(createEmptyCanvasState(800, 600));});});-describe('createNewCanvasStateV2', () => {- it('seeds exactly one empty inpaint mask, selected, with legacy-default fill', () => {- const state = createNewCanvasStateV2();- const { layers, selectedLayerId } = state.document;-- expect(layers).toHaveLength(1);- const mask = layers[0];- expect(mask?.type).toBe('inpaint_mask');- expect(mask?.name).toBe('Inpaint Mask 1');- expect(mask?.isEnabled).toBe(true);- expect(mask?.isLocked).toBe(false);- expect(mask?.opacity).toBe(1);- // Empty = no bitmap (no strokes); the diagonal-hatch fill is the legacy default.- expect(mask && 'mask' in mask ? mask.mask : null).toEqual({- bitmap: null,- fill: { color: '#e07575', style: 'diagonal' },- });- // The seeded mask is the initially selected layer.- expect(selectedLayerId).toBe(mask?.id);+describe('loadCanvasState ingress repair', () => {+ const stateWith = (stacks: CanvasStateContractV3['document']['stacks'], selectedLayerId: string | null = null) => {+ const state = createEmptyCanvasState();+ return { ...state, document: { ...state.document, selectedLayerId, stacks } };+ };++ it('repairs a dangling selection to a real node and reports it', () => {+ const result = loadCanvasState(stateWith(stacksFrom([createEmptyPaintLayer('A', 'a')]), 'ghost'));+ expect(result.status).toBe('loaded');+ if (result.status !== 'loaded') {+ return;+ }+ expect(result.value.document.selectedLayerId).toBe('a');+ expect(result.diagnostics).toMatchObject([{ path: 'document.selectedLayerId' }]);+ const clean = loadCanvasState(stateWith(stacksFrom([createEmptyPaintLayer('A', 'a')]), 'a'));+ expect(clean.status === 'loaded' && clean.diagnostics).toEqual([]);});- it('matches the layers-panel inpaint-mask factory shape (kept in lockstep)', () => {- const state = createNewCanvasStateV2();- const mask = state.document.layers[0];- // Rebuild the expected layer via the canonical factory, pinning the minted id- // and name so only the contract shape is compared.- const expected = createInpaintMaskLayer(nextInpaintMaskName([]), mask?.id ?? '');+ it('refuses a stack it does not know', () => {+ const state = stateWith({ ...stacksFrom([]), extra: [] } as CanvasStateContractV3['document']['stacks']);+ expect(refusal(state)).toMatchObject({+ diagnostics: [{ path: 'document.stacks.extra' }],+ scope: 'document',+ status: 'invalid',+ });+ });- expect(mask).toEqual(expected);+ it('drops display flags the raster stack cannot hold instead of persisting them', () => {+ const leaf = { ...createEmptyPaintLayer('A', 'a'), isHidden: true, children: [] };+ const group = groupContract('g', [], { isHidden: false });+ const loaded = load(stateWith({ ...stacksFrom([]), raster: [leaf, group] }));+ expect(loaded.document.stacks.raster[0]).toEqual(createEmptyPaintLayer('A', 'a'));+ expect(loaded.document.stacks.raster[1]).toEqual(groupContract('g'));});- it('honors a custom document size while staying otherwise identical to an empty canvas', () => {- const state = createNewCanvasStateV2(800, 600);-- expect(state.document.width).toBe(800);- expect(state.document.height).toBe(600);- expect(state.document.bbox).toEqual({ height: 600, width: 800, x: 0, y: 0 });- // Only the document's layers/selection differ from the empty canvas.- expect({ ...state, document: { ...state.document, layers: [], selectedLayerId: null } }).toEqual(- createEmptyCanvasStateV2(800, 600)- );+ it('caps the node count', () => {+ const leaves = Array.from({ length: 10_001 }, (_, index) => createEmptyPaintLayer(`L${index}`, `l${index}`));+ expect(refusal(stateWith(stacksFrom(leaves)))).toMatchObject({+ diagnostics: [{ message: 'document exceeds 10000 nodes' }],+ status: 'invalid',+ });});- it('does not disturb the migration/empty path (absent input still migrates to an empty, mask-free canvas)', () => {- // The new-canvas seed is scoped to fresh projects only; migrating absent- // input keeps producing an empty, mask-free document.- expect(migrate(undefined).document.layers).toEqual([]);- expect(createEmptyCanvasStateV2().document.layers).toEqual([]);+ it('fills the staging area from its defaults, keeping only well-typed fields', () => {+ const state = createEmptyCanvasState();+ const loaded = load({+ ...state,+ stagingArea: { autoSwitchMode: 'bogus', isVisible: false, pendingImages: 'nope' },+ });+ expect(loaded.stagingArea).toEqual({ ...state.stagingArea, isVisible: false });});});diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.tsindex 57bd712f3a..91fe3c6f93 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts@@ -1,15 +1,19 @@import type {- CanvasDocumentContractV2,- CanvasImageRef,+ CanvasDocumentContractV3,+ CanvasGroupContract,CanvasInpaintMaskLayerContract,CanvasLayerBaseContract,CanvasLayerContract,- CanvasRasterLayerContractV2,+ CanvasNodeContract,CanvasSnapshotContract,+ CanvasStackForests,CanvasStagingAreaContractV2,- CanvasStateContractV2,+ CanvasStateContractV3,+ LayerStackKind,} from '@workbench/canvas-engine/api';+import { CANVAS_MAX_NODE_COUNT, CANVAS_MAX_NODE_DEPTH, LAYER_STACK_ORDER } from '@workbench/canvas-engine/api';+import { repairSelectedLayerId } from '@workbench/canvas-engine/document/selectionRepair';import { z } from 'zod';import type { CanvasLoadDiagnostic, CanvasLoadResult, CanvasVersionScope } from './canvasLoadContracts';@@ -24,7 +28,7 @@ const createMigrationId = (prefix: string): string =>`${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;export const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null;+ typeof value === 'object' && value !== null && !Array.isArray(value);const zFiniteNumber = z.number().finite();const zCoordinate = z.object({ x: zFiniteNumber, y: zFiniteNumber });@@ -116,7 +120,9 @@ const zGeneratedImage = z.object({thumbnailUrl: z.string(),width: zFiniteNumber.nonnegative(),});-const zModelIdentifier = z.object({ base: z.string(), key: z.string(), name: z.string(), type: z.string() });+const zModelIdentifier = z+ .object({ base: z.string(), key: z.string(), name: z.string(), type: z.string() })+ .passthrough();const zReferenceImage = z.object({config: z.discriminatedUnion('type', [z.object({@@ -210,15 +216,13 @@ const zCanvasLayer = z.discriminatedUnion('type', [const asNumber = (value: unknown, fallback: number): number => (typeof value === 'number' ? value : fallback);-const asString = (value: unknown, fallback: string): string => (typeof value === 'string' ? value : fallback);-const asPositiveNumber = (value: unknown, fallback: number): number => {const numeric = asNumber(value, fallback);return numeric > 0 ? numeric : fallback;};-/** A positive whole-pixel dimension, shared by creation and every migration path. */+/** A positive whole-pixel dimension, shared by creation and every load path. */const asPositiveInteger = (value: unknown, fallback: number): number =>Math.max(1, Math.round(asPositiveNumber(value, fallback)));@@ -239,38 +243,39 @@ const normalizeCanvasDocumentGeometry = (rawWidth: unknown, rawHeight: unknown,};};-export const createEmptyCanvasStateV2 = (+const createEmptyStacks = (): CanvasStackForests => ({+ control: [],+ inpaint_mask: [],+ raster: [],+ regional_guidance: [],+});++export const createEmptyCanvasState = (width = DEFAULT_CANVAS_DOCUMENT_WIDTH,height = DEFAULT_CANVAS_DOCUMENT_HEIGHT-): CanvasStateContractV2 => ({- document: createEmptyCanvasDocumentV2(width, height),+): CanvasStateContractV3 => ({+ document: createEmptyCanvasDocument(width, height),documentRevision: 0,snapshots: [],- stagingArea: createDefaultStagingAreaV2(),- version: 2,+ stagingArea: createDefaultStagingArea(),+ version: 3,});-export const createEmptyCanvasDocumentV2 = (+export const createEmptyCanvasDocument = (width = DEFAULT_CANVAS_DOCUMENT_WIDTH,height = DEFAULT_CANVAS_DOCUMENT_HEIGHT-): CanvasDocumentContractV2 => {- const geometry = normalizeCanvasDocumentGeometry(width, height);- return {- background: 'transparent',- ...geometry,- layers: [],- selectedLayerId: null,- version: 2,- };-};+): CanvasDocumentContractV3 => ({+ background: 'transparent',+ ...normalizeCanvasDocumentGeometry(width, height),+ selectedLayerId: null,+ stacks: createEmptyStacks(),+ version: 3,+});/**- * A brand-new project's default inpaint mask: one empty mask (no bitmap/strokes)- * with the legacy-default diagonal-hatch fill in the first cycled mask colour- * (legacy `rgb(224,117,117)`). Mirrors `createInpaintMaskLayer` /- * `DEFAULT_INPAINT_MASK_FILL` in `widgets/layers/layerOps` — duplicated here so- * the pure reducer/migration module doesn't pull in the layers-panel/engine- * module graph; `canvasMigration.test.ts` locks the shape against that factory.+ * A brand-new project's default inpaint mask: one empty mask with the default diagonal-hatch fill+ * in the first cycled mask colour. Mirrors `createInpaintMaskLayer` in `widgets/layers/layerOps`,+ * duplicated so this pure module does not pull in the panel module graph.*/const createInitialInpaintMaskLayer = (): CanvasInpaintMaskLayerContract => ({blendMode: 'normal',@@ -284,30 +289,20 @@ const createInitialInpaintMaskLayer = (): CanvasInpaintMaskLayerContract => ({type: 'inpaint_mask',});-/**- * A fresh canvas state for a newly created project: an empty document that- * already carries one empty inpaint mask (selected), matching legacy, which seeds- * a canvas session with an inpaint mask present. The mask has no content, so it- * does NOT flip generation-mode detection to inpaint (see `detectCanvasMode`).- *- * This is the NEW-canvas path only. The migration / absent-input path- * (`loadCanvasState`) and `createEmptyCanvasStateV2` stay empty, so existing- * and migrated documents are left untouched.- */-export const createNewCanvasStateV2 = (+/** A fresh canvas state for a newly created project: an empty document with one selected empty inpaint mask. */+export const createNewCanvasState = (width = DEFAULT_CANVAS_DOCUMENT_WIDTH,height = DEFAULT_CANVAS_DOCUMENT_HEIGHT-): CanvasStateContractV2 => {- const base = createEmptyCanvasStateV2(width, height);+): CanvasStateContractV3 => {+ const base = createEmptyCanvasState(width, height);const mask = createInitialInpaintMaskLayer();-return {...base,- document: { ...base.document, layers: [mask], selectedLayerId: mask.id },+ document: { ...base.document, selectedLayerId: mask.id, stacks: { ...base.document.stacks, inpaint_mask: [mask] } },};};-const createDefaultStagingAreaV2 = (): CanvasStagingAreaContractV2 => ({+const createDefaultStagingArea = (): CanvasStagingAreaContractV2 => ({areThumbnailsVisible: true,autoSwitchMode: 'off',isVisible: false,@@ -317,9 +312,8 @@ const createDefaultStagingAreaV2 = (): CanvasStagingAreaContractV2 => ({});/**- * Converts a v1 `{x,y,width,height}` placement rect, plus the native size of the image it- * places, into a v2 `transform`. Shared by the migration path and the live "accept staged- * image into a raster layer" reducer, which still works from a v1-shaped placement.+ * Converts a `{x,y,width,height}` placement rect, plus the native size of the image it places,+ * into a layer `transform`. Used by the "accept staged image into a raster layer" reducer path.*/export const placementToTransform = (placement: { x: number; y: number; width: number; height: number },@@ -333,64 +327,6 @@ export const placementToTransform = (y: placement.y,});-/** Migrates a single v1 `CanvasRasterLayerContract` (or bare imageName string) into a v2 raster layer. */-const migrateLayerToV2 = (rawLayer: unknown, index: number): CanvasRasterLayerContractV2 => {- if (typeof rawLayer === 'string') {- return {- blendMode: 'normal',- id: rawLayer || createMigrationId('layer'),- isEnabled: true,- isLocked: false,- name: rawLayer || `Layer ${index + 1}`,- opacity: 1,- source: { image: { height: 0, imageName: rawLayer, width: 0 }, type: 'image' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };- }-- const layer = isRecord(rawLayer) ? rawLayer : {};- const image: CanvasImageRef = {- height: asNumber(layer.height, 0),- imageName: asString(layer.imageName, ''),- width: asNumber(layer.width, 0),- };- const placement = isRecord(layer.placement) ? layer.placement : {};- const placementX = asNumber(placement.x, 0);- const placementY = asNumber(placement.y, 0);- const placementWidth = asNumber(placement.width, image.width);- const placementHeight = asNumber(placement.height, image.height);- const placementOpacity = typeof placement.opacity === 'number' ? placement.opacity : 1;-- return {- blendMode: 'normal',- id: asString(layer.id, createMigrationId('layer')),- isEnabled: true,- isLocked: false,- name: asString(layer.label, `Layer ${index + 1}`),- opacity: placementOpacity,- source: { image, type: 'image' },- transform: placementToTransform(- { height: placementHeight, width: placementWidth, x: placementX, y: placementY },- image.width,- image.height- ),- type: 'raster',- };-};--const migrateDocumentToV2 = (rawDocument: Record<string, unknown>): CanvasDocumentContractV2 => {- const rawLayers = Array.isArray(rawDocument.layers) ? rawDocument.layers : [];-- return {- background: 'transparent',- ...normalizeCanvasDocumentGeometry(rawDocument.width, rawDocument.height),- layers: rawLayers.map((rawLayer, index) => migrateLayerToV2(rawLayer, index)),- selectedLayerId: null,- version: 2,- };-};-const AUTO_SWITCH_MODES: CanvasStagingAreaContractV2['autoSwitchMode'][] = ['off', 'latest', 'progress'];const asAutoSwitchMode = (value: unknown): CanvasStagingAreaContractV2['autoSwitchMode'] =>@@ -398,13 +334,10 @@ const asAutoSwitchMode = (value: unknown): CanvasStagingAreaContractV2['autoSwit? (value as CanvasStagingAreaContractV2['autoSwitchMode']): 'off';-/**- * Normalizes a v1 or v2 staging area. v1 never had `autoSwitchMode`, so it's absent from raw- * input and defaults to `'off'`; already-v2 input keeps its existing value.- */-const migrateStagingAreaToV2 = (rawCanvas: Record<string, unknown>): CanvasStagingAreaContractV2 => {+/** Fills the known optional defaults of a staging area. */+const normalizeStagingArea = (rawCanvas: Record<string, unknown>): CanvasStagingAreaContractV2 => {const rawStagingArea = isRecord(rawCanvas.stagingArea) ? rawCanvas.stagingArea : {};- const defaults = createDefaultStagingAreaV2();+ const defaults = createDefaultStagingArea();return {areThumbnailsVisible:@@ -433,27 +366,14 @@ type Refusal =type LoadStep<T> = Extract<CanvasLoadResult<T>, { status: 'loaded' }> | Refusal;-const LEGACY_CANVAS_VERSION = 1;--type DeclaredVersion =- | { kind: 'absent' }- | { kind: 'legacy' }- | { kind: 'current' }- | { kind: 'future'; version: number }- | { kind: 'malformed' };+type DeclaredVersion = { kind: 'current' } | { kind: 'other'; version: number } | { kind: 'malformed' };const classifyVersion = (value: unknown): DeclaredVersion => {- if (value === undefined) {- return { kind: 'absent' };- }- if (value === LEGACY_CANVAS_VERSION) {- return { kind: 'legacy' };- }if (value === MAX_SUPPORTED_CANVAS_SCHEMA_VERSION) {return { kind: 'current' };}- if (typeof value === 'number' && Number.isInteger(value) && value > MAX_SUPPORTED_CANVAS_SCHEMA_VERSION) {- return { kind: 'future', version: value };+ if (typeof value === 'number' && Number.isInteger(value) && value >= 1) {+ return { kind: 'other', version: value };}return { kind: 'malformed' };};@@ -472,22 +392,46 @@ const unsupported = (scope: CanvasVersionScope, version: number): Refusal => ({version,});-const describeLayerIssue = (value: Record<string, unknown>, path: string, issues: readonly z.core.$ZodIssue[]) => {+/** Refuses any declared version other than the current one before anything is defaulted or parsed. */+const checkVersion = (value: Record<string, unknown>, scope: CanvasVersionScope, path: string): Refusal | null => {+ const version = classifyVersion(value.version);+ switch (version.kind) {+ case 'current':+ return null;+ case 'other':+ return unsupported(scope, version.version);+ case 'malformed':+ return invalid(scope, [+ { message: `canvas version ${describeVersion(value.version)} is not recognized`, path: `${path}version` },+ ]);+ }+};++const describeIssue = (value: Record<string, unknown>, path: string, issues: readonly z.core.$ZodIssue[]) => {const issue = issues[0];- const detail = issue- ? `${issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''}${issue.message}`- : 'invalid layer';+ const detail = issue ? `${issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''}${issue.message}` : 'invalid node';const type = typeof value.type === 'string' ? value.type : undefined;- return { message: type ? `${type} layer is invalid (${detail})` : `layer is invalid (${detail})`, path };+ return { message: type ? `${type} node is invalid (${detail})` : `node is invalid (${detail})`, path };};-type ParsedLayer = { layer: CanvasLayerContract } | { diagnostic: CanvasLoadDiagnostic };+const zGroupShell = z.object({+ id: z.string(),+ isEnabled: z.boolean(),+ isHidden: z.boolean().optional(),+ isLocked: z.boolean(),+ name: z.string(),+ type: z.literal('group'),+});-/** Fills the known optional defaults on a v2 layer, then validates it strictly. */-const parseCanvasLayer = (value: unknown, path: string): ParsedLayer => {- if (!isRecord(value)) {- return { diagnostic: { message: 'layer is not an object', path } };- }+interface ParseContext {+ stack: CanvasLayerContract['type'];+ readonly ids: Set<string>;+ readonly diagnostics: CanvasLoadDiagnostic[];+ count: number;+}++/** Fills the known optional defaults on a leaf, then validates it strictly. */+const parseLeaf = (value: Record<string, unknown>, path: string, context: ParseContext): CanvasLayerContract | null => {let candidate: Record<string, unknown> = value;if (value.type === 'control') {candidate = {@@ -505,80 +449,146 @@ const parseCanvasLayer = (value: unknown, path: string): ParsedLayer => {};}const parsed = zCanvasLayer.safeParse(candidate);- return parsed.success- ? { layer: candidate as unknown as CanvasLayerContract }- : { diagnostic: describeLayerIssue(value, path, parsed.error.issues) };+ if (!parsed.success) {+ context.diagnostics.push(describeIssue(value, path, parsed.error.issues));+ return null;+ }+ const layer = parsed.data as CanvasLayerContract;+ if (layer.type !== context.stack) {+ context.diagnostics.push({ message: `${layer.type} layer does not belong to the ${context.stack} stack`, path });+ return null;+ }+ return layer;+};++const parseNode = (value: unknown, path: string, depth: number, context: ParseContext): CanvasNodeContract | null => {+ if (!isRecord(value)) {+ context.diagnostics.push({ message: 'node is not an object', path });+ return null;+ }+ context.count += 1;+ if (context.count > CANVAS_MAX_NODE_COUNT) {+ context.diagnostics.push({ message: `document exceeds ${CANVAS_MAX_NODE_COUNT} nodes`, path });+ return null;+ }+ if (typeof value.id === 'string') {+ if (context.ids.has(value.id)) {+ context.diagnostics.push({ message: `node id ${JSON.stringify(value.id)} is not unique`, path: `${path}.id` });+ return null;+ }+ context.ids.add(value.id);+ }+ if (value.type !== 'group') {+ return parseLeaf(value, path, context);+ }+ const shell = zGroupShell.safeParse(value);+ if (!shell.success) {+ context.diagnostics.push(describeIssue(value, path, shell.error.issues));+ return null;+ }+ if (context.stack === 'raster' && shell.data.isHidden === true) {+ context.diagnostics.push({ message: 'a raster group has no display-only hidden state', path: `${path}.isHidden` });+ return null;+ }+ if (context.stack === 'raster') {+ delete shell.data.isHidden;+ }+ if (depth >= CANVAS_MAX_NODE_DEPTH) {+ context.diagnostics.push({ message: `group nests deeper than ${CANVAS_MAX_NODE_DEPTH} levels`, path });+ return null;+ }+ if (!Array.isArray(value.children)) {+ context.diagnostics.push({ message: 'group children is not an array', path: `${path}.children` });+ return null;+ }+ const children = value.children.map((child, index) =>+ parseNode(child, `${path}.children[${index}]`, depth + 1, context)+ );+ if (children.some((child) => child === null)) {+ return null;+ }+ const group: CanvasGroupContract = { ...shell.data, children: children as CanvasNodeContract[] };+ return group;};-type ParsedLayers = { layers: CanvasLayerContract[] } | { diagnostics: CanvasLoadDiagnostic[] };+type ParsedStacks = { stacks: CanvasStackForests } | { diagnostics: CanvasLoadDiagnostic[] };-const parseCanvasLayers = (value: unknown, path: string): ParsedLayers => {- if (!Array.isArray(value)) {- return { diagnostics: [{ message: 'layers is not an array', path }] };+const parseStacks = (value: unknown, path: string): ParsedStacks => {+ if (!isRecord(value)) {+ return { diagnostics: [{ message: 'stacks is not an object', path }] };}- const layers: CanvasLayerContract[] = [];- const diagnostics: CanvasLoadDiagnostic[] = [];- value.forEach((entry, index) => {- const parsed = parseCanvasLayer(entry, `${path}[${index}]`);- if ('layer' in parsed) {- layers.push(parsed.layer);- } else {- diagnostics.push(parsed.diagnostic);+ const stacks = createEmptyStacks();+ const context: ParseContext = { count: 0, diagnostics: [], ids: new Set(), stack: 'raster' };+ for (const key of Object.keys(value)) {+ if (!LAYER_STACK_ORDER.includes(key as LayerStackKind)) {+ context.diagnostics.push({ message: `unknown stack ${JSON.stringify(key)}`, path: `${path}.${key}` });}- });- return diagnostics.length > 0 ? { diagnostics } : { layers };+ }+ for (const stack of LAYER_STACK_ORDER) {+ const roots = value[stack] === undefined ? [] : value[stack];+ if (!Array.isArray(roots)) {+ context.diagnostics.push({ message: `${stack} stack is not an array`, path: `${path}.${stack}` });+ continue;+ }+ context.stack = stack;+ const parsed = roots.map((root, index) => parseNode(root, `${path}.${stack}[${index}]`, 0, context));+ stacks[stack] = parsed.filter((node): node is CanvasNodeContract => node !== null);+ }+ return context.diagnostics.length > 0 ? { diagnostics: context.diagnostics } : { stacks };};-/** Re-validates an in-memory v2 document, filling known optional defaults; `null` when any layer is invalid. */+/** Re-validates an in-memory document, filling known optional defaults; `null` when any node is invalid. */export const normalizeCanvasDocumentContract = (- document: CanvasDocumentContractV2-): CanvasDocumentContractV2 | null => {- const parsed = parseCanvasLayers(document.layers, 'layers');- return 'layers' in parsed+ document: CanvasDocumentContractV3+): CanvasDocumentContractV3 | null => {+ const parsed = parseStacks(document.stacks, 'stacks');+ return 'stacks' in parsed? {...document,...normalizeCanvasDocumentGeometry(document.width, document.height, document.bbox),- layers: parsed.layers,+ stacks: parsed.stacks,}: null;};-const loadCanvasDocumentV2 = (+const loadCanvasDocument = (value: unknown,scope: CanvasVersionScope,path: string-): LoadStep<CanvasDocumentContractV2> => {+): LoadStep<CanvasDocumentContractV3> => {if (!isRecord(value)) {return invalid(scope, [{ message: 'document is not an object', path }]);}- const version = classifyVersion(value.version);- if (version.kind === 'future') {- return unsupported(scope, version.version);- }- if (version.kind === 'legacy' || version.kind === 'malformed') {- return invalid(scope, [- {- message: `document version ${describeVersion(value.version)} is not valid inside a version 2 canvas`,- path: `${path}.version`,- },- ]);+ const refusal = value.version === undefined ? null : checkVersion(value, scope, `${path}.`);+ if (refusal) {+ return refusal;}- const layers = parseCanvasLayers(value.layers === undefined ? [] : value.layers, `${path}.layers`);- if ('diagnostics' in layers) {- return invalid(scope, layers.diagnostics);+ const stacks = parseStacks(value.stacks, `${path}.stacks`);+ if ('diagnostics' in stacks) {+ return invalid(scope, stacks.diagnostics);}+ const declaredSelection = typeof value.selectedLayerId === 'string' ? value.selectedLayerId : null;+ const selectedLayerId = repairSelectedLayerId(stacks.stacks, declaredSelection);return {- diagnostics: [],+ diagnostics:+ declaredSelection !== null && selectedLayerId !== declaredSelection+ ? [+ {+ message: `selected layer ${JSON.stringify(declaredSelection)} is not in the document`,+ path: `${path}.selectedLayerId`,+ },+ ]+ : [],status: 'loaded',value: {background:value.background === 'transparent' || isRecord(value.background)- ? (value.background as CanvasDocumentContractV2['background'])+ ? (value.background as CanvasDocumentContractV3['background']): 'transparent',...normalizeCanvasDocumentGeometry(value.width, value.height, value.bbox),- layers: layers.layers,- selectedLayerId: typeof value.selectedLayerId === 'string' ? value.selectedLayerId : null,- version: 2,+ selectedLayerId,+ stacks: stacks.stacks,+ version: 3,},};};@@ -594,14 +604,28 @@ const loadCanvasSnapshot = (value: unknown, path: string): LoadStep<CanvasSnapshmissing.map((key) => ({ message: `snapshot ${key} is missing`, path: `${path}.${key}` })));}- const document = loadCanvasDocumentV2(value.document, 'snapshot', `${path}.document`);+ const document = loadCanvasDocument(value.document, 'snapshot', `${path}.document`);return document.status === 'loaded'- ? { diagnostics: [], status: 'loaded', value: { ...value, document: document.value } as CanvasSnapshotContract }+ ? {+ diagnostics: document.diagnostics,+ status: 'loaded',+ value: { ...value, document: document.value } as CanvasSnapshotContract,+ }: document;};-const loadCanvasStateV2 = (canvas: Record<string, unknown>): LoadStep<CanvasStateContractV2> => {- const document = loadCanvasDocumentV2(canvas.document === undefined ? {} : canvas.document, 'document', 'document');+const loadCanvasStateStep = (canvas: unknown): LoadStep<CanvasStateContractV3> => {+ if (canvas === undefined || canvas === null) {+ return { diagnostics: [], status: 'loaded', value: createEmptyCanvasState() };+ }+ if (!isRecord(canvas) || Array.isArray(canvas)) {+ return invalid('state', [{ message: 'canvas state is not an object', path: '' }]);+ }+ const refusal = checkVersion(canvas, 'state', '');+ if (refusal) {+ return refusal;+ }+ const document = loadCanvasDocument(canvas.document === undefined ? {} : canvas.document, 'document', 'document');if (document.status !== 'loaded') {return document;}@@ -610,82 +634,34 @@ const loadCanvasStateV2 = (canvas: Record<string, unknown>): LoadStep<CanvasStatreturn invalid('state', [{ message: 'snapshots is not an array', path: 'snapshots' }]);}const snapshots: CanvasSnapshotContract[] = [];+ const diagnostics = [...document.diagnostics];for (const [index, rawSnapshot] of rawSnapshots.entries()) {const snapshot = loadCanvasSnapshot(rawSnapshot, `snapshots[${index}]`);if (snapshot.status !== 'loaded') {return snapshot;}snapshots.push(snapshot.value);+ diagnostics.push(...snapshot.diagnostics);}return {- diagnostics: [],+ diagnostics,status: 'loaded',value: {document: document.value,documentRevision: asNumber(canvas.documentRevision, 0),snapshots,- stagingArea: migrateStagingAreaToV2(canvas),- version: 2,- },- };-};--const loadLegacyCanvasState = (rawCanvas: Record<string, unknown>): LoadStep<CanvasStateContractV2> => {- const rawDocument = isRecord(rawCanvas.document) ? rawCanvas.document : rawCanvas;- if (rawDocument !== rawCanvas) {- const version = classifyVersion(rawDocument.version);- if (version.kind === 'future') {- return unsupported('document', version.version);- }- if (version.kind === 'current' || version.kind === 'malformed') {- return invalid('document', [- {- message: `document version ${describeVersion(rawDocument.version)} is not valid inside a legacy canvas`,- path: 'document.version',- },- ]);- }- }- return {- diagnostics: [{ message: 'migrated legacy canvas state to version 2', path: 'version' }],- status: 'loaded',- value: {- document: migrateDocumentToV2(rawDocument),- documentRevision: 0,- snapshots: [],- stagingArea: migrateStagingAreaToV2(rawCanvas),- version: 2,+ stagingArea: normalizeStagingArea(canvas),+ version: 3,},};};-const loadCanvasStateStep = (canvas: unknown): LoadStep<CanvasStateContractV2> => {- if (canvas === undefined || canvas === null) {- return loadLegacyCanvasState({});- }- if (!isRecord(canvas) || Array.isArray(canvas)) {- return invalid('state', [{ message: 'canvas state is not an object', path: '' }]);- }- const version = classifyVersion(canvas.version);- switch (version.kind) {- case 'future':- return unsupported('state', version.version);- case 'malformed':- return invalid('state', [- { message: `canvas version ${describeVersion(canvas.version)} is not recognized`, path: 'version' },- ]);- case 'current':- return loadCanvasStateV2(canvas);- default:- return loadLegacyCanvasState(canvas);- }-};-/**- * Version-checks persisted canvas state before anything migrates or defaults it: absent and v1- * state enter the known migration path, v2 is validated strictly, anything newer is refused.+ * Version-checks persisted canvas state before anything is defaulted or parsed: an absent state is+ * a fresh empty canvas, the current version is validated strictly, every other declared version is+ * refused so its raw payload stays available for recovery.*/-export const loadCanvasState = (canvas: unknown): CanvasLoadResult<CanvasStateContractV2> => {+export const loadCanvasState = (canvas: unknown): CanvasLoadResult<CanvasStateContractV3> => {const step = loadCanvasStateStep(canvas);return step.status === 'loaded' ? step : { ...step, raw: canvas };};diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.tsindex 8d5f6ec826..6ecb01d88e 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts@@ -6,12 +6,13 @@ import type {} from '@workbench/canvas-engine/contracts';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import { getDocumentLeaves } from '@workbench/canvas-engine/api';import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';-import { createEmptyCanvasDocumentV2 } from './canvasMigration';+import { createEmptyCanvasDocument } from './canvasMigration';import { createCanvasProjectMutationPort } from './canvasProjectMutationPort';import { createWorkbenchStore } from './workbenchStore';@@ -56,10 +57,9 @@ const getLayer = (projectId: string,layerId: string): CanvasLayerContract | undefined =>- store- .getState()- .projects.find((project) => project.id === projectId)- ?.canvas.document.layers.find((layer) => layer.id === layerId);+ getDocumentLeaves(store.getState().projects.find((project) => project.id === projectId)?.canvas.document).find(+ (layer) => layer.id === layerId+ );const getPaintSource = (layer: CanvasLayerContract | undefined@@ -77,7 +77,7 @@ const setupProjects = (originLayer: CanvasLayerContract, otherLayer: CanvasLayerconst store = createWorkbenchStore();const originProjectId = store.getState().activeProjectId;store.commands.canvas.apply(originProjectId, {- document: createEmptyCanvasDocumentV2(),+ document: createEmptyCanvasDocument(),type: 'replaceCanvasDocument',});store.commands.canvas.apply(originProjectId, {@@ -88,7 +88,7 @@ const setupProjects = (originLayer: CanvasLayerContract, otherLayer: CanvasLayerstore.commands.projects.create();const otherProjectId = store.getState().activeProjectId;store.commands.canvas.apply(otherProjectId, {- document: createEmptyCanvasDocumentV2(),+ document: createEmptyCanvasDocument(),type: 'replaceCanvasDocument',});store.commands.canvas.apply(otherProjectId, {diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.tsindex fb8ec3bbc4..a7fcc3e958 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts@@ -2,14 +2,14 @@ import type {CanvasEditIntent,CanvasMutationOrigin,CanvasProjectMutation,- CanvasStateContractV2,+ CanvasStateContractV3,} from '@workbench/canvas-engine/api';import type { WorkbenchState } from '@workbench/projectContracts';import type { WorkbenchCanvasCommands } from './workbenchStore';export interface CanvasProjectMutationPort {- getCanvasState(): CanvasStateContractV2 | null;+ getCanvasState(): CanvasStateContractV3 | null;subscribe(listener: () => void): () => void;dispatch(mutation: CanvasProjectMutation, origin?: CanvasMutationOrigin): boolean;commitEdit(intent: CanvasEditIntent): void;@@ -23,7 +23,7 @@ export const createCanvasProjectMutationPort = (},projectId: string): CanvasProjectMutationPort => {- const getCanvasState = (): CanvasStateContractV2 | null =>+ const getCanvasState = (): CanvasStateContractV3 | null =>store.getState().projects.find((project) => project.id === projectId)?.canvas ?? null;return {diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex 440e5b79b0..057e1ebcac 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -1,20 +1,44 @@import type { Project } from '@workbench/projectContracts';import {- type CanvasDocumentContractV2,+ type CanvasDocumentContractV3,type CanvasLayerBasePatch,type CanvasLayerConfigPatch,type CanvasLayerContract,+ type CanvasNodeContract,+ type CanvasNodeInsertion,+ type CanvasNodeInsertionAnchor,+ type CanvasNodeMove,type CanvasProjectMutation,type CanvasRasterLayerContractV2,- type CanvasStateContractV2,- type FlatLayerInsertion,- type FlatLayerInsertionAnchor,- type ReorderFlatStackCommand,+ type CanvasStackForests,+ type CanvasStateContractV3,+ type ReorderSiblingsCommand,+ CANVAS_MAX_NODE_COUNT,+ CANVAS_MAX_NODE_DEPTH,+ GROUP_PATCH_KEYS,isHideableLayer,+ isNodeHidden,} from '@workbench/canvas-engine/api';-import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import { reorderLayerStack } from '@workbench/canvas-engine/document/layerStacks';+import {+ childrenAt,+ getDocumentIndex,+ getDocumentLayer,+ hasDocumentNode,+ indexStacks,+ outermostNodes,+ type CanvasDocumentIndex,+ type CanvasNodeEntry,+} from '@workbench/canvas-engine/document/documentIndex';+import {+ collectSubtree,+ collectSubtreeLeaves,+ isGroupNode,+ removeNodes,+ updateNodes,+} from '@workbench/canvas-engine/document/documentTree';+import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import { isOverlayStack, layerStackOf, reorderSiblings } from '@workbench/canvas-engine/document/layerStacks';import { repairSelectedLayerId } from '@workbench/canvas-engine/document/selectionRepair';import { normalizeCanvasDocumentContract } from './canvasMigration';@@ -37,10 +61,9 @@ const CANVAS_PROJECT_MUTATION_TYPES: ReadonlySet<string> = new Set<CanvasProject'deleteCanvasSnapshot','discardAllStagedImages','discardSelectedStagedImage',- 'duplicateCanvasLayer','mergeCanvasLayersDown','removeCanvasLayers',- 'reorderCanvasLayerStacks',+ 'reorderCanvasSiblings','replaceCanvasDocument','replaceCanvasLayer','resizeCanvasDocument',@@ -63,10 +86,6 @@ const CANVAS_PROJECT_MUTATION_TYPES: ReadonlySet<string> = new Set<CanvasProjectexport const isCanvasProjectMutation = (value: { type: string }): value is CanvasProjectMutation =>CANVAS_PROJECT_MUTATION_TYPES.has(value.type);-type CanvasLayers = CanvasDocumentContractV2['layers'];--const layerExists = (layers: CanvasLayers, id: string): boolean => layers.some((layer) => layer.id === id);-const AUTO_LAYER_NAME_PATTERN = /^Layer (\d+)$/;export const nextLayerName = (existingNames: readonly string[]): string => {@@ -87,254 +106,385 @@ export const nextLayerName = (existingNames: readonly string[]): string => {return `Layer ${n}`;};-const withRepairedSelection = (document: CanvasDocumentContractV2): CanvasDocumentContractV2 => {- const selectedLayerId = repairSelectedLayerId(document.layers, document.selectedLayerId);+const withRepairedSelection = (document: CanvasDocumentContractV3): CanvasDocumentContractV3 => {+ const selectedLayerId = repairSelectedLayerId(document.stacks, document.selectedLayerId);return selectedLayerId === document.selectedLayerId ? document : { ...document, selectedLayerId };};-const setCanvasDocument = (project: Project, document: CanvasDocumentContractV2): Project =>+const setCanvasDocument = (project: Project, document: CanvasDocumentContractV3): Project =>document === project.canvas.document ? project : { ...project, canvas: { ...project.canvas, document } };const updateCanvasDocument = (project: Project,- update: (document: CanvasDocumentContractV2) => CanvasDocumentContractV2+ update: (document: CanvasDocumentContractV3) => CanvasDocumentContractV3): Project => setCanvasDocument(project, update(project.canvas.document));-const setCanvasState = (project: Project, canvas: CanvasStateContractV2): Project =>+const setCanvasState = (project: Project, canvas: CanvasStateContractV3): Project =>canvas === project.canvas ? project : { ...project, canvas };-const mapCanvasLayer = (- document: CanvasDocumentContractV2,+const withStacks = (document: CanvasDocumentContractV3, stacks: CanvasStackForests): CanvasDocumentContractV3 =>+ stacks === document.stacks ? document : { ...document, stacks };++const withinLimits = (stacks: CanvasStackForests): boolean => {+ const index = indexStacks(stacks);+ return index.maxDepth <= CANVAS_MAX_NODE_DEPTH && index.nodes.length <= CANVAS_MAX_NODE_COUNT;+};++const mapNode = (+ document: CanvasDocumentContractV3,+ id: string,+ update: (node: CanvasNodeContract) => CanvasNodeContract+): CanvasDocumentContractV3 => withStacks(document, updateNodes(document.stacks, new Map([[id, update]])));++const mapLayer = (+ document: CanvasDocumentContractV3,id: string,update: (layer: CanvasLayerContract) => CanvasLayerContract-): CanvasDocumentContractV2 => {- let changed = false;- const layers = document.layers.map((layer) => {- if (layer.id !== id) {- return layer;- }- const next = update(layer);- changed ||= next !== layer;- return next;- });- return changed ? { ...document, layers } : document;-};+): CanvasDocumentContractV3 => mapNode(document, id, (node) => (isGroupNode(node) ? node : update(node)));++const mapNodes = (+ document: CanvasDocumentContractV3,+ updates: Iterable<[string, (node: CanvasNodeContract) => CanvasNodeContract]>+): CanvasDocumentContractV3 => withStacks(document, updateNodes(document.stacks, new Map(updates)));const setCanvasLayersEnabled = (- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,updates: readonly { id: string; isEnabled: boolean }[]-): CanvasDocumentContractV2 => {- const targets = new Map(updates.map((update) => [update.id, update.isEnabled]));- let changed = false;- const layers = document.layers.map((layer) => {- const isEnabled = targets.get(layer.id);- if (isEnabled === undefined || isEnabled === layer.isEnabled) {- return layer;- }- changed = true;- return { ...layer, isEnabled };- });- return changed ? { ...document, layers } : document;-};+): CanvasDocumentContractV3 =>+ mapNodes(+ document,+ updates.map(({ id, isEnabled }) => [id, (node) => (node.isEnabled === isEnabled ? node : { ...node, isEnabled })])+ );-/**- * Bulk display-visibility update. Layers that cannot be hidden (raster) are- * skipped rather than silently gaining a meaningless field: for them visibility- * and participation are the same fact, which `isEnabled` already carries.- */+const isHideableNode = (index: CanvasDocumentIndex, node: CanvasNodeContract): boolean =>+ isGroupNode(node) ? isOverlayStack(index.byId.get(node.id)!.stack) : isHideableLayer(node);++/** Bulk display-visibility update; raster-stack nodes have no display axis and are skipped. */const setCanvasLayersHidden = (- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,updates: readonly { id: string; isHidden: boolean }[]-): CanvasDocumentContractV2 => {- const targets = new Map(updates.map((update) => [update.id, update.isHidden]));- let changed = false;- const layers = document.layers.map((layer) => {- const isHidden = targets.get(layer.id);- if (isHidden === undefined || !isHideableLayer(layer) || isHidden === (layer.isHidden === true)) {- return layer;- }- changed = true;- return { ...layer, isHidden };- });- return changed ? { ...document, layers } : document;+): CanvasDocumentContractV3 => {+ const index = getDocumentIndex(document);+ return mapNodes(+ document,+ updates.map(({ id, isHidden }) => [+ id,+ (node) => (!isHideableNode(index, node) || isHidden === isNodeHidden(node) ? node : { ...node, isHidden }),+ ])+ );};const setCanvasLayerPositions = (- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,updates: readonly { id: string; x: number; y: number }[]-): CanvasDocumentContractV2 => {+): CanvasDocumentContractV3 => {const positions = new Map(updates.map((update) => [update.id, update]));if (positions.size !== updates.length ||updates.some(- (update) => !layerExists(document.layers, update.id) || !Number.isFinite(update.x) || !Number.isFinite(update.y)+ (update) => !getDocumentLayer(document, update.id) || !Number.isFinite(update.x) || !Number.isFinite(update.y))) {return document;}- let changed = false;- const layers = document.layers.map((layer) => {- const position = positions.get(layer.id);- if (!position || (layer.transform.x === position.x && layer.transform.y === position.y)) {- return layer;+ return mapNodes(+ document,+ updates.map(({ id, x, y }) => [+ id,+ (node) =>+ isGroupNode(node) || (node.transform.x === x && node.transform.y === y)+ ? node+ : { ...node, transform: { ...node.transform, x, y } },+ ])+ );+};++/**+ * Swaps the leaf `layer.id` names for `layer`. A leaf of another type cannot stay in its forest, so+ * it leaves its group and lands in its new stack at `anchor`, or at the top like a fresh layer.+ */+const replaceLeaf = (+ projectId: string,+ document: CanvasDocumentContractV3,+ layer: CanvasLayerContract,+ anchor?: CanvasNodeInsertionAnchor+): CanvasDocumentContractV3 => {+ const existing = getDocumentLayer(document, layer.id);+ if (!existing) {+ return document;+ }+ if (existing.type === layer.type) {+ return mapLayer(document, layer.id, () => layer);+ }+ const target = layerStackOf(layer);+ if (anchor && (anchor.projectId !== projectId || anchor.stack !== target)) {+ return document;+ }+ const stacks = removeNodes(document.stacks, new Set([layer.id]));+ return withStacks(+ document,+ anchor ? insertNodesAtAnchor(stacks, anchor, [layer]) : { ...stacks, [target]: [layer, ...stacks[target]] }+ );+};++/** The stack every leaf of `nodes` belongs to, or `null` when they disagree; an empty group fits any stack. */+const nodesStack = (nodes: readonly CanvasNodeContract[], fallback: CanvasNodeInsertionAnchor['stack']) => {+ const stacks = new Set(nodes.flatMap((node) => collectSubtreeLeaves(node).map(layerStackOf)));+ return stacks.size === 0 ? fallback : stacks.size === 1 ? [...stacks][0]! : null;+};++const isInsertionValid = (projectId: string, insertion: CanvasNodeInsertion): boolean =>+ insertion.anchor.projectId === projectId &&+ nodesStack(insertion.nodes, insertion.anchor.stack) === insertion.anchor.stack &&+ (insertion.anchor.stack !== 'raster' ||+ insertion.nodes+ .flatMap((root) => collectSubtree(root))+ .every((node) => !isGroupNode(node) || node.isHidden === undefined));++/** The subtrees a move detaches, or `null` when its ids are not distinct, present nodes of the anchor's stack. */+const movedBlock = (index: CanvasDocumentIndex, move: CanvasNodeMove): CanvasNodeEntry[] | null => {+ const outer = outermostNodes(index, move.ids);+ return outer.length === new Set(move.ids).size && outer.every((entry) => entry.stack === move.anchor.stack)+ ? outer+ : null;+};++/** One move at a time; each anchor resolves against the forest the previous move produced. */+const applyMovesInSequence = (stacks: CanvasStackForests, moves: readonly CanvasNodeMove[]) => {+ let next = stacks;+ for (const move of moves) {+ const block = movedBlock(indexStacks(next), move);+ if (!block) {+ return null;}- changed = true;- return { ...layer, transform: { ...layer.transform, x: position.x, y: position.y } };- });- return changed ? { ...document, layers } : document;+ next = insertNodesAtAnchor(+ removeNodes(next, new Set(move.ids)),+ move.anchor,+ block.map((entry) => entry.node)+ );+ }+ return next;};-const isInsertionValid = (projectId: string, insertion: FlatLayerInsertion): boolean =>- insertion.anchor.projectId === projectId && insertion.layers.every((layer) => layer.type === insertion.anchor.stack);+const siblingKey = (stack: CanvasNodeInsertionAnchor['stack'], parentId: string | null): string =>+ `${stack}\0${parentId ?? ''}`;++/**+ * Applies every move with one removal pass, one index, and one rebuild. Anchors resolve on the+ * same ladder as {@link insertNodesAtAnchor}, against sibling lists that already hold the earlier+ * moves, so the result matches applying the moves one after another. Moves whose anchors name a+ * moving node, or whose blocks nest, take the sequential path, since only it can see the forest+ * between moves.+ */+const applyMoves = (stacks: CanvasStackForests, moves: readonly CanvasNodeMove[], projectId: string) => {+ if (moves.length === 0) {+ return stacks;+ }+ if (moves.some((move) => move.anchor.projectId !== projectId)) {+ return null;+ }+ const index = indexStacks(stacks);+ const movingIds = new Set(moves.flatMap((move) => move.ids));+ if (movingIds.size !== moves.reduce((count, move) => count + new Set(move.ids).size, 0)) {+ return null;+ }+ const namesMoving = (id: string | null) => id !== null && movingIds.has(id);+ if (+ outermostNodes(index, movingIds).length !== movingIds.size ||+ moves.some(+ ({ anchor }) => namesMoving(anchor.beforeId) || namesMoving(anchor.afterId) || anchor.parentPath.some(namesMoving)+ )+ ) {+ return applyMovesInSequence(stacks, moves);+ }+ const blocks = moves.map((move) => movedBlock(index, move));+ if (blocks.some((block) => block === null)) {+ return null;+ }+ const removed = removeNodes(stacks, movingIds);+ const removedIndex = indexStacks(removed);+ const lists = new Map<string, CanvasNodeContract[]>();+ const listFor = (stack: CanvasNodeInsertionAnchor['stack'], parentId: string | null): CanvasNodeContract[] => {+ const key = siblingKey(stack, parentId);+ let list = lists.get(key);+ if (!list) {+ list = [...(childrenAt(removedIndex, stack, parentId) ?? [])];+ lists.set(key, list);+ }+ return list;+ };+ const survivingGroup = (stack: CanvasNodeInsertionAnchor['stack'], id: string): boolean => {+ const entry = removedIndex.byId.get(id);+ return !!entry && entry.stack === stack && isGroupNode(entry.node);+ };+ moves.forEach((move, position) => {+ const { anchor } = move;+ const nodes = blocks[position]!.map((entry) => entry.node);+ const before = anchor.beforeId ? removedIndex.byId.get(anchor.beforeId) : undefined;+ const after = anchor.afterId ? removedIndex.byId.get(anchor.afterId) : undefined;+ let list: CanvasNodeContract[];+ let at: number;+ if (before && before.stack === anchor.stack) {+ list = listFor(anchor.stack, before.parentId);+ at = list.findIndex((node) => node.id === anchor.beforeId);+ } else if (after && after.stack === anchor.stack) {+ list = listFor(anchor.stack, after.parentId);+ at = list.findIndex((node) => node.id === anchor.afterId) + 1;+ } else {+ const parentId = [...anchor.parentPath].reverse().find((id) => survivingGroup(anchor.stack, id)) ?? null;+ list = listFor(anchor.stack, parentId);+ at = 0;+ }+ list.splice(at, 0, ...nodes);+ });+ const materialize = (+ nodes: readonly CanvasNodeContract[],+ stack: CanvasNodeInsertionAnchor['stack']+ ): readonly CanvasNodeContract[] => {+ let changed = false;+ const next = nodes.map((node) => {+ if (!isGroupNode(node)) {+ return node;+ }+ const children = materialize(lists.get(siblingKey(stack, node.id)) ?? node.children, stack);+ if (children === node.children) {+ return node;+ }+ changed = true;+ return { ...node, children: [...children] };+ });+ return changed ? next : nodes;+ };+ const next = { ...removed };+ for (const stack of Object.keys(next) as CanvasNodeInsertionAnchor['stack'][]) {+ const roots = materialize(lists.get(siblingKey(stack, null)) ?? removed[stack], stack);+ if (roots !== removed[stack]) {+ next[stack] = [...roots];+ }+ }+ return next;+};const applyLayerStackMutation = (projectId: string,- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,mutation: Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }>-): CanvasDocumentContractV2 => {- const currentIds = new Set(document.layers.map((layer) => layer.id));- const removeIds = new Set(mutation.removeIds ?? []);- if ([...removeIds].some((id) => !currentIds.has(id))) {- return document;- }- const projectedIds = new Set(currentIds);- for (const id of removeIds) {- projectedIds.delete(id);- }+): CanvasDocumentContractV3 => {+ let stacks = document.stacks;+ const knownIds = new Set(getDocumentIndex(document).byId.keys());for (const insertion of mutation.add ?? []) {if (!isInsertionValid(projectId, insertion)) {return document;}- for (const layer of insertion.layers) {- if (currentIds.has(layer.id) || projectedIds.has(layer.id)) {+ for (const node of insertion.nodes.flatMap((root) => collectSubtree(root))) {+ if (knownIds.has(node.id)) {return document;}- projectedIds.add(layer.id);+ knownIds.add(node.id);}+ if (insertion.nodes.length > 0) {+ stacks = insertNodesAtAnchor(stacks, insertion.anchor, insertion.nodes);+ }+ }+ const moved = applyMoves(stacks, mutation.move ?? [], projectId);+ if (!moved) {+ return document;+ }+ const removeIds = new Set(mutation.removeIds ?? []);+ const beforeRemoval = indexStacks(moved);+ if ([...removeIds].some((id) => !beforeRemoval.byId.has(id))) {+ return document;}+ stacks = removeNodes(moved, removeIds);+ const index = indexStacks(stacks);if (- mutation.enabledUpdates.some((update) => !projectedIds.has(update.id)) ||- (mutation.lockedUpdates?.some((update) => !projectedIds.has(update.id)) ?? false) ||+ mutation.enabledUpdates.some((update) => !index.byId.has(update.id)) ||+ (mutation.lockedUpdates?.some((update) => !index.byId.has(update.id)) ?? false) ||(mutation.selectedLayerId !== undefined &&mutation.selectedLayerId !== null &&- !projectedIds.has(mutation.selectedLayerId))+ !index.byId.has(mutation.selectedLayerId))) {return document;}- let layers: CanvasLayers = document.layers;- let changed = false;- for (const insertion of mutation.add ?? []) {- if (insertion.layers.length > 0) {- layers = insertLayersAtAnchor(layers, insertion.anchor, insertion.layers);- changed = true;- }- }- if (removeIds.size > 0) {- layers = layers.filter((layer) => !removeIds.has(layer.id));- changed = true;- }const enabledById = new Map(mutation.enabledUpdates.map((update) => [update.id, update.isEnabled]));const lockedById = new Map(mutation.lockedUpdates?.map((update) => [update.id, update.isLocked]) ?? []);- let baseChanged = false;- const nextLayers = layers.map((layer) => {- const isEnabled = enabledById.get(layer.id);- const isLocked = lockedById.get(layer.id);- const enabledChanged = isEnabled !== undefined && isEnabled !== layer.isEnabled;- const lockedChanged = isLocked !== undefined && isLocked !== layer.isLocked;- if (!enabledChanged && !lockedChanged) {- return layer;- }- baseChanged = true;- changed = true;- return {- ...layer,- ...(enabledChanged ? { isEnabled: isEnabled as boolean } : {}),- ...(lockedChanged ? { isLocked: isLocked as boolean } : {}),- };- });- if (baseChanged) {- layers = nextLayers;+ stacks = updateNodes(+ stacks,+ new Map(+ [...new Set([...enabledById.keys(), ...lockedById.keys()])].map((id) => [+ id,+ (node) => {+ const isEnabled = enabledById.get(id) ?? node.isEnabled;+ const isLocked = lockedById.get(id) ?? node.isLocked;+ return isEnabled === node.isEnabled && isLocked === node.isLocked ? node : { ...node, isEnabled, isLocked };+ },+ ])+ )+ );+ if (stacks !== document.stacks && !withinLimits(stacks)) {+ return document;}const selectedLayerId =mutation.selectedLayerId === undefined- ? repairSelectedLayerId(layers, document.selectedLayerId, document.layers)+ ? repairSelectedLayerId(stacks, document.selectedLayerId, document.stacks): mutation.selectedLayerId;- changed ||= document.selectedLayerId !== selectedLayerId;- return changed- ? {- ...document,- layers,- selectedLayerId,- }- : document;+ return stacks === document.stacks && selectedLayerId === document.selectedLayerId+ ? document+ : { ...document, selectedLayerId, stacks };};const addLayer = (projectId: string,- document: CanvasDocumentContractV2,+ document: CanvasDocumentContractV3,layer: CanvasLayerContract,- anchor: FlatLayerInsertionAnchor-): CanvasDocumentContractV2 => {- if (- !isInsertionValid(projectId, { anchor, layers: [layer] }) ||- document.layers.some((candidate) => candidate.id === layer.id)- ) {+ anchor: CanvasNodeInsertionAnchor+): CanvasDocumentContractV3 => {+ if (!isInsertionValid(projectId, { anchor, nodes: [layer] }) || hasDocumentNode(document, layer.id)) {return document;}- return {- ...document,- layers: insertLayersAtAnchor(document.layers, anchor, [layer]),- selectedLayerId: layer.id,- };-};--const removeLayers = (document: CanvasDocumentContractV2, ids: readonly string[]): CanvasDocumentContractV2 => {- const removed = new Set(ids);- const layers = document.layers.filter((layer) => !removed.has(layer.id));- if (layers.length === document.layers.length) {- return document;- }- const selectedLayerId = repairSelectedLayerId(layers, document.selectedLayerId, document.layers);- return { ...document, layers, selectedLayerId };+ const stacks = insertNodesAtAnchor(document.stacks, anchor, [layer]);+ return withinLimits(stacks) ? { ...document, selectedLayerId: layer.id, stacks } : document;};-const duplicateLayer = (document: CanvasDocumentContractV2, sourceId: string, newId: string) => {- const index = document.layers.findIndex((layer) => layer.id === sourceId);- if (index === -1) {+const removeLayers = (document: CanvasDocumentContractV3, ids: readonly string[]): CanvasDocumentContractV3 => {+ const stacks = removeNodes(document.stacks, new Set(ids));+ if (stacks === document.stacks) {return document;}- const source = document.layers[index] as CanvasLayerContract;- const duplicate = structuredClone(source);- duplicate.id = newId;- duplicate.name = `${source.name} copy`;return {...document,- layers: [...document.layers.slice(0, index), duplicate, ...document.layers.slice(index)],- selectedLayerId: newId,+ selectedLayerId: repairSelectedLayerId(stacks, document.selectedLayerId, document.stacks),+ stacks,};};-const reorderLayerStacks = (- document: CanvasDocumentContractV2,- stacks: readonly ReorderFlatStackCommand[]-): CanvasDocumentContractV2 => {- if (new Set(stacks.map((command) => command.stack)).size !== stacks.length) {+const reorderCanvasSiblings = (+ document: CanvasDocumentContractV3,+ orders: readonly ReorderSiblingsCommand[]+): CanvasDocumentContractV3 => {+ if (new Set(orders.map((order) => `${order.stack}\0${order.parentId ?? ''}`)).size !== orders.length) {return document;}- let layers: CanvasLayers = document.layers;- for (const command of stacks) {- const next = reorderLayerStack(layers, command);+ let stacks = document.stacks;+ for (const order of orders) {+ const next = reorderSiblings(stacks, order);if (!next) {return document;}- layers = next;+ stacks = next;}- return layers.every((layer, index) => layer === document.layers[index]) ? document : { ...document, layers };+ return withStacks(document, stacks);};-const patchLayer = (layer: CanvasLayerContract, patch: CanvasLayerBasePatch): CanvasLayerContract => {+const patchNode = (node: CanvasNodeContract, patch: CanvasLayerBasePatch): CanvasNodeContract => {+ if (isGroupNode(node)) {+ const allowed = Object.fromEntries(+ Object.entries(patch).filter(([key]) => GROUP_PATCH_KEYS.includes(key as keyof CanvasLayerBasePatch))+ );+ return Object.keys(allowed).length === 0 ? node : { ...node, ...allowed };+ }const { transform, ...rest } = patch;- return { ...layer, ...rest, transform: transform ? { ...layer.transform, ...transform } : layer.transform };+ return { ...node, ...rest, transform: transform ? { ...node.transform, ...transform } : node.transform };};const patchLayerConfig = (layer: CanvasLayerContract, config: CanvasLayerConfigPatch): CanvasLayerContract => {@@ -380,7 +530,42 @@ const patchLayerConfig = (layer: CanvasLayerContract, config: CanvasLayerConfigPreturn layer;};-const clampBbox = (bbox: CanvasDocumentContractV2['bbox'], width: number, height: number) => {+const mergeLayersDown = (+ document: CanvasDocumentContractV3,+ mutation: Extract<CanvasProjectMutation, { type: 'mergeCanvasLayersDown' }>+): CanvasDocumentContractV3 => {+ const index = getDocumentIndex(document);+ const upper = index.byId.get(mutation.upperLayerId);+ if (!upper || upper.stack !== 'raster' || isGroupNode(upper.node)) {+ return document;+ }+ const below = childrenAt(index, upper.stack, upper.parentId)?.[upper.siblingIndex + 1];+ if (!below || below.type !== 'raster') {+ return document;+ }+ const merged: CanvasRasterLayerContractV2 = {+ blendMode: below.blendMode,+ id: below.id,+ isEnabled: below.isEnabled,+ isLocked: below.isLocked,+ name: below.name,+ opacity: below.opacity,+ source: mutation.source,+ transform: below.transform,+ type: 'raster',+ };+ const stacks = removeNodes(+ updateNodes(document.stacks, new Map([[below.id, () => merged]])),+ new Set([upper.node.id])+ );+ return {+ ...document,+ selectedLayerId: repairSelectedLayerId(stacks, document.selectedLayerId, document.stacks),+ stacks,+ };+};++const clampBbox = (bbox: CanvasDocumentContractV3['bbox'], width: number, height: number) => {const clampedWidth = Math.min(Math.max(1, Math.round(bbox.width)), width);const clampedHeight = Math.min(Math.max(1, Math.round(bbox.height)), height);return {@@ -391,7 +576,7 @@ const clampBbox = (bbox: CanvasDocumentContractV2['bbox'], width: number, height};};-const clearStagingArea = (stagingArea: CanvasStateContractV2['stagingArea']) => ({+const clearStagingArea = (stagingArea: CanvasStateContractV3['stagingArea']) => ({...stagingArea,isVisible: false,pendingImageIds: [],@@ -422,22 +607,20 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProreturn project;}const { anchor, layer } = mutation;- if (- !isInsertionValid(project.id, { anchor, layers: [layer] }) ||- project.canvas.document.layers.some((candidate) => candidate.id === layer.id)- ) {+ const { document } = project.canvas;+ if (!isInsertionValid(project.id, { anchor, nodes: [layer] }) || hasDocumentNode(document, layer.id)) {+ return project;+ }+ const stacks = insertNodesAtAnchor(document.stacks, anchor, [layer]);+ if (!withinLimits(stacks)) {return project;}- const selectedLayerId = mutation.continueStaging ? project.canvas.document.selectedLayerId : layer.id;+ const selectedLayerId = mutation.continueStaging ? document.selectedLayerId : layer.id;return {...project,canvas: {...project.canvas,- document: {- ...project.canvas.document,- layers: insertLayersAtAnchor(project.canvas.document.layers, anchor, [layer]),- selectedLayerId,- },+ document: { ...document, selectedLayerId, stacks },stagingArea: mutation.continueStaging? project.canvas.stagingArea: clearStagingArea(project.canvas.stagingArea),@@ -450,9 +633,10 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProconst stagingMatchesCommit = mutation.continueStaging? project.canvas.stagingArea === mutation.stagingArea: project.canvas.stagingArea.pendingImages.length === 0;+ const { document } = project.canvas;if (- project.canvas.document.selectedLayerId !== expectedSelectedLayerId ||- !project.canvas.document.layers.includes(mutation.layer) ||+ document.selectedLayerId !== expectedSelectedLayerId ||+ getDocumentLayer(document, mutation.layer.id) !== mutation.layer ||project.events[0] !== mutation.event ||!stagingMatchesCommit) {@@ -463,9 +647,9 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProcanvas: {...project.canvas,document: {- ...project.canvas.document,- layers: project.canvas.document.layers.filter((layer) => layer !== mutation.layer),+ ...document,selectedLayerId: mutation.selectedLayerId,+ stacks: removeNodes(document.stacks, new Set([mutation.layer.id])),},stagingArea: mutation.stagingArea,},@@ -580,18 +764,16 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProreturn updateCanvasDocument(project, (document) => applyLayerStackMutation(project.id, document, mutation));case 'removeCanvasLayers':return updateCanvasDocument(project, (document) => removeLayers(document, mutation.ids));- case 'duplicateCanvasLayer':- return updateCanvasDocument(project, (document) => duplicateLayer(document, mutation.sourceId, mutation.newId));- case 'reorderCanvasLayerStacks':- return updateCanvasDocument(project, (document) => reorderLayerStacks(document, mutation.stacks));+ case 'reorderCanvasSiblings':+ return updateCanvasDocument(project, (document) => reorderCanvasSiblings(document, mutation.orders));case 'updateCanvasLayer':return updateCanvasDocument(project, (document) =>- mapCanvasLayer(document, mutation.id, (layer) => patchLayer(layer, mutation.patch))+ mapNode(document, mutation.id, (node) => patchNode(node, mutation.patch)));case 'replaceCanvasLayer':- return updateCanvasDocument(project, (document) =>- mapCanvasLayer(document, mutation.layerId, () => mutation.layer)- );+ return mutation.layer.id === mutation.layerId+ ? updateCanvasDocument(project, (document) => replaceLeaf(project.id, document, mutation.layer))+ : project;case 'setCanvasLayersEnabled':return updateCanvasDocument(project, (document) => setCanvasLayersEnabled(document, mutation.updates));case 'setCanvasLayerPositions':@@ -600,49 +782,24 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProreturn updateCanvasDocument(project, (document) => setCanvasLayersHidden(document, mutation.updates));case 'updateCanvasLayerSource':return updateCanvasDocument(project, (document) =>- mapCanvasLayer(document, mutation.id, (layer) =>+ mapLayer(document, mutation.id, (layer) =>layer.type === 'raster' || layer.type === 'control' ? { ...layer, source: mutation.source } : layer));case 'updateCanvasLayerConfig':return updateCanvasDocument(project, (document) =>- mapCanvasLayer(document, mutation.id, (layer) => patchLayerConfig(layer, mutation.config))+ mapLayer(document, mutation.id, (layer) => patchLayerConfig(layer, mutation.config)));case 'convertCanvasLayer': {- if (mutation.layer.type !== mutation.targetType || !layerExists(project.canvas.document.layers, mutation.id)) {+ if (mutation.layer.type !== mutation.targetType) {return project;}const converted = structuredClone(mutation.layer);converted.id = mutation.id;- return updateCanvasDocument(project, (document) => mapCanvasLayer(document, mutation.id, () => converted));- }- case 'mergeCanvasLayersDown': {- const document = project.canvas.document;- const upperIndex = document.layers.findIndex((layer) => layer.id === mutation.upperLayerId);- const below = upperIndex === -1 ? undefined : document.layers[upperIndex + 1];- if (!below) {- return project;- }- const merged: CanvasRasterLayerContractV2 = {- blendMode: below.blendMode,- id: below.id,- isEnabled: below.isEnabled,- isLocked: below.isLocked,- name: below.name,- opacity: below.opacity,- source: mutation.source,- transform: below.transform,- type: 'raster',- };- const layers = document.layers- .filter((_, index) => index !== upperIndex)- .map((layer) => (layer.id === below.id ? merged : layer));- return setCanvasDocument(project, {- ...document,- layers,- selectedLayerId: repairSelectedLayerId(layers, document.selectedLayerId, document.layers),- });+ return updateCanvasDocument(project, (document) => replaceLeaf(project.id, document, converted, mutation.anchor));}+ case 'mergeCanvasLayersDown':+ return updateCanvasDocument(project, (document) => mergeLayersDown(document, mutation));case 'setCanvasBbox':return updateCanvasDocument(project, (document) => ({...document,@@ -655,11 +812,9 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro}));case 'setCanvasSelectedLayer':return updateCanvasDocument(project, (document) =>- mutation.id !== null && !layerExists(document.layers, mutation.id)+ (mutation.id !== null && !hasDocumentNode(document, mutation.id)) || document.selectedLayerId === mutation.id? document- : document.selectedLayerId === mutation.id- ? document- : { ...document, selectedLayerId: mutation.id }+ : { ...document, selectedLayerId: mutation.id });case 'resizeCanvasDocument': {const width = Math.max(1, Math.round(mutation.width));@@ -674,13 +829,28 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProheight),height,- layers:+ stacks:offsetX === 0 && offsetY === 0- ? document.layers- : document.layers.map((layer) => ({- ...layer,- transform: { ...layer.transform, x: layer.transform.x + offsetX, y: layer.transform.y + offsetY },- })),+ ? document.stacks+ : updateNodes(+ document.stacks,+ new Map(+ getDocumentIndex(document).leaves.map((leaf) => [+ leaf.id,+ (node) =>+ isGroupNode(node)+ ? node+ : {+ ...node,+ transform: {+ ...node.transform,+ x: node.transform.x + offsetX,+ y: node.transform.y + offsetY,+ },+ },+ ])+ )+ ),width,}));}diff --git a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.tsindex bb0b18a8bc..2db23152a8 100644--- a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts@@ -1,8 +1,16 @@+/** Oldest canvas document schema this build reads; earlier documents are refused, not migrated. */+export const MIN_SUPPORTED_CANVAS_SCHEMA_VERSION = 3;+/** Newest canvas document schema this build can safely read, edit, and write. */-export const MAX_SUPPORTED_CANVAS_SCHEMA_VERSION = 2;+export const MAX_SUPPORTED_CANVAS_SCHEMA_VERSION = 3;++/** Whether a project whose documents need at least `minimumCanvasSchemaVersion` can be opened here. */+export const isCanvasSchemaVersionSupported = (minimumCanvasSchemaVersion: number): boolean =>+ minimumCanvasSchemaVersion >= MIN_SUPPORTED_CANVAS_SCHEMA_VERSION &&+ minimumCanvasSchemaVersion <= MAX_SUPPORTED_CANVAS_SCHEMA_VERSION;/** Compatibility floor for a new synced project until its document actually adopts a newer schema. */-export const DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION = 2;+export const DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION = 3;const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === 'object' && value !== null && !Array.isArray(value);diff --git a/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts b/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.tsindex 2772764c5f..727f38b181 100644--- a/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts@@ -5,7 +5,7 @@ import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryConimport { describe, expect, it } from 'vitest';-import { createEmptyCanvasStateV2 } from './canvasMigration';+import { createEmptyCanvasState } from './canvasMigration';import {getCancelableCanvasStagingQueueItemId,getCanvasQueuePlaceholderSlots,@@ -46,7 +46,7 @@ const createCanvas = ({revision?: number;stagedImages?: CanvasStagingCandidateContract[];} = {}) => {- const canvas = createEmptyCanvasStateV2(1024, 1024);+ const canvas = createEmptyCanvasState(1024, 1024);return {...canvas,diff --git a/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts b/invokeai/frontend/webv2/src/workbench/canvasStagingView.tsindex 493ca70334..de4fd8ae11 100644--- a/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts@@ -1,4 +1,4 @@-import type { CanvasStagingCandidateContract, CanvasStateContractV2 } from '@workbench/canvas-engine/api';+import type { CanvasStagingCandidateContract, CanvasStateContractV3 } from '@workbench/canvas-engine/api';import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';@@ -25,7 +25,7 @@ export interface CanvasCandidateSlot {export type CanvasStagingSlot = CanvasCandidateSlot | CanvasQueuePlaceholderSlot;-const isActiveCanvasQueueItemForDocument = (canvas: CanvasStateContractV2, item: QueueItem): boolean =>+const isActiveCanvasQueueItemForDocument = (canvas: CanvasStateContractV3, item: QueueItem): boolean =>item.snapshot.destination === 'canvas' &&(item.status === 'pending' || item.status === 'running') &&item.snapshot.canvas.documentRevision === canvas.documentRevision;@@ -115,7 +115,7 @@ const createPlaceholderSlot = (item: QueueItem, itemIndex: number): CanvasQueueP};export const getCanvasQueuePlaceholderSlots = (- canvas: CanvasStateContractV2,+ canvas: CanvasStateContractV3,queueItems: readonly QueueItem[]): CanvasQueuePlaceholderSlot[] => {const placeholders: CanvasQueuePlaceholderSlot[] = [];@@ -170,7 +170,7 @@ const getCandidatesByQueueItemId = (};const getCanvasStagingSlotsForQueueItem = (- canvas: CanvasStateContractV2,+ canvas: CanvasStateContractV3,item: QueueItem,candidates: readonly CanvasStagingCandidateContract[]): CanvasStagingSlot[] => {@@ -225,7 +225,7 @@ const getCanvasStagingSlotsForQueueItem = (};export const getCanvasStagingSlots = (- canvas: CanvasStateContractV2,+ canvas: CanvasStateContractV3,queueItems: readonly QueueItem[]): CanvasStagingSlot[] => {const candidatesByQueueItemId = getCandidatesByQueueItemId(canvas.stagingArea.pendingImages);@@ -249,11 +249,11 @@ export const getCanvasStagingSlots = (return [...orphanCandidateSlots, ...slots];};-export const getCanvasStagingSlotCount = (canvas: CanvasStateContractV2, queueItems: readonly QueueItem[]): number =>+export const getCanvasStagingSlotCount = (canvas: CanvasStateContractV3, queueItems: readonly QueueItem[]): number =>getCanvasStagingSlots(canvas, queueItems).length;export const getFirstCanvasPlaceholderSlotIndex = (- canvas: CanvasStateContractV2,+ canvas: CanvasStateContractV3,queueItems: readonly QueueItem[]): number => getCanvasStagingSlots(canvas, queueItems).findIndex((slot) => slot.kind === 'placeholder');diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex 868c9b1927..7b22fddf8e 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -22,6 +22,7 @@ import { getVideoWidgetValidationReasons, normalizeVideoWidgetValues } from '@feimport { getProjectGraphReadiness } from '@features/workflow/graph';import { getInvocationTemplatesSnapshot } from '@features/workflow/react';import { areArraysEqual, createStableSelector } from '@platform/state/selectors';+import { compileContributingLayers } from '@workbench/canvas-engine/api';import { getBlockingControlLayerIssues } from './controlLayerChecks';import { getProjectWidgetValues } from './widgetState';@@ -133,7 +134,7 @@ export const getInvocationRouteInput = (project: Project): InvocationRouteInputheight: project.canvas.document.bbox.height,width: project.canvas.document.bbox.width,},- canvasLayers: project.canvas.document.layers,+ canvasLayers: compileContributingLayers(project.canvas.document),generateValues: getProjectWidgetValues(project, 'generate'),upscaleValues: getProjectWidgetValues(project, 'upscale'),videoValues: getProjectWidgetValues(project, 'video'),diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCompatibilityBadge.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCompatibilityBadge.tsxindex 0f6c76096a..d89a966ea1 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCompatibilityBadge.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCompatibilityBadge.tsx@@ -1,6 +1,7 @@import type { ProjectSummary } from '@workbench/projects/library';import { Badge } from '@chakra-ui/react';+import { MIN_SUPPORTED_CANVAS_SCHEMA_VERSION } from '@workbench/canvasSchemaVersion';import { isProjectSummaryCompatible } from '@workbench/projects/library';import { useTranslation } from 'react-i18next';@@ -14,7 +15,11 @@ export const ProjectCompatibilityBadge = ({ summary }: { summary: ProjectSummaryreturn (<Badge alignSelf="flex-start" colorPalette="orange" size="xs" variant="surface">- {t('projects.requiresNewerInvoke')}+ {t(+ summary.minimumCanvasSchemaVersion < MIN_SUPPORTED_CANVAS_SCHEMA_VERSION+ ? 'projects.legacyFormat'+ : 'projects.requiresNewerInvoke'+ )}</Badge>);};diff --git a/invokeai/frontend/webv2/src/workbench/persistence.test.ts b/invokeai/frontend/webv2/src/workbench/persistence.test.tsindex 17e047524e..d28f543975 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.test.ts@@ -93,7 +93,7 @@ describe('workbench persistence migration', () => {it('gates every cached project before stripping transient state', () => {const state = createInitialWorkbenchState();const supported = state.projects[0]!;- const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 3 } };+ const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 4 } };const hydrated = hydratePersistedWorkbenchSnapshot({savedAt: '2026-06-09T00:00:00.000Z',state: { ...state, projects: [supported, future] },@@ -102,7 +102,7 @@ describe('workbench persistence migration', () => {expect(hydrated?.state.projects.map((project) => project.id)).toEqual([supported.id]);expect(hydrated?.refusedProjects).toMatchObject([- { projectId: 'future', raw: future, refusal: { status: 'unsupported-version', version: 3 }, source: 'canvas' },+ { projectId: 'future', raw: future, refusal: { status: 'unsupported-version', version: 4 }, source: 'canvas' },]);});@@ -118,7 +118,7 @@ describe('workbench persistence migration', () => {snapshot: {canvas: {...project.canvas,- document: { ...project.canvas.document, layers: [{ id: 'unknown', type: 'future-layer' }] },+ document: { ...project.canvas.document, stacks: { raster: [{ id: 'unknown', type: 'future-layer' }] } },},},},@@ -149,7 +149,7 @@ describe('workbench persistence migration', () => {it('repoints a refused active project at the first loadable one', () => {const state = createInitialWorkbenchState();const supported = state.projects[0]!;- const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 3 } };+ const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 4 } };const hydrated = hydratePersistedWorkbenchSnapshot({savedAt: '2026-06-09T00:00:00.000Z',state: { ...state, activeProjectId: 'future', projects: [supported, future] },@@ -162,7 +162,7 @@ describe('workbench persistence migration', () => {it('moves refused projects into a sibling bucket verbatim and forgets them on request', async () => {const state = createInitialWorkbenchState();const supported = state.projects[0]!;- const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 3 } };+ const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 4 } };storage.set('invokeai:v7:webv2:workbench',@@ -191,7 +191,7 @@ describe('workbench persistence migration', () => {it('does not remove an unsupported project from the primary cache if recovery retention fails', async () => {const state = createInitialWorkbenchState();const supported = state.projects[0]!;- const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 3 } };+ const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 4 } };const storageKey = 'invokeai:v7:webv2:workbench';storage.set(@@ -224,7 +224,7 @@ describe('workbench persistence migration', () => {it('does not classify a failed primary-cache compaction as corrupt input', async () => {const state = createInitialWorkbenchState();const supported = state.projects[0]!;- const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 3 } };+ const future = { ...supported, id: 'future', name: 'Future', canvas: { ...supported.canvas, version: 4 } };const storageKey = 'invokeai:v7:webv2:workbench';storage.set(@@ -265,7 +265,7 @@ describe('workbench persistence migration', () => {projectId: 'future',projectName: 'Future',raw: null,- refusal: { raw: null, scope: 'document', status: 'unsupported-version', version: 3 },+ refusal: { raw: null, scope: 'document', status: 'unsupported-version', version: 4 },source: 'canvas',},]);diff --git a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.tsindex 44de26e81a..572ee5f5f3 100644--- a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts@@ -1,9 +1,9 @@import { describe, expect, it } from 'vitest';-import { createEmptyCanvasStateV2 } from './canvasMigration';+import { createEmptyCanvasState } from './canvasMigration';import { gateProjectCanvases } from './projectCanvasGate';-const canvas = createEmptyCanvasStateV2();+const canvas = createEmptyCanvasState();const queueItem = (id: string, itemCanvas: unknown) => ({ id, snapshot: { canvas: itemCanvas } });describe('gateProjectCanvases', () => {@@ -14,14 +14,14 @@ describe('gateProjectCanvases', () => {});it('refuses a project whose live canvas is unsupported or invalid, keeping the raw document', () => {- const future = { canvas: { ...canvas, version: 3 }, id: 'p', name: 'P' };+ const future = { canvas: { ...canvas, version: 4 }, id: 'p', name: 'P' };const broken = { canvas: { ...canvas, version: '2' }, id: 'p', name: 'P' };expect(gateProjectCanvases(future)).toMatchObject({projectId: 'p',projectName: 'P',raw: future,- refusal: { scope: 'state', status: 'unsupported-version', version: 3 },+ refusal: { scope: 'state', status: 'unsupported-version', version: 4 },source: 'canvas',});expect(gateProjectCanvases(broken)).toMatchObject({@@ -33,7 +33,7 @@ describe('gateProjectCanvases', () => {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 futureItem = queueItem('future', { ...canvas, version: 4 });const invalidProject = { canvas, id: 'p', name: 'P', queue: { items: [invalidItem] } };expect(gateProjectCanvases(invalidProject)).toMatchObject({@@ -44,7 +44,7 @@ describe('gateProjectCanvases', () => {});expect(gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [futureItem] } })).toMatchObject({queueItem: { index: 0, itemId: 'future' },- refusal: { status: 'unsupported-version', version: 3 },+ refusal: { status: 'unsupported-version', version: 4 },source: 'queue-item',});diff --git a/invokeai/frontend/webv2/src/workbench/projectContracts.ts b/invokeai/frontend/webv2/src/workbench/projectContracts.tsindex a3bcea732e..44f9dc12f5 100644--- a/invokeai/frontend/webv2/src/workbench/projectContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/projectContracts.ts@@ -1,7 +1,7 @@import type { ProjectGraphState } from '@features/workflow/contracts';import type { BackendConnectionStatus } from '@platform/transport/types';-import type { CanvasStateContractV2 } from './canvas-engine/api';+import type { CanvasStateContractV3 } from './canvas-engine/api';import type { CanvasLoadRefusal } from './canvasLoadContracts';import type { GraphContract } from './graphContracts';import type { InvocationControllerState } from './invocationContracts';@@ -48,7 +48,7 @@ export interface Project {*/floatingWidgets?: Record<WidgetInstanceId, FloatingWidgetState>;widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;- canvas: CanvasStateContractV2;+ canvas: CanvasStateContractV3;graphHistory: GraphHistorySnapshot[];promptHistory: PromptHistoryItem[];undoRedo: UndoRedoHistory;diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.tsindex e9048a2f91..ccdd1b9cfb 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts@@ -39,7 +39,7 @@ beforeEach(() => {describe('createProjectSettled', () => {const request = { data: {}, name: 'Imported', project_id: 'project-1' };const post = () => ({- body: JSON.stringify({ ...request, max_canvas_schema_version: 2, minimum_canvas_schema_version: 2 }),+ body: JSON.stringify({ ...request, max_canvas_schema_version: 3, minimum_canvas_schema_version: 3 }),method: 'POST',signal: expect.anything(),});@@ -71,7 +71,7 @@ describe('createProjectSettled', () => {expect(transport.apiFetchJson).toHaveBeenNthCalledWith(2, '/api/v1/projects/', post());expect(transport.apiFetchJson).toHaveBeenNthCalledWith(3,- '/api/v1/projects/project-1?max_canvas_schema_version=2',+ '/api/v1/projects/project-1?max_canvas_schema_version=3',expect.anything());});@@ -142,7 +142,7 @@ describe('canvas schema compatibility declarations', () => {await getProject('project/one');- expect(transport.apiFetchJson).toHaveBeenCalledWith('/api/v1/projects/project%2Fone?max_canvas_schema_version=2', {+ expect(transport.apiFetchJson).toHaveBeenCalledWith('/api/v1/projects/project%2Fone?max_canvas_schema_version=3', {signal: undefined,});});@@ -156,8 +156,8 @@ describe('canvas schema compatibility declarations', () => {body: JSON.stringify({data: {},name: 'Project',- max_canvas_schema_version: 2,- minimum_canvas_schema_version: 2,+ max_canvas_schema_version: 3,+ minimum_canvas_schema_version: 3,}),method: 'POST',signal: undefined,@@ -168,19 +168,19 @@ describe('canvas schema compatibility declarations', () => {transport.apiFetchJson.mockResolvedValueOnce({ project_id: 'project-1' });await updateProject('project-1', {- data: { canvas: { version: 2 } },+ data: { canvas: { version: 3 } },expected_revision: 4,- minimum_canvas_schema_version: 2,+ minimum_canvas_schema_version: 3,name: 'Project',});expect(transport.apiFetchJson).toHaveBeenCalledWith('/api/v1/projects/project-1', {body: JSON.stringify({- data: { canvas: { version: 2 } },+ data: { canvas: { version: 3 } },expected_revision: 4,- minimum_canvas_schema_version: 2,+ minimum_canvas_schema_version: 3,name: 'Project',- max_canvas_schema_version: 2,+ max_canvas_schema_version: 3,}),method: 'PUT',signal: undefined,@@ -192,8 +192,8 @@ describe('canvas schema compatibility declarations', () => {JSON.stringify({detail: {code: 'canvas_schema_unsupported',- max_canvas_schema_version: 2,- minimum_canvas_schema_version: 3,+ max_canvas_schema_version: 3,+ minimum_canvas_schema_version: 4,},}),412@@ -205,7 +205,7 @@ describe('canvas schema compatibility declarations', () => {isProjectCanvasSchemaUnsupportedError(new ApiError(JSON.stringify({- detail: { code: 'different_precondition', max_canvas_schema_version: 2, minimum_canvas_schema_version: 3 },+ detail: { code: 'different_precondition', max_canvas_schema_version: 3, minimum_canvas_schema_version: 4 },}),412)@@ -217,7 +217,7 @@ describe('canvas schema compatibility declarations', () => {JSON.stringify({detail: {code: 'canvas_schema_unsupported',- max_canvas_schema_version: 2,+ max_canvas_schema_version: 3,minimum_canvas_schema_version: 3.5,},}),diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsxindex 8c6e688b29..304f5080fe 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx@@ -1,6 +1,6 @@import type { ProjectRecordDTO } from '@workbench/projects/api';-import { Badge, Dialog, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';+import { Dialog, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';import { flushGenerateDrafts } from '@features/generation/react';import { useMountEffect } from '@platform/react/useMountEffect';import {@@ -12,7 +12,9 @@ import { areArraysEqual } from '@platform/state/selectors';import { getApiErrorMessage } from '@platform/transport/http';import { Button, CloseButton, Row, Scrollable } from '@platform/ui';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { MIN_SUPPORTED_CANVAS_SCHEMA_VERSION } from '@workbench/canvasSchemaVersion';import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';+import { ProjectCompatibilityBadge } from '@workbench/launchpad/projects/ProjectCompatibilityBadge';import {isProjectSummaryCompatible,refreshProjectLibrary,@@ -66,7 +68,14 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClosconst owner = captureAccountScope();if (!isProjectSummaryCompatible(summary)) {- notify.error(t('projects.couldNotOpen'), t('projects.file.updateClient'));+ notify.error(+ t('projects.couldNotOpen'),+ t(+ summary.minimumCanvasSchemaVersion < MIN_SUPPORTED_CANVAS_SCHEMA_VERSION+ ? 'projects.file.legacyCanvasProject'+ : 'projects.file.updateClient'+ )+ );return;}@@ -203,7 +212,6 @@ const OpenProjectRow = ({}) => {const open = useCallback(() => void onOpen(summary), [onOpen, summary]);const { t } = useTranslation();- const isCompatible = isProjectSummaryCompatible(summary);return (<Row asChild gap="2.5" px="2.5" py="2" rounded="md" _disabled={disabledRowStyles}>@@ -213,11 +221,7 @@ const OpenProjectRow = ({<Text color="fg.muted" fontSize="2xs">{t('projects.editedRelative', { time: formatRelativeTime(summary.updatedAt) })}</Text>- {!isCompatible ? (- <Badge alignSelf="flex-start" colorPalette="orange" size="xs" variant="surface">- {t('projects.requiresNewerInvoke')}- </Badge>- ) : null}+ <ProjectCompatibilityBadge summary={summary} /></Stack>{isBusy ? <Spinner color="fg.muted" size="xs" /> : <Icon as={ArrowRightIcon} boxSize="3.5" color="fg.muted" />}</button>diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.tsindex efca9b5420..6e67421e25 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts@@ -2,6 +2,7 @@ import type { AccountScope } from '@platform/state/accountLifecycle';import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/api';import type * as apiModule from '@workbench/projects/api';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { ProjectCreateAbsentError } from '@workbench/projects/api';import { createDraftProject } from '@workbench/workbenchState';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -79,7 +80,7 @@ const sourceRecord = (document: Record<string, unknown> = {}): ProjectRecordDTO...project,canvas: {...project.canvas,- document: { ...project.canvas.document, layers: [rasterImageLayer('l1', 'shared.png')] },+ document: { ...project.canvas.document, stacks: stacksFrom([rasterImageLayer('l1', 'shared.png')]) },},id: 'source',name: 'Source',@@ -112,9 +113,9 @@ const createdData = (): Record<string, unknown> =>const restoredLayerName = (): string =>(createdData().canvas as {- document: { layers: { source: { image: { imageName: string } } }[] };+ document: { stacks: { raster: { source: { image: { imageName: string } } }[] } };}- ).document.layers[0]!.source.image.imageName;+ ).document.stacks.raster[0]!.source.image.imageName;beforeEach(async () => {vi.resetModules();diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.tsindex 238833a73c..43e49ec5b9 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts@@ -16,17 +16,23 @@ const imageRef = (imageName: string) => ({ height: 64, imageName, width: 64 });const projectDocument = (): Record<string, unknown> => ({canvas: {document: {- layers: [- { id: 'l1', source: { image: imageRef('live-a.png'), type: 'image' } },- { id: 'l2', source: { bitmap: imageRef('live-b.png'), type: 'paint' } },- ],+ stacks: {+ raster: [+ { id: 'l1', source: { image: imageRef('live-a.png'), type: 'image' } },+ { id: 'l2', source: { bitmap: imageRef('live-b.png'), type: 'paint' } },+ ],+ },},- snapshots: [{ document: { layers: [{ id: 'old', source: { image: imageRef('history.png'), type: 'image' } }] } }],+ snapshots: [+ { document: { stacks: { raster: [{ id: 'old', source: { image: imageRef('history.png'), type: 'image' } }] } } },+ ],},id: 'project-1',layout: {},name: 'My project',- queue: { items: [{ snapshot: { canvas: { document: { layers: [{ source: { image: imageRef('q.png') } }] } } } }] },+ queue: {+ items: [{ snapshot: { canvas: { document: { stacks: { raster: [{ source: { image: imageRef('q.png') } }] } } } } }],+ },});const planInput = {diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/format.tsindex dad1e7ceb3..61909ec7c7 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts@@ -1,5 +1,7 @@import type { RefusedWorkbenchProject } from '@workbench/projectContracts';+import { MIN_SUPPORTED_CANVAS_SCHEMA_VERSION } from '@workbench/canvasSchemaVersion';+/*** What an `.invk` is called and how reading one can fail.*@@ -61,5 +63,11 @@ export class InvkFormatError extends Error {}/** The archive-format reason that matches a project the canvas version gate refused. */-export const toInvkFormatReason = (refused: RefusedWorkbenchProject): InvkFormatReason =>- refused.refusal.status === 'unsupported-version' ? 'unsupported-version' : 'damaged';+export const toInvkFormatReason = (refused: RefusedWorkbenchProject): InvkFormatReason => {+ if (refused.refusal.status !== 'unsupported-version') {+ return 'damaged';+ }+ return refused.refusal.version < MIN_SUPPORTED_CANVAS_SCHEMA_VERSION+ ? 'legacy-canvas-project'+ : 'unsupported-version';+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex abf8b1d0b4..0d702fa918 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -36,7 +36,7 @@ let account: typeof accountLifecycleModule;const summaryDto = (id: string, name: string, updatedAt: string) => ({board_id: `board-for-${id}`,created_at: '2026-06-01 08:00:00.000',- minimum_canvas_schema_version: 2,+ minimum_canvas_schema_version: 3,name,project_id: id,revision: 1,@@ -111,12 +111,12 @@ describe('refreshProjectLibrary', () => {expect(status).toBe('ready');expect(summaries.map((summary) => summary.id)).toEqual(['newer', 'older']);expect(summaries[0].updatedAt).toBe('2026-06-10T10:00:00.000Z');- expect(summaries[0].minimumCanvasSchemaVersion).toBe(2);+ expect(summaries[0].minimumCanvasSchemaVersion).toBe(3);});it('identifies summaries that require a newer canvas reader without fetching the document', async () => {api.listProjects.mockResolvedValue([- { ...summaryDto('future', 'Future', '2026-06-10 10:00:00.000'), minimum_canvas_schema_version: 3 },+ { ...summaryDto('future', 'Future', '2026-06-10 10:00:00.000'), minimum_canvas_schema_version: 4 },]);await library.refreshProjectLibrary();diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex db87314406..697ee04885 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -8,10 +8,7 @@ import {import { createExternalStore } from '@platform/state/externalStore';import { createSingleFlight } from '@platform/state/singleFlight';import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';-import {- DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,- MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,-} from '@workbench/canvasSchemaVersion';+import { DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION, isCanvasSchemaVersionSupported } from '@workbench/canvasSchemaVersion';import { createLocalStorageWorkbenchPersistence } from '@workbench/persistence';import type { ProjectTransferIssues } from './invk/transfer';@@ -205,7 +202,7 @@ export const upsertProjectSummary = (};export const isProjectSummaryCompatible = (summary: ProjectSummary): boolean =>- summary.minimumCanvasSchemaVersion <= MAX_SUPPORTED_CANVAS_SCHEMA_VERSION;+ isCanvasSchemaVersionSupported(summary.minimumCanvasSchemaVersion);/*** Every mutation below branches on one question: does the workbench hold this project? If so itdiff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.tsindex b7ca58f764..f7c04abe58 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts@@ -37,9 +37,9 @@ const noMappings = { images: new Map<string, string>(), videos: new Map<string,const projectDocument = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({canvas: {- document: { layers: [imageLayer('layer-1', 'live-image.png')], version: 2 },- snapshots: [{ document: { layers: [imageLayer('layer-old', 'snapshot-image.png')] }, id: 'snap-1' }],- version: 2,+ document: { stacks: { raster: [imageLayer('layer-1', 'live-image.png')] }, version: 3 },+ snapshots: [{ document: { stacks: { raster: [imageLayer('layer-old', 'snapshot-image.png')] } }, id: 'snap-1' }],+ version: 3,},events: [{ imageName: 'event-image.png' }],graphHistory: [{ document: { nodes: [{ data: { image: { image_name: 'history-image.png' } } }] }, id: 'gh-1' }],@@ -48,7 +48,9 @@ const projectDocument = (overrides: Record<string, unknown> = {}): Record<stringname: 'Project',projectGraph: { nodes: [{ data: { inputs: { image: { image_name: 'graph-image.png' } } }, id: 'node-1' }] },queue: {- items: [{ id: 'q-1', snapshot: { canvas: { document: { layers: [imageLayer('l', 'queue-image.png')] } } } }],+ items: [+ { id: 'q-1', snapshot: { canvas: { document: { stacks: { raster: [imageLayer('l', 'queue-image.png')] } } } } },+ ],},widgetInstances: {'upscale-1': { state: { values: { inputImage: { image_name: 'upscale-input.png' } } }, typeId: 'upscale' },@@ -81,19 +83,27 @@ describe('collectLiveAssetRefs', () => {expect(images.has('recent-a.png')).toBe(false);});- it('finds references nested through arrays and mask bitmaps', () => {+ it('finds references nested through groups, arrays and mask bitmaps', () => {const { images } = collectLiveAssetRefs(projectDocument({canvas: {document: {- layers: [- { id: 'mask-1', mask: { bitmap: imageRef('mask.png'), fill: {} }, type: 'inpaint_mask' },- {- id: 'rg-1',- referenceImages: [{ config: { image: imageRef('reference.png'), type: 'ip_adapter' } }],- type: 'regional_guidance',- },- ],+ stacks: {+ inpaint_mask: [+ {+ children: [{ id: 'mask-1', mask: { bitmap: imageRef('mask.png'), fill: {} }, type: 'inpaint_mask' }],+ id: 'group-1',+ type: 'group',+ },+ ],+ regional_guidance: [+ {+ id: 'rg-1',+ referenceImages: [{ config: { image: imageRef('reference.png'), type: 'ip_adapter' } }],+ type: 'regional_guidance',+ },+ ],+ },},},})@@ -292,7 +302,7 @@ describe('stripInstallationState', () => {* authored input that has to survive the round trip.*/it.each([- ['no selection', { canvas: { document: { layers: [imageLayer('l1', 'a.png')] } }, id: 'p1' }],+ ['no selection', { canvas: { document: { stacks: { raster: [imageLayer('l1', 'a.png')] } } }, id: 'p1' }],['an already-blank URL',{ widgetStates: { gallery: { values: { recentImages: [{ imageName: 'a.png', imageUrl: '' }] } } } },@@ -317,9 +327,9 @@ describe('remapAssetRefs', () => {const remapped = remapAssetRefs(projectDocument(), {...noMappings,images: new Map([['live-image.png', 'uploaded-1.png']]),- }) as { canvas: { document: { layers: { source: { image: { imageName: string } } }[] } } };+ }) as { canvas: { document: { stacks: { raster: { source: { image: { imageName: string } } }[] } } } };- expect(remapped.canvas.document.layers[0]!.source.image.imageName).toBe('uploaded-1.png');+ expect(remapped.canvas.document.stacks.raster[0]!.source.image.imageName).toBe('uploaded-1.png');});it('rewrites history references too, so nothing keeps pointing at the pre-import name', () => {@@ -330,16 +340,20 @@ describe('remapAssetRefs', () => {['snapshot-image.png', 'uploaded-snapshot.png'],]),}) as {- canvas: { snapshots: { document: { layers: { source: { image: { imageName: string } } }[] } }[] };+ canvas: { snapshots: { document: { stacks: { raster: { source: { image: { imageName: string } } }[] } } }[] };queue: {- items: { snapshot: { canvas: { document: { layers: { source: { image: { imageName: string } } }[] } } } }[];+ items: {+ snapshot: { canvas: { document: { stacks: { raster: { source: { image: { imageName: string } } }[] } } } };+ }[];};};- expect(remapped.queue.items[0]!.snapshot.canvas.document.layers[0]!.source.image.imageName).toBe(+ expect(remapped.queue.items[0]!.snapshot.canvas.document.stacks.raster[0]!.source.image.imageName).toBe('uploaded-queue.png');- expect(remapped.canvas.snapshots[0]!.document.layers[0]!.source.image.imageName).toBe('uploaded-snapshot.png');+ expect(remapped.canvas.snapshots[0]!.document.stacks.raster[0]!.source.image.imageName).toBe(+ 'uploaded-snapshot.png'+ );});it('rewrites the backend spelling of the key as well', () => {@@ -366,18 +380,18 @@ describe('remapAssetRefs', () => {/** The namespaces are separate, so a shared name must not cross over. */it('never rewrites an image through the video mapping, or the reverse', () => {const document = projectDocument({- canvas: { document: { layers: [imageLayer('l', 'shared')] } },+ canvas: { document: { stacks: { raster: [imageLayer('l', 'shared')] } } },projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'shared' } } }, id: 'n' }] },});const remapped = remapAssetRefs(document, {images: new Map([['shared', 'image-side']]),videos: new Map([['shared', 'video-side']]),}) as {- canvas: { document: { layers: { source: { image: { imageName: string } } }[] } };+ canvas: { document: { stacks: { raster: { source: { image: { imageName: string } } }[] } } };projectGraph: { nodes: { data: { inputs: { video: { video_name: string } } } }[] };};- expect(remapped.canvas.document.layers[0]!.source.image.imageName).toBe('image-side');+ expect(remapped.canvas.document.stacks.raster[0]!.source.image.imageName).toBe('image-side');expect(remapped.projectGraph.nodes[0]!.data.inputs.video.video_name).toBe('video-side');});@@ -385,13 +399,39 @@ describe('remapAssetRefs', () => {const remapped = remapAssetRefs(projectDocument(), {...noMappings,images: new Map([['not-present.png', 'other.png']]),- }) as { canvas: { document: { layers: { source: { image: { imageName: string } } }[] } } };+ }) as { canvas: { document: { stacks: { raster: { source: { image: { imageName: string } } }[] } } } };- expect(remapped.canvas.document.layers[0]!.source.image.imageName).toBe('live-image.png');+ expect(remapped.canvas.document.stacks.raster[0]!.source.image.imageName).toBe('live-image.png');});});describe('selectCoverImageName', () => {+ it('reads the top-most raster leaf through nested groups', () => {+ const document = projectDocument({+ canvas: {+ document: {+ stacks: {+ raster: [+ {+ children: [+ {+ children: [{ id: 'deep', source: { image: imageRef('deep.png'), type: 'image' }, type: 'raster' }],+ id: 'inner',+ type: 'group',+ },+ { id: 'later', source: { image: imageRef('later.png'), type: 'image' }, type: 'raster' },+ ],+ id: 'outer',+ type: 'group',+ },+ ],+ },+ },+ },+ });+ expect(selectCoverImageName(document)).toBe('deep.png');+ });+it('prefers the newest gallery result', () => {expect(selectCoverImageName(projectDocument({ widgetInstances: galleryInstance(['newest.png', 'older.png']) }))@@ -406,14 +446,17 @@ describe('selectCoverImageName', () => {expect(selectCoverImageName(projectDocument({- canvas: { document: { layers: [paintLayer('empty', null), imageLayer('below', 'below.png')] } },+ canvas: { document: { stacks: { raster: [paintLayer('empty', null), imageLayer('below', 'below.png')] } } },}))).toBe('below.png');});it.each([- ['a project that has produced nothing', { canvas: { document: { layers: [] } }, id: 'p', layout: {}, name: 'n' }],+ [+ 'a project that has produced nothing',+ { canvas: { document: { stacks: { raster: [] } } }, id: 'p', layout: {}, name: 'n' },+ ],['a document missing the canvas entirely', { id: 'p', layout: {}, name: 'n' }],])('is null for %s', (_label, document) => {expect(selectCoverImageName(document)).toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.tsindex 65b33f444c..5f2bb95e47 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts@@ -270,17 +270,22 @@ const readGalleryRecentImageName = (projectDocument: Record<string, unknown>): sreturn null;};+/** Leaves of a raw forest in preorder, tolerating malformed nodes. */+const rawLeaves = (nodes: unknown): Record<string, unknown>[] =>+ Array.isArray(nodes)+ ? nodes.flatMap((node) => (!isRecord(node) ? [] : node.type === 'group' ? rawLeaves(node.children) : [node]))+ : [];+const readTopmostCanvasImageName = (projectDocument: Record<string, unknown>): string | null => {const canvas = projectDocument.canvas;- if (!isRecord(canvas) || !isRecord(canvas.document) || !Array.isArray(canvas.document.layers)) {+ if (!isRecord(canvas) || !isRecord(canvas.document) || !isRecord(canvas.document.stacks)) {return null;}- // Layer index 0 is the top-most layer, which is the one a person would call- // "what this project looks like".- for (const layer of canvas.document.layers) {- if (!isRecord(layer) || !isRecord(layer.source)) {+ // The top-most raster leaf is the one a person would call "what this project looks like".+ for (const layer of rawLeaves(canvas.document.stacks.raster)) {+ if (!isRecord(layer.source)) {continue;}diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex b3ac46de35..7a5d7916bb 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -1,3 +1,4 @@+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createDraftProject } from '@workbench/workbenchState';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -124,7 +125,7 @@ const projectWithRestorableAssets = (includeVideo = true) => {...project.canvas,document: {...project.canvas.document,- layers: [rasterImageLayer('restored-image', 'archive-image.png')],+ stacks: stacksFrom([rasterImageLayer('restored-image', 'archive-image.png')]),},},...(includeVideo ? { futureVideoInput: { video_name: 'archive-video.mp4' } } : {}),@@ -187,7 +188,11 @@ describe('exportOpenProject', () => {it('reaches the server through the mocked transport', async () => {api.getProject.mockResolvedValue({data: {- canvas: { document: { layers: [{ id: 'l', source: { image: { imageName: 'pinned.png' }, type: 'image' } }] } },+ canvas: {+ document: {+ stacks: { raster: [{ id: 'l', source: { image: { imageName: 'pinned.png' }, type: 'image' } }] },+ },+ },id: 'p1',layout: {},name: 'Pinned',@@ -220,7 +225,7 @@ describe('exportLibraryProject', () => {api.getProject.mockResolvedValue({data: document,- minimum_canvas_schema_version: 3,+ minimum_canvas_schema_version: 4,name: 'Future history',project_id: 'p1',revision: 3,@@ -233,7 +238,7 @@ describe('exportLibraryProject', () => {const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));const manifest = JSON.parse(readEntryText(entries.get('manifest.json')!)) as Record<string, unknown>;- expect(manifest.minimumCanvasSchemaVersion).toBe(3);+ expect(manifest.minimumCanvasSchemaVersion).toBe(4);});/**@@ -337,7 +342,7 @@ describe('what a transfer reports', () => {...project.canvas,document: {...project.canvas.document,- layers: [rasterImageLayer('l1', 'a.png'), rasterImageLayer('l2', 'b.png')],+ stacks: stacksFrom([rasterImageLayer('l1', 'a.png'), rasterImageLayer('l2', 'b.png')]),},},name: 'Two layers',@@ -421,7 +426,7 @@ describe('importing a project board', () => {...project,canvas: {...project.canvas,- document: { ...project.canvas.document, layers: [rasterImageLayer('l1', 'shared.png')] },+ document: { ...project.canvas.document, stacks: stacksFrom([rasterImageLayer('l1', 'shared.png')]) },},name: 'Board project',};@@ -477,10 +482,10 @@ describe('importing a project board', () => {await projectFile.importProjectFile(await exportedBoardArchive());const { data } = api.createProjectSettled.mock.calls[0]![0] as {- data: { canvas: { document: { layers: Array<{ source: { image: { imageName: string } } }> } } };+ data: { canvas: { document: { stacks: { raster: Array<{ source: { image: { imageName: string } } }> } } } };};- expect(data.canvas.document.layers[0]?.source.image.imageName).toBe('board-shared.png');+ expect(data.canvas.document.stacks.raster[0]?.source.image.imageName).toBe('board-shared.png');});/** The dedup that document references get is deliberately not applied to board membership. */@@ -510,9 +515,9 @@ describe('importing a project board', () => {const outcome = await projectFile.importProjectFile(await exportedBoardArchive());const { data } = api.createProjectSettled.mock.calls[0]![0] as {- data: { canvas: { document: { layers: Array<{ source: { image: { imageName: string } } }> } } };+ data: { canvas: { document: { stacks: { raster: Array<{ source: { image: { imageName: string } } }> } } } };};- const restoredName = data.canvas.document.layers[0]!.source.image.imageName;+ const restoredName = data.canvas.document.stacks.raster[0]!.source.image.imageName;expect(restoredName).not.toBe('shared.png');expect(restoredName).toContain('-missing-image-');@@ -538,7 +543,7 @@ describe('importing a project board', () => {await projectFile.importProjectFile(capturedArchive());expect(transport.createStagingBoard).not.toHaveBeenCalled();- expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({ minimum_canvas_schema_version: 2 });+ expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({ minimum_canvas_schema_version: 3 });expect(api.createProjectSettled.mock.calls[0]![0]).not.toHaveProperty('board_id');});@@ -553,7 +558,7 @@ describe('importing a project board', () => {const rewrittenEntries = new Map([...entries].map(([path, bytes]) => [path, binaryEntry(bytes)]));- rewrittenEntries.set('manifest.json', textEntry(JSON.stringify({ ...manifest, minimumCanvasSchemaVersion: 3 })));+ rewrittenEntries.set('manifest.json', textEntry(JSON.stringify({ ...manifest, minimumCanvasSchemaVersion: 4 })));const archive = new File([await writeArchive(rewrittenEntries)], original.name);await expect(projectFile.importProjectFile(archive)).rejects.toMatchObject({ reason: 'unsupported-version' });@@ -726,7 +731,7 @@ describe('importProjectFile', () => {...project.canvas,document: {...project.canvas.document,- layers: [rasterImageLayer('image-layer', 'legacy.png')],+ stacks: stacksFrom([rasterImageLayer('image-layer', 'legacy.png')]),},},futureDocumentKey: { survives: true },@@ -759,12 +764,12 @@ describe('importProjectFile', () => {const createRequest = api.createProjectSettled.mock.calls[0]![0] as { data: Record<string, unknown> };const invocation = createRequest.data.invocation as { sourceId: string };const canvas = createRequest.data.canvas as {- document: { layers: Array<{ source: { image: { imageName: string } } }> };+ document: { stacks: { raster: Array<{ source: { image: { imageName: string } } }> } };};expect(invocation.sourceId).toBe('workflow');expect(createRequest.data.futureDocumentKey).toEqual({ survives: true });- expect(canvas.document.layers[0]?.source.image.imageName).toBe('server-legacy.png');+ expect(canvas.document.stacks.raster[0]?.source.image.imageName).toBe('server-legacy.png');});it('imports the shipped legacy JSON envelope under a fresh canonical identity without restoring assets', async () => {@@ -816,7 +821,7 @@ describe('importProjectFile', () => {JSON.stringify({document: {},kind: 'invokeai-project',- version: 2,+ version: 4,}),],['a missing document', JSON.stringify({ kind: 'invokeai-project', version: 1 })],diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectLoadRefusal.ts b/invokeai/frontend/webv2/src/workbench/projects/projectLoadRefusal.tsindex 30d8cee139..e48ee2379a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectLoadRefusal.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectLoadRefusal.ts@@ -1,6 +1,8 @@import type { RefusedWorkbenchProject } from '@workbench/projectContracts';import type { TFunction } from 'i18next';+import { MIN_SUPPORTED_CANVAS_SCHEMA_VERSION } from '@workbench/canvasSchemaVersion';+export interface RefusedProjectNotice {title: string;message: string;@@ -13,7 +15,12 @@ export const describeRefusedProject = (refused: RefusedWorkbenchProject, t: TFunreturn {message:refused.refusal.status === 'unsupported-version'- ? t('projects.load.unsupportedVersion', { name })+ ? t(+ refused.refusal.version < MIN_SUPPORTED_CANVAS_SCHEMA_VERSION+ ? 'projects.load.legacyVersion'+ : 'projects.load.unsupportedVersion',+ { name }+ ): t('projects.load.invalid', { name }),title: t('projects.couldNotOpen'),};diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.tsindex 5d49cff06b..cbbb5cfb9a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts@@ -63,7 +63,7 @@ describe('project document serialization', () => {it('refuses a document whose canvas was written by a newer client, keeping the raw document', () => {const project = getProject();const document = serializeProjectDocument(project);- const future = { ...document, canvas: { ...(document.canvas as object), version: 3 } };+ const future = { ...document, canvas: { ...(document.canvas as object), version: 4 } };const result = deserializeProjectDocument(future);@@ -71,7 +71,7 @@ describe('project document serialization', () => {refused: {projectId: project.id,raw: future,- refusal: { scope: 'state', status: 'unsupported-version', version: 3 },+ refusal: { scope: 'state', status: 'unsupported-version', version: 4 },source: 'canvas',},status: 'refused',diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.tsindex 6a540c3f82..fd651962d1 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts@@ -63,7 +63,7 @@ const api = vi.hoisted(() => {created_at: '2026-06-10 08:00:00.000',data: structuredClone(data),name: data.name as string,- minimum_canvas_schema_version: 2,+ minimum_canvas_schema_version: 3,project_id: id,revision: 1,updated_at: '2026-06-10 08:00:00.000',@@ -340,18 +340,18 @@ describe('loadWorkbench session hydration', () => {);api.createProject.mockImplementationOnce(() => {api.__seed(persistence.serializeProjectDocument({ ...local, name: 'Newer server project' }));- api.__records.get(local.id)!.minimum_canvas_schema_version = 3;+ api.__records.get(local.id)!.minimum_canvas_schema_version = 4;return Promise.reject(Object.assign(new Error('conflict'), { __status: 409 }));});- api.getProject.mockRejectedValueOnce(api.__schemaError(3, 2));+ api.getProject.mockRejectedValueOnce(api.__schemaError(4, 3));const snapshot = await service.loadWorkbench();const recoveredRecord = [...api.__records.values()].find((record) => record.project_id !== local.id);expect(api.updateProject).not.toHaveBeenCalled();expect(api.__records.get(local.id)).toMatchObject({- minimum_canvas_schema_version: 3,+ minimum_canvas_schema_version: 4,name: 'Newer server project',});expect(recoveredRecord?.data).toMatchObject({@@ -740,7 +740,7 @@ describe('saveWorkbench', () => {api.updateProject.mockRejectedValueOnce(new Error('offline'));await service.saveWorkbench(stateWithProjects([edited]));- setPersistedCanvasSchemaFloor(project.id, 3);+ setPersistedCanvasSchemaFloor(project.id, 4);const server = api.__records.get(project.id)!;@@ -765,7 +765,7 @@ describe('saveWorkbench', () => {await reconnected.saveWorkbench(replay!.state);expect(api.createProject).toHaveBeenLastCalledWith(- expect.objectContaining({ minimum_canvas_schema_version: 3 }),+ expect.objectContaining({ minimum_canvas_schema_version: 4 }),expect.any(AbortSignal));expect([...api.__records.values()]).toEqual(@@ -802,7 +802,7 @@ describe('saveWorkbench', () => {api.listProjects.mockImplementationOnce(async () => {const summaries = await listProjects();- api.__records.get(project.id)!.minimum_canvas_schema_version = 3;+ api.__records.get(project.id)!.minimum_canvas_schema_version = 4;return summaries;});@@ -813,7 +813,7 @@ describe('saveWorkbench', () => {await reconnected.saveWorkbench(replay!.state);expect(api.createProject).toHaveBeenLastCalledWith(- expect.objectContaining({ minimum_canvas_schema_version: 3 }),+ expect.objectContaining({ minimum_canvas_schema_version: 4 }),expect.any(AbortSignal));});@@ -879,7 +879,7 @@ describe('saveWorkbench', () => {api.updateProject.mockRejectedValueOnce(new Error('offline'));await service.saveWorkbench(stateWithProjects([edited]));- setPersistedCanvasSchemaFloor(project.id, 3);+ setPersistedCanvasSchemaFloor(project.id, 4);api.__records.delete(project.id);const reconnected = persistence.createSyncedWorkbenchPersistence(account.captureAccountScope());@@ -916,7 +916,7 @@ describe('saveWorkbench', () => {await restartedAgain.saveWorkbench(replayAgain!.state);expect(api.createProject).toHaveBeenLastCalledWith(- expect.objectContaining({ minimum_canvas_schema_version: 3 }),+ expect.objectContaining({ minimum_canvas_schema_version: 4 }),expect.any(AbortSignal));expect(api.__records.has(project.id)).toBe(false);@@ -937,7 +937,7 @@ describe('saveWorkbench', () => {api.updateProject.mockRejectedValueOnce(new Error('offline'));await service.saveWorkbench(stateWithProjects([edited]));- api.__records.get(project.id)!.minimum_canvas_schema_version = 3;+ api.__records.get(project.id)!.minimum_canvas_schema_version = 4;const reconnected = persistence.createSyncedWorkbenchPersistence(account.captureAccountScope());const replay = await reconnected.loadWorkbench();@@ -1553,14 +1553,14 @@ describe('hydrateProjectFromServer', () => {});it('reports a server schema precondition as an unsupported project instead of as missing', async () => {- api.getProject.mockRejectedValueOnce(api.__schemaError(3, 2));+ api.getProject.mockRejectedValueOnce(api.__schemaError(4, 3));expect(await service.hydrateProjectFromServer('future', 'Future project')).toEqual({refused: {projectId: 'future',projectName: 'Future project',raw: null,- refusal: { raw: null, scope: 'document', status: 'unsupported-version', version: 3 },+ refusal: { raw: null, scope: 'document', status: 'unsupported-version', version: 4 },source: 'canvas',},status: 'refused',@@ -1839,13 +1839,13 @@ describe('authoritative project boards', () => {await service.saveWorkbench(stateWithProjects([staleLocal]));const lowerFloorRecoveryId = [...api.__records.keys()].find((id) => id !== project.id)!;- api.__records.get(project.id)!.minimum_canvas_schema_version = 3;+ api.__records.get(project.id)!.minimum_canvas_schema_version = 4;const retried = await service.saveWorkbench(stateWithProjects([staleLocal]));const raisedFloorRecoveryId = retried.conflicts[0]!.recoveredIdentity.id;expect(raisedFloorRecoveryId).not.toBe(lowerFloorRecoveryId);- expect(api.__records.get(lowerFloorRecoveryId)?.minimum_canvas_schema_version).toBe(2);- expect(api.__records.get(raisedFloorRecoveryId)?.minimum_canvas_schema_version).toBe(3);+ expect(api.__records.get(lowerFloorRecoveryId)?.minimum_canvas_schema_version).toBe(3);+ expect(api.__records.get(raisedFloorRecoveryId)?.minimum_canvas_schema_version).toBe(4);});it('uses a distinct recovery identity for a later conflict after reconciliation is durable', async () => {@@ -1987,12 +1987,12 @@ describe('authoritative project boards', () => {const opened = await openServerProject(project.id);const edited = { ...opened, name: 'Local work' };- api.updateProject.mockRejectedValueOnce(api.__schemaError(3, 2));+ api.updateProject.mockRejectedValueOnce(api.__schemaError(4, 3));await expect(service.flushProjectToServer(edited)).resolves.toEqual({documentJson: JSON.stringify(persistence.serializeProjectDocument(edited)),kind: 'schema-refused',- refusal: { maxCanvasSchemaVersion: 2, minimumCanvasSchemaVersion: 3 },+ refusal: { maxCanvasSchemaVersion: 3, minimumCanvasSchemaVersion: 4 },});const callsAfterRefusal = api.updateProject.mock.calls.length;@@ -2021,7 +2021,7 @@ describe('authoritative project boards', () => {});try {- api.updateProject.mockRejectedValueOnce(api.__schemaError(3, 2));+ api.updateProject.mockRejectedValueOnce(api.__schemaError(4, 3));await service.saveWorkbench(stateWithProjects([edited]));const cachedBeforeOmission = storage.get('invokeai:v7:webv2:workbench');@@ -2043,7 +2043,7 @@ describe('authoritative project boards', () => {const opened = await openServerProject(project.id);const edited = { ...opened, name: 'Local work that must survive' };- api.updateProject.mockRejectedValueOnce(api.__schemaError(3, 2));+ api.updateProject.mockRejectedValueOnce(api.__schemaError(4, 3));await service.saveWorkbench(stateWithProjects([edited]));storage.set('invokeai:v7:webv2:workbench:refused-projects',@@ -2051,7 +2051,7 @@ describe('authoritative project boards', () => {[project.id]: persistence.serializeProjectDocument({ ...edited, name: 'Older retained edit' }),}));- api.__records.get(project.id)!.minimum_canvas_schema_version = 3;+ api.__records.get(project.id)!.minimum_canvas_schema_version = 4;const reloaded = persistence.createSyncedWorkbenchPersistence(account.captureAccountScope());@@ -2077,7 +2077,7 @@ describe('authoritative project boards', () => {const opened = await openServerProject(project.id);const edited = { ...opened, name: 'Divergent local work' };- api.updateProject.mockRejectedValueOnce(api.__schemaError(3, 2));+ api.updateProject.mockRejectedValueOnce(api.__schemaError(4, 3));await service.saveWorkbench(stateWithProjects([edited]));const reloaded = persistence.createSyncedWorkbenchPersistence(account.captureAccountScope());@@ -2099,11 +2099,11 @@ describe('authoritative project boards', () => {const opened = await openServerProject(project.id);api.updateProject.mockRejectedValueOnce(Object.assign(new Error('conflict'), { __status: 409 }));- api.getProject.mockRejectedValueOnce(api.__schemaError(3, 2));+ api.getProject.mockRejectedValueOnce(api.__schemaError(4, 3));await expect(service.flushProjectToServer({ ...opened, name: 'Local work' })).resolves.toMatchObject({kind: 'schema-refused',- refusal: { maxCanvasSchemaVersion: 2, minimumCanvasSchemaVersion: 3 },+ refusal: { maxCanvasSchemaVersion: 3, minimumCanvasSchemaVersion: 4 },});});@@ -2114,7 +2114,7 @@ describe('authoritative project boards', () => {api.__records.set(project.id, {...server,- minimum_canvas_schema_version: 3,+ minimum_canvas_schema_version: 4,revision: server.revision + 1,});@@ -2128,7 +2128,7 @@ describe('authoritative project boards', () => {expect(updateRequests[0]).not.toHaveProperty('minimum_canvas_schema_version');expect(updateRequests[1]).not.toHaveProperty('minimum_canvas_schema_version');expect(api.__records.get(project.id)).toMatchObject({- minimum_canvas_schema_version: 3,+ minimum_canvas_schema_version: 4,name: 'Local edit',revision: 3,});@@ -2376,7 +2376,7 @@ describe('canvas version gate', () => {const futureProject = (name: string): Project => {const draft = { ...createDraftProject([]), name };- return { ...draft, canvas: { ...draft.canvas, version: 3 } as unknown as Project['canvas'] };+ return { ...draft, canvas: { ...draft.canvas, version: 4 } as unknown as Project['canvas'] };};const cacheKey = 'invokeai:v7:webv2:workbench';@@ -2395,21 +2395,21 @@ describe('canvas version gate', () => {await service.flushProjectToServer(future);expect(api.createProject).toHaveBeenCalledWith(- expect.objectContaining({ minimum_canvas_schema_version: 3, project_id: future.id }),+ expect.objectContaining({ minimum_canvas_schema_version: 4, project_id: future.id }),expect.any(AbortSignal));});it('retains a server floor when deletion recovery forks a document with a lower live version', async () => {const project = seedServerProject('Future floor');- api.__records.get(project.id)!.minimum_canvas_schema_version = 3;+ api.__records.get(project.id)!.minimum_canvas_schema_version = 4;const opened = await openServerProject(project.id);api.__records.delete(project.id);await service.flushProjectToServer({ ...opened, name: 'Recovered locally' });expect(api.createProject).toHaveBeenLastCalledWith(- expect.objectContaining({ minimum_canvas_schema_version: 3 }),+ expect.objectContaining({ minimum_canvas_schema_version: 4 }),expect.any(AbortSignal));});@@ -2423,7 +2423,7 @@ describe('canvas version gate', () => {api.__records.set(project.id, {...serverRecord,data: persistence.serializeProjectDocument(winningServer),- minimum_canvas_schema_version: 3,+ minimum_canvas_schema_version: 4,name: winningServer.name,revision: serverRecord.revision + 1,});@@ -2431,14 +2431,14 @@ describe('canvas version gate', () => {await service.flushProjectToServer({ ...opened, name: 'Divergent local edit' });expect(api.createProject).toHaveBeenLastCalledWith(- expect.objectContaining({ minimum_canvas_schema_version: 3 }),+ expect.objectContaining({ minimum_canvas_schema_version: 4 }),expect.any(AbortSignal));});it('retains a server schema refusal during boot instead of treating the project as missing', async () => {const future = seedServerProject('Future server project');- api.__records.get(future.id)!.minimum_canvas_schema_version = 3;+ api.__records.get(future.id)!.minimum_canvas_schema_version = 4;seedSessionBlob({account: createInitialWorkbenchState().account,activeProjectId: future.id,@@ -2451,7 +2451,7 @@ describe('canvas version gate', () => {projectId: future.id,projectName: 'Future server project',raw: null,- refusal: { raw: null, scope: 'document', status: 'unsupported-version', version: 3 },+ refusal: { raw: null, scope: 'document', status: 'unsupported-version', version: 4 },source: 'canvas',},]);@@ -2463,7 +2463,7 @@ describe('canvas version gate', () => {const future = seedServerProject('Future server project');const cached = { ...future, name: 'Local work that must remain cached' };- api.__records.get(future.id)!.minimum_canvas_schema_version = 3;+ api.__records.get(future.id)!.minimum_canvas_schema_version = 4;seedCache([cached]);seedSessionBlob({account: createInitialWorkbenchState().account,@@ -2534,7 +2534,7 @@ describe('canvas version gate', () => {{projectId: future.id,projectName: 'From the future',- refusal: { scope: 'state', status: 'unsupported-version', version: 3 },+ refusal: { scope: 'state', status: 'unsupported-version', version: 4 },source: 'canvas',},]);@@ -2605,7 +2605,7 @@ describe('canvas version gate', () => {projects: [{ ...snapshot!.state.projects[0]!, name: 'Edited' }],});- expect(api.__records.get(future.id)?.data.canvas).toMatchObject({ version: 3 });+ expect(api.__records.get(future.id)?.data.canvas).toMatchObject({ version: 4 });expect(api.__records.get(future.id)?.revision).toBe(1);});@@ -2617,7 +2617,7 @@ describe('canvas version gate', () => {const result = await service.hydrateProjectFromServer(future.id);expect(result).toMatchObject({- refused: { projectId: future.id, refusal: { status: 'unsupported-version', version: 3 }, source: 'canvas' },+ refused: { projectId: future.id, refusal: { status: 'unsupported-version', version: 4 }, source: 'canvas' },status: 'refused',});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex 1cc6b3ce49..a13ae45c7b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -5,6 +5,7 @@ import { assertAccountScopeCurrent, captureAccountScope, type AccountScope } froimport {DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,getProjectCanvasSchemaRequirement,+ isCanvasSchemaVersionSupported,MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,} from '@workbench/canvasSchemaVersion';import { timeWorkbenchPerf } from '@workbench/performanceMarks';@@ -1646,7 +1647,7 @@ const loadFromBackend = async (openIds.map(async (id) => {const summary = summaryById.get(id);- if (summary && summary.minimum_canvas_schema_version > MAX_SUPPORTED_CANVAS_SCHEMA_VERSION) {+ if (summary && !isCanvasSchemaVersionSupported(summary.minimum_canvas_schema_version)) {return {refused: toDeclaredSchemaRefusal(id, summary.name, summary.minimum_canvas_schema_version),status: 'refused' as const,diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.tsindex 83f2874936..3e0c01dfec 100644--- a/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts@@ -1,12 +1,12 @@import type { GenerateWidgetValues } from '@features/generation/contracts';import type { QueueItem, QueueState, QueueSubmissionSnapshot } from '@features/queue/contracts';-import type { CanvasStateContractV2 } from './canvas-engine/api';+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 WorkbenchQueueSubmissionContext {- canvas: CanvasStateContractV2;+ canvas: CanvasStateContractV3;generate?: {negativePromptNodeId: string;positivePromptNodeId: string;diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.tsindex 95847541c8..3a8fedf1f8 100644--- a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts@@ -123,7 +123,10 @@ describe('normalizeWorkbenchQueueHistory', () => {...item,snapshot: {...item.snapshot,- canvas: { ...canvas, document: { ...canvas.document, layers: [{ id: 'broken', type: 'mystery' }] } },+ canvas: {+ ...canvas,+ document: { ...canvas.document, stacks: { raster: [{ id: 'broken', type: 'mystery' }] } },+ },},},],diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.tsindex f73c0ec877..98e861e72f 100644--- a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts@@ -5,7 +5,7 @@ import type {QueueSourceId,QueueSubmissionPresentation,} from '@features/queue/contracts';-import type { CanvasStateContractV2 } from '@workbench/canvas-engine/api';+import type { CanvasStateContractV3 } from '@workbench/canvas-engine/api';import type { GraphContract } from '@workbench/graphContracts';import type { WidgetInstanceContract, WidgetInstanceId, WidgetStateMap } from '@workbench/widgetContracts';@@ -21,7 +21,7 @@ type UnknownRecord = Record<string, unknown>;type PresentationSource = { batchCount: number; height?: number; positivePrompt?: string; width?: number } | null;export interface QueueHistoryNormalizationContext {- canvas: CanvasStateContractV2;+ canvas: CanvasStateContractV3;widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;}@@ -252,7 +252,7 @@ const getBackendSubmission = (const normalizeLegacyQueueItem = (value: unknown,index: number,- canvas: CanvasStateContractV2,+ canvas: CanvasStateContractV3,context: QueueHistoryNormalizationContext): WorkbenchQueueItem => {const item = isRecord(value) ? value : {};@@ -331,7 +331,7 @@ const normalizeLegacyQueueItem = (* 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: CanvasStateContractV2): CanvasStateContractV2 => ({+const unplaceableCanvas = (canvas: CanvasStateContractV3): CanvasStateContractV3 => ({...canvas,documentRevision: -1,});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsxindex 57831d514c..1c03a3d6cb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx@@ -1,4 +1,4 @@-import type { CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasStateContractV3 } from '@workbench/canvas-engine/contracts';import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';import type { EngineDeps, EngineRegistry } from '@workbench/canvas-operations/engineRegistry';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';@@ -6,7 +6,7 @@ import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationimport { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { createEngineRegistry } from '@workbench/canvas-operations/engineRegistry';-import { createEmptyCanvasStateV2 } from '@workbench/canvasMigration';+import { createEmptyCanvasState } from '@workbench/canvasMigration';import { act, StrictMode } from 'react';import { createRoot } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -73,7 +73,7 @@ const createTrackedRoot = (host: HTMLDivElement) => {return { root, unmount };};-const createEngineDeps = (state: CanvasStateContractV2): EngineDeps => {+const createEngineDeps = (state: CanvasStateContractV3): EngineDeps => {const listeners = new Set<() => void>();const mutationPort: CanvasProjectMutationPort = {commitEdit: () => undefined,@@ -127,7 +127,7 @@ describe('CanvasSurface browser lifecycle', () => {it('is StrictMode-safe across resize, registry reacquisition, detachment, and project switching', async () => {const gracePeriodMs = 80;const registry = createTrackedRegistry(gracePeriodMs);- const projectADeps = createEngineDeps(createEmptyCanvasStateV2(64, 64));+ const projectADeps = createEngineDeps(createEmptyCanvasState(64, 64));const firstProjectA = acquireTrackedEngine(registry, 'project-a', projectADeps);const disposeA = vi.spyOn(firstProjectA.engine.lifecycle, 'dispose');const beginCooldownA = vi.spyOn(firstProjectA.engine.lifecycle, 'beginCooldown');@@ -152,7 +152,7 @@ describe('CanvasSurface browser lifecycle', () => {const projectBReference = acquireTrackedEngine(registry,'project-b',- createEngineDeps(createEmptyCanvasStateV2(32, 48))+ createEngineDeps(createEmptyCanvasState(32, 48)));const projectB = projectBReference.engine;const attachA = vi.spyOn(projectA.surface, 'attach');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.tsindex 478b7dfb20..45df3daf80 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts@@ -1,5 +1,7 @@-import type { CanvasDocumentContractV2, Rect } from '@workbench/canvas-engine/api';+import type { CanvasDocumentContractV3, Rect } from '@workbench/canvas-engine/api';+import { getDocumentLeaves } from '@workbench/canvas-engine/api';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it, vi, type Mock } from 'vitest';import {@@ -14,16 +16,16 @@ const BBOX: Rect = { height: 64, width: 64, x: 0, y: 0 };const FIT_LAYERS: Rect = { height: 128, width: 256, x: 8, y: 16 };const FIT_MASKS: Rect = { height: 32, width: 32, x: 4, y: 4 };-const documentOf = (): CanvasDocumentContractV2 =>+const documentOf = (): CanvasDocumentContractV3 =>({background: { color: '#000000', type: 'transparent' },bbox: BBOX,height: 512,- layers: [],+ stacks: stacksFrom([]),selectedLayerId: null,- version: 2,+ version: 3,width: 768,- }) as unknown as CanvasDocumentContractV2;+ }) as unknown as CanvasDocumentContractV3;const createEngine = (viewportSize = { height: 600, width: 800 }) => {const zoomAtPoint = vi.fn();@@ -102,7 +104,7 @@ describe('applyFitBbox', () => {describe('confirmNewCanvas', () => {const replaced = (engine: ReturnType<typeof createEngine>['engine']) =>- (engine.document.replaceDocument as Mock).mock.calls[0]?.[0] as CanvasDocumentContractV2;+ (engine.document.replaceDocument as Mock).mock.calls[0]?.[0] as CanvasDocumentContractV3;it('replaces the document at the current dimensions through the engine', () => {const { engine } = createEngine();@@ -115,8 +117,8 @@ describe('confirmNewCanvas', () => {it('seeds exactly one empty inpaint mask', () => {const { engine } = createEngine();confirmNewCanvas({ document: { height: 64, width: 64 }, editingLocked: false, engine });- expect(replaced(engine).layers).toHaveLength(1);- expect(replaced(engine).layers[0]?.type).toBe('inpaint_mask');+ expect(getDocumentLeaves(replaced(engine))).toHaveLength(1);+ expect(getDocumentLeaves(replaced(engine))[0]?.type).toBe('inpaint_mask');});it('refuses while editing is locked — the second gate behind the confirm dialog', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.tsindex 503bbce32f..9c4ea2f2e1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts@@ -1,11 +1,11 @@import type {CanvasDocumentCapability,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,Rect,StructuralCommitResult,} from '@workbench/canvas-engine/api';-import { createNewCanvasStateV2 } from '@workbench/canvasMigration';+import { createNewCanvasState } from '@workbench/canvasMigration';/*** The slice of the engine the header's actions drive. Structural rather than the@@ -27,7 +27,7 @@ export interface CanvasHeaderCommandEngine {/** The minimum the destructive replace needs — kept narrow so its memo deps stay tight. */export interface NewCanvasContext {- readonly document: Pick<CanvasDocumentContractV2, 'width' | 'height'>;+ readonly document: Pick<CanvasDocumentContractV3, 'width' | 'height'>;/** An in-flight operation owns the document; every mutating header action is inert. */readonly editingLocked: boolean;readonly engine: Pick<CanvasHeaderCommandEngine, 'document'>;@@ -35,7 +35,7 @@ export interface NewCanvasContext {export interface CanvasHeaderCommandContext extends NewCanvasContext {readonly engine: CanvasHeaderCommandEngine;- readonly document: CanvasDocumentContractV2;+ readonly document: CanvasDocumentContractV3;readonly fitLayersRect: Rect | null;readonly fitMasksRect: Rect | null;/** Opens the confirm dialog. The destructive replace only runs from its confirm. */@@ -82,7 +82,7 @@ export const confirmNewCanvas = (ctx: NewCanvasContext): void => {if (ctx.editingLocked) {return;}- ctx.engine.document.replaceDocument(createNewCanvasStateV2(ctx.document.width, ctx.document.height).document);+ ctx.engine.document.replaceDocument(createNewCanvasState(ctx.document.width, ctx.document.height).document);};/**diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.tsindex fb713242de..ba79592425 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts@@ -2,7 +2,7 @@ import type { QueueHistoryItemStatus } from '@features/queue/contracts';import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';-import { createEmptyCanvasStateV2 } from '@workbench/canvasMigration';+import { createEmptyCanvasState } from '@workbench/canvasMigration';import { describe, expect, it } from 'vitest';import {@@ -24,7 +24,7 @@ const createStagedCandidate = (): CanvasStagingCandidateContract => ({});const createCanvas = ({ revision = 1, staged = false }: { revision?: number; staged?: boolean } = {}) => {- const canvas = createEmptyCanvasStateV2(512, 512);+ const canvas = createEmptyCanvasState(512, 512);const pendingImages = staged ? [createStagedCandidate()] : [];return {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.tsindex c020a8dc6b..a37f64b63b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts@@ -1,9 +1,9 @@-import type { CanvasStateContractV2, ToolId } from '@workbench/canvas-engine/api';+import type { CanvasStateContractV3, ToolId } from '@workbench/canvas-engine/api';import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';import { getCanvasStagingSlots } from '@workbench/canvasStagingView';-export const isCanvasInteractionLocked = (canvas: CanvasStateContractV2, queueItems: readonly QueueItem[]): boolean =>+export const isCanvasInteractionLocked = (canvas: CanvasStateContractV3, queueItems: readonly QueueItem[]): boolean =>getCanvasStagingSlots(canvas, queueItems).length > 0 ||queueItems.some((item) =>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.tsindex b461ba8b19..b894c22101 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts@@ -1,5 +1,6 @@-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';import { computeFitBboxToLayers, computeFitBboxToMasks, fitRectToGrid, unionRenderableBounds } from './fitBbox';@@ -51,16 +52,16 @@ const inpaintMask = (bitmap: { imageName: string; width: number; height: number } | null): CanvasLayerContract => maskLayer('inpaint_mask', id, x, y, bitmap);-const docWith = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 =>+const docWith = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 =>({background: 'transparent',bbox: { height: 512, width: 512, x: 0, y: 0 },height: 1024,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 1024,- }) as CanvasDocumentContractV2;+ }) as CanvasDocumentContractV3;describe('fitRectToGrid', () => {it('snaps the rect inward to grid multiples (top-left up, size down)', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.tsindex fdcaaac7b2..62aa92aeda 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts@@ -21,13 +21,14 @@*/import {+ compileDocumentLeaves,getSourceBounds,isEmpty,isRenderableLayer,- union,- type CanvasDocumentContractV2,+ type CanvasDocumentContractV3,type CanvasLayerContract,type Rect,+ union,} from '@workbench/canvas-engine/api';/** Fixed outward padding (document px) applied to the mask union before grid-fitting. */@@ -56,12 +57,13 @@ export const fitRectToGrid = (rect: Rect, gridSize: number): Rect => {* gate.*/export const unionRenderableBounds = (- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,predicate: (layer: CanvasLayerContract) => boolean): Rect | null => {let bounds: Rect | null = null;- for (const layer of doc.layers) {- if (!isRenderableLayer(layer) || !predicate(layer)) {+ for (const leaf of compileDocumentLeaves(doc)) {+ const layer = leaf.layer;+ if (!leaf.contributionEnabled || !isRenderableLayer(layer) || !predicate(layer)) {continue;}const layerBounds = getSourceBounds(layer, doc);@@ -74,7 +76,7 @@ export const unionRenderableBounds = (};/** The grid-snapped bbox that tightly fits all visible content, or `null` when there is none. */-export const computeFitBboxToLayers = (doc: CanvasDocumentContractV2, gridSize: number): Rect | null => {+export const computeFitBboxToLayers = (doc: CanvasDocumentContractV3, gridSize: number): Rect | null => {const bounds = unionRenderableBounds(doc, () => true);if (!bounds) {return null;@@ -85,7 +87,7 @@ export const computeFitBboxToLayers = (doc: CanvasDocumentContractV2, gridSize:/** The padded, grid-snapped bbox that fits the visible INPAINT masks (legacy parity), or `null` when there are none. */export const computeFitBboxToMasks = (- doc: CanvasDocumentContractV2,+ doc: CanvasDocumentContractV3,gridSize: number,padding: number = MASK_FIT_PADDING): Rect | null => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.tsindex f2e2b80130..fcecdf678d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts@@ -1,10 +1,10 @@import type { GenerateModelConfig, MainModelConfig } from '@features/generation/contracts';import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasControlLayerContract,CanvasLayerContract,CanvasRasterLayerContractV2,- CanvasStateContractV2,+ CanvasStateContractV3,RegionalGuidanceReferenceImage,RegionalGuidanceReferenceImageAsset,} from '@workbench/canvas-engine/contracts';@@ -16,6 +16,8 @@ import type { WorkbenchAction } from '@workbench/workbenchState.testing';import type { WorkbenchCommands } from '@workbench/workbenchStore';import { getDefaultGenerateSettings } from '@features/generation/settings';+import { getDocumentLeaves } from '@workbench/canvas-engine/api';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import {composeForGeneration,@@ -97,13 +99,13 @@ const rasterLayer = (id: string, size = 64): CanvasRasterLayerContractV2 => ({type: 'raster',});-const makeDoc = (layers: CanvasRasterLayerContractV2[], size = 64): CanvasDocumentContractV2 => ({+const makeDoc = (layers: CanvasRasterLayerContractV2[], size = 64): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: size, width: size, x: 0, y: 0 },height: size,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: size,});@@ -133,7 +135,7 @@ interface Harness {}interface HarnessOptions {- document?: CanvasDocumentContractV2;+ document?: CanvasDocumentContractV3;destination?: 'canvas' | 'gallery';model?: GenerateModelConfig;strength?: number;@@ -201,7 +203,7 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {const releaseRasterSnapshot = vi.fn();const dedupe = createCompositeDedupeCache();- const makeCanvas = (document: CanvasDocumentContractV2): CanvasStateContractV2 => ({+ const makeCanvas = (document: CanvasDocumentContractV3): CanvasStateContractV3 => ({document: structuredClone(document),documentRevision: 0,snapshots: [],@@ -213,7 +215,7 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {pendingImages: [],selectedImageIndex: 0,},- version: 2,+ version: 3,});const executorDeps: GenerationCompositeExecutorDeps = {@@ -522,7 +524,7 @@ describe('runCanvasInvocation', () => {pendingImages: [],selectedImageIndex: 0,},- version: 2,+ version: 3,},documentGeneration: 0,});@@ -634,7 +636,7 @@ describe('runCanvasInvocation', () => {pendingImages: [],selectedImageIndex: 0,},- version: 2,+ version: 3,},documentGeneration: 9,});@@ -646,7 +648,7 @@ describe('runCanvasInvocation', () => {liveDocument = {...liveDocument,bbox: { height: 64, width: 64, x: 101, y: 202 },- layers: [rasterLayer('replacement-layer')],+ stacks: stacksFrom([rasterLayer('replacement-layer')]),};return result;};@@ -657,7 +659,7 @@ describe('runCanvasInvocation', () => {expect(harness.notices()).toEqual([]);expect(harness.submittedGraphs()).toHaveLength(1);expect(harness.submittedGraphs()[0]?.canvas.document.bbox).toEqual({ height: 64, width: 64, x: 7, y: 11 });- expect(harness.submittedGraphs()[0]?.canvas.document.layers[0]?.id).toBe('frozen-layer');+ expect(getDocumentLeaves(harness.submittedGraphs()[0]?.canvas.document)[0]?.id).toBe('frozen-layer');expect(harness.releaseRasterSnapshot).toHaveBeenCalledTimes(1);expect(harness.dedupe.byKey.size).toBeGreaterThan(0);});@@ -680,7 +682,7 @@ describe('runCanvasInvocation', () => {pendingImages: [],selectedImageIndex: 0,},- version: 2,+ version: 3,},documentGeneration: 3,});@@ -1022,13 +1024,13 @@ const inpaintMaskLayer = (id: string): CanvasLayerContract => ({type: 'inpaint_mask',});-const docWithLayers = (layers: CanvasLayerContract[], size = 64): CanvasDocumentContractV2 => ({+const docWithLayers = (layers: CanvasLayerContract[], size = 64): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: size, width: size, x: 0, y: 0 },height: size,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: size,});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsxindex fb0530c9d7..1e32d3c811 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx@@ -3,6 +3,7 @@ import type { CanvasLayerSourceContract, GradientStop, GradientToolOptions } froimport { createListCollection, HStack, NumberInput, Text } from '@chakra-ui/react';import { ColorPicker, Select } from '@platform/ui';+import { getDocumentLayer } from '@workbench/canvas-engine/api';import { useGradientOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';@@ -39,9 +40,7 @@ export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {const selected = useActiveProjectSelector((project): SelectedGradient | null => {const { document } = project.canvas;- const layer = document.selectedLayerId- ? document.layers.find((entry) => entry.id === document.selectedLayerId)- : undefined;+ const layer = document.selectedLayerId ? getDocumentLayer(document, document.selectedLayerId) : undefined;if (layer && layer.type === 'raster' && layer.source.type === 'gradient') {return { id: layer.id, source: layer.source };}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsxindex 7b9de63136..7f1f7f423c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx@@ -5,6 +5,7 @@ import type { ReactNode } from 'react';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createControlLayer, createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';import { createDraftProject } from '@workbench/workbenchState';import { renderToStaticMarkup } from 'react-dom/server';@@ -54,9 +55,9 @@ const renderRow = (layer: CanvasLayerContract): Map<string, CapturedButton> => {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers: [layer],+ stacks: stacksFrom([layer]),selectedLayerId: layer.id,- version: 2,+ version: 3,width: 100,};activeProject.current = project;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsxindex 2805fc2676..22b598d7b3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx@@ -2,7 +2,7 @@ import type { SelectionOp } from '@workbench/canvas-engine/api';import { HStack, Text } from '@chakra-ui/react';import { Button } from '@platform/ui';-import { isLayerPixelEditEligible } from '@workbench/canvas-engine/api';+import { isLeafPixelEditEligible, lookupDocumentLeaf } from '@workbench/canvas-engine/api';import { useCanvasHasSelection } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback } from 'react';@@ -65,10 +65,7 @@ export const SelectionOptionsRow = ({ engine, hintKey, mode, onModeChange }: Sel// visible). Same eligibility the engine enforces; used to disable the buttons.const canPaintTarget = useActiveProjectSelector((project) => {const { document } = project.canvas;- const layer = document.selectedLayerId- ? document.layers.find((entry) => entry.id === document.selectedLayerId)- : undefined;- return isLayerPixelEditEligible(layer);+ return isLeafPixelEditEligible(lookupDocumentLeaf(document, document.selectedLayerId ?? ''));});const onFill = useCallback(() => engine.selection.fillSelection(), [engine]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsxindex cc23a3fe21..cb2cd815c0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx@@ -3,7 +3,7 @@ import type { CanvasLayerSourceContract, ShapeToolOptions } from '@workbench/canimport { createListCollection, HStack, NumberInput, Text } from '@chakra-ui/react';import { ColorPicker, Select, ToggleIconButton } from '@platform/ui';-import { MAX_SHAPE_STROKE_WIDTH } from '@workbench/canvas-engine/api';+import { MAX_SHAPE_STROKE_WIDTH, getDocumentLayer } from '@workbench/canvas-engine/api';import { useShapeOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';@@ -44,9 +44,7 @@ export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {const selected = useActiveProjectSelector((project): SelectedShape | null => {const { document } = project.canvas;- const layer = document.selectedLayerId- ? document.layers.find((entry) => entry.id === document.selectedLayerId)- : undefined;+ const layer = document.selectedLayerId ? getDocumentLayer(document, document.selectedLayerId) : undefined;if (layer && layer.type === 'raster' && layer.source.type === 'shape') {return { id: layer.id, source: layer.source };}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsxindex 7a59c20782..19df521ca3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx@@ -8,6 +8,7 @@ import {MIN_TEXT_FONT_SIZE,TEXT_FONT_FAMILIES,TEXT_FONT_WEIGHTS,+ getDocumentLayer,} from '@workbench/canvas-engine/api';import { useTextEditSession, useTextOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';@@ -96,9 +97,7 @@ export const TextOptions = ({ engine }: ToolOptionsComponentProps) => {const selected = useActiveProjectSelector((project): SelectedText | null => {const { document } = project.canvas;- const layer = document.selectedLayerId- ? document.layers.find((entry) => entry.id === document.selectedLayerId)- : undefined;+ const layer = document.selectedLayerId ? getDocumentLayer(document, document.selectedLayerId) : undefined;if (layer && layer.type === 'raster' && layer.source.type === 'text') {return { id: layer.id, source: layer.source };}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.tsindex 954392fec7..e75135a5c4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts@@ -1,8 +1,9 @@import type { StructuralCommitResult } from '@workbench/canvas-engine/api';import type { TFunction } from 'i18next';-import { createFlatDocumentModel } from '@workbench/canvas-engine/api';-import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';+import { createDocumentModel } from '@workbench/canvas-engine/api';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';import { describe, expect, it, vi } from 'vitest';@@ -38,8 +39,8 @@ describe('reportStructuralCommit', () => {describe('commitPreparedEdit', () => {const layer = createEmptyPaintLayer('Layer', 'a');- const document = { ...createEmptyCanvasDocumentV2(), layers: [layer], selectedLayerId: 'a' };- const model = createFlatDocumentModel(document, { editRevision: 3, projectId: 'p' });+ const document = { ...createEmptyCanvasDocument(), stacks: stacksFrom([layer]), selectedLayerId: 'a' };+ const model = createDocumentModel(document, { editRevision: 3, projectId: 'p' });it('commits a prepared edit through the engine transaction', () => {const commitPrepared = vi.fn(() => ({ status: 'committed' as const }));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.tsindex bc777fc30c..48600a4495 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts@@ -1,9 +1,9 @@import type {CanvasDocumentCapability,CanvasLayerCapability,- FlatCanvasDocumentModel,- FlatDocumentRefusal,- PrepareFlatEditResult,+ CanvasDocumentModel,+ DocumentRefusal,+ PrepareEditResult,StructuralCommitResult,} from '@workbench/canvas-engine/api';import type { TFunction } from 'i18next';@@ -61,14 +61,14 @@ export interface CanvasPreparedEngine {export type PreparedCommitOutcome =| StructuralCommitResult- | { status: 'refused'; refusal: FlatDocumentRefusal }+ | { status: 'refused'; refusal: DocumentRefusal }| { status: 'unchanged' };/** Prepares an edit against the engine's current model and commits it; refusals and no-ops never dispatch. */export const commitPreparedEdit = (engine: CanvasPreparedEngine | null,label: string,- prepare: (model: FlatCanvasDocumentModel) => PrepareFlatEditResult+ prepare: (model: CanvasDocumentModel) => PrepareEditResult): PreparedCommitOutcome => {const model = engine?.document.model() ?? null;if (!engine || !model) {@@ -85,7 +85,7 @@ export const commitPreparedEdit = (}};-const REFUSAL_KEYS: Record<FlatDocumentRefusal['status'], string> = {+const REFUSAL_KEYS: Record<DocumentRefusal['status'], string> = {'invalid-target': 'widgets.canvas.structural.refusedInvalidTarget',locked: 'widgets.canvas.structural.refusedLocked',missing: 'widgets.canvas.structural.refusedMissing',@@ -93,6 +93,17 @@ const REFUSAL_KEYS: Record<FlatDocumentRefusal['status'], string> = {'wrong-type': 'widgets.canvas.structural.refusedWrongType',};+const INVALID_TARGET_KEYS: Partial<Record<Extract<DocumentRefusal, { status: 'invalid-target' }>['reason'], string>> = {+ cycle: 'widgets.canvas.structural.refusedCycle',+ 'depth-exceeded': 'widgets.canvas.structural.refusedDepth',+ 'node-limit': 'widgets.canvas.structural.refusedNodeLimit',+ 'not-siblings': 'widgets.canvas.structural.refusedNotSiblings',+};++const refusalKey = (refusal: DocumentRefusal): string =>+ (refusal.status === 'invalid-target' ? INVALID_TARGET_KEYS[refusal.reason] : undefined) ??+ REFUSAL_KEYS[refusal.status];+export const reportPreparedCommit = (outcome: PreparedCommitOutcome,reportError: (title: string, message: string) => void,@@ -102,7 +113,7 @@ export const reportPreparedCommit = (return;}if (outcome.status === 'refused') {- reportError(t('widgets.canvas.structural.failed'), t(REFUSAL_KEYS[outcome.refusal.status]));+ reportError(t('widgets.canvas.structural.failed'), t(refusalKey(outcome.refusal)));return;}reportStructuralCommit(outcome, reportError, t);@@ -110,7 +121,7 @@ export const reportPreparedCommit = (export type PreparedCommit = (label: string,- prepare: (model: FlatCanvasDocumentModel) => PrepareFlatEditResult+ prepare: (model: CanvasDocumentModel) => PrepareEditResult) => PreparedCommitOutcome;/** A widget-side prepared commit that reports every refusal the user needs to hear about. */diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex d7d9531c70..cb359cafd2 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1,7 +1,7 @@import type { GalleryImageItem, GalleryVideoItem, GeneratedImageContract } from '@features/gallery';import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';-import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/api';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/api';import type {CanvasControlLayerContract,CanvasInpaintMaskLayerContract,@@ -15,12 +15,14 @@ import type { Project, WorkbenchState } from '@workbench/projectContracts';import { GALLERY_RECENT_IMAGE_LIMIT, legacyGeneratedImageToGalleryItem } from '@features/gallery/contracts';import { MAX_PROMPT_HISTORY } from '@features/generation/settings';import { createDefaultUpscaleWidgetValues } from '@features/upscale';+import { getDocumentLeaves } from '@workbench/canvas-engine/api';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { afterEach, describe, expect, it, vi } from 'vitest';import type { CanvasProjectMutation } from './canvasProjectMutations';-import { createEmptyCanvasDocumentV2 } from './canvasMigration';+import { createEmptyCanvasDocument } from './canvasMigration';import { getCanvasStagingCandidateFingerprint, getCanvasStagingSlots } from './canvasStagingView';import { layoutPresets } from './layoutPresets';import { resolveSavedLayoutPreset } from './layoutPresetSnapshots';@@ -74,10 +76,9 @@ const CANVAS_MUTATION_TYPES = new Set<CanvasProjectMutation['type']>(['deleteCanvasSnapshot','discardAllStagedImages','discardSelectedStagedImage',- 'duplicateCanvasLayer','mergeCanvasLayersDown','removeCanvasLayers',- 'reorderCanvasLayerStacks',+ 'reorderCanvasSiblings','replaceCanvasDocument','replaceCanvasLayer','rollbackStagedImageCommit',@@ -125,7 +126,7 @@ const commitSelectedStagedImage = (state: WorkbenchState, projectId = state.actiid: `accepted-${candidate.imageName}`,isEnabled: true,isLocked: false,- name: `Layer ${project.canvas.document.layers.length + 1}`,+ name: `Layer ${getDocumentLeaves(project.canvas.document).length + 1}`,opacity: placement.opacity,source: {image: { height: candidate.height, imageName: candidate.imageName, width: candidate.width },@@ -299,7 +300,7 @@ const getProject = (state: WorkbenchState, projectId: string): Project => {const getActiveProject = (state: WorkbenchState): Project => getProject(state, state.activeProjectId);-type CanvasLayer = Project['canvas']['document']['layers'][number];+type CanvasLayer = CanvasLayerContract;const getRasterLayerImageName = (layer: CanvasLayer | undefined): string | undefined =>layer?.type === 'raster' && layer.source.type === 'image' ? layer.source.image.imageName : undefined;@@ -362,21 +363,26 @@ const createInpaintMaskLayer = (id: string): CanvasLayerContract =>/** Adds layers top-to-bottom in array order (each `addCanvasLayer` inserts at index 0). */// A new project's canvas now seeds one empty inpaint mask (see-// `createNewCanvasStateV2`). These layer-reducer/staging tests exercise layer+// `createNewCanvasState`). These layer-reducer/staging tests exercise layer// mechanics where that default mask is incidental, so they start from an empty// canvas document to keep their expectations focused on the layers under test.const withEmptyCanvas = (state: WorkbenchState): WorkbenchState =>- workbenchReducer(state, { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' });+ workbenchReducer(state, { document: createEmptyCanvasDocument(), type: 'replaceCanvasDocument' });-const withCanvasLayers = (state: WorkbenchState, layers: Project['canvas']['document']['layers']): WorkbenchState =>+const withCanvasLayers = (state: WorkbenchState, layers: readonly CanvasLayerContract[]): WorkbenchState =>workbenchReducer(state, {- document: { ...createEmptyCanvasDocumentV2(), layers: [...layers], selectedLayerId: layers[0]?.id ?? null },+ document: {+ ...createEmptyCanvasDocument(),+ stacks: stacksFrom([...layers]),+ selectedLayerId: layers[0]?.id ?? null,+ },type: 'replaceCanvasDocument',});const getCanvas = (state: WorkbenchState) => getActiveProject(state).canvas;-const getLayerIds = (state: WorkbenchState): string[] => getCanvas(state).document.layers.map((layer) => layer.id);+const getLayerIds = (state: WorkbenchState): string[] =>+ getDocumentLeaves(getCanvas(state).document).map((layer) => layer.id);const withInvocationDestination = (state: WorkbenchState, destination: 'canvas' | 'gallery'): WorkbenchState => ({...state,@@ -1690,7 +1696,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = workbenchReducer(state, { candidate, projectId, type: 'appendCanvasStagingCandidate' });state = commitSelectedStagedImage(state);- const acceptedLayer = getActiveProject(state).canvas.document.layers[0];+ const acceptedLayer = getDocumentLeaves(getActiveProject(state).canvas.document)[0];expect(getRasterLayerImageName(acceptedLayer)).toBe('dimension-changing-result.png');expect(getRasterLayerPlacement(acceptedLayer)).toEqual(candidate.placement);@@ -1717,10 +1723,10 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = commitSelectedStagedImage(state, originProjectId);expect(state.activeProjectId).toBe(activeProjectId);- expect(getRasterLayerImageName(getProject(state, originProjectId).canvas.document.layers[0])).toBe(+ expect(getRasterLayerImageName(getDocumentLeaves(getProject(state, originProjectId).canvas.document)[0])).toBe('origin-result.png');- expect(getProject(state, activeProjectId).canvas.document.layers).not.toContainEqual(+ expect(getDocumentLeaves(getProject(state, activeProjectId).canvas.document)).not.toContainEqual(expect.objectContaining({source: expect.objectContaining({ image: expect.objectContaining({ imageName: 'origin-result.png' }) }),})@@ -1763,10 +1769,10 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = commitSelectedStagedImage(state);let project = getActiveProject(state);- const acceptedLayerId = project.canvas.document.layers[0]?.id;+ const acceptedLayerId = getDocumentLeaves(project.canvas.document)[0]?.id;- expect(project.canvas.document.layers).toHaveLength(1);- expect(getRasterLayerImageName(project.canvas.document.layers[0])).toBe('candidate.png');+ expect(getDocumentLeaves(project.canvas.document)).toHaveLength(1);+ expect(getRasterLayerImageName(getDocumentLeaves(project.canvas.document)[0])).toBe('candidate.png');expect(project.canvas.document.selectedLayerId).toBe(acceptedLayerId);expect(project.canvas.stagingArea.pendingImages).toEqual([]);// Deliberate semantic change (P0.2): canvas is engine-owned, so accepting a@@ -1776,14 +1782,14 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = commitSelectedStagedImage(state);project = getActiveProject(state);- expect(project.canvas.document.layers).toHaveLength(1);+ expect(getDocumentLeaves(project.canvas.document)).toHaveLength(1);// Project undo neither snapshots nor restores canvas: the accepted layer survives.state = workbenchReducer(state, { type: 'undoProjectChange' });project = getActiveProject(state);- expect(project.canvas.document.layers).toHaveLength(1);- expect(getRasterLayerImageName(project.canvas.document.layers[0])).toBe('candidate.png');+ expect(getDocumentLeaves(project.canvas.document)).toHaveLength(1);+ expect(getRasterLayerImageName(getDocumentLeaves(project.canvas.document)[0])).toBe('candidate.png');});it('discards selected and all staged canvas candidates without touching accepted document layers', () => {@@ -1803,7 +1809,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {let project = getActiveProject(state);- expect(project.canvas.document.layers).toEqual([]);+ expect(getDocumentLeaves(project.canvas.document)).toEqual([]);expect(project.canvas.stagingArea.pendingImageIds).toEqual(['candidate-1.png']);expect(project.canvas.stagingArea.selectedImageIndex).toBe(0);expect(project.canvas.stagingArea.isVisible).toBe(true);@@ -1841,7 +1847,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = commitSelectedStagedImage(state);let project = getActiveProject(state);- const acceptedLayer = project.canvas.document.layers[0];+ const acceptedLayer = project.canvas.document.stacks.raster[0] as CanvasLayer | undefined;expect(getRasterLayerImageName(acceptedLayer)).toBe('candidate-2.png');expect(getRasterLayerPlacement(acceptedLayer)).toEqual({ height: 768, opacity: 1, width: 512, x: 0, y: 0 });@@ -1850,7 +1856,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = workbenchReducer(state, { type: 'undoProjectChange' });project = getActiveProject(state);- expect(getRasterLayerImageName(project.canvas.document.layers[0])).toBe('candidate-2.png');+ expect(getRasterLayerImageName(project.canvas.document.stacks.raster[0] as CanvasLayer)).toBe('candidate-2.png');});it('cycles pending canvas placeholder slots before results complete', () => {@@ -2008,7 +2014,9 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = commitSelectedStagedImage(state);- expect(getRasterLayerImageName(getActiveProject(state).canvas.document.layers[0])).toBe('candidate-2.png');+ expect(getRasterLayerImageName(getActiveProject(state).canvas.document.stacks.raster[0] as CanvasLayer)).toBe(+ 'candidate-2.png'+ );});it('discards the selected candidate when placeholders precede it in the staging strip', () => {@@ -4007,16 +4015,16 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'applyCanvasProjectMutation',} as WorkbenchAction);- expect(getProject(state, originProjectId).canvas.document.layers[0]?.opacity).toBe(0.25);- expect(getProject(state, activeProjectId).canvas.document.layers[0]?.opacity).not.toBe(0.25);+ expect(getDocumentLeaves(getProject(state, originProjectId).canvas.document)[0]?.opacity).toBe(0.25);+ expect(getDocumentLeaves(getProject(state, activeProjectId).canvas.document)[0]?.opacity).not.toBe(0.25);});it('seeds a new project canvas with a single empty inpaint mask, selected', () => {const state = createInitialWorkbenchState();const { document } = getActiveProject(state).canvas;- expect(document.layers).toHaveLength(1);- const mask = document.layers[0];+ expect(getDocumentLeaves(document)).toHaveLength(1);+ const mask = getDocumentLeaves(document)[0];expect(mask?.type).toBe('inpaint_mask');// Empty: no bitmap (no strokes) — so it never flips generation-mode detection.expect(mask && 'mask' in mask ? mask.mask.bitmap : 'missing').toBeNull();@@ -4098,7 +4106,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {summary: 'Accepted staged.png into a new raster layer',type: 'canvas-layer-accepted' as const,};- const commit = (anchor: FlatLayerInsertionAnchor) =>+ const commit = (anchor: CanvasNodeInsertionAnchor) =>workbenchReducer(state, {anchor,candidateFingerprint: getCanvasStagingCandidateFingerprint(candidate),@@ -4171,7 +4179,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {],});- const layers = getCanvas(state).document.layers;+ const layers = getDocumentLeaves(getCanvas(state).document);const mask = layers.find((layer) => layer.id === 'm')!;const raster = layers.find((layer) => layer.id === 'r')!;@@ -4200,7 +4208,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {createRasterLayer('b'),createRasterLayer('c'),]);- const before = getCanvas(state).document.layers;+ const before = getDocumentLeaves(getCanvas(state).document);// Hide 'a' and 'c' in one dispatch; 'b' is unlisted and must keep its object identity.state = workbenchReducer(state, {@@ -4210,7 +4218,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {{ id: 'c', isEnabled: false },],});- const after = getCanvas(state).document.layers;+ const after = getDocumentLeaves(getCanvas(state).document);expect(after.map((layer) => [layer.id, layer.isEnabled])).toEqual([['a', false],@@ -4228,7 +4236,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {createRasterLayer('b'),createRasterLayer('c'),]);- const before = getCanvas(state).document.layers;+ const before = getDocumentLeaves(getCanvas(state).document);state = workbenchReducer(state, {enabledUpdates: [],@@ -4240,7 +4248,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'applyCanvasLayerStackMutation',});- const after = getCanvas(state).document.layers;+ const after = getDocumentLeaves(getCanvas(state).document);expect(after.map((layer) => [layer.id, layer.isLocked])).toEqual([['a', true],['b', false],@@ -4269,7 +4277,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {});expect(getCanvas(state).document.selectedLayerId).toBe('c');- expect(getCanvas(state).document.layers[0]?.isLocked).toBe(false);+ expect(getDocumentLeaves(getCanvas(state).document)[0]?.isLocked).toBe(false);});it('repairs an omitted stack-mutation selection to the nearest same-stack neighbour', () => {@@ -4287,7 +4295,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'applyCanvasLayerStackMutation',});- expect(getLayerIds(state)).toEqual(['a', 'b', 'c']);+ expect(getLayerIds(state)).toEqual(['c', 'a', 'b']);expect(getCanvas(state).document.selectedLayerId).toBe('b');});@@ -4302,7 +4310,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'applyCanvasLayerStackMutation',});- expect(getCanvas(state).document.layers[0]?.isLocked).toBe(true);+ expect(getDocumentLeaves(getCanvas(state).document)[0]?.isLocked).toBe(true);expect(getCanvas(state).document.selectedLayerId).toBeNull();});@@ -4312,8 +4320,8 @@ describe('workbenchReducer canvas v2 layer reducers', () => {const projectId = initial.activeProjectId;const removed = workbenchReducer(initial, {add: [- { anchor: { ...stackTopAnchor(projectId), beforeId: 'b' }, layers: [layers[0]!] },- { anchor: { ...stackTopAnchor(projectId), afterId: 'b' }, layers: [layers[2]!] },+ { anchor: { ...stackTopAnchor(projectId), beforeId: 'b' }, nodes: [layers[0]!] },+ { anchor: { ...stackTopAnchor(projectId), afterId: 'b' }, nodes: [layers[2]!] },],enabledUpdates: [],selectedLayerId: 'c',@@ -4332,7 +4340,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'setCanvasSelectedLayer',});const merged = workbenchReducer(initial, {- add: [{ anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: 'a' }, layers: [result] }],+ add: [{ anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: 'a' }, nodes: [result] }],enabledUpdates: [],removeIds: ['a', 'c'],selectedLayerId: 'result',@@ -4344,15 +4352,15 @@ describe('workbenchReducer canvas v2 layer reducers', () => {const restored = workbenchReducer(merged, {add: [- { anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: 'b' }, layers: [layers[0]!] },- { anchor: { ...stackTopAnchor(initial.activeProjectId), afterId: 'b' }, layers: [layers[2]!] },+ { anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: 'b' }, nodes: [layers[0]!] },+ { anchor: { ...stackTopAnchor(initial.activeProjectId), afterId: 'b' }, nodes: [layers[2]!] },],enabledUpdates: [],removeIds: ['result'],selectedLayerId: 'c',type: 'applyCanvasLayerStackMutation',});- expect(getCanvas(restored).document.layers).toEqual(layers);+ expect(getDocumentLeaves(getCanvas(restored).document)).toEqual(layers);expect(getCanvas(restored).document.selectedLayerId).toBe('c');});@@ -4365,7 +4373,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {{ id: 'b', x: 13, y: 18 },],});- expect(getCanvas(moved).document.layers.map((layer) => layer.transform)).toMatchObject([+ expect(getDocumentLeaves(getCanvas(moved).document).map((layer) => layer.transform)).toMatchObject([{ x: 3, y: -2 },{ x: 13, y: 18 },]);@@ -4399,10 +4407,10 @@ describe('workbenchReducer canvas v2 layer reducers', () => {id: unrelated.id,type: 'setCanvasSelectedLayer',});- const unrelatedBefore = getCanvas(initial).document.layers[0];+ const unrelatedBefore = getDocumentLeaves(getCanvas(initial).document)[0];const applied = workbenchReducer(initial, {- add: [{ anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: upper.id }, layers: [result] }],+ add: [{ anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: upper.id }, nodes: [result] }],enabledUpdates: [{ id: upper.id, isEnabled: false },{ id: below.id, isEnabled: false },@@ -4412,14 +4420,14 @@ describe('workbenchReducer canvas v2 layer reducers', () => {});expect(applied).toBeDefined();- expect(getCanvas(applied).document.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ expect(getDocumentLeaves(getCanvas(applied).document).map((layer) => [layer.id, layer.isEnabled])).toEqual([['unrelated', false],['result', true],['upper', false],['below', false],]);expect(getCanvas(applied).document.selectedLayerId).toBe(result.id);- expect(getCanvas(applied).document.layers[0]).toBe(unrelatedBefore);+ expect(getDocumentLeaves(getCanvas(applied).document)[0]).toBe(unrelatedBefore);const reverted = workbenchReducer(applied, {enabledUpdates: [@@ -4431,13 +4439,13 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'applyCanvasLayerStackMutation',});- expect(getCanvas(reverted).document.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ expect(getDocumentLeaves(getCanvas(reverted).document).map((layer) => [layer.id, layer.isEnabled])).toEqual([['unrelated', false],['upper', true],['below', true],]);expect(getCanvas(reverted).document.selectedLayerId).toBe(unrelated.id);- expect(getCanvas(reverted).document.layers[0]).toBe(unrelatedBefore);+ expect(getDocumentLeaves(getCanvas(reverted).document)[0]).toBe(unrelatedBefore);});it('inserts a batch in order and selects the exact requested layer', () => {@@ -4447,13 +4455,13 @@ describe('workbenchReducer canvas v2 layer reducers', () => {const initial = withCanvasLayers(createInitialWorkbenchState(), [existing]);const next = workbenchReducer(initial, {- add: [{ anchor: stackTopAnchor(initial.activeProjectId), layers: [layerA, layerB] }],+ add: [{ anchor: stackTopAnchor(initial.activeProjectId), nodes: [layerA, layerB] }],enabledUpdates: [],selectedLayerId: layerB.id,type: 'applyCanvasLayerStackMutation',});- expect(getCanvas(next).document.layers).toEqual([layerA, layerB, existing]);+ expect(getDocumentLeaves(getCanvas(next).document)).toEqual([layerA, layerB, existing]);expect(getCanvas(next).document.selectedLayerId).toBe(layerB.id);});@@ -4467,14 +4475,14 @@ describe('workbenchReducer canvas v2 layer reducers', () => {const layerB = createRasterLayer('b');const next = workbenchReducer(state, {- add: [{ anchor: stackTopAnchor(firstProjectId), layers: [layerA, layerB] }],+ add: [{ anchor: stackTopAnchor(firstProjectId), nodes: [layerA, layerB] }],enabledUpdates: [],projectId: firstProjectId,selectedLayerId: layerB.id,type: 'applyCanvasLayerStackMutation',});- expect(getProject(next, firstProjectId).canvas.document.layers.slice(0, 2)).toEqual([layerA, layerB]);+ expect(getDocumentLeaves(getProject(next, firstProjectId).canvas.document).slice(0, 2)).toEqual([layerA, layerB]);expect(getProject(next, firstProjectId).canvas.document.selectedLayerId).toBe(layerB.id);expect(getProject(next, secondProjectId)).toBe(secondProjectBefore);});@@ -4486,19 +4494,19 @@ describe('workbenchReducer canvas v2 layer reducers', () => {);const invalidActions = [{- add: [{ anchor: stackTopAnchor(initial.activeProjectId), layers: [createRasterLayer('a')] }],+ add: [{ anchor: stackTopAnchor(initial.activeProjectId), nodes: [createRasterLayer('a')] }],enabledUpdates: [{ id: 'b', isEnabled: false }],selectedLayerId: 'b',type: 'applyCanvasLayerStackMutation',},{- add: [{ anchor: stackTopAnchor('other-project'), layers: [createRasterLayer('c')] }],+ add: [{ anchor: stackTopAnchor('other-project'), nodes: [createRasterLayer('c')] }],enabledUpdates: [{ id: 'b', isEnabled: false }],selectedLayerId: 'c',type: 'applyCanvasLayerStackMutation',},{- add: [{ anchor: stackTopAnchor(initial.activeProjectId, 'control'), layers: [createRasterLayer('c')] }],+ add: [{ anchor: stackTopAnchor(initial.activeProjectId, 'control'), nodes: [createRasterLayer('c')] }],enabledUpdates: [{ id: 'b', isEnabled: false }],selectedLayerId: 'c',type: 'applyCanvasLayerStackMutation',@@ -4526,7 +4534,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'applyCanvasLayerStackMutation',},{- add: [{ anchor: stackTopAnchor(initial.activeProjectId), layers: [createRasterLayer('a')] }],+ add: [{ anchor: stackTopAnchor(initial.activeProjectId), nodes: [createRasterLayer('a')] }],enabledUpdates: [],removeIds: ['a'],selectedLayerId: 'b',@@ -4534,7 +4542,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {},{add: [- { anchor: stackTopAnchor(initial.activeProjectId), layers: [createRasterLayer('c'), createRasterLayer('c')] },+ { anchor: stackTopAnchor(initial.activeProjectId), nodes: [createRasterLayer('c'), createRasterLayer('c')] },],enabledUpdates: [{ id: 'b', isEnabled: false }],selectedLayerId: 'c',@@ -4549,7 +4557,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {it('preserves the layers array for a selection-only layer stack mutation', () => {const initial = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);- const before = getCanvas(initial).document.layers;+ const before = getDocumentLeaves(getCanvas(initial).document);const next = workbenchReducer(initial, {enabledUpdates: [],@@ -4557,53 +4565,38 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'applyCanvasLayerStackMutation',});- expect(getCanvas(next).document.layers).toBe(before);+ expect(getDocumentLeaves(getCanvas(next).document)).toBe(before);expect(getCanvas(next).document.selectedLayerId).toBe('b');});- it('duplicates a layer above its source with a copy name and selects the duplicate', () => {- let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);-- state = workbenchReducer(state, { newId: 'b-copy', sourceId: 'b', type: 'duplicateCanvasLayer' });-- expect(getLayerIds(state)).toEqual(['a', 'b-copy', 'b']);- expect(getCanvas(state).document.selectedLayerId).toBe('b-copy');-- const [, duplicate, source] = getCanvas(state).document.layers;-- expect(duplicate?.name).toBe('b copy');- expect(duplicate).not.toBe(source);- expect(getRasterLayerImageName(duplicate)).toBe(getRasterLayerImageName(source));- });-it('reorders layers only when the id set matches, and preserves layer identity', () => {const state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'),createRasterLayer('b'),createRasterLayer('c'),]);- const originalLayerA = getCanvas(state).document.layers.find((layer) => layer.id === 'a');+ const originalLayerA = getDocumentLeaves(getCanvas(state).document).find((layer) => layer.id === 'a');const reordered = workbenchReducer(state, {- stacks: [{ orderedIds: ['c', 'a', 'b'], stack: 'raster' }],- type: 'reorderCanvasLayerStacks',+ orders: [{ orderedIds: ['c', 'a', 'b'], parentId: null, stack: 'raster' }],+ type: 'reorderCanvasSiblings',});expect(getLayerIds(reordered)).toEqual(['c', 'a', 'b']);// Untouched layer objects are reused, not cloned.- expect(getCanvas(reordered).document.layers.find((layer) => layer.id === 'a')).toBe(originalLayerA);+ expect(getDocumentLeaves(getCanvas(reordered).document).find((layer) => layer.id === 'a')).toBe(originalLayerA);const ignoredMissing = workbenchReducer(state, {- stacks: [{ orderedIds: ['c', 'a'], stack: 'raster' }],- type: 'reorderCanvasLayerStacks',+ orders: [{ orderedIds: ['c', 'a'], parentId: null, stack: 'raster' }],+ type: 'reorderCanvasSiblings',});const ignoredUnknown = workbenchReducer(state, {- stacks: [{ orderedIds: ['c', 'a', 'z'], stack: 'raster' }],- type: 'reorderCanvasLayerStacks',+ orders: [{ orderedIds: ['c', 'a', 'z'], parentId: null, stack: 'raster' }],+ type: 'reorderCanvasSiblings',});const ignoredWrongStack = workbenchReducer(state, {- stacks: [{ orderedIds: ['c', 'a', 'b'], stack: 'control' }],- type: 'reorderCanvasLayerStacks',+ orders: [{ orderedIds: ['c', 'a', 'b'], parentId: null, stack: 'control' }],+ type: 'reorderCanvasSiblings',});expect(getLayerIds(ignoredMissing)).toEqual(['a', 'b', 'c']);@@ -4620,42 +4613,42 @@ describe('workbenchReducer canvas v2 layer reducers', () => {]);const reordered = workbenchReducer(state, {- stacks: [- { orderedIds: ['b', 'a'], stack: 'raster' },- { orderedIds: ['y', 'x'], stack: 'control' },+ orders: [+ { orderedIds: ['b', 'a'], parentId: null, stack: 'raster' },+ { orderedIds: ['y', 'x'], parentId: null, stack: 'control' },],- type: 'reorderCanvasLayerStacks',+ type: 'reorderCanvasSiblings',});- expect(getLayerIds(reordered)).toEqual(['b', 'y', 'a', 'x']);+ expect(getLayerIds(reordered)).toEqual(['y', 'x', 'b', 'a']);const refused = workbenchReducer(state, {- stacks: [- { orderedIds: ['b', 'a'], stack: 'raster' },- { orderedIds: ['a', 'b'], stack: 'raster' },+ orders: [+ { orderedIds: ['b', 'a'], parentId: null, stack: 'raster' },+ { orderedIds: ['a', 'b'], parentId: null, stack: 'raster' },],- type: 'reorderCanvasLayerStacks',+ type: 'reorderCanvasSiblings',});expect(refused).toBe(state);const partiallyInvalid = workbenchReducer(state, {- stacks: [- { orderedIds: ['b', 'a'], stack: 'raster' },- { orderedIds: ['y'], stack: 'control' },+ orders: [+ { orderedIds: ['b', 'a'], parentId: null, stack: 'raster' },+ { orderedIds: ['y'], parentId: null, stack: 'control' },],- type: 'reorderCanvasLayerStacks',+ type: 'reorderCanvasSiblings',});expect(partiallyInvalid).toBe(state);const unchanged = workbenchReducer(state, {- stacks: [{ orderedIds: ['a', 'b'], stack: 'raster' }],- type: 'reorderCanvasLayerStacks',+ orders: [{ orderedIds: ['a', 'b'], parentId: null, stack: 'raster' }],+ type: 'reorderCanvasSiblings',});expect(unchanged).toBe(state);});it('updates base props with a field-wise transform merge and leaves other layers untouched', () => {const state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);- const originalLayerB = getCanvas(state).document.layers.find((layer) => layer.id === 'b');+ const originalLayerB = getDocumentLeaves(getCanvas(state).document).find((layer) => layer.id === 'b');const updated = workbenchReducer(state, {id: 'a',@@ -4663,15 +4656,15 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'updateCanvasLayer',});- const layerA = getCanvas(updated).document.layers.find((layer) => layer.id === 'a');+ const layerA = getDocumentLeaves(getCanvas(updated).document).find((layer) => layer.id === 'a');expect(layerA?.name).toBe('Renamed');expect(layerA?.opacity).toBe(0.5);expect(layerA?.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 12, y: 0 });- expect(getCanvas(updated).document.layers.find((layer) => layer.id === 'b')).toBe(originalLayerB);+ expect(getDocumentLeaves(getCanvas(updated).document).find((layer) => layer.id === 'b')).toBe(originalLayerB);});- it('replaces one complete layer contract in place and no-ops when the id is missing', () => {+ it('replaces a leaf, moving it to the top of its new stack when the type changes, and no-ops when the id is missing', () => {const state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'),createRasterLayer('b'),@@ -4708,13 +4701,13 @@ describe('workbenchReducer canvas v2 layer reducers', () => {layerId: 'b',type: 'replaceCanvasLayer',});- const afterLayers = getCanvas(replaced).document.layers;+ const afterLayers = getDocumentLeaves(getCanvas(replaced).document);- expect(afterLayers.map((layer) => layer.id)).toEqual(['a', 'b', 'c']);- expect(afterLayers[1]).toBe(replacement);- expect(afterLayers[1]).toEqual(replacement);- expect(afterLayers[0]).toBe(beforeDocument.layers[0]);- expect(afterLayers[2]).toBe(beforeDocument.layers[2]);+ expect(afterLayers.map((layer) => layer.id)).toEqual(['b', 'a', 'c']);+ expect(afterLayers[0]).toBe(replacement);+ expect(getCanvas(replaced).document.stacks.control).toEqual([replacement]);+ expect(afterLayers[1]).toBe(getDocumentLeaves(beforeDocument)[0]);+ expect(afterLayers[2]).toBe(getDocumentLeaves(beforeDocument)[2]);const missing = workbenchReducer(replaced, {layer: replacement,@@ -4731,7 +4724,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {state = workbenchReducer(state, { id: 'a', source: newSource, type: 'updateCanvasLayerSource' });- expect(getRasterLayerImageName(getCanvas(state).document.layers[0])).toBe('swapped.png');+ expect(getRasterLayerImageName(getDocumentLeaves(getCanvas(state).document)[0])).toBe('swapped.png');});it('applies per-type config patches and ignores mismatched layer types', () => {@@ -4743,7 +4736,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'updateCanvasLayerConfig',});- const controlLayer = getCanvas(state).document.layers[0];+ const controlLayer = getDocumentLeaves(getCanvas(state).document)[0];expect(controlLayer?.type).toBe('control');@@ -4760,7 +4753,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'updateCanvasLayerConfig',});- expect(getCanvas(unchanged).document.layers[0]).toBe(controlLayer);+ expect(getDocumentLeaves(getCanvas(unchanged).document)[0]).toBe(controlLayer);});it('persists filter settings on raster layers', () => {@@ -4772,7 +4765,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'updateCanvasLayerConfig',});- const raster = getCanvas(state).document.layers[0];+ const raster = getDocumentLeaves(getCanvas(state).document)[0];expect(raster?.type).toBe('raster');if (raster?.type === 'raster') {expect(raster.filter).toEqual({ settings: { radius: 4 }, type: 'content_shuffle' });@@ -4793,7 +4786,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'updateCanvasLayerConfig',});- const layer = getCanvas(state).document.layers[0];+ const layer = getDocumentLeaves(getCanvas(state).document)[0];expect(layer?.type).toBe('inpaint_mask');if (layer?.type === 'inpaint_mask') {// Bitmap + content offset persisted; the fill is preserved (merged, not replaced).@@ -4810,7 +4803,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {id: 'm',type: 'updateCanvasLayerConfig',});- const after = getCanvas(recolored).document.layers[0];+ const after = getDocumentLeaves(getCanvas(recolored).document)[0];if (after?.type === 'inpaint_mask') {expect(after.mask.fill).toEqual({ color: '#00ff00', style: 'grid' });expect(after.mask.bitmap).toMatchObject({ imageName: 'mask.png' });@@ -4847,8 +4840,8 @@ describe('workbenchReducer canvas v2 layer reducers', () => {type: 'updateCanvasLayerConfig',});- const mask = getCanvas(state).document.layers[0];- const control = getCanvas(state).document.layers[1];+ const mask = getDocumentLeaves(getCanvas(state).document)[0];+ const control = getDocumentLeaves(getCanvas(state).document)[1];expect(mask?.type).toBe('inpaint_mask');if (mask?.type === 'inpaint_mask') {@@ -4861,29 +4854,36 @@ describe('workbenchReducer canvas v2 layer reducers', () => {}});- it('converts a layer in place, preserving its id and z-order', () => {+ it('converts a layer into its new stack, preserving its id', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);const converted = createControlLayer('ignored-id');state = workbenchReducer(state, { id: 'b', layer: converted, targetType: 'control', type: 'convertCanvasLayer' });- expect(getLayerIds(state)).toEqual(['a', 'b']);- expect(getCanvas(state).document.layers[1]?.type).toBe('control');- expect(getCanvas(state).document.layers[1]?.id).toBe('b');+ expect(getLayerIds(state)).toEqual(['b', 'a']);+ expect(getCanvas(state).document.stacks.raster.map((node) => node.id)).toEqual(['a']);+ expect(getDocumentLeaves(getCanvas(state).document)[0]?.type).toBe('control');+ expect(getDocumentLeaves(getCanvas(state).document)[0]?.id).toBe('b');});- it('merges a layer down: the layer below becomes a raster with the merged paint source', () => {- let state = withCanvasLayers(createInitialWorkbenchState(), [+ it('merges a layer down into the raster sibling below and refuses when no raster sibling is below', () => {+ const mergedSource = { bitmap: { height: 8, imageName: 'merged.png', width: 8 }, type: 'paint' } as const;+ const withControl = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('top'),createControlLayer('bottom'),]);+ expect(+ workbenchReducer(withControl, { source: mergedSource, type: 'mergeCanvasLayersDown', upperLayerId: 'top' })+ ).toBe(withControl);+ let state = withCanvasLayers(createInitialWorkbenchState(), [+ createRasterLayer('top'),+ createRasterLayer('bottom'),+ ]);state = workbenchReducer(state, { id: 'bottom', type: 'setCanvasSelectedLayer' });- const mergedSource = { bitmap: { height: 8, imageName: 'merged.png', width: 8 }, type: 'paint' } as const;-state = workbenchReducer(state, { source: mergedSource, type: 'mergeCanvasLayersDown', upperLayerId: 'top' });- const layers = getCanvas(state).document.layers;+ const layers = getDocumentLeaves(getCanvas(state).document);expect(getLayerIds(state)).toEqual(['bottom']);expect(layers[0]?.type).toBe('raster');@@ -4923,8 +4923,8 @@ describe('workbenchReducer canvas v2 layer reducers', () => {expect(document.width).toBe(300);expect(document.height).toBe(256);- expect(document.layers[0]?.transform.x).toBe(20);- expect(document.layers[0]?.transform.y).toBe(10);+ expect(getDocumentLeaves(document)[0]?.transform.x).toBe(20);+ expect(getDocumentLeaves(document)[0]?.transform.y).toBe(10);expect(document.bbox.x + document.bbox.width).toBeLessThanOrEqual(300);expect(document.bbox.y + document.bbox.height).toBeLessThanOrEqual(256);});@@ -4932,8 +4932,8 @@ describe('workbenchReducer canvas v2 layer reducers', () => {it('replaces the whole document with a deep copy', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);const replacement = {- ...createEmptyCanvasDocumentV2(),- layers: [createRasterLayer('fresh')],+ ...createEmptyCanvasDocument(),+ stacks: stacksFrom([createRasterLayer('fresh')]),selectedLayerId: 'fresh',};@@ -4941,13 +4941,13 @@ describe('workbenchReducer canvas v2 layer reducers', () => {expect(getLayerIds(state)).toEqual(['fresh']);expect(getCanvas(state).document).not.toBe(replacement);- expect(getCanvas(state).document.layers[0]).not.toBe(replacement.layers[0]);+ expect(getDocumentLeaves(getCanvas(state).document)[0]).not.toBe(getDocumentLeaves(replacement)[0]);});it('canonicalizes whole-pixel geometry across document replacement and snapshots', () => {let state = createInitialWorkbenchState();const fractional = {- ...createEmptyCanvasDocumentV2(),+ ...createEmptyCanvasDocument(),bbox: { height: 99.6, width: 100.4, x: 1.2, y: -2.6 },height: 511.6,width: 512.4,@@ -5000,7 +5000,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {),};- state = workbenchReducer(state, { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' });+ state = workbenchReducer(state, { document: createEmptyCanvasDocument(), type: 'replaceCanvasDocument' });const { stagingArea } = getCanvas(state);expect(stagingArea.pendingImages).toEqual([]);@@ -5012,8 +5012,8 @@ describe('workbenchReducer canvas v2 layer reducers', () => {it('repairs a dangling selectedLayerId on replaceCanvasDocument (falls back to the top layer)', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);const replacement = {- ...createEmptyCanvasDocumentV2(),- layers: [createRasterLayer('top'), createRasterLayer('bottom')],+ ...createEmptyCanvasDocument(),+ stacks: stacksFrom([createRasterLayer('top'), createRasterLayer('bottom')]),selectedLayerId: 'ghost', // names no layer in the incoming document};@@ -5024,7 +5024,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {it('nulls a dangling selectedLayerId when the replacement document has no layers', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);- const replacement = { ...createEmptyCanvasDocumentV2(), layers: [], selectedLayerId: 'ghost' };+ const replacement = { ...createEmptyCanvasDocument(), stacks: stacksFrom([]), selectedLayerId: 'ghost' };state = workbenchReducer(state, { document: replacement, type: 'replaceCanvasDocument' });@@ -5034,8 +5034,8 @@ describe('workbenchReducer canvas v2 layer reducers', () => {it('preserves a valid selectedLayerId on replaceCanvasDocument', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);const replacement = {- ...createEmptyCanvasDocumentV2(),- layers: [createRasterLayer('top'), createRasterLayer('bottom')],+ ...createEmptyCanvasDocument(),+ stacks: stacksFrom([createRasterLayer('top'), createRasterLayer('bottom')]),selectedLayerId: 'bottom',};@@ -5057,13 +5057,13 @@ describe('workbenchReducer canvas v2 layer reducers', () => {const restored = getCanvas(state).document;expect(restored.selectedLayerId).not.toBe('ghost');- expect(restored.selectedLayerId).toBe(restored.layers[0]?.id);+ expect(restored.selectedLayerId).toBe(getDocumentLeaves(restored)[0]?.id);});it('normalizes a control adapter when restoring a saved canvas snapshot', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createControlLayer('ctrl')]);state = workbenchReducer(state, { createdAt: 'now', id: 'snap-1', name: 'First', type: 'saveCanvasSnapshot' });- const snapshotLayer = getCanvas(state).snapshots[0]!.document.layers[0];+ const snapshotLayer = getDocumentLeaves(getCanvas(state).snapshots[0]!.document)[0];if (snapshotLayer?.type !== 'control') {throw new Error('expected a control layer');}@@ -5077,7 +5077,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'restoreCanvasSnapshot' });- const restored = getCanvas(state).document.layers[0];+ const restored = getDocumentLeaves(getCanvas(state).document)[0];expect(restored?.type === 'control' ? restored.adapter : null).toEqual({beginEndStepPct: [0, 1],controlMode: null,@@ -5093,7 +5093,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {state = workbenchReducer(state, { createdAt: 'now', id: 'snap-1', name: 'First', type: 'saveCanvasSnapshot' });expect(getCanvas(state).snapshots).toHaveLength(1);- expect(getCanvas(state).snapshots[0]?.document.layers.map((layer) => layer.id)).toEqual(['a']);+ expect(getDocumentLeaves(getCanvas(state).snapshots[0]?.document).map((layer) => layer.id)).toEqual(['a']);// Mutate the live document, then restore the snapshot back over it.state = workbenchReducer(state, {@@ -5126,7 +5126,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {expect(getCanvas(state).documentRevision).toBe(initialRevision);// replaceCanvasDocument is a wholesale swap: bump.- state = workbenchReducer(state, { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' });+ state = workbenchReducer(state, { document: createEmptyCanvasDocument(), type: 'replaceCanvasDocument' });expect(getCanvas(state).documentRevision).toBe(initialRevision + 1);// restoreCanvasSnapshot is a wholesale swap: bump — even though the restored@@ -5468,7 +5468,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =// The user confirms a new canvas while the generation is still in flight: a// wholesale swap that clears staging and bumps documentRevision (new session).const swapped = workbenchReducer(submitted, {- document: createEmptyCanvasDocumentV2(),+ document: createEmptyCanvasDocument(),type: 'replaceCanvasDocument',});@@ -5802,7 +5802,7 @@ describe('auto invocation route switching', () => {state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });state = workbenchReducer(state, {- add: [{ anchor: { ...stackTopAnchor(state.activeProjectId), afterId: 'a' }, layers: [createRasterLayer('b')] }],+ add: [{ anchor: { ...stackTopAnchor(state.activeProjectId), afterId: 'a' }, nodes: [createRasterLayer('b')] }],enabledUpdates: [],selectedLayerId: 'b',type: 'applyCanvasLayerStackMutation',diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 4239e6f253..2f0b89ff60 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -3,9 +3,9 @@ import type { ModelConfig } from '@features/models';import type { QueueCompiledSubmission, QueueHistoryItemStatus } from '@features/queue/contracts';import type { ProjectGraphState } from '@features/workflow/contracts';import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasPlacementContract,- CanvasStateContractV2,+ CanvasStateContractV3,CanvasStagingCandidateContract,} from '@workbench/canvas-engine/api';import type { DeveloperLogNamespace } from '@workbench/diagnostics/contracts';@@ -84,7 +84,7 @@ import {type CanvasEditIntent,type WorkbenchActionOrigin,} from './autoRoutePolicy';-import { createNewCanvasStateV2, loadCanvasState } from './canvasMigration';+import { createNewCanvasState, loadCanvasState } from './canvasMigration';import { applyCanvasProjectMutation, type CanvasProjectMutation } from './canvasProjectMutations';import { gateProjectCanvases } from './projectCanvasGate';import { getProjectWidgetValues } from './widgetState';@@ -363,7 +363,7 @@ type WorkbenchReducerAction =| {type: 'submitCanvasInvocationSnapshot';backendSupportsCancellation: boolean;- canvas: CanvasStateContractV2;+ canvas: CanvasStateContractV3;destination: ResultDestination;generate: QueueGenerateSnapshot;graph: GraphContract;@@ -633,7 +633,7 @@ const clonePlacement = (placement: CanvasPlacementContract): CanvasPlacementContconst createCenteredPlacement = (image: Pick<GeneratedImageContract, 'height' | 'width'>,- document: Pick<CanvasDocumentContractV2, 'height' | 'width'>+ document: Pick<CanvasDocumentContractV3, 'height' | 'width'>): CanvasPlacementContract => {const imageWidth = image.width > 0 ? image.width : document.width;const imageHeight = image.height > 0 ? image.height : document.height;@@ -652,7 +652,7 @@ const createCenteredPlacement = (const normalizeStagingCandidate = (image: CanvasStagingCandidateContract | GeneratedImageContract,- document: Pick<CanvasDocumentContractV2, 'height' | 'width'>,+ document: Pick<CanvasDocumentContractV3, 'height' | 'width'>,sourceBackendItemId?: number): CanvasStagingCandidateContract => ({...image,@@ -689,9 +689,9 @@ const getCanvasStagingSlotCountWithPendingImages = ();const getCanvasWithPendingImages = (- canvas: CanvasStateContractV2,+ canvas: CanvasStateContractV3,pendingImages: CanvasStagingCandidateContract[]-): CanvasStateContractV2 => ({+): CanvasStateContractV3 => ({...canvas,stagingArea: {...canvas.stagingArea,@@ -952,11 +952,11 @@ const getGalleryItemFromPersistedValue = (values: Record<string, unknown>, value* migration boundary: callers with genuinely unknown/legacy input must run* `loadCanvasState` first (see `normalizeWorkbenchProject`).*/-const cloneCanvas = (canvas: CanvasStateContractV2): CanvasStateContractV2 => {+const cloneCanvas = (canvas: CanvasStateContractV3): CanvasStateContractV3 => {const document = structuredClone(canvas.document);return {- version: 2,+ version: 3,document,documentRevision: canvas.documentRevision,snapshots: canvas.snapshots.map((snapshot) => ({ ...snapshot, document: structuredClone(snapshot.document) })),@@ -1703,7 +1703,7 @@ export const normalizeWorkbenchProject = (project: Project): Project => {return assembleWorkbenchProject(project, cloneCanvas(canvas.status === 'loaded' ? canvas.value : project.canvas));};-const assembleWorkbenchProject = (project: Project, canvas: CanvasStateContractV2): Project => {+const assembleWorkbenchProject = (project: Project, canvas: CanvasStateContractV3): Project => {const legacyWidgetRegions = project.widgetRegions as| Partial<Record<WidgetRegion | 'left-panel' | 'right-panel' | 'status-bar', WidgetRegionState>>| undefined;@@ -1848,7 +1848,7 @@ export const clampPanelSize = (region: WidgetRegion, sizePx: number): number =>return Math.min(max, Math.max(min, sizePx));};-const createCanvasState = (): CanvasStateContractV2 => createNewCanvasStateV2();+const createCanvasState = (): CanvasStateContractV3 => createNewCanvasState();const createProject = (index: number, id: string, preset: LayoutPreset): Project =>applyLayoutPresetToProject(@@ -2992,7 +2992,7 @@ const enqueueCompiledSnapshot = (widgetStates: WidgetStateMap;},backendSupportsCancellation: boolean,- canvasSnapshot?: CanvasStateContractV2+ canvasSnapshot?: CanvasStateContractV3): Project => {const submittedAt = now();const queueItemId = createId('queue-item');