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): consume the document model from rendering, planning and export
Josh Corbettdb08b4973b48
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 9825272cef..57bc72a0c9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -588,7 +588,6 @@ export {LAYER_STACK_ORDER,LAYER_STACKS_TOP_FIRST,layerStackOf,- layerStackRank,moveLayersWithinStacks,reorderLayerStack,type LayerStackKind,@@ -615,7 +614,11 @@ export {type PreparedFlatEdit,type PrepareFlatEditResult,} from './document-model/flatDocumentCommands';-export { createFlatDocumentModel, type FlatCanvasDocumentModel } from './document-model/flatDocumentModel';+export {+ createFlatDocumentModel,+ type FlatCanvasDocumentModel,+ mergeDownEligibility,+} from './document-model/flatDocumentModel';export { checkFlatEditPostconditions, type FlatEditPostcondition } from './document-model/postconditions';export {planScreenComposition,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex 5bca34efbe..d959d71c11 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@ -5,8 +5,8 @@ import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCacheimport 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 { isMergeableRasterLayer } from '@workbench/canvas-engine/document/layerEligibility';import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';import { canMergeSelectedRasters, getMergeVisibleRasterLayers } from '@workbench/canvas-engine/document/mergeVisible';@@ -51,12 +51,12 @@ export class MergeLayerController {if (!document) {return false;}- 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 || !isMergeableRasterLayer(upper) || !isMergeableRasterLayer(below)) {+ const eligibility = mergeDownEligibility(document, upperLayerId);+ if (eligibility.status !== 'eligible') {return false;}+ const upper = lookupDocumentLayer(document, eligibility.upperId)!;+ const below = lookupDocumentLayer(document, eligibility.lowerId)!;const upperCache = this.deps.layers.get(upper.id);const belowCache = this.deps.layers.get(below.id);const upperHasContent = this.deps.hasExportableContent(upper.id);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.tsindex bf06d0211e..6038067ef3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts@@ -1,5 +1,4 @@import type { CanvasDocumentSnapshot, PsdExportResult } from '@workbench/canvas-engine/capabilities';-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type {CanvasDetachedLayerSurface,CaptureRasterSnapshotResult,@@ -13,6 +12,7 @@ import {type PsdExportLayerInput,type PsdExportPlan,} from '@workbench/canvas-engine/export/psdExport';+import { isExportableRasterLayer } from '@workbench/canvas-engine/layerExportGuards';type RasterMemoryReservationResult =| { status: 'ok'; lease: { release(): void } }@@ -32,23 +32,6 @@ export interface PsdExportControllerOptions {readonly reserve: (bytes: number) => RasterMemoryReservationResult;}-const isExportable = (layer: CanvasLayerContract): boolean => {- if (layer.type !== 'raster') {- return false;- }- switch (layer.source.type) {- case 'paint':- case 'image':- case 'gradient':- case 'text':- return true;- case 'shape':- return layer.source.kind !== 'polygon';- default:- return false;- }-};-export const PSD_ALLOCATION_BYTES_PER_PIXEL = 8;export const derivePsdPixelAreaLimit = (availableBytes: number): number =>@@ -82,7 +65,7 @@ export class PsdExportController {return 'stale';}const document = documentSnapshot.canvas.document;- const layers = document.layers.filter(isExportable);+ const layers = document.layers.filter(isExportableRasterLayer);if (layers.length === 0) {return 'nothing';}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.tsnew file mode 100644index 0000000000..d0425d6bc0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentFixtures.testStub.ts@@ -0,0 +1,75 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';++import { LAYER_STACK_ORDER } from '@workbench/canvas-engine/document/layerStacks';++const base = (id: string) => ({+ blendMode: 'normal' as const,+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+});++const mask = () => ({ bitmap: null, fill: { color: '#e07575', style: 'diagonal' as const } });++/** A complete layer contract of `type`, accepted by the reducer's normaliser as-is. */+export const layerContract = (+ id: string,+ type: CanvasLayerContract['type'] = 'raster',+ overrides: Partial<CanvasLayerContract> = {}+): CanvasLayerContract => {+ const contract = ((): CanvasLayerContract => {+ switch (type) {+ case 'raster':+ return { ...base(id), source: { bitmap: null, type: 'paint' }, type };+ case 'control':+ return {+ ...base(id),+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ source: { bitmap: null, type: 'paint' },+ type,+ withTransparencyEffect: false,+ };+ case 'inpaint_mask':+ return { ...base(id), mask: mask(), type };+ case 'regional_guidance':+ return {+ ...base(id),+ autoNegative: false,+ mask: mask(),+ negativePrompt: null,+ positivePrompt: null,+ referenceImages: [],+ type,+ };+ }+ })();+ return { ...contract, ...overrides } as CanvasLayerContract;+};++export const flatDocument = (+ layers: readonly CanvasLayerContract[],+ selectedLayerId: string | null = null+): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: 512, width: 512, x: 0, y: 0 },+ height: 512,+ layers: [...layers],+ selectedLayerId,+ version: 2,+ width: 512,+});++/** `count` layers cycling through every stack in flat order, ids `l0` (top) … `l{count-1}`. */+export const createLargeFlatDocument = (+ count: number,+ selectedLayerId: string | null = 'l0'+): CanvasDocumentContractV2 =>+ flatDocument(+ Array.from({ length: count }, (_, index) =>+ layerContract(`l${index}`, LAYER_STACK_ORDER[index % LAYER_STACK_ORDER.length]!)+ ),+ selectedLayerId+ );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.tsindex 87a0166e5a..27bfcb90ac 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts@@ -10,50 +10,18 @@ import { describe, expect, it } from 'vitest';import type { FlatDocumentCommand, PreparedFlatEdit, PrepareFlatEditResult } from './flatDocumentCommands';-import { createFlatDocumentModel, flatDocumentModelCounters } from './flatDocumentModel';+import { layerContract } from './documentFixtures.testStub';+import {+ compileDocumentLeaves,+ createFlatDocumentModel,+ flatDocumentModelCounters,+ lookupDocumentLayer,+ lookupDocumentLeaf,+ mergeDownEligibility,+} from './flatDocumentModel';import { checkFlatEditPostconditions } from './postconditions';-const base = (id: string) => ({- blendMode: 'normal' as const,- id,- isEnabled: true,- isLocked: false,- name: id,- opacity: 1,- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },-});-const mask = { bitmap: null, fill: { color: '#e07575', style: 'diagonal' as const } };-const contract = (id: string, type: CanvasLayerContract['type']): CanvasLayerContract => {- switch (type) {- case 'raster':- return { ...base(id), source: { bitmap: null, type: 'paint' }, type };- case 'control':- return {- ...base(id),- adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },- source: { bitmap: null, type: 'paint' },- type,- withTransparencyEffect: false,- };- case 'inpaint_mask':- return { ...base(id), mask, type };- case 'regional_guidance':- return {- ...base(id),- autoNegative: false,- mask,- negativePrompt: null,- positivePrompt: null,- referenceImages: [],- type,- };- }-};-const layer = (- id: string,- type: CanvasLayerContract['type'] = 'raster',- overrides: Partial<CanvasLayerContract> = {}-) => ({ ...contract(id, type), ...overrides }) as CanvasLayerContract;+const layer = layerContract;const interleaved = (): CanvasLayerContract[] => [layer('i1', 'inpaint_mask'),@@ -332,6 +300,90 @@ describe('createFlatDocumentModel', () => {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 },@@ -576,6 +628,40 @@ describe('createFlatDocumentModel', () => {});});+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 when a layer and its stack position are unchanged', () => {+ const before = projectWith(interleaved(), 'r1').canvas.document;+ const after: CanvasDocumentContractV2 = { ...before, selectedLayerId: 'c1' };+ const untouched = compileDocumentLeaves(before);+ const reused = compileDocumentLeaves(after, before);+ expect(reused).toBe(untouched);++ const renamed: CanvasDocumentContractV2 = {+ ...before,+ layers: before.layers.map((layer) => (layer.id === 'r1' ? { ...layer, name: 'renamed' } : layer)),+ };+ const recompiled = compileDocumentLeaves(renamed, before);+ 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('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;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.tsindex 0274809d77..4c38d07886 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts@@ -78,6 +78,12 @@ export const flatDocumentModelCounters = { indexBuilds: 0, leafCompilations: 0,const indexes = new WeakMap<CanvasDocumentContractV2, DocumentIndex>();+/** The most recent compilation, reused when a caller has no previous document to offer. */+let latestLeaves: {+ readonly layers: CanvasDocumentContractV2['layers'];+ readonly leaves: readonly SemanticLeafV2[];+} | null = null;+const buildIndex = (document: CanvasDocumentContractV2): DocumentIndex => {flatDocumentModelCounters.indexBuilds += 1;const byId = new Map<string, LayerIndexEntry>();@@ -113,8 +119,11 @@ const compileLeaves = (if (index.leaves) {return index.leaves;}- const reusable = previousDocument ? indexOf(previousDocument).leaves : null;- if (reusable && previousDocument?.layers === document.layers) {+ const previous = previousDocument+ ? { layers: previousDocument.layers, leaves: indexOf(previousDocument).leaves }+ : latestLeaves;+ const reusable = previous?.leaves ?? null;+ if (reusable && previous?.layers === document.layers) {index.leaves = reusable;return reusable;}@@ -130,33 +139,93 @@ const compileLeaves = (return compileSemanticLeaf(layer, entry.stackIndex);});index.leaves = leaves;+ latestLeaves = { layers: document.layers, 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; `previousDocument` lets unchanged leaves keep their identity. */+export const compileDocumentLeaves = (+ document: CanvasDocumentContractV2,+ previousDocument: CanvasDocumentContractV2 | null = null+): readonly SemanticLeafV2[] => compileLeaves(document, indexOf(document), previousDocument);++/** 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;+};++/** 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 = document.layers[upper.index + 1];+ 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, including the same transform axes and nested config fields. */-const sameKeys = (left: Record<string, unknown>, right: Record<string, unknown>): boolean => {+/**+ * 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 && !Array.isArray(a) && typeof b === 'object' && b !== null- ? sameKeys(a as Record<string, unknown>, b as Record<string, unknown>)- : true;+ 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 missing = (ids: readonly string[]): FlatDocumentRefusal => ({ ids, status: 'missing' });-const stackOrders = (layers: readonly CanvasLayerContract[],stacks: readonly LayerStackKind[]@@ -388,7 +457,7 @@ export const createFlatDocumentModel = (if (Object.keys(command.patch).length === 0) {return { operation: 'patch nothing', status: 'unsupported' };}- if (command.before && !sameKeys(command.before, command.patch)) {+ 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);@@ -440,7 +509,10 @@ export const createFlatDocumentModel = (if (Object.keys(command.config).length <= 1) {return { operation: 'patch nothing', status: 'unsupported' };}- if (command.before && !sameKeys(command.before, command.config)) {+ 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)) {@@ -616,32 +688,7 @@ export const createFlatDocumentModel = (};return {- canMergeDown: (upperId) => {- const upper = index.byId.get(upperId);- if (!upper) {- return missing([upperId]);- }- if (upper.stack !== 'raster') {- return { actual: upper.stack, expected: ['raster'], status: 'wrong-type' };- }- const lower = layers[upper.index + 1];- 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 };- },+ canMergeDown: (upperId) => mergeDownEligibility(document, upperId),compileLeaves: () => compileLeaves(document, index, previousDocument),document,getLayer: (id) => index.byId.get(id)?.layer ?? null,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 01eaf7d6dd..8146da6eaf 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@@ -16,6 +16,13 @@ export interface ScreenCompositionPlan {readonly isolationLayerId: string | null;}+/** Every overlay stack visible: the view state of a screen with no stack switched off. */+export const ALL_OVERLAY_STACKS_SHOWN: Readonly<Record<OverlayStackKind, boolean>> = {+ control: true,+ inpaint_mask: true,+ regional_guidance: true,+};+const isStackShown = (stack: LayerStackKind, view: CanvasScreenViewState): boolean =>stack === 'raster' || view.showOverlayStacks[stack];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 14fbb798a9..cfdbcbcbe1 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@@ -7,7 +7,6 @@ import {haveSameStackOrders,LAYER_STACK_ORDER,LAYER_STACKS_TOP_FIRST,- layerStackRank,moveLayersWithinStacks,reorderLayerStack,} from './layerStacks';@@ -23,7 +22,6 @@ describe('layer stacks', () => {it('declares one composite order and its panel mirror', () => {expect(LAYER_STACK_ORDER).toEqual(['raster', 'control', 'regional_guidance', 'inpaint_mask']);expect(LAYER_STACKS_TOP_FIRST).toEqual([...LAYER_STACK_ORDER].reverse());- expect(layers.map(layerStackRank)).toEqual([3, 0, 1, 0]);});it('reads a stack in flat order, empty stacks included', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.tsindex f22b4ced1c..6a3a8380c5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts@@ -15,8 +15,6 @@ export const LAYER_STACKS_TOP_FIRST: readonly LayerStackKind[] = [...LAYER_STACKexport const layerStackOf = (layer: CanvasLayerContract): LayerStackKind => layer.type;-export const layerStackRank = (layer: CanvasLayerContract): number => LAYER_STACK_ORDER.indexOf(layer.type);-/** Reorders one stack; `orderedIds` must be exactly the stack's current members, top first. */export interface ReorderFlatStackCommand {readonly stack: LayerStackKind;diff --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 ab66a9a692..e8d0579c15 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@@ -150,10 +150,11 @@ describe('SAM isolation', () => {rect: { height: 8, width: 8, x: 0, y: 0 },}) as unknown as SamPreviewState;- it('composites only the isolated layer', () => {+ 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']);+ expect(doc.layers.map((entry) => entry.id)).toEqual(['a', 'b']);+ expect(lastCompositeOptions().isolationLayerId).toBe('a');});it('clips to the preview rect', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex 3cb1c0a61c..efa610777a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -70,8 +70,8 @@ export interface CompositeFrame {* the one evicted.** SAM isolation makes this frame describe one layer instead of the document:- * the composite is filtered down to the isolated layer and clipped to the- * preview rect, and every other in-flight embellishment — filter previews, the+ * the composite is narrowed to the isolated layer through `isolationLayerId`+ * and clipped to the preview rect, and every other in-flight embellishment — filter previews, the* staged candidate, the floating selection, transform overrides — is suppressed,* because none of them describe what the user is being asked to judge.*/@@ -174,10 +174,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF});ensureLayerCaches(doc, activeFrameLayerIds);- const compositeDoc = isolatedIds- ? { ...doc, layers: doc.layers.filter((layer) => isolatedIds.has(layer.id)) }- : doc;- compositeDocument(screen, compositeDoc, layerCache, view, {+ compositeDocument(screen, doc, layerCache, view, {// Confines the clear, the checkerboard and every layer blit to the pixels// that actually changed; `null` repaints the whole viewport.damage: isolatedGuard ? null : damage,@@ -202,6 +199,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF// Crisp + cheap when zoomed in (nearest-neighbor up-scale), smooth when// shrinking (bilinear down-scale). See `shouldSmoothAtZoom`.imageSmoothing: shouldSmoothAtZoom(viewport.getZoom()),+ isolationLayerId: isolatedGuard?.layerId ?? null,// Non-destructive control-filter previews, drawn in place of the layer's// committed pixels. Snapshotted only when one is actually active — this// runs every composite frame, so an unconditional copy would allocate adiff --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 03817c3b2b..b43a40b956 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@@ -135,7 +135,7 @@ describe('compositeDocument', () => {expect(drawImages[0]!.args[0]).toBe(caches.get('b')!.surface.canvas);});- it('isolates the named layer even when disabled and suppresses unrelated staged content', () => {+ it('isolates the named layer and suppresses staged content and filter previews', () => {const backend = createTestStubRasterBackend();const caches = createLayerCacheStore(backend);const isolated = caches.getOrCreate('isolated', 10, 10);@@ -144,17 +144,11 @@ describe('compositeDocument', () => {const staged = backend.createSurface(10, 10);const target = backend.createSurface(200, 200);- compositeDocument(- target,- makeDoc([rasterLayer('isolated', { isEnabled: false }), rasterLayer('other')]),- caches,- VIEW,- {- layerPreviews: new Map([['isolated', { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: filterPreview }]]),- onlyLayerId: 'isolated',- stagedPreview: { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: staged },- }- );+ compositeDocument(target, makeDoc([rasterLayer('isolated'), rasterLayer('other')]), caches, VIEW, {+ layerPreviews: new Map([['isolated', { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: filterPreview }]]),+ isolationLayerId: 'isolated',+ stagedPreview: { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: staged },+ });const drawImages = target.callLog.filter((entry) => entry.op === 'drawImage');expect(drawImages).toHaveLength(1);@@ -727,16 +721,27 @@ describe('compositeDocument — hidden layers', () => {expect(maskCache.surface.width).toBe(10);});- it('still draws a hidden layer while it is the isolated operation target', () => {- // An operation preview acts ON that layer; suppressing it would leave the- // user editing something they cannot see.+ it('draws nothing for a disabled layer even while it is the isolated target', () => {+ const backend = createTestStubRasterBackend();+ const caches = createLayerCacheStore(backend);+ caches.getOrCreate('isolated', 10, 10);+ const target = backend.createSurface(200, 200);++ compositeDocument(target, makeDoc([rasterLayer('isolated', { isEnabled: false })]), caches, VIEW, {+ isolationLayerId: 'isolated',+ });++ expect(target.callLog.some((e) => e.op === 'drawImage')).toBe(false);+ });++ it('draws nothing for a hidden layer even while it is the isolated target', () => {const backend = createTestStubRasterBackend();const caches = createLayerCacheStore(backend);caches.getOrCreate('m', 10, 10);const target = backend.createSurface(200, 200);- compositeDocument(target, makeDoc([hiddenMask('m')]), caches, VIEW, { backend, onlyLayerId: 'm' });+ compositeDocument(target, makeDoc([hiddenMask('m')]), caches, VIEW, { backend, isolationLayerId: 'm' });- expect(target.callLog.some((e) => e.op === 'drawImage')).toBe(true);+ expect(target.callLog.some((e) => e.op === 'drawImage')).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 8fd4ee092b..762ba7057a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -19,10 +19,14 @@ import type {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 { LayerDamage, Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';-import { isLayerContributing, isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';-import { LAYER_STACK_ORDER, layerStackRank } from '@workbench/canvas-engine/document/layerStacks';+import { compileDocumentLeaves, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/flatDocumentModel';+import {+ ALL_OVERLAY_STACKS_SHOWN,+ planScreenComposition,+} from '@workbench/canvas-engine/document-model/screenComposition';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';import { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';@@ -157,8 +161,11 @@ export interface CompositeOptions {* `null`/absent ⇒ no previews.*/layerPreviews?: ReadonlyMap<string, { surface: RasterSurface; rect: Rect }> | null;- /** When set, transiently composites only this layer (even if disabled) and suppresses staged content. */- onlyLayerId?: string | null;+ /**+ * Draws only this leaf and suppresses staged content and filter previews. A leaf the document+ * would not draw (disabled or hidden) stays undrawn even while isolated.+ */+ isolationLayerId?: string | null;/*** Returns a raster layer's ADJUSTED cache surface (brightness/contrast/* saturation/curves applied), or `null` when the layer has identity (or no)@@ -190,6 +197,9 @@ type Ctx = RasterSurface['ctx'];export const blendToComposite = (mode: CanvasBlendMode): GlobalCompositeOperation =>mode === 'normal' ? 'source-over' : (mode as GlobalCompositeOperation);+const isIsolated = (opts: CompositeOptions): boolean =>+ opts.isolationLayerId !== null && opts.isolationLayerId !== undefined;+const setTransformFromMat = (ctx: Ctx, m: Mat2d): void => {ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);};@@ -198,8 +208,12 @@ const identityTransform = (ctx: Ctx): void => {ctx.setTransform(1, 0, 0, 1, 0, 0);};-const getEffectiveLayerMatrix = (layer: CanvasLayerContract, opts: CompositeOptions): Mat2d => {- const override = opts.transformOverrides?.get(layer.id);+const getEffectiveLayerMatrix = (leaf: SemanticLeafV2, opts: CompositeOptions): Mat2d => {+ const override = opts.transformOverrides?.get(leaf.id);+ if (!override) {+ return leaf.worldTransform;+ }+ const { layer } = leaf;return fromTRS({ x: override?.x ?? layer.transform.x, y: override?.y ?? layer.transform.y },override?.rotation ?? layer.transform.rotation,@@ -209,13 +223,13 @@ const getEffectiveLayerMatrix = (layer: CanvasLayerContract, opts: CompositeOpti};const isDefinitelyOffscreen = (- layer: CanvasLayerContract,+ leaf: SemanticLeafV2,entry: LayerCacheEntry,view: Mat2d,target: RasterSurface,opts: CompositeOptions): boolean => {- const bounds = transformBounds(multiply(view, getEffectiveLayerMatrix(layer, opts)), entry.rect);+ const bounds = transformBounds(multiply(view, getEffectiveLayerMatrix(leaf, opts)), entry.rect);if (![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)) {return false;}@@ -298,11 +312,11 @@ const resolveDamage = (}let accumulated: Rect | null = null;for (const region of damage) {- const layer = doc.layers.find((candidate) => candidate.id === region.layerId);- if (!layer) {+ const leaf = lookupDocumentLeaf(doc, region.layerId);+ if (!leaf) {return null;}- const bounds = transformBounds(multiply(view, getEffectiveLayerMatrix(layer, opts)), region.rect);+ const bounds = transformBounds(multiply(view, getEffectiveLayerMatrix(leaf, opts)), region.rect);accumulated = accumulated ? union(accumulated, bounds) : bounds;}if (!accumulated) {@@ -382,22 +396,23 @@ const drawMaskLayer = (*/const drawCachedLayer = (ctx: Ctx,- layer: CanvasLayerContract,+ leaf: SemanticLeafV2,entry: LayerCacheEntry,view: Mat2d,opts: CompositeOptions): void => {+ const { layer } = leaf;ctx.save();ctx.globalAlpha = layer.opacity;ctx.globalCompositeOperation = blendToComposite(layer.blendMode);- const layerMat = getEffectiveLayerMatrix(layer, opts);+ const layerMat = getEffectiveLayerMatrix(leaf, opts);setTransformFromMat(ctx, multiply(view, layerMat));// The cache surface holds pixels for `entry.rect` in layer-local space; draw// it at that local origin (offset paint/mask layers place their content off-zero).const origin = { x: entry.rect.x, y: entry.rect.y };- const preview = opts.onlyLayerId ? null : (opts.layerPreviews?.get(layer.id) ?? null);+ const preview = isIsolated(opts) ? null : (opts.layerPreviews?.get(layer.id) ?? null);if (preview) {// Non-destructive filter preview: draw the full backend output at its// layer-local rect (through the already-applied layer transform), including@@ -461,15 +476,16 @@ const drawCachedLayer = (*/const drawFloatingSelection = (ctx: Ctx,- layer: CanvasLayerContract,+ leaf: SemanticLeafV2,view: Mat2d,opts: CompositeOptions,float: NonNullable<CompositeOptions['floatingSelection']>): void => {+ const { layer } = leaf;ctx.save();ctx.globalAlpha = layer.opacity;ctx.globalCompositeOperation = blendToComposite(layer.blendMode);- setTransformFromMat(ctx, multiply(multiply(view, getEffectiveLayerMatrix(layer, opts)), float.matrix));+ setTransformFromMat(ctx, multiply(multiply(view, getEffectiveLayerMatrix(leaf, opts)), float.matrix));ctx.drawImage(float.surface.canvas, float.rect.x, float.rect.y);ctx.restore();};@@ -527,48 +543,36 @@ export const compositeDocument = (ctx.clip();}- // Composite stack by stack in `LAYER_STACK_ORDER`; within a stack the flat- // array order holds (index 0 is top-most, so iterate in reverse). The- // `stagedPreview` lands on top of every stack.- const drawStack = (rank: number): void => {- for (let i = doc.layers.length - 1; i >= 0; i--) {- const layer = doc.layers[i];- if (- !layer ||- // Disabled OR hidden: neither draws. `onlyLayerId` (an isolated- // operation preview) overrides both — the user is acting on that layer.- ((!isLayerContributing(layer) || isLayerHidden(layer)) && layer.id !== opts.onlyLayerId) ||- layer.id === opts.skipLayerId ||- (opts.onlyLayerId && layer.id !== opts.onlyLayerId) ||- layerStackRank(layer) !== rank- ) {- continue;- }- opts.diagnostics?.increment('layersConsidered');- const float = opts.floatingSelection?.layerId === layer.id ? opts.floatingSelection : null;- const entry = caches.get(layer.id);- // Skip layers with no cache or an empty content rect (a brand-new / cleared- // paint / mask layer holds no pixels — nothing to draw). A float still draws:- // its pixels are detached, so an emptied source layer must not hide them.- if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {- if (float) {- drawFloatingSelection(ctx, layer, view, opts, float);- }- continue;- }- if (isDefinitelyOffscreen(layer, entry, view, target, opts) && !float) {- opts.diagnostics?.increment('layersCulled');- continue;- }- drawCachedLayer(ctx, layer, entry, view, opts);+ // The plan lists the leaves to draw bottom first; the `stagedPreview` lands on top of every stack.+ const plan = planScreenComposition(compileDocumentLeaves(doc), {+ isolationLayerId: opts.isolationLayerId ?? null,+ showOverlayStacks: ALL_OVERLAY_STACKS_SHOWN,+ });+ for (const leaf of plan.leaves) {+ if (leaf.id === opts.skipLayerId) {+ continue;+ }+ opts.diagnostics?.increment('layersConsidered');+ const float = opts.floatingSelection?.layerId === leaf.id ? opts.floatingSelection : null;+ const entry = caches.get(leaf.id);+ // Skip layers with no cache or an empty content rect (a brand-new / cleared+ // paint / mask layer holds no pixels — nothing to draw). A float still draws:+ // its pixels are detached, so an emptied source layer must not hide them.+ if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {if (float) {- drawFloatingSelection(ctx, layer, view, opts, float);+ drawFloatingSelection(ctx, leaf, view, opts, float);}- opts.diagnostics?.increment('layersDrawn');+ continue;+ }+ if (isDefinitelyOffscreen(leaf, entry, view, target, opts) && !float) {+ opts.diagnostics?.increment('layersCulled');+ continue;+ }+ drawCachedLayer(ctx, leaf, entry, view, opts);+ if (float) {+ drawFloatingSelection(ctx, leaf, view, opts, float);}- };- for (let rank = 0; rank < LAYER_STACK_ORDER.length; rank++) {- drawStack(rank);+ opts.diagnostics?.increment('layersDrawn');}if (opts.clipRect) {@@ -577,7 +581,7 @@ export const compositeDocument = (// Staged generation preview over its bbox (document space), with a subtle// dashed outline so the pending result reads distinctly from committed pixels.- const staged = opts.onlyLayerId ? null : opts.stagedPreview;+ const staged = isIsolated(opts) ? null : opts.stagedPreview;if (staged) {ctx.save();setTransformFromMat(ctx, view);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 798da29fb8..913d8e47c1 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@@ -21,6 +21,7 @@ const documentOf = (layerIds: readonly string[]): CanvasDocumentContractV2 =>({layers: layerIds.map((id) => ({id,+ type: 'raster',transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 20 },})),}) as unknown as CanvasDocumentContractV2;@@ -63,7 +64,7 @@ describe('floatingSelectionFrame', () => {it('reports nothing when the layer transform cannot be inverted', () => {const collapsed = {- layers: [{ id: 'layer-1', transform: { rotation: 0, scaleX: 0, scaleY: 0, x: 0, y: 0 } }],+ layers: [{ id: 'layer-1', type: 'raster', transform: { rotation: 0, scaleX: 0, scaleY: 0, x: 0, y: 0 } }],} as unknown as CanvasDocumentContractV2;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 d04b9560d3..ebbae90950 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/floatingSelectionFrame.ts@@ -2,8 +2,8 @@ import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contractimport 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 { floatDocumentMatrix } from '@workbench/canvas-engine/selection/floatingSelection';-import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';import type { CompositeOptions } from './compositor';@@ -29,12 +29,12 @@ export const floatingSelectionFrame = (float: FloatingSelection | null,doc: CanvasDocumentContractV2 | null): FloatingSelectionFrame | null => {- const layer = float && doc ? doc.layers.find((candidate) => candidate.id === float.layerId) : undefined;- if (!float || !layer) {+ const leaf = float && doc ? lookupDocumentLeaf(doc, float.layerId) : null;+ if (!float || !leaf) {return null;}const matrix = bakeMatrix(float.transform);- const ants = floatDocumentMatrix(layerMatrix(layer.transform), matrix);+ const ants = floatDocumentMatrix(leaf.worldTransform, matrix);if (!ants) {return null;}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 f1a5369490..5ac320251e 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,4 +1,9 @@-import type { CanvasDocumentContractV2, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type {+ CanvasControlLayerContract,+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+} from '@workbench/canvas-engine/contracts';import { describe, expect, it } from 'vitest';@@ -16,7 +21,22 @@ const layer = (id: string, x: number, y: number, width = 100, height = 100): Cantype: 'raster',});-const document = (layers: CanvasRasterLayerContractV2[]): CanvasDocumentContractV2 => ({+const hiddenControl = (id: string): CanvasControlLayerContract => ({+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ blendMode: 'normal',+ id,+ isEnabled: true,+ isHidden: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { image: { height: 100, imageName: `${id}.png`, width: 100 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'control',+ withTransparencyEffect: false,+});++const document = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 1_000,@@ -50,6 +70,23 @@ describe('calculateActiveFrameLayerIds', () => {).toEqual(new Set(['paint']));});+ it('demands a hidden layer only while an isolated operation reads it', () => {+ const doc = document([hiddenControl('hidden'), layer('base', 0, 0)]);+ const viewport = { height: 200, width: 200, x: 0, y: 0 };++ expect(calculateActiveFrameLayerIds({ document: doc, viewport })).toEqual(new Set(['base']));+ expect(calculateActiveFrameLayerIds({ document: doc, isolationLayerIds: new Set(['hidden']), viewport })).toEqual(+ new Set(['hidden'])+ );+ expect(+ calculateActiveFrameLayerIds({+ document: document([{ ...hiddenControl('off'), isEnabled: false }]),+ isolationLayerIds: new Set(['off']),+ viewport,+ })+ ).toEqual(new Set());+ });+it('limits demand to isolated layers', () => {const doc = document([layer('isolated', 0, 0), layer('covered', 0, 0)]);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.tsindex 802981f6e0..20599a2ba6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts@@ -1,7 +1,7 @@import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import { isLayerContributing, isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';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';@@ -26,12 +26,13 @@ export const calculateActiveFrameLayerIds = ({viewport,}: FrameDemandInput): Set<string> => {const active = new Set<string>();- for (const layer of document.layers) {- // A hidden layer draws nothing this frame, so it needs no cache allocated —- // but an isolated operation preview still targets it.+ for (const leaf of compileDocumentLeaves(document)) {+ const { layer } = leaf;+ // A hidden layer draws nothing, so it needs no cache — unless an isolated+ // operation reads its pixels, which still requires them rasterized.if (- !isLayerContributing(layer) ||- (isLayerHidden(layer) && !isolationLayerIds?.has(layer.id)) ||+ !leaf.contributionEnabled ||+ (leaf.documentHidden && !isolationLayerIds?.has(layer.id)) ||!renderableSourceOf(layer) ||(isolationLayerIds && !isolationLayerIds.has(layer.id))) {@@ -42,16 +43,14 @@ export const calculateActiveFrameLayerIds = ({const localRect =liveRect && !isEmpty(liveRect) ? (isEmpty(sourceRect) ? liveRect : union(sourceRect, liveRect)) : sourceRect;const override = transformOverrides?.get(layer.id);- const transform = override- ? {- rotation: override.rotation ?? layer.transform.rotation,- scaleX: override.scaleX ?? layer.transform.scaleX,- scaleY: override.scaleY ?? layer.transform.scaleY,- x: override.x,- y: override.y,- }- : layer.transform;- const matrix = fromTRS({ x: transform.x, y: transform.y }, transform.rotation, transform.scaleX, transform.scaleY);+ const matrix = override+ ? fromTRS(+ { x: override.x, y: override.y },+ override.rotation ?? layer.transform.rotation,+ override.scaleX ?? layer.transform.scaleX,+ override.scaleY ?? layer.transform.scaleY+ )+ : leaf.worldTransform;if (intersect(transformBounds(matrix, localRect), viewport)) {active.add(layer.id);}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/hidden-overlay-isolated.png b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/hidden-overlay-isolated.pngindex 839b9c66f8..065c9599b5 100644Binary files a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/hidden-overlay-isolated.png and b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/hidden-overlay-isolated.png differdiff --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 48c6c67968..6ef8c0d4f3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts@@ -184,11 +184,11 @@ describe('compositor goldens', () => {});}- it('skips a hidden control layer unless it is isolated', async () => {+ it('skips a hidden control layer, isolated or not', async () => {const layers = [control('control', { isHidden: true }), raster('base')];const paint = { base: BASE, control: { paint: solid('#8a2be2'), rect: { height: 30, width: 90, x: 35, y: 30 } } };await expectGolden('hidden-overlay', render(layers, paint));- await expectGolden('hidden-overlay-isolated', render(layers, paint, { onlyLayerId: 'control' }));+ await expectGolden('hidden-overlay-isolated', render(layers, paint, { isolationLayerId: 'control' }));});it('renders the generation base from enabled raster layers only', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.tsindex 07ddb034e2..0f39c02874 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts@@ -10,8 +10,13 @@ import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatimport type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { Mat2d, ToolId, Vec2 } from '@workbench/canvas-engine/types';+import {+ compileDocumentLeaves,+ lookupDocumentLayer,+ lookupDocumentLeaf,+} from '@workbench/canvas-engine/document-model/flatDocumentModel';import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';-import { hittableLayerRect, layerMatrix, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';+import { hittableLayerRect, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';import { transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';import type { FloatingSelectionFrame } from './floatingSelectionFrame';@@ -66,8 +71,8 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =if (getActiveToolId() !== 'move') {return null;}- const overridden = doc.layers.find((layer) => transformOverrides.has(layer.id));- const target = overridden ?? doc.layers.find((layer) => layer.id === doc.selectedLayerId);+ const overridden = compileDocumentLeaves(doc).find((leaf) => transformOverrides.has(leaf.id))?.layer;+ const target = overridden ?? (doc.selectedLayerId ? lookupDocumentLayer(doc, doc.selectedLayerId) : null);if (!target) {return null;}@@ -84,11 +89,11 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =// The float frames its own pixels. Its rect and transform are LAYER-LOCAL,// so the resulting geometry is projected out through the layer's matrix to// reach the document space the overlay draws in.- const floatLayer = doc.layers.find((candidate) => candidate.id === float.layerId);- if (!floatLayer) {+ const floatLeaf = lookupDocumentLeaf(doc, float.layerId);+ if (!floatLeaf) {return null;}- const toDocument = layerMatrix(floatLayer.transform);+ const toDocument = floatLeaf.worldTransform;const geometry = transformOverlayGeometry(float.transform, float.pixels.rect);return {center: applyToPoint(toDocument, geometry.center),@@ -101,7 +106,7 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =if (!session) {return null;}- const layer = doc.layers.find((candidate) => candidate.id === session.layerId);+ const layer = lookupDocumentLayer(doc, session.layerId);// The layer's LOCAL content rect (off-origin aware): the frame must wrap the// pixels where the compositor draws them, not an assumed origin-anchored box.const rect = layer ? hittableLayerRect(layer, doc) : 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 0ba933f320..f861835738 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts@@ -2,14 +2,14 @@ import type {CanvasAdjustmentsContract,CanvasBlendMode,CanvasDocumentContractV2,- CanvasLayerContract,CanvasLayerSourceContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';+import type { SemanticLeafV2 } 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 { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';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';@@ -56,9 +56,10 @@ const defaultReadImageData = (surface: RasterSurface, rect: Rect): ImageData =>const defaultWriteImageData = (surface: RasterSurface, imageData: ImageData, x: number, y: number): void =>surface.ctx.putImageData(imageData, x, y);-/** True when a layer is an enabled raster layer with rasterizable, non-empty pixels. */-const isBaseRasterLayer = (layer: CanvasLayerContract): layer is CanvasRasterLayerContractV2 => {- if (!isLayerContributing(layer) || layer.type !== 'raster') {+/** True when a leaf is a contributing raster layer with rasterizable, non-empty pixels. */+const isBaseRasterLeaf = (leaf: SemanticLeafV2): leaf is SemanticLeafV2 & { layer: CanvasRasterLayerContractV2 } => {+ const { layer } = leaf;+ if (!leaf.contributionEnabled || layer.type !== 'raster') {return false;}if (layer.source.type === 'image') {@@ -153,7 +154,9 @@ 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 => {- const layers = document.layers.filter(isBaseRasterLayer).map((layer) => toLayerRef(layer, document));+ const layers = compileDocumentLeaves(document)+ .filter(isBaseRasterLeaf)+ .map((leaf) => toLayerRef(leaf.layer, document));return {bbox: rect,key: `base-raster|${rectKey(rect)}|${layers.map(layerKey).join('|')}`,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.tsindex 5cd02d1f98..bab806ff26 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationCompositePlan.ts@@ -11,10 +11,10 @@ import {adjustmentsKey,getBaseRasterContentBounds,getCompositeLayerBounds,- isLayerContributing,planBaseRasterComposite,} from '@workbench/canvas-engine/api';-import { isCompositableControlLayer, isCompositableRegionalGuidanceLayer } from '@workbench/canvasLayerContent';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';+import { hasControlLayerContent, hasRegionalGuidanceMaskContent } from '@workbench/canvasLayerContent';import type {CompositeEntry,@@ -63,9 +63,24 @@ const layerKey = (ref: CompositeLayerRef): string => {export { getBaseRasterContentBounds, getCompositeLayerBounds, planBaseRasterComposite };-/** True when a layer is an enabled inpaint mask with persisted (non-empty) alpha. */-const isActiveInpaintMaskLayer = (layer: CanvasLayerContract): layer is CanvasInpaintMaskLayerContract =>- isLayerContributing(layer) && layer.type === 'inpaint_mask' && layer.mask.bitmap !== null;+/** The contributing layers, in flat order, narrowed to the ones that satisfy `hasContent`. */+const contributingLayers = <T extends CanvasLayerContract>(+ document: CanvasDocumentContractV2,+ hasContent: (layer: CanvasLayerContract) => layer is T+): T[] =>+ compileDocumentLeaves(document)+ .filter((leaf) => leaf.contributionEnabled)+ .map((leaf) => leaf.layer)+ .filter(hasContent);++const isInpaintMaskWithContent = (layer: CanvasLayerContract): layer is CanvasInpaintMaskLayerContract =>+ layer.type === 'inpaint_mask' && layer.mask.bitmap !== null;++const isControlLayerWithContent = (layer: CanvasLayerContract): layer is CanvasControlLayerContract =>+ layer.type === 'control' && hasControlLayerContent(layer);++const isRegionalGuidanceWithMask = (layer: CanvasLayerContract): layer is CanvasRegionalGuidanceLayerContract =>+ layer.type === 'regional_guidance' && hasRegionalGuidanceMaskContent(layer);/** The native content rect of a mask layer's persisted bitmap (layer-local, at its offset). */const maskContentRect = (@@ -122,7 +137,7 @@ const deriveMaskKey = (kind: string, bbox: Rect, layers: CompositeMaskLayerRef[]export const planComposites = (document: CanvasDocumentContractV2, bbox: Rect): CompositePlan => {const entries: CompositeEntry[] = [planBaseRasterComposite(document, bbox)];- const maskLayers = document.layers.filter(isActiveInpaintMaskLayer);+ const maskLayers = contributingLayers(document, isInpaintMaskWithContent);if (maskLayers.length > 0) {const denoiseRefs = maskLayers.map((layer) =>@@ -211,7 +226,7 @@ export interface ControlCompositeEntry {* paint into the img2img/inpaint source.*/export const planControlComposites = (document: CanvasDocumentContractV2, bbox: Rect): ControlCompositeEntry[] =>- document.layers.filter(isCompositableControlLayer).map((layer) => {+ contributingLayers(document, isControlLayerWithContent).map((layer) => {const ref = toControlLayerRef(layer, document);return {entry: {@@ -280,7 +295,7 @@ export const planRegionalMaskComposites = (document: CanvasDocumentContractV2,bbox: Rect): RegionalMaskCompositeEntry[] =>- document.layers.filter(isCompositableRegionalGuidanceLayer).map((layer) => {+ contributingLayers(document, isRegionalGuidanceWithMask).map((layer) => {const ref = toRegionalMaskRef(layer);return {entry: {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex 16fd1b0b4c..2bd9ea6162 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@ -250,7 +250,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC// or a mask directly below the selection. `engine.layers.mergeLayerDown` also// guards this itself (defense in depth for callers other than this hotkey),// but checking here keeps the two surfaces visibly in lockstep.- if (engine && selectedLayer && canMergeLayerDown(layers, selectedIndex, true)) {+ if (engine && selectedLayer && canMergeLayerDown(document, selectedLayer.id, true)) {engine.layers.mergeLayerDown(selectedLayer.id);}}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.tsindex efc87c13bc..954392fec7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts@@ -1,6 +1,4 @@import type { StructuralCommitResult } from '@workbench/canvas-engine/api';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';import type { TFunction } from 'i18next';import { createFlatDocumentModel } from '@workbench/canvas-engine/api';@@ -8,31 +6,10 @@ import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';import { describe, expect, it, vi } from 'vitest';-import {- commitPreparedEdit,- commitStructuralEdit,- reportPreparedCommit,- reportStructuralCommit,-} from './useStructuralCommit';+import { commitPreparedEdit, reportPreparedCommit, reportStructuralCommit } from './useStructuralCommit';-const forward: CanvasProjectMutation = { ids: ['a'], type: 'removeCanvasLayers' };-const inverse: CanvasProjectMutation = { id: 'a', type: 'setCanvasSelectedLayer' };const t = ((key: string) => key) as unknown as TFunction;-describe('commitStructuralEdit', () => {- it('routes through the engine and returns its result', () => {- const commitStructural = vi.fn(() => ({ status: 'committed' as const }));- const engine = { layers: { commitStructural } } as unknown as CanvasStructuralEngine;-- expect(commitStructuralEdit(engine, 'Delete layer', forward, inverse)).toEqual({ status: 'committed' });- expect(commitStructural).toHaveBeenCalledWith('Delete layer', forward, inverse);- });-- it('refuses as not-ready without an engine instead of dispatching unrecorded', () => {- expect(commitStructuralEdit(null, 'Delete layer', forward, inverse)).toEqual({ status: 'not-ready' });- });-});-describe('reportStructuralCommit', () => {it.each<StructuralCommitResult>([{ status: 'committed' }, { status: 'busy' }])('stays silent for %j', (result) => {const report = vi.fn();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.tsindex 81eb2600a5..bc777fc30c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts@@ -1,34 +1,17 @@import type {CanvasDocumentCapability,CanvasLayerCapability,- CanvasStructuralEngine,FlatCanvasDocumentModel,FlatDocumentRefusal,PrepareFlatEditResult,StructuralCommitResult,} from '@workbench/canvas-engine/api';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { TFunction } from 'i18next';import { useNotify } from '@workbench/useNotify';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-export type StructuralCommit = (- label: string,- forward: CanvasProjectMutation,- inverse: CanvasProjectMutation-) => StructuralCommitResult;--/** Commits through the engine's guarded history; without a mounted engine there is no transaction context. */-export const commitStructuralEdit = (- engine: CanvasStructuralEngine | null,- label: string,- forward: CanvasProjectMutation,- inverse: CanvasProjectMutation-): StructuralCommitResult =>- engine ? engine.layers.commitStructural(label, forward, inverse) : { status: 'not-ready' };-/*** Explains a refused structural edit. `busy` stays silent because an in-flight operation already* disables the controls that could reach here; every other refusal drops the edit and says so.@@ -70,21 +53,6 @@ export const reportStructuralCommit = (};/** A widget-side structural commit that reports the refusals the user needs to hear about. */-export const useStructuralCommit = (engine: CanvasStructuralEngine | null): StructuralCommit => {- const notify = useNotify();- const { t } = useTranslation();-- return useCallback(- (label, forward, inverse) => {- const result = commitStructuralEdit(engine, label, forward, inverse);-- reportStructuralCommit(result, notify.error, t);- return result;- },- [engine, notify, t]- );-};-/** The engine surface a prepared edit needs: the document model and the transaction. */export interface CanvasPreparedEngine {readonly document: Pick<CanvasDocumentCapability, 'model'>;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsxindex 889aa1e97e..376f417854 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx@@ -1,18 +1,19 @@-import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/api';+import type { CanvasRasterLayerContractV2, PreparedFlatEdit } from '@workbench/canvas-engine/api';/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';import { ChakraProvider } from '@chakra-ui/react';import { applyThemeToRoot } from '@theme/applyTheme';import { system } from '@theme/system';+import { createFlatDocumentModel } from '@workbench/canvas-engine/api';+import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';import { createInstance } from 'i18next';import { act, useMemo, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';-import { AdjustmentsPopover } from './AdjustmentsPopover';+import { type AdjustmentsEngine, AdjustmentsPopover } from './AdjustmentsPopover';import { CURVE_SIZE } from './curveEditorMath';const i18n = createInstance();@@ -41,6 +42,8 @@ const createLayer = (): CanvasRasterLayerContractV2 =>type: 'raster',}) as unknown as CanvasRasterLayerContractV2;+const commits: PreparedFlatEdit[] = [];+const Harness = () => {const [layer, setLayer] = useState(createLayer);@@ -56,14 +59,23 @@ const Harness = () => {};return {+ document: {+ model: () =>+ createFlatDocumentModel(+ { ...createEmptyCanvasDocumentV2(), layers: [layer], selectedLayerId: layer.id },+ { editRevision: 0, projectId: 'test-project' }+ ),+ },layers: {applyStructuralPreview: apply,- commitStructural: (_label: string, forward: CanvasProjectMutation) => ({- status: apply(forward) ? ('committed' as const) : ('dispatch-rejected' as const),- }),+ commitPrepared: (_label: string, edit: PreparedFlatEdit) => {+ commits.push(edit);+ return { status: apply(edit.forward) ? ('committed' as const) : ('dispatch-rejected' as const) };+ },},- } as unknown as CanvasStructuralEngine;- }, []);+ } as unknown as AdjustmentsEngine;+ // Rebuilt per layer change so the stub's model reflects the previewed layer, as the engine's does.+ }, [layer]);return <AdjustmentsPopover engine={engine} layer={layer} />;};@@ -110,6 +122,7 @@ const pointer = (target: Element, type: string, x: number, y: number): void => {};afterEach(async () => {+ commits.length = 0;await settle(() => root?.unmount());host?.remove();host = null;@@ -131,6 +144,29 @@ describe('curves editor', () => {await settle(() => pointer(target, 'pointerup', start.x, start.y + 40));expect(Number(handles(svg).at(-1)!.getAttribute('cy'))).toBeCloseTo(during, 5);+ expect(commits).toHaveLength(1);+ const edit = commits[0]!;+ expect(edit.inverse).toMatchObject({ id: 'layer-1', type: 'updateCanvasLayerConfig' });+ expect((edit.inverse as { config: { adjustments?: unknown } }).config.adjustments).toEqual(+ createLayer().adjustments+ );+ expect(+ (edit.forward as { config: { adjustments: { curves: { r: unknown[] } } } }).config.adjustments.curves.r+ ).not.toEqual(createLayer().adjustments?.curves?.r);+ });++ it('restores the pre-drag curve and records nothing when the drag is cancelled', async () => {+ const svg = await render();+ const target = handles(svg).at(-1)!;+ const before = Number(target.getAttribute('cy'));+ const start = centreOf(target);++ await settle(() => pointer(target, 'pointerdown', start.x, start.y));+ await settle(() => pointer(target, 'pointermove', start.x, start.y + 40));+ await settle(() => pointer(target, 'pointercancel', start.x, start.y + 40));++ expect(Number(handles(svg).at(-1)!.getAttribute('cy'))).toBeCloseTo(before, 5);+ expect(commits).toHaveLength(0);});it('adds a point under the pointer rather than offset from it', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsxindex 7bbfff48f8..d77ba08c1a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx@@ -1,12 +1,13 @@import type { SliderValueChangeDetails } from '@chakra-ui/react';import type { CanvasAdjustmentsContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/api';+import type { CanvasPreparedEngine } from '@workbench/widgets/canvas/useStructuralCommit';import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';import type { PointerEvent as ReactPointerEvent } from 'react';import { chakra, createListCollection, HStack, Stack, Text } from '@chakra-ui/react';import { Button, Field, Select, Slider } from '@platform/ui';import { DEFAULT_ADJUSTMENTS, buildCurveLut } from '@workbench/canvas-engine/api';-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -68,7 +69,7 @@ const withCurve = (const formatSigned = (value: number): string => `${value > 0 ? '+' : ''}${Math.round(value * 100)}`;interface AdjustmentsPopoverProps {- engine: CanvasStructuralEngine | null;+ engine: AdjustmentsEngine | null;layer: CanvasRasterLayerContractV2;}@@ -77,38 +78,49 @@ export const AdjustmentsPopover = ({ engine, layer }: AdjustmentsPopoverProps) =return <AdjustmentsControls adjustments={adjustments} engine={engine} layer={layer} />;};+export type AdjustmentsEngine = CanvasStructuralEngine & CanvasPreparedEngine;+interface AdjustmentsControlsProps {adjustments: CanvasAdjustmentsContract;- engine: CanvasStructuralEngine | null;+ engine: AdjustmentsEngine | null;layer: CanvasRasterLayerContractV2;}type ScalarKey = 'brightness' | 'contrast' | 'saturation';const AdjustmentsControls = ({ adjustments, engine, layer }: AdjustmentsControlsProps) => {- const commitStructural = useStructuralCommit(engine);+ const commitPrepared = usePreparedCommit(engine);const { t } = useTranslation();+ // The layer's adjustments when the current gesture started; `undefined` when it had none, so undo+ // restores "no adjustments" rather than the defaults the controls display.+ const gestureBaselineRef = useRef<{ adjustments: CanvasAdjustmentsContract | undefined } | null>(null);const patchLive = useCallback((next: CanvasAdjustmentsContract) => {+ gestureBaselineRef.current ??= { adjustments: layer.adjustments };applyStructuralPreview(engine, {config: { adjustments: next, layerType: 'raster' },id: layer.id,type: 'updateCanvasLayerConfig',});},- [engine, layer.id]+ [engine, layer]);const commit = useCallback((label: string, next: CanvasAdjustmentsContract, before: CanvasAdjustmentsContract) => {- commitStructural(- label,- { config: { adjustments: next, layerType: 'raster' }, id: layer.id, type: 'updateCanvasLayerConfig' },- { config: { adjustments: before, layerType: 'raster' }, id: layer.id, type: 'updateCanvasLayerConfig' }+ const baseline = gestureBaselineRef.current ? gestureBaselineRef.current.adjustments : before;+ gestureBaselineRef.current = null;+ commitPrepared(label, (model) =>+ model.prepare({+ before: { adjustments: baseline, layerType: 'raster' },+ config: { adjustments: next, layerType: 'raster' },+ id: layer.id,+ type: 'patch-config',+ }));},- [commitStructural, layer.id]+ [commitPrepared, layer.id]);const handleScalarLive = useCallback(@@ -134,7 +146,13 @@ const AdjustmentsControls = ({ adjustments, engine, layer }: AdjustmentsControls[adjustments, patchLive]);- const handleCurveCancel = useCallback((before: CanvasAdjustmentsContract) => patchLive(before), [patchLive]);+ const handleCurveCancel = useCallback(+ (before: CanvasAdjustmentsContract) => {+ patchLive(before);+ gestureBaselineRef.current = null;+ },+ [patchLive]+ );const handleCurveCommit = useCallback((current: CanvasAdjustmentsContract, before: CanvasAdjustmentsContract) => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex 420bc50beb..e9ac9cc8c7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -20,7 +20,7 @@ import {import { useModelsSelector } from '@features/models';import { Field, Select, Slider } from '@platform/ui';import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -69,7 +69,7 @@ interface ControlLayerSettingsProps {*/export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: ControlLayerSettingsProps) => {const { t } = useTranslation();- const commitStructural = useStructuralCommit(engine);+ const commitPrepared = usePreparedCommit(engine);const models = useModelsSelector((snapshot) => snapshot.models);const mainModel = useSelectedMainModel();const base = mainModel?.base ?? null;@@ -78,13 +78,16 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contconst commitAdapter = useCallback((next: Partial<CanvasControlAdapterContract>, before: Partial<CanvasControlAdapterContract>, label: string) => {- commitStructural(- label,- { config: { adapter: next, layerType: 'control' }, id: layer.id, type: 'updateCanvasLayerConfig' },- { config: { adapter: before, layerType: 'control' }, id: layer.id, type: 'updateCanvasLayerConfig' }+ commitPrepared(label, (model) =>+ model.prepare({+ before: { adapter: before, layerType: 'control' },+ config: { adapter: next, layerType: 'control' },+ id: layer.id,+ type: 'patch-config',+ }));},- [commitStructural, layer.id]+ [commitPrepared, layer.id]);// Adapter kinds supported by the selected base. Z-Image Control is only shown@@ -247,21 +250,16 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contconst handleTransparencyToggle = useCallback(({ checked }: { checked: boolean }) => {- commitStructural(- t('widgets.layers.control.transparencyEffect'),- {+ commitPrepared(t('widgets.layers.control.transparencyEffect'), (model) =>+ model.prepare({+ before: { layerType: 'control', withTransparencyEffect: layer.withTransparencyEffect },config: { layerType: 'control', withTransparencyEffect: checked },id: layer.id,- type: 'updateCanvasLayerConfig',- },- {- config: { layerType: 'control', withTransparencyEffect: !checked },- id: layer.id,- type: 'updateCanvasLayerConfig',- }+ type: 'patch-config',+ }));},- [commitStructural, layer.id, t]+ [commitPrepared, layer.id, layer.withTransparencyEffect, t]);const controlModeCollection = useMemo(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsxindex a77370edaf..e6b3fdc0bd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx@@ -4,7 +4,7 @@ import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps'import { createListCollection, HStack, Stack } from '@chakra-ui/react';import { Button, ColorPicker, Field, Select, Slider } from '@platform/ui';-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -22,11 +22,11 @@ const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [const formatUnitPercent = (value: number): string => `${Math.round(value * 100)}%`;-const noiseConfig = (value: number) => ({ layerType: 'inpaint_mask', noiseLevel: value }) as const;-const denoiseConfig = (value: number) => ({ layerType: 'inpaint_mask', denoiseLimit: value }) as const;+const noiseConfig = (value: number | undefined) => ({ layerType: 'inpaint_mask', noiseLevel: value }) as const;+const denoiseConfig = (value: number | undefined) => ({ layerType: 'inpaint_mask', denoiseLimit: value }) as const;interface InpaintMaskSettingsProps {- engine: CanvasStructuralEngine | null;+ engine: (CanvasStructuralEngine & CanvasPreparedEngine) | null;layer: CanvasInpaintMaskLayerContract;}@@ -36,15 +36,15 @@ interface InpaintMaskSettingsProps {* denoise-limit sliders (0–1), and an in-place mask invert. `noiseLevel` /* `denoiseLimit` are wired to the contract now (consumed by the NEXT task's graph* builder); they have no generation effect yet. Fill/noise/denoise edits go- * through the canvas undo stack (`commitStructural` → `updateCanvasLayerConfig`);+ * through the canvas undo stack as prepared `patch-config` edits;* invert is an engine pixel op (its own undoable image patch).*/export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps) => {const { t } = useTranslation();- const commitStructural = useStructuralCommit(engine);+ const commitPrepared = usePreparedCommit(engine);const fillBeforeRef = useRef<CanvasMaskFillContract | null>(null);- const noiseBeforeRef = useRef<number | null>(null);- const denoiseBeforeRef = useRef<number | null>(null);+ const noiseBeforeRef = useRef<{ value: number | undefined } | null>(null);+ const denoiseBeforeRef = useRef<{ value: number | undefined } | null>(null);const fill = layer.mask.fill;const noiseLevel = layer.noiseLevel ?? 0;@@ -63,13 +63,16 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)const commitFill = useCallback((next: CanvasMaskFillContract, before: CanvasMaskFillContract) => {- commitStructural(- t('widgets.layers.maskFill.fill'),- { config: { layerType: 'inpaint_mask', mask: { fill: next } }, id: layer.id, type: 'updateCanvasLayerConfig' },- { config: { layerType: 'inpaint_mask', mask: { fill: before } }, id: layer.id, type: 'updateCanvasLayerConfig' }+ commitPrepared(t('widgets.layers.maskFill.fill'), (model) =>+ model.prepare({+ before: { layerType: 'inpaint_mask', mask: { fill: before } },+ config: { layerType: 'inpaint_mask', mask: { fill: next } },+ id: layer.id,+ type: 'patch-config',+ }));},- [commitStructural, layer.id, t]+ [commitPrepared, layer.id, t]);const handleColorChange = useCallback(@@ -124,28 +127,24 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)) {return;}- if (noiseBeforeRef.current === null) {- noiseBeforeRef.current = noiseLevel;- }+ noiseBeforeRef.current ??= { value: layer.noiseLevel };},- [engine, layer.id, noiseLevel]+ [engine, layer]);const handleNoiseChangeEnd = useCallback(({ value }: SliderValueChangeDetails) => {const next = value[0];- const before = noiseBeforeRef.current ?? noiseLevel;+ const before = noiseBeforeRef.current ? noiseBeforeRef.current.value : layer.noiseLevel;noiseBeforeRef.current = null;if (next === undefined || !Number.isFinite(next)) {return;}- commitStructural(- t('widgets.layers.maskFill.noiseLevel'),- { config: noiseConfig(next), id: layer.id, type: 'updateCanvasLayerConfig' },- { config: noiseConfig(before), id: layer.id, type: 'updateCanvasLayerConfig' }+ commitPrepared(t('widgets.layers.maskFill.noiseLevel'), (model) =>+ model.prepare({ before: noiseConfig(before), config: noiseConfig(next), id: layer.id, type: 'patch-config' }));},- [commitStructural, layer.id, noiseLevel, t]+ [commitPrepared, layer.id, layer.noiseLevel, t]);const handleDenoiseChange = useCallback(@@ -163,28 +162,29 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)) {return;}- if (denoiseBeforeRef.current === null) {- denoiseBeforeRef.current = denoiseLimit;- }+ denoiseBeforeRef.current ??= { value: layer.denoiseLimit };},- [denoiseLimit, engine, layer.id]+ [engine, layer]);const handleDenoiseChangeEnd = useCallback(({ value }: SliderValueChangeDetails) => {const next = value[0];- const before = denoiseBeforeRef.current ?? denoiseLimit;+ const before = denoiseBeforeRef.current ? denoiseBeforeRef.current.value : layer.denoiseLimit;denoiseBeforeRef.current = null;if (next === undefined || !Number.isFinite(next)) {return;}- commitStructural(- t('widgets.layers.maskFill.denoiseLimit'),- { config: denoiseConfig(next), id: layer.id, type: 'updateCanvasLayerConfig' },- { config: denoiseConfig(before), id: layer.id, type: 'updateCanvasLayerConfig' }+ commitPrepared(t('widgets.layers.maskFill.denoiseLimit'), (model) =>+ model.prepare({+ before: denoiseConfig(before),+ config: denoiseConfig(next),+ id: layer.id,+ type: 'patch-config',+ }));},- [commitStructural, denoiseLimit, layer.id, t]+ [commitPrepared, layer.denoiseLimit, layer.id, t]);const handleInvert = useCallback(() => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsxindex d2d73f7852..a34494a08e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx@@ -4,7 +4,7 @@ import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngiimport { Box, Popover, Portal, Stack, Switch, Text } from '@chakra-ui/react';import { IconButton } from '@platform/ui';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { SlidersHorizontalIcon } from 'lucide-react';import { useCallback, useState } from 'react';@@ -187,27 +187,22 @@ const RasterLayerSettings = ({layer: Extract<CanvasLayerContract, { type: 'raster' }>;onOperationStarted(): void;}) => {- const commitStructural = useStructuralCommit(engine);+ const commitPrepared = usePreparedCommit(engine);const { t } = useTranslation();const isLocked = layer.isTransparencyLocked === true;const handleTransparencyLock = useCallback((details: { checked: boolean }) => {- commitStructural(- t('widgets.layers.adjustments.transparencyLock'),- {+ commitPrepared(t('widgets.layers.adjustments.transparencyLock'), (model) =>+ model.prepare({+ before: { isTransparencyLocked: isLocked, layerType: 'raster' },config: { isTransparencyLocked: details.checked, layerType: 'raster' },id: layer.id,- type: 'updateCanvasLayerConfig',- },- {- config: { isTransparencyLocked: isLocked, layerType: 'raster' },- id: layer.id,- type: 'updateCanvasLayerConfig',- }+ type: 'patch-config',+ }));},- [commitStructural, isLocked, layer.id, t]+ [commitPrepared, isLocked, layer.id, t]);return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex 1dd292e88a..664860ffe8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -26,7 +26,7 @@ import {import { Button, ColorPicker, DropZone, Field, Select, Slider } from '@platform/ui';import { useQueryClient } from '@tanstack/react-query';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useWorkbenchCommands } from '@workbench/WorkbenchContext';import { ImageIcon, PlusIcon, XIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';@@ -81,7 +81,7 @@ const createReferenceImage = (base: string | null): RegionalGuidanceReferenceImacreateRegionalReferenceImage(base);interface RegionalGuidanceSettingsProps {- engine: CanvasStructuralEngine | null;+ engine: (CanvasStructuralEngine & CanvasPreparedEngine) | null;layer: CanvasRegionalGuidanceLayerContract;}@@ -90,12 +90,12 @@ interface RegionalGuidanceSettingsProps {* positive + negative prompt, an Auto-Negative toggle, the mask fill colour/style* + invert, and a per-region reference-images section (add/remove/enable + model* + weight, mirroring the generate widget's IP-Adapter fields). Prompt/toggle/fill- * edits go through the canvas undo stack (`commitStructural` →- * `updateCanvasLayerConfig`); invert is an engine pixel op.+ * edits go through the canvas undo stack as prepared `patch-config` edits;+ * invert is an engine pixel op.*/export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettingsProps) => {const { t } = useTranslation();- const commitStructural = useStructuralCommit(engine);+ const commitPrepared = usePreparedCommit(engine);const { notifications } = useWorkbenchCommands();const queryClient = useQueryClient();const models = useModelsSelector((snapshot) => snapshot.models);@@ -116,13 +116,16 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst commitConfig = useCallback((label: string, next: RegionalConfigPatch, before: RegionalConfigPatch) => {- commitStructural(- label,- { config: { layerType: 'regional_guidance', ...next }, id: layer.id, type: 'updateCanvasLayerConfig' },- { config: { layerType: 'regional_guidance', ...before }, id: layer.id, type: 'updateCanvasLayerConfig' }+ commitPrepared(label, (model) =>+ model.prepare({+ before: { layerType: 'regional_guidance', ...before },+ config: { layerType: 'regional_guidance', ...next },+ id: layer.id,+ type: 'patch-config',+ }));},- [commitStructural, layer.id]+ [commitPrepared, layer.id]);const handlePositiveBlur = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex be0c16e9de..f81cad3efe 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -220,7 +220,7 @@ const canMoveBackward = (context: LayerContextActionState): boolean => {};const hasMergeableLayerBelow = (context: LayerContextActionState): boolean =>- canMergeLayerDown(context.document.layers, context.index, true);+ canMergeLayerDown(context.document, context.layer.id, true);const isBooleanRasterLayer = (layer: CanvasLayerContract | undefined): boolean =>!!layer && layer.isEnabled && layer.type === 'raster' && isPixelBackedLayer(layer);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.tsindex 5ab0b8cd56..77ed01230f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts@@ -1,4 +1,8 @@-import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+} from '@workbench/canvas-engine/contracts';import { describe, expect, it, vi } from 'vitest';@@ -139,33 +143,41 @@ describe('isMergeableRasterLayer', () => {});describe('canMergeLayerDown', () => {- const layers = [paintLayer('top'), imageLayer('mid'), maskLayer('bottom')];+ const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ layers,+ selectedLayerId: null,+ version: 2,+ width: 100,+ });+ const document = documentOf([paintLayer('top'), imageLayer('mid'), maskLayer('bottom')]);it('requires an engine (merge is pixel work)', () => {- expect(canMergeLayerDown(layers, 0, false)).toBe(false);+ expect(canMergeLayerDown(document, 'top', false)).toBe(false);});it('allows merging when the layer and the one below are both mergeable', () => {- expect(canMergeLayerDown(layers, 0, true)).toBe(true);+ expect(canMergeLayerDown(document, 'top', true)).toBe(true);});it('disallows merging into a non-mergeable below layer', () => {- // index 1 (mid, image) sits above the mask layer, which cannot be merged into.- expect(canMergeLayerDown(layers, 1, true)).toBe(false);+ expect(canMergeLayerDown(document, 'mid', true)).toBe(false);});it('disallows merging the bottom-most layer (nothing below)', () => {- expect(canMergeLayerDown(layers, 2, true)).toBe(false);+ expect(canMergeLayerDown(document, 'bottom', true)).toBe(false);});it('disallows merging when the upper layer is locked', () => {- const lockedTop = [paintLayer('top', { isLocked: true }), imageLayer('mid'), maskLayer('bottom')];- expect(canMergeLayerDown(lockedTop, 0, true)).toBe(false);+ const lockedTop = documentOf([paintLayer('top', { isLocked: true }), imageLayer('mid'), maskLayer('bottom')]);+ expect(canMergeLayerDown(lockedTop, 'top', true)).toBe(false);});it('disallows merging when the below layer is locked', () => {- const lockedMid = [paintLayer('top'), { ...imageLayer('mid'), isLocked: true }, maskLayer('bottom')];- expect(canMergeLayerDown(lockedMid, 0, true)).toBe(false);+ const lockedMid = documentOf([paintLayer('top'), { ...imageLayer('mid'), isLocked: true }, maskLayer('bottom')]);+ expect(canMergeLayerDown(lockedMid, 'top', true)).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex b6aa8d2616..dd01c37876 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -24,7 +24,7 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';export type { CanvasStructuralEngine } from '@workbench/canvas-engine/api';-import { getSourceContentRect, isMergeableRasterLayer } from '@workbench/canvas-engine/api';+import { getSourceContentRect, isMergeableRasterLayer, mergeDownEligibility } from '@workbench/canvas-engine/api';import { CONTROL_ADAPTER_DEFAULTS } from '@workbench/controlAdapters';type LayerTransform = CanvasLayerBaseContract['transform'];@@ -609,23 +609,9 @@ export const convertRasterControlLayer = (return null;};-/**- * Whether the layer at `index` can be merged down: an engine must be attached- * (merge is pixel work), a layer must exist directly below it, and both that- * layer and the one below must be mergeable raster layers.- */-export const canMergeLayerDown = (- layers: readonly CanvasLayerContract[],- index: number,- hasEngine: boolean-): boolean => {- if (!hasEngine) {- return false;- }- const layer = layers[index];- const below = layers[index + 1];- return !!layer && !!below && isMergeableRasterLayer(layer) && isMergeableRasterLayer(below);-};+/** Whether the layers panel may offer merge-down for `layerId`; merging is pixel work, so it needs an engine. */+export const canMergeLayerDown = (document: CanvasDocumentContractV2, layerId: string, hasEngine: boolean): boolean =>+ hasEngine && mergeDownEligibility(document, layerId).status === 'eligible';/** Applies a guarded live edit without recording history until the interaction ends. */export const applyStructuralPreview = (engine: CanvasStructuralEngine | null, action: CanvasProjectMutation): boolean =>