Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(canvas): add the pure flat document model

Josh Corbett118a0f33b98e
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 97d561d45d..d6415974f1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -572,7 +572,6 @@ export { bboxEquals, constrainBboxToRatio, roundBbox } from './tools/bboxHitTest
export { isEmpty, union } from './math/rect';
export { ZOOM_PRESETS } from './math/snapping';
export { isLayerPixelEditEligible } from './editing/controlPixelEdit';
-export { type HideableLayer, isHideableLayer, isLayerHidden } from './document/sources';
export {
getStackOrder,
haveSameStackOrders,
@@ -587,8 +586,11 @@ export {
type ReorderFlatStackCommand,
} from './document/layerStacks';
export {
+ type HideableLayer,
+ isHideableLayer,
isLayerContributing,
isLayerEditable,
+ isLayerHidden,
isLayerPaintable,
isMergeableRasterLayer,
isLayerTransparencyLocked,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
new file mode 100644
index 0000000000..ce2cafda64
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
@@ -0,0 +1,71 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type {
+ LayerStackKind,
+ LayerStackMoveKind,
+ ReorderFlatStackCommand,
+} from '@workbench/canvas-engine/document/layerStacks';
+import type { CanvasLayerBasePatch, CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+
+import type { FlatEditPostcondition } from './postconditions';
+
+export type FlatDocumentCommand =
+ | {
+ readonly type: 'insert';
+ readonly layers: readonly CanvasLayerContract[];
+ /** Land above this layer when it belongs to the inserted layer's stack; otherwise at the stack top. */
+ readonly aboveId: string | null;
+ /** The primary selection afterwards; defaults to the last inserted layer. */
+ readonly selectId?: string | null;
+ }
+ | { readonly type: 'remove'; readonly ids: readonly string[] }
+ | { readonly type: 'duplicate'; readonly sourceId: string; readonly newId: string }
+ | { readonly type: 'move'; readonly ids: readonly string[]; readonly kind: LayerStackMoveKind }
+ | { readonly type: 'reorder'; readonly stacks: readonly ReorderFlatStackCommand[] }
+ | { readonly type: 'patch'; readonly id: string; readonly patch: CanvasLayerBasePatch }
+ | { readonly type: 'select'; readonly id: string | null };
+
+export type FlatDocumentRefusal =
+ | { readonly status: 'missing'; readonly ids: readonly string[] }
+ | { readonly status: 'locked'; readonly ids: readonly string[] }
+ | {
+ readonly status: 'wrong-type';
+ readonly expected: readonly CanvasLayerContract['type'][];
+ readonly actual: string;
+ }
+ | { readonly status: 'invalid-target'; readonly targetId: string; readonly reason: FlatInvalidTargetReason }
+ | { readonly status: 'unsupported'; readonly operation: string };
+
+export type FlatInvalidTargetReason =
+ | 'id-exists'
+ | 'foreign-stack'
+ | 'not-stack-members'
+ | 'no-layer-below'
+ | 'not-mergeable';
+
+export type FlatEditHistoryPolicy = 'record' | 'none';
+
+/** A flat edit ready for the transaction module: what to dispatch, what must hold afterwards, how to record it. */
+export interface PreparedFlatEdit {
+ readonly forward: CanvasProjectMutation;
+ readonly inverse: CanvasProjectMutation;
+ readonly projectId: string;
+ readonly expectedRevision: number;
+ readonly selectionBefore: string | null;
+ readonly selectionAfter: string | null;
+ readonly touchedIds: readonly string[];
+ readonly touchedStacks: readonly LayerStackKind[];
+ readonly postconditions: readonly FlatEditPostcondition[];
+ /** Flat commands never need prepared pixels; pixel-bearing edits keep their own controllers. */
+ readonly rasterWork: null;
+ readonly history: FlatEditHistoryPolicy;
+}
+
+export type PrepareFlatEditResult =
+ | { readonly status: 'prepared'; readonly edit: PreparedFlatEdit }
+ /** The command describes the document as it already is; there is nothing to dispatch. */
+ | { readonly status: 'unchanged' }
+ | FlatDocumentRefusal;
+
+export type MergeDownEligibility =
+ | { readonly status: 'eligible'; readonly upperId: string; readonly lowerId: string }
+ | FlatDocumentRefusal;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts
new file mode 100644
index 0000000000..226c6de82a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts
@@ -0,0 +1,474 @@
+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { Project } from '@workbench/projectContracts';
+
+import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';
+import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';
+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { describe, expect, it } from 'vitest';
+
+import type { FlatDocumentCommand, PreparedFlatEdit, PrepareFlatEditResult } from './flatDocumentCommands';
+
+import { createFlatDocumentModel, flatDocumentModelCounters } 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 interleaved = (): CanvasLayerContract[] => [
+ layer('i1', 'inpaint_mask'),
+ layer('r1'),
+ layer('c1', 'control'),
+ layer('r2'),
+ layer('g1', 'regional_guidance'),
+ layer('r3'),
+];
+
+const projectWith = (layers: CanvasLayerContract[], selectedLayerId: string | null): Project => {
+ const initial = createInitialWorkbenchState().projects[0]!;
+ const project = applyCanvasProjectMutation(initial, {
+ document: { ...createEmptyCanvasDocumentV2(), layers, selectedLayerId },
+ type: 'replaceCanvasDocument',
+ });
+ if (ids(project.canvas.document).join() !== layers.map((entry) => entry.id).join()) {
+ throw new Error('fixture document was not accepted by the reducer');
+ }
+ return project;
+};
+
+const context = (project: Project) => ({ editRevision: 0, projectId: project.id });
+const modelOf = (project: Project) => createFlatDocumentModel(project.canvas.document, context(project));
+
+const ids = (document: CanvasDocumentContractV2): string[] => document.layers.map((entry) => entry.id);
+const byId = (left: CanvasLayerContract, right: CanvasLayerContract): number => left.id.localeCompare(right.id);
+
+const roundTrip = (project: Project, command: FlatDocumentCommand): { after: Project; edit: PreparedFlatEdit } => {
+ const result = modelOf(project).prepare(command);
+ if (result.status !== 'prepared') {
+ throw new Error(`expected a prepared edit, got ${JSON.stringify(result)}`);
+ }
+ const after = applyCanvasProjectMutation(project, result.edit.forward);
+ expect(after.canvas.document).not.toBe(project.canvas.document);
+ expect(checkFlatEditPostconditions(after.canvas.document, result.edit.postconditions)).toBe(true);
+ expect(after.canvas.document.selectedLayerId).toBe(result.edit.selectionAfter);
+ const restored = applyCanvasProjectMutation(after, result.edit.inverse).canvas.document;
+ const original = project.canvas.document;
+ expect(haveSameStackOrders(restored.layers, original.layers)).toBe(true);
+ expect([...restored.layers].sort(byId)).toEqual([...original.layers].sort(byId));
+ expect({ ...restored, layers: [] }).toEqual({ ...original, layers: [] });
+ return { after, edit: result.edit };
+};
+
+describe('createFlatDocumentModel', () => {
+ it('indexes lookup and stack order once per document identity', () => {
+ const project = projectWith(interleaved(), 'r2');
+ const before = flatDocumentModelCounters.indexBuilds;
+ const model = modelOf(project);
+ const again = modelOf(project);
+
+ expect(flatDocumentModelCounters.indexBuilds).toBe(before + 1);
+ expect(model.getLayer('r2')?.id).toBe('r2');
+ expect(model.getLayer('ghost')).toBeNull();
+ expect(model.getStack('raster').map((entry) => entry.id)).toEqual(['r1', 'r2', 'r3']);
+ expect(again.getStack('raster')).toBe(model.getStack('raster'));
+ });
+
+ it('compiles semantic leaves with stack positions and world transforms', () => {
+ const project = projectWith(
+ [
+ layer('i1', 'inpaint_mask', { isHidden: true } as Partial<CanvasLayerContract>),
+ layer('r1', 'raster', { isLocked: true }),
+ ],
+ 'r1'
+ );
+ const leaves = modelOf(project).compileLeaves();
+
+ expect(leaves.map((leaf) => [leaf.id, leaf.stack, leaf.stackIndex])).toEqual([
+ ['i1', 'inpaint_mask', 0],
+ ['r1', 'raster', 0],
+ ]);
+ expect(leaves[0]).toMatchObject({ contributionEnabled: true, documentHidden: true, locked: false });
+ expect(leaves[1]).toMatchObject({ documentHidden: false, locked: true });
+ expect(leaves[1]!.worldTransform).toEqual({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ });
+
+ it('keeps leaf identity for unaffected layers across an edit and reuses leaves for a selection-only change', () => {
+ const project = projectWith(interleaved(), 'r2');
+ const first = modelOf(project);
+ const leaves = first.compileLeaves();
+ const compilations = flatDocumentModelCounters.leafCompilations;
+ const compiled = flatDocumentModelCounters.leavesCompiled;
+
+ const selected = applyCanvasProjectMutation(project, { id: 'r1', type: 'setCanvasSelectedLayer' });
+ const second = createFlatDocumentModel(selected.canvas.document, context(project), first);
+ expect(second.compileLeaves()).toBe(leaves);
+ expect(flatDocumentModelCounters.leafCompilations).toBe(compilations);
+
+ const renamed = applyCanvasProjectMutation(selected, {
+ id: 'r2',
+ patch: { name: 'Renamed' },
+ type: 'updateCanvasLayer',
+ });
+ const third = createFlatDocumentModel(renamed.canvas.document, context(project), second);
+ const next = third.compileLeaves();
+ expect(flatDocumentModelCounters.leafCompilations).toBe(compilations + 1);
+ expect(flatDocumentModelCounters.leavesCompiled).toBe(compiled + 1);
+ expect(next.filter((leaf, index) => leaf === leaves[index]).map((leaf) => leaf.id)).toEqual([
+ 'i1',
+ 'r1',
+ 'c1',
+ 'g1',
+ 'r3',
+ ]);
+ expect(next[3]!.layer.name).toBe('Renamed');
+
+ const moved = applyCanvasProjectMutation(renamed, {
+ stacks: [{ orderedIds: ['r3', 'r1', 'r2'], stack: 'raster' }],
+ type: 'reorderCanvasLayerStacks',
+ });
+ const fourth = createFlatDocumentModel(moved.canvas.document, context(project), third).compileLeaves();
+ expect(fourth.filter((leaf) => next.includes(leaf)).map((leaf) => leaf.id)).toEqual(['i1', 'c1', 'g1']);
+ });
+
+ describe('prepare', () => {
+ it('inserts above the compatible leaf and restores the previous selection on undo', () => {
+ const project = projectWith(interleaved(), 'r2');
+ const { after, edit } = roundTrip(project, { aboveId: 'r2', layers: [layer('n1')], type: 'insert' });
+
+ expect(ids(after.canvas.document)).toEqual(['i1', 'r1', 'c1', 'n1', 'r2', 'g1', 'r3']);
+ expect(edit).toMatchObject({
+ history: 'record',
+ postconditions: [
+ { kind: 'stack-order', orderedIds: ['r1', 'n1', 'r2', 'r3'], stack: 'raster' },
+ { id: 'n1', kind: 'selection' },
+ ],
+ selectionAfter: 'n1',
+ touchedIds: ['n1'],
+ touchedStacks: ['raster'],
+ });
+ });
+
+ it('inserts a foreign-stack layer at its stack top and honours an explicit selection', () => {
+ const project = projectWith(interleaved(), 'r2');
+ const { after } = roundTrip(project, {
+ aboveId: 'r2',
+ layers: [layer('m2', 'inpaint_mask')],
+ selectId: null,
+ type: 'insert',
+ });
+
+ expect(ids(after.canvas.document)).toEqual(['m2', 'i1', 'r1', 'c1', 'r2', 'g1', 'r3']);
+ expect(after.canvas.document.selectedLayerId).toBeNull();
+ });
+
+ it('keeps the given order for several layers whether or not their stacks are empty', () => {
+ const populated = roundTrip(projectWith(interleaved(), 'r1'), {
+ aboveId: null,
+ layers: [layer('a'), layer('b'), layer('m', 'inpaint_mask')],
+ type: 'insert',
+ });
+ expect(ids(populated.after.canvas.document)).toEqual(['m', 'i1', 'a', 'b', 'r1', 'c1', 'r2', 'g1', 'r3']);
+ expect(populated.edit.touchedStacks).toEqual(['inpaint_mask', 'raster']);
+
+ const empty = roundTrip(projectWith([layer('c1', 'control')], 'c1'), {
+ aboveId: null,
+ layers: [layer('a'), layer('b')],
+ type: 'insert',
+ });
+ expect(ids(empty.after.canvas.document)).toEqual(['a', 'b', 'c1']);
+ });
+
+ it('removes layers, repairs the selection within the stack, and restores them between their neighbours', () => {
+ const project = projectWith(interleaved(), 'r2');
+ const { after, edit } = roundTrip(project, { ids: ['r2', 'i1'], type: 'remove' });
+
+ expect(ids(after.canvas.document)).toEqual(['r1', 'c1', 'g1', 'r3']);
+ expect(edit).toMatchObject({
+ selectionAfter: 'r3',
+ touchedIds: ['r2', 'i1'],
+ touchedStacks: ['inpaint_mask', 'raster'],
+ });
+ });
+
+ it('falls back to another stack when the removed primary had no stack neighbour left', () => {
+ const project = projectWith(
+ [layer('c1', 'control'), layer('r1'), layer('r2'), layer('g1', 'regional_guidance')],
+ 'r2'
+ );
+ const { edit } = roundTrip(project, { ids: ['r1', 'r2'], type: 'remove' });
+ expect(edit.selectionAfter).toBe('g1');
+ });
+
+ it('duplicates above the source and removes the copy on undo', () => {
+ const project = projectWith(interleaved(), 'r1');
+ const { after, edit } = roundTrip(project, { newId: 'r2-copy', sourceId: 'r2', type: 'duplicate' });
+
+ expect(ids(after.canvas.document)).toEqual(['i1', 'r1', 'c1', 'r2-copy', 'r2', 'g1', 'r3']);
+ expect(after.canvas.document.selectedLayerId).toBe('r2-copy');
+ expect(edit.postconditions[0]).toEqual({
+ kind: 'stack-order',
+ orderedIds: ['r1', 'r2-copy', 'r2', 'r3'],
+ stack: 'raster',
+ });
+ });
+
+ it('moves within stacks and reorders several stacks at once', () => {
+ const project = projectWith(interleaved(), 'r3');
+ const moved = roundTrip(project, { ids: ['r3'], kind: 'front', type: 'move' });
+ expect(ids(moved.after.canvas.document)).toEqual(['i1', 'r3', 'c1', 'r1', 'g1', 'r2']);
+ expect(moved.edit.touchedIds).toEqual(['r3', 'r1', 'r2']);
+
+ const reordered = roundTrip(project, {
+ stacks: [
+ { orderedIds: ['r2', 'r1', 'r3'], stack: 'raster' },
+ { orderedIds: ['c1'], stack: 'control' },
+ ],
+ type: 'reorder',
+ });
+ expect(ids(reordered.after.canvas.document)).toEqual(['i1', 'r2', 'c1', 'r1', 'g1', 'r3']);
+ expect(reordered.edit).toMatchObject({ touchedIds: ['r2', 'r1'], touchedStacks: ['control', 'raster'] });
+ });
+
+ it('patches base fields and transforms with an exact inverse', () => {
+ const project = projectWith(interleaved(), 'r1');
+ const { after, edit } = roundTrip(project, {
+ id: 'r1',
+ patch: { name: 'Renamed', opacity: 0.5, transform: { x: 12 } },
+ type: 'patch',
+ });
+
+ expect(after.canvas.document.layers[1]).toMatchObject({
+ name: 'Renamed',
+ opacity: 0.5,
+ transform: { x: 12, y: 0 },
+ });
+ expect(edit.inverse).toEqual({
+ id: 'r1',
+ patch: { name: 'r1', opacity: 1, transform: { x: 0 } },
+ type: 'updateCanvasLayer',
+ });
+ expect(edit.postconditions).toEqual([
+ { id: 'r1', kind: 'patched', patch: { name: 'Renamed', opacity: 0.5, transform: { x: 12 } } },
+ ]);
+ });
+
+ it('patches locked or disabled layers like the current inputs do and reports a same-value patch as unchanged', () => {
+ const project = projectWith([layer('locked', 'raster', { isEnabled: false, isLocked: true })], 'locked');
+ const model = modelOf(project);
+ expect(model.prepare({ id: 'locked', patch: { name: 'x', opacity: 0.2 }, type: 'patch' }).status).toBe(
+ 'prepared'
+ );
+ expect(model.prepare({ id: 'locked', patch: { isEnabled: true, isLocked: false }, type: 'patch' }).status).toBe(
+ 'prepared'
+ );
+ expect(model.prepare({ id: 'locked', patch: { transform: { x: 1 } }, type: 'patch' }).status).toBe('prepared');
+ expect(model.prepare({ id: 'locked', patch: { name: 'locked', transform: { x: 0 } }, type: 'patch' })).toEqual({
+ status: 'unchanged',
+ });
+ });
+
+ it('selects without recording history and reports the current selection as unchanged', () => {
+ const project = projectWith(interleaved(), 'r1');
+ const { edit } = roundTrip(project, { id: 'c1', type: 'select' });
+ expect(edit).toMatchObject({ history: 'none', selectionAfter: 'c1', selectionBefore: 'r1', touchedIds: [] });
+ expect(modelOf(project).prepare({ id: 'r1', type: 'select' })).toEqual({ status: 'unchanged' });
+ });
+
+ it.each<[string, FlatDocumentCommand, PrepareFlatEditResult]>([
+ ['a move already at the boundary', { ids: ['r1'], kind: 'front', type: 'move' }, { status: 'unchanged' }],
+ [
+ 'a reorder that keeps the order',
+ { stacks: [{ orderedIds: ['r1', 'r2', 'r3'], stack: 'raster' }], type: 'reorder' },
+ { status: 'unchanged' },
+ ],
+ ])('reports %s as unchanged', (_label, command, result) => {
+ expect(modelOf(projectWith(interleaved(), 'r1')).prepare(command)).toEqual(result);
+ });
+
+ it.each<[string, FlatDocumentCommand, PrepareFlatEditResult]>([
+ ['a missing removal', { ids: ['ghost', 'r1'], type: 'remove' }, { ids: ['ghost'], status: 'missing' }],
+ ['a locked removal', { ids: ['locked'], type: 'remove' }, { ids: ['locked'], status: 'locked' }],
+ ['an empty removal', { ids: [], type: 'remove' }, { operation: 'remove nothing', status: 'unsupported' }],
+ [
+ 'a clashing insert',
+ { aboveId: null, layers: [layer('r1')], type: 'insert' },
+ { reason: 'id-exists', status: 'invalid-target', targetId: 'r1' },
+ ],
+ [
+ 'an empty insert',
+ { aboveId: null, layers: [], type: 'insert' },
+ { operation: 'insert nothing', status: 'unsupported' },
+ ],
+ [
+ 'a missing duplicate source',
+ { newId: 'x', sourceId: 'ghost', type: 'duplicate' },
+ { ids: ['ghost'], status: 'missing' },
+ ],
+ [
+ 'a duplicate onto an existing id',
+ { newId: 'r1', sourceId: 'r2', type: 'duplicate' },
+ { reason: 'id-exists', status: 'invalid-target', targetId: 'r1' },
+ ],
+ ['an empty move', { ids: [], kind: 'front', type: 'move' }, { operation: 'move nothing', status: 'unsupported' }],
+ [
+ 'a reorder missing a member',
+ { stacks: [{ orderedIds: ['r1'], stack: 'raster' }], type: 'reorder' },
+ { reason: 'not-stack-members', status: 'invalid-target', targetId: 'r1' },
+ ],
+ [
+ 'a reorder naming a foreign id',
+ { stacks: [{ orderedIds: ['r1', 'r2', 'c1'], stack: 'raster' }], type: 'reorder' },
+ { reason: 'foreign-stack', status: 'invalid-target', targetId: 'c1' },
+ ],
+ [
+ 'a reorder naming an unknown id',
+ { stacks: [{ orderedIds: ['r1', 'r2', 'ghost'], stack: 'raster' }], type: 'reorder' },
+ { ids: ['ghost'], status: 'missing' },
+ ],
+ [
+ 'a reorder of one stack twice',
+ {
+ stacks: [
+ { orderedIds: ['r2', 'r1', 'r3'], stack: 'raster' },
+ { orderedIds: ['r1', 'r2', 'r3'], stack: 'raster' },
+ ],
+ type: 'reorder',
+ },
+ { operation: 'reorder one stack twice', status: 'unsupported' },
+ ],
+ [
+ 'a patch of nothing',
+ { id: 'r1', patch: {}, type: 'patch' },
+ { operation: 'patch nothing', status: 'unsupported' },
+ ],
+ ['a selection of a missing layer', { id: 'ghost', type: 'select' }, { ids: ['ghost'], status: 'missing' }],
+ ])('refuses %s', (_label, command, refusal) => {
+ const project = projectWith([...interleaved(), layer('locked', 'raster', { isLocked: true })], 'r1');
+ expect(modelOf(project).prepare(command)).toEqual(refusal);
+ });
+
+ it('stamps every prepared edit with the project id and edit revision it was built against', () => {
+ const project = projectWith(interleaved(), 'r1');
+ const result = createFlatDocumentModel(project.canvas.document, {
+ editRevision: 7,
+ projectId: project.id,
+ }).prepare({
+ ids: ['r1'],
+ type: 'remove',
+ });
+ expect(result).toMatchObject({ edit: { expectedRevision: 7, projectId: project.id }, status: 'prepared' });
+ });
+ });
+
+ describe('canMergeDown', () => {
+ it('targets the layer directly below in flat order, like the reducer', () => {
+ const project = projectWith([layer('a'), layer('b'), layer('c1', 'control'), layer('r2')], 'a');
+ const model = modelOf(project);
+ expect(model.canMergeDown('a')).toEqual({ lowerId: 'b', status: 'eligible', upperId: 'a' });
+ expect(model.canMergeDown('b')).toEqual({ reason: 'not-mergeable', status: 'invalid-target', targetId: 'c1' });
+ });
+
+ it('reports an unmergeable neighbour before a lock and a lock before a disabled layer', () => {
+ const lockedControl = projectWith([layer('r1'), layer('c1', 'control', { isLocked: true })], null);
+ expect(modelOf(lockedControl).canMergeDown('r1')).toEqual({
+ reason: 'not-mergeable',
+ status: 'invalid-target',
+ targetId: 'c1',
+ });
+ const lockedUpper = projectWith([layer('a', 'raster', { isEnabled: false, isLocked: true }), layer('b')], null);
+ expect(modelOf(lockedUpper).canMergeDown('a')).toEqual({ ids: ['a'], status: 'locked' });
+ });
+
+ it.each<[string, CanvasLayerContract[], string, object]>([
+ ['the bottom layer', interleaved(), 'r3', { reason: 'no-layer-below', status: 'invalid-target', targetId: 'r3' }],
+ ['a mask', interleaved(), 'i1', { actual: 'inpaint_mask', expected: ['raster'], status: 'wrong-type' }],
+ ['a missing id', interleaved(), 'ghost', { ids: ['ghost'], status: 'missing' }],
+ [
+ 'a locked lower layer',
+ [layer('a'), layer('b', 'raster', { isLocked: true })],
+ 'a',
+ { ids: ['b'], status: 'locked' },
+ ],
+ [
+ 'a disabled upper layer',
+ [layer('a', 'raster', { isEnabled: false }), layer('b')],
+ 'a',
+ { reason: 'not-mergeable', status: 'invalid-target', targetId: 'a' },
+ ],
+ ])('refuses %s', (_label, layers, upperId, refusal) => {
+ expect(modelOf(projectWith(layers, null)).canMergeDown(upperId)).toEqual(refusal);
+ });
+ });
+});
+
+describe('checkFlatEditPostconditions', () => {
+ const document = projectWith(interleaved(), 'r2').canvas.document;
+
+ it.each([
+ ['present ids', { ids: ['r1', 'c1'], kind: 'present' as const }, true],
+ ['a missing present id', { ids: ['r1', 'ghost'], kind: 'present' as const }, false],
+ ['absent ids', { ids: ['ghost'], kind: 'absent' as const }, true],
+ ['a present absent id', { ids: ['r1'], kind: 'absent' as const }, false],
+ [
+ 'the exact stack order',
+ { kind: 'stack-order' as const, orderedIds: ['r1', 'r2', 'r3'], stack: 'raster' as const },
+ true,
+ ],
+ [
+ 'a shorter stack order',
+ { kind: 'stack-order' as const, orderedIds: ['r1', 'r2'], stack: 'raster' as const },
+ false,
+ ],
+ [
+ 'a permuted stack order',
+ { kind: 'stack-order' as const, orderedIds: ['r2', 'r1', 'r3'], stack: 'raster' as const },
+ false,
+ ],
+ ['the selection', { id: 'r2', kind: 'selection' as const }, true],
+ ['another selection', { id: 'r1', kind: 'selection' as const }, false],
+ ['an applied patch', { id: 'r1', kind: 'patched' as const, patch: { name: 'r1', transform: { x: 0 } } }, true],
+ ['an unapplied patch', { id: 'r1', kind: 'patched' as const, patch: { name: 'r1', transform: { x: 3 } } }, false],
+ ['a patch of a missing layer', { id: 'ghost', kind: 'patched' as const, patch: { name: 'x' } }, false],
+ ])('checks %s', (_label, postcondition, expected) => {
+ expect(checkFlatEditPostconditions(document, [postcondition])).toBe(expected);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
new file mode 100644
index 0000000000..9156c23481
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
@@ -0,0 +1,450 @@
+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertion } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
+import type { CanvasLayerBasePatch, CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+
+import {
+ captureInsertionAnchor,
+ captureRestoreAnchor,
+ insertLayersAtAnchor,
+} from '@workbench/canvas-engine/document/insertionAnchors';
+import { isLayerContributing, isPixelBackedLayer } from '@workbench/canvas-engine/document/layerEligibility';
+import {
+ getStackOrder,
+ LAYER_STACKS_TOP_FIRST,
+ layerStackOf,
+ moveLayersWithinStacks,
+ reorderLayerStack,
+} from '@workbench/canvas-engine/document/layerStacks';
+import { repairSelectedLayerId } from '@workbench/canvas-engine/document/selectionRepair';
+
+import type {
+ FlatDocumentCommand,
+ FlatDocumentRefusal,
+ MergeDownEligibility,
+ PreparedFlatEdit,
+ PrepareFlatEditResult,
+} from './flatDocumentCommands';
+import type { FlatEditPostcondition } from './postconditions';
+import type { SemanticLeafV2 } from './semanticLeaf';
+
+import { isPatchApplied } from './postconditions';
+import { compileSemanticLeaf } from './semanticLeaf';
+
+export interface FlatDocumentModelContext {
+ readonly projectId: string;
+ readonly editRevision: number;
+}
+
+/**
+ * The pure document seam over a v2 canvas document: lookup, stack order, semantic leaves and
+ * prepared flat edits, with no knowledge of the engine, the screen or the panel. Indexes are built
+ * once per document identity and leaves keep their identity while their layer and stack position
+ * are unchanged.
+ */
+export interface FlatCanvasDocumentModel {
+ readonly document: CanvasDocumentContractV2;
+ getLayer(id: string): CanvasLayerContract | null;
+ getStack(kind: LayerStackKind): readonly CanvasLayerContract[];
+ compileLeaves(): readonly SemanticLeafV2[];
+ canMergeDown(upperId: string): MergeDownEligibility;
+ prepare(command: FlatDocumentCommand): PrepareFlatEditResult;
+}
+
+interface LayerIndexEntry {
+ readonly layer: CanvasLayerContract;
+ readonly index: number;
+ readonly stack: LayerStackKind;
+ readonly stackIndex: number;
+}
+
+interface DocumentIndex {
+ readonly byId: ReadonlyMap<string, LayerIndexEntry>;
+ readonly stacks: Readonly<Record<LayerStackKind, readonly CanvasLayerContract[]>>;
+ leaves: readonly SemanticLeafV2[] | null;
+}
+
+/** Deterministic work counters for budget tests; never consulted by production logic. */
+export const flatDocumentModelCounters = { indexBuilds: 0, leafCompilations: 0, leavesCompiled: 0 };
+
+const indexes = new WeakMap<CanvasDocumentContractV2, DocumentIndex>();
+
+const buildIndex = (document: CanvasDocumentContractV2): DocumentIndex => {
+ flatDocumentModelCounters.indexBuilds += 1;
+ const byId = new Map<string, LayerIndexEntry>();
+ const stacks: Record<LayerStackKind, CanvasLayerContract[]> = {
+ control: [],
+ inpaint_mask: [],
+ raster: [],
+ regional_guidance: [],
+ };
+ document.layers.forEach((layer, index) => {
+ const stack = layerStackOf(layer);
+ byId.set(layer.id, { index, layer, stack, stackIndex: stacks[stack].length });
+ stacks[stack].push(layer);
+ });
+ return { byId, leaves: null, stacks };
+};
+
+const indexOf = (document: CanvasDocumentContractV2): DocumentIndex => {
+ const existing = indexes.get(document);
+ if (existing) {
+ return existing;
+ }
+ const built = buildIndex(document);
+ indexes.set(document, built);
+ return built;
+};
+
+const compileLeaves = (
+ document: CanvasDocumentContractV2,
+ index: DocumentIndex,
+ previous: FlatCanvasDocumentModel | null
+): readonly SemanticLeafV2[] => {
+ if (index.leaves) {
+ return index.leaves;
+ }
+ const reusable = previous ? indexOf(previous.document).leaves : null;
+ if (reusable && previous?.document.layers === document.layers) {
+ index.leaves = reusable;
+ return reusable;
+ }
+ flatDocumentModelCounters.leafCompilations += 1;
+ const previousById = new Map(reusable?.map((leaf) => [leaf.id, leaf]) ?? []);
+ const leaves = document.layers.map((layer) => {
+ const entry = index.byId.get(layer.id)!;
+ const before = previousById.get(layer.id);
+ if (before && before.layer === layer && before.stackIndex === entry.stackIndex) {
+ return before;
+ }
+ flatDocumentModelCounters.leavesCompiled += 1;
+ return compileSemanticLeaf(layer, entry.stackIndex);
+ });
+ index.leaves = leaves;
+ return leaves;
+};
+
+const unique = <T>(values: readonly T[]): T[] => [...new Set(values)];
+
+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[]
+): FlatEditPostcondition[] =>
+ stacks.map((stack) => ({ kind: 'stack-order', orderedIds: getStackOrder(layers, stack).orderedIds, stack }));
+
+const patchInverse = (layer: CanvasLayerContract, patch: CanvasLayerBasePatch): CanvasLayerBasePatch => {
+ const inverse: Record<string, unknown> = {};
+ for (const key of Object.keys(patch) as (keyof CanvasLayerBasePatch)[]) {
+ if (key === 'transform') {
+ const transform: Record<string, number> = {};
+ for (const axis of Object.keys(patch.transform ?? {}) as (keyof CanvasLayerContract['transform'])[]) {
+ transform[axis] = layer.transform[axis];
+ }
+ inverse.transform = transform;
+ } else {
+ inverse[key] = layer[key];
+ }
+ }
+ return inverse as CanvasLayerBasePatch;
+};
+
+export const createFlatDocumentModel = (
+ document: CanvasDocumentContractV2,
+ context: FlatDocumentModelContext,
+ previous: FlatCanvasDocumentModel | null = null
+): FlatCanvasDocumentModel => {
+ const index = indexOf(document);
+ const { layers, selectedLayerId } = document;
+
+ const lookup = (ids: readonly string[]): { entries: LayerIndexEntry[] } | FlatDocumentRefusal => {
+ const absent = ids.filter((id) => !index.byId.has(id));
+ return absent.length > 0 ? missing(absent) : { entries: ids.map((id) => index.byId.get(id)!) };
+ };
+
+ const prepared = (
+ forward: CanvasProjectMutation,
+ inverse: CanvasProjectMutation,
+ detail: Omit<
+ PreparedFlatEdit,
+ 'forward' | 'inverse' | 'projectId' | 'expectedRevision' | 'selectionBefore' | 'rasterWork'
+ >
+ ): PrepareFlatEditResult => ({
+ edit: {
+ ...detail,
+ expectedRevision: context.editRevision,
+ forward,
+ inverse,
+ projectId: context.projectId,
+ rasterWork: null,
+ selectionBefore: selectedLayerId,
+ },
+ status: 'prepared',
+ });
+
+ const prepareInsert = (command: Extract<FlatDocumentCommand, { type: 'insert' }>): PrepareFlatEditResult => {
+ if (command.layers.length === 0) {
+ return { operation: 'insert nothing', status: 'unsupported' };
+ }
+ const ids = command.layers.map((layer) => layer.id);
+ const clash = ids.find((id, at) => index.byId.has(id) || ids.indexOf(id) !== at);
+ if (clash !== undefined) {
+ return { reason: 'id-exists', status: 'invalid-target', targetId: clash };
+ }
+ const selectionAfter = command.selectId === undefined ? ids.at(-1)! : command.selectId;
+ if (selectionAfter !== null && !ids.includes(selectionAfter) && !index.byId.has(selectionAfter)) {
+ return missing([selectionAfter]);
+ }
+ const touchedStacks = stacksTopFirst(command.layers.map(layerStackOf));
+ const add: FlatLayerInsertion[] = touchedStacks.map((stack) => ({
+ anchor: captureInsertionAnchor(layers, {
+ aboveId: command.aboveId,
+ editRevision: context.editRevision,
+ projectId: context.projectId,
+ stack,
+ }),
+ layers: command.layers.filter((layer) => layerStackOf(layer) === stack),
+ }));
+ const expected = add.reduce(
+ (next, insertion) => insertLayersAtAnchor(next, insertion.anchor, insertion.layers),
+ layers
+ );
+ return prepared(
+ { add, enabledUpdates: [], selectedLayerId: selectionAfter, type: 'applyCanvasLayerStackMutation' },
+ { enabledUpdates: [], removeIds: ids, selectedLayerId, type: 'applyCanvasLayerStackMutation' },
+ {
+ history: 'record',
+ postconditions: [...stackOrders(expected, touchedStacks), { id: selectionAfter, kind: 'selection' }],
+ selectionAfter,
+ touchedIds: ids,
+ touchedStacks,
+ }
+ );
+ };
+
+ const prepareRemove = (command: Extract<FlatDocumentCommand, { type: 'remove' }>): PrepareFlatEditResult => {
+ const ids = unique(command.ids);
+ if (ids.length === 0) {
+ return { operation: 'remove nothing', status: 'unsupported' };
+ }
+ const found = lookup(ids);
+ if ('status' in found) {
+ return found;
+ }
+ const locked = found.entries.filter((entry) => entry.layer.isLocked).map((entry) => entry.layer.id);
+ if (locked.length > 0) {
+ return { ids: locked, status: 'locked' };
+ }
+ const removed = new Set(ids);
+ const remaining = layers.filter((layer) => !removed.has(layer.id));
+ const selectionAfter = repairSelectedLayerId(remaining, selectedLayerId, layers);
+ const touchedStacks = stacksTopFirst(found.entries.map((entry) => entry.stack));
+ const add: FlatLayerInsertion[] = layers
+ .filter((layer) => removed.has(layer.id))
+ .map((layer) => ({
+ anchor: captureRestoreAnchor(layers, layer.id, context.projectId, context.editRevision)!,
+ layers: [layer],
+ }));
+ return prepared(
+ { ids: [...ids], type: 'removeCanvasLayers' },
+ { add, enabledUpdates: [], selectedLayerId, type: 'applyCanvasLayerStackMutation' },
+ {
+ history: 'record',
+ postconditions: [...stackOrders(remaining, touchedStacks), { id: selectionAfter, kind: 'selection' }],
+ selectionAfter,
+ touchedIds: ids,
+ touchedStacks,
+ }
+ );
+ };
+
+ const prepareDuplicate = (command: Extract<FlatDocumentCommand, { type: 'duplicate' }>): PrepareFlatEditResult => {
+ const source = index.byId.get(command.sourceId);
+ if (!source) {
+ return missing([command.sourceId]);
+ }
+ if (index.byId.has(command.newId)) {
+ return { reason: 'id-exists', status: 'invalid-target', targetId: command.newId };
+ }
+ const stackIds = getStackOrder(layers, source.stack).orderedIds;
+ const orderedIds = [...stackIds.slice(0, source.stackIndex), command.newId, ...stackIds.slice(source.stackIndex)];
+ return prepared(
+ { newId: command.newId, sourceId: command.sourceId, type: 'duplicateCanvasLayer' },
+ { enabledUpdates: [], removeIds: [command.newId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },
+ {
+ history: 'record',
+ postconditions: [
+ { kind: 'stack-order', orderedIds, stack: source.stack },
+ { id: command.newId, kind: 'selection' },
+ ],
+ selectionAfter: command.newId,
+ touchedIds: [command.newId],
+ touchedStacks: [source.stack],
+ }
+ );
+ };
+
+ const prepareReorder = (
+ stacks: readonly { stack: LayerStackKind; orderedIds: readonly string[] }[]
+ ): PrepareFlatEditResult => {
+ if (stacks.length === 0) {
+ return { operation: 'reorder nothing', status: 'unsupported' };
+ }
+ if (new Set(stacks.map((command) => command.stack)).size !== stacks.length) {
+ return { operation: 'reorder one stack twice', status: 'unsupported' };
+ }
+ const touchedIds: string[] = [];
+ for (const command of stacks) {
+ const current = getStackOrder(layers, command.stack).orderedIds;
+ const unknown = command.orderedIds.filter((id) => !index.byId.has(id));
+ if (unknown.length > 0) {
+ return missing(unknown);
+ }
+ const foreign = command.orderedIds.find((id) => index.byId.get(id)!.stack !== command.stack);
+ if (foreign !== undefined) {
+ return { reason: 'foreign-stack', status: 'invalid-target', targetId: foreign };
+ }
+ if (!reorderLayerStack(layers, command)) {
+ return {
+ reason: 'not-stack-members',
+ status: 'invalid-target',
+ targetId: command.orderedIds[0] ?? current[0]!,
+ };
+ }
+ touchedIds.push(...command.orderedIds.filter((id, position) => current[position] !== id));
+ }
+ if (touchedIds.length === 0) {
+ return { status: 'unchanged' };
+ }
+ return prepared(
+ {
+ stacks: stacks.map((command) => ({ orderedIds: [...command.orderedIds], stack: command.stack })),
+ type: 'reorderCanvasLayerStacks',
+ },
+ { stacks: stacks.map((command) => getStackOrder(layers, command.stack)), type: 'reorderCanvasLayerStacks' },
+ {
+ history: 'record',
+ postconditions: stacks.map((command) => ({
+ kind: 'stack-order',
+ orderedIds: command.orderedIds,
+ stack: command.stack,
+ })),
+ selectionAfter: selectedLayerId,
+ touchedIds,
+ touchedStacks: stacksTopFirst(stacks.map((command) => command.stack)),
+ }
+ );
+ };
+
+ const prepareMove = (command: Extract<FlatDocumentCommand, { type: 'move' }>): PrepareFlatEditResult => {
+ const ids = unique(command.ids);
+ if (ids.length === 0) {
+ return { operation: 'move nothing', status: 'unsupported' };
+ }
+ const found = lookup(ids);
+ if ('status' in found) {
+ return found;
+ }
+ const stacks = moveLayersWithinStacks(layers, ids, command.kind);
+ return stacks.length === 0 ? { status: 'unchanged' } : prepareReorder(stacks);
+ };
+
+ const preparePatch = (command: Extract<FlatDocumentCommand, { type: 'patch' }>): PrepareFlatEditResult => {
+ const entry = index.byId.get(command.id);
+ if (!entry) {
+ return missing([command.id]);
+ }
+ if (Object.keys(command.patch).length === 0) {
+ return { operation: 'patch nothing', status: 'unsupported' };
+ }
+ if (isPatchApplied(entry.layer, command.patch)) {
+ return { status: 'unchanged' };
+ }
+ return prepared(
+ { id: command.id, patch: command.patch, type: 'updateCanvasLayer' },
+ { id: command.id, patch: patchInverse(entry.layer, command.patch), type: 'updateCanvasLayer' },
+ {
+ history: 'record',
+ postconditions: [{ id: command.id, kind: 'patched', patch: command.patch }],
+ selectionAfter: selectedLayerId,
+ touchedIds: [command.id],
+ touchedStacks: [entry.stack],
+ }
+ );
+ };
+
+ const prepareSelect = (command: Extract<FlatDocumentCommand, { type: 'select' }>): PrepareFlatEditResult => {
+ if (command.id !== null && !index.byId.has(command.id)) {
+ return missing([command.id]);
+ }
+ if (command.id === selectedLayerId) {
+ return { status: 'unchanged' };
+ }
+ return prepared(
+ { id: command.id, type: 'setCanvasSelectedLayer' },
+ { id: selectedLayerId, type: 'setCanvasSelectedLayer' },
+ {
+ history: 'none',
+ postconditions: [{ id: command.id, kind: 'selection' }],
+ selectionAfter: command.id,
+ touchedIds: [],
+ touchedStacks: [],
+ }
+ );
+ };
+
+ return {
+ canMergeDown: (upperId) => {
+ 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 };
+ },
+ compileLeaves: () => compileLeaves(document, index, previous),
+ document,
+ getLayer: (id) => index.byId.get(id)?.layer ?? null,
+ getStack: (kind) => index.stacks[kind],
+ prepare: (command) => {
+ switch (command.type) {
+ case 'insert':
+ return prepareInsert(command);
+ case 'remove':
+ return prepareRemove(command);
+ case 'duplicate':
+ return prepareDuplicate(command);
+ case 'move':
+ return prepareMove(command);
+ case 'reorder':
+ return prepareReorder(command.stacks);
+ case 'patch':
+ return preparePatch(command);
+ case 'select':
+ return prepareSelect(command);
+ }
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts
new file mode 100644
index 0000000000..5d75ca5af2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts
@@ -0,0 +1,49 @@
+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
+import type { CanvasLayerBasePatch } from '@workbench/canvas-engine/mutationContracts';
+
+import { getStackOrder } from '@workbench/canvas-engine/document/layerStacks';
+
+/** What a document must show after a prepared edit landed; evaluated against the reducer document. */
+export type FlatEditPostcondition =
+ | { readonly kind: 'present'; readonly ids: readonly string[] }
+ | { readonly kind: 'absent'; readonly ids: readonly string[] }
+ | { readonly kind: 'stack-order'; readonly stack: LayerStackKind; readonly orderedIds: readonly string[] }
+ | { readonly kind: 'selection'; readonly id: string | null }
+ | { readonly kind: 'patched'; readonly id: string; readonly patch: CanvasLayerBasePatch };
+
+/** Whether every field named by `patch` already holds its patched value on `layer`. */
+export const isPatchApplied = (layer: CanvasLayerContract, patch: CanvasLayerBasePatch): boolean =>
+ (Object.keys(patch) as (keyof CanvasLayerBasePatch)[]).every((key) =>
+ key === 'transform'
+ ? (Object.keys(patch.transform ?? {}) as (keyof CanvasLayerContract['transform'])[]).every(
+ (axis) => layer.transform[axis] === patch.transform?.[axis]
+ )
+ : layer[key] === patch[key]
+ );
+
+export const checkFlatEditPostconditions = (
+ document: CanvasDocumentContractV2,
+ postconditions: readonly FlatEditPostcondition[]
+): boolean =>
+ postconditions.every((postcondition) => {
+ switch (postcondition.kind) {
+ case 'present':
+ return postcondition.ids.every((id) => document.layers.some((layer) => layer.id === id));
+ case 'absent':
+ return postcondition.ids.every((id) => !document.layers.some((layer) => layer.id === id));
+ case 'stack-order': {
+ const { orderedIds } = getStackOrder(document.layers, postcondition.stack);
+ return (
+ orderedIds.length === postcondition.orderedIds.length &&
+ orderedIds.every((id, index) => id === postcondition.orderedIds[index])
+ );
+ }
+ case 'selection':
+ return document.selectedLayerId === postcondition.id;
+ case 'patched': {
+ const layer = document.layers.find((candidate) => candidate.id === postcondition.id);
+ return layer !== undefined && isPatchApplied(layer, postcondition.patch);
+ }
+ }
+ });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts
new file mode 100644
index 0000000000..e3fcfccf3d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts
@@ -0,0 +1,75 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+
+import { describe, expect, it } from 'vitest';
+
+import type { CanvasScreenViewState } from './screenComposition';
+
+import { planScreenComposition } from './screenComposition';
+import { compileSemanticLeaf } from './semanticLeaf';
+
+const leaf = (
+ id: string,
+ type: CanvasLayerContract['type'],
+ overrides: Partial<CanvasLayerContract> = {},
+ stackIndex = 0
+) =>
+ compileSemanticLeaf(
+ {
+ id,
+ isEnabled: true,
+ isLocked: false,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type,
+ ...overrides,
+ } as CanvasLayerContract,
+ stackIndex
+ );
+
+const view = (overrides: Partial<CanvasScreenViewState> = {}): CanvasScreenViewState => ({
+ isolationLayerId: null,
+ showOverlayStacks: { control: true, inpaint_mask: true, regional_guidance: true },
+ ...overrides,
+});
+
+const leaves = [
+ leaf('i1', 'inpaint_mask'),
+ leaf('r1', 'raster'),
+ leaf('c1', 'control', { isHidden: true } as Partial<CanvasLayerContract>),
+ leaf('r2', 'raster', { isEnabled: false }, 1),
+ leaf('g1', 'regional_guidance'),
+ leaf('r3', 'raster', {}, 2),
+];
+
+const drawn = (plan: ReturnType<typeof planScreenComposition>): string[] => plan.leaves.map((leaf) => leaf.id);
+
+describe('planScreenComposition', () => {
+ it('draws contributing, unhidden leaves stack by stack, bottom first', () => {
+ expect(drawn(planScreenComposition(leaves, view()))).toEqual(['r3', 'r1', 'g1', 'i1']);
+ });
+
+ it('applies overlay stack switches without touching raster leaves', () => {
+ const plan = planScreenComposition(
+ leaves,
+ view({ showOverlayStacks: { control: true, inpaint_mask: false, regional_guidance: false } })
+ );
+ expect(drawn(plan)).toEqual(['r3', 'r1']);
+ });
+
+ it('isolates one drawable leaf regardless of the stack switches', () => {
+ const plan = planScreenComposition(
+ leaves,
+ view({
+ isolationLayerId: 'g1',
+ showOverlayStacks: { control: false, inpaint_mask: false, regional_guidance: false },
+ })
+ );
+ expect(plan).toEqual({ isolationLayerId: 'g1', leaves: [leaves[4]] });
+ expect(drawn(planScreenComposition(leaves, view({ isolationLayerId: 'r1' })))).toEqual(['r1']);
+ });
+
+ it('draws nothing when the isolated leaf is hidden, disabled or absent', () => {
+ for (const isolationLayerId of ['c1', 'r2', 'ghost']) {
+ expect(planScreenComposition(leaves, view({ isolationLayerId })).leaves).toEqual([]);
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts
new file mode 100644
index 0000000000..01eaf7d6dd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts
@@ -0,0 +1,43 @@
+import type { LayerStackKind, OverlayStackKind } from '@workbench/canvas-engine/document/layerStacks';
+
+import { LAYER_STACK_ORDER } from '@workbench/canvas-engine/document/layerStacks';
+
+import type { SemanticLeafV2 } from './semanticLeaf';
+
+/** Screen-only state that never enters the document: overlay stack switches and isolation. */
+export interface CanvasScreenViewState {
+ readonly showOverlayStacks: Readonly<Record<OverlayStackKind, boolean>>;
+ readonly isolationLayerId: string | null;
+}
+
+/** Leaves to draw, bottom first, after the view state is applied to the document facts. */
+export interface ScreenCompositionPlan {
+ readonly leaves: readonly SemanticLeafV2[];
+ readonly isolationLayerId: string | null;
+}
+
+const isStackShown = (stack: LayerStackKind, view: CanvasScreenViewState): boolean =>
+ stack === 'raster' || view.showOverlayStacks[stack];
+
+/**
+ * Isolation narrows the frame to one leaf; it never draws a leaf the document itself would not
+ * draw, so a disabled or hidden isolated leaf produces an empty plan.
+ */
+export const planScreenComposition = (
+ leaves: readonly SemanticLeafV2[],
+ view: CanvasScreenViewState
+): ScreenCompositionPlan => {
+ const drawn: SemanticLeafV2[] = [];
+ for (const stack of LAYER_STACK_ORDER) {
+ for (let index = leaves.length - 1; index >= 0; index -= 1) {
+ const leaf = leaves[index]!;
+ if (leaf.stack !== stack || !leaf.contributionEnabled || leaf.documentHidden) {
+ continue;
+ }
+ if (view.isolationLayerId === null ? isStackShown(stack, view) : leaf.id === view.isolationLayerId) {
+ drawn.push(leaf);
+ }
+ }
+ }
+ return { isolationLayerId: view.isolationLayerId, leaves: drawn };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticLeaf.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticLeaf.ts
new file mode 100644
index 0000000000..278773634d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticLeaf.ts
@@ -0,0 +1,36 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
+import type { Mat2d } from '@workbench/canvas-engine/types';
+
+import { isLayerContributing, isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';
+import { layerStackOf } from '@workbench/canvas-engine/document/layerStacks';
+import { fromTRS } from '@workbench/canvas-engine/math/mat2d';
+
+/** Document facts about one layer; nothing about the screen, the panel or the session. */
+export interface SemanticLeafV2 {
+ readonly id: string;
+ readonly stack: LayerStackKind;
+ /** Position within its own stack, 0 = top. */
+ readonly stackIndex: number;
+ readonly layer: CanvasLayerContract;
+ readonly contributionEnabled: boolean;
+ readonly documentHidden: boolean;
+ readonly locked: boolean;
+ readonly worldTransform: Mat2d;
+}
+
+export const compileSemanticLeaf = (layer: CanvasLayerContract, stackIndex: number): SemanticLeafV2 => ({
+ contributionEnabled: isLayerContributing(layer),
+ documentHidden: isLayerHidden(layer),
+ id: layer.id,
+ layer,
+ locked: layer.isLocked,
+ stack: layerStackOf(layer),
+ stackIndex,
+ worldTransform: fromTRS(
+ { x: layer.transform.x, y: layer.transform.y },
+ layer.transform.rotation,
+ layer.transform.scaleX,
+ layer.transform.scaleY
+ ),
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts
index 79edd6587c..595f28dd28 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerEligibility.ts
@@ -14,6 +14,15 @@ export const isLayerTransparencyLocked = (layer: CanvasLayerContract): boolean =
export const isLayerPaintable = (layer: CanvasLayerContract): boolean =>
isLayerEditable(layer) && layer.type !== 'control';
+/** Overlay layers show where an effect applies, so they can be hidden on screen without leaving generation. */
+export type HideableLayer = Extract<CanvasLayerContract, { type: 'control' | 'inpaint_mask' | 'regional_guidance' }>;
+
+export const isHideableLayer = (layer: CanvasLayerContract): layer is HideableLayer =>
+ layer.type === 'control' || layer.type === 'inpaint_mask' || layer.type === 'regional_guidance';
+
+/** Display only: generation and export never consult it. */
+export const isLayerHidden = (layer: CanvasLayerContract): boolean => isHideableLayer(layer) && layer.isHidden === true;
+
/** Whether the layer holds pixels rather than a parametric source. */
export const isPixelBackedLayer = (layer: CanvasLayerContract): boolean =>
(layer.type === 'raster' || layer.type === 'control') &&
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
index 534f02b8d2..f22b4ced1c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
@@ -7,6 +7,8 @@ import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
*/
export type LayerStackKind = CanvasLayerContract['type'];
+export type OverlayStackKind = Exclude<LayerStackKind, 'raster'>;
+
export const LAYER_STACK_ORDER: readonly LayerStackKind[] = ['raster', 'control', 'regional_guidance', 'inpaint_mask'];
export const LAYER_STACKS_TOP_FIRST: readonly LayerStackKind[] = [...LAYER_STACK_ORDER].reverse();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts
index 7910ba43cf..9ba4a935d7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.test.ts
@@ -6,12 +6,11 @@ import type {
import { describe, expect, it } from 'vitest';
+import { isHideableLayer, isLayerHidden } from './layerEligibility';
import {
getSourceBounds,
getSourceContentRect,
getSourcePixelSize,
- isHideableLayer,
- isLayerHidden,
isMaskLayer,
isRenderableLayer,
maskAsPaintSource,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts
index 1c41c89226..8a80c85494 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts
@@ -39,27 +39,6 @@ const hasSource = (layer: CanvasLayerContract): layer is SourceLayer =>
export const isMaskLayer = (layer: CanvasLayerContract): layer is MaskLayer =>
layer.type === 'inpaint_mask' || layer.type === 'regional_guidance';
-/**
- * The layer types that can be hidden without being disabled — everything drawn
- * on canvas purely to SHOW you where an effect applies.
- *
- * Raster layers are excluded on purpose: the raster stack is the generation
- * input, so hiding one and still generating from it is not a state that can be
- * explained to a user. Their contracts have no `isHidden` field at all.
- */
-export type HideableLayer = Extract<CanvasLayerContract, { type: 'control' | 'inpaint_mask' | 'regional_guidance' }>;
-
-/** True when `layer` supports being hidden independently of being enabled. */
-export const isHideableLayer = (layer: CanvasLayerContract): layer is HideableLayer =>
- layer.type === 'control' || isMaskLayer(layer);
-
-/**
- * True when `layer`'s on-canvas preview is suppressed. DISPLAY ONLY — callers
- * that decide what the image contains (generation, export) must NOT consult it;
- * that is `isEnabled`'s job.
- */
-export const isLayerHidden = (layer: CanvasLayerContract): boolean => isHideableLayer(layer) && layer.isHidden === true;
-
/**
* A mask layer's alpha bitmap viewed as a `paint` source, so the whole paint
* pipeline (rasterize, content-sized cache, growth, stroke, persistence) can
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
index 9e7b760bd8..8fd4ee092b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -21,9 +21,8 @@ import type {
import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
import type { LayerDamage, Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
-import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';
+import { isLayerContributing, isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';
import { LAYER_STACK_ORDER, layerStackRank } from '@workbench/canvas-engine/document/layerStacks';
-import { isLayerHidden } from '@workbench/canvas-engine/document/sources';
import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';
import { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts
index b673f7093b..802981f6e0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts
@@ -1,8 +1,8 @@
import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
import type { Rect } from '@workbench/canvas-engine/types';
-import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';
-import { getSourceContentRect, isLayerHidden, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
+import { isLayerContributing, isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';
+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';