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.

test(canvas): enforce the document seam and add deterministic budgets

Josh Corbetta13cf42f8a91
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index d30e4ce7ef..da4ef9599a 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -7,7 +7,7 @@
"#architecture/source-analysis": "./src/architecture/tsSourceAnalysis.ts"
},
"scripts": {
- "architecture:check": "vitest run --config vitest.config.mts src/architecture/dependencyPolicy.test.ts src/architecture/workbenchOwnership.test.ts src/architecture/architectureWorkflow.test.ts src/architecture/tsSourceAnalysis.test.ts && node scripts/write-workbench-ownership-inventory.mjs && node scripts/write-contract-caller-matrix.mjs && node scripts/write-canvas-import-matrix.mjs",
+ "architecture:check": "vitest run --config vitest.config.mts src/architecture/dependencyPolicy.test.ts src/architecture/workbenchOwnership.test.ts src/architecture/architectureWorkflow.test.ts src/architecture/canvasSeamOwnership.test.ts src/architecture/tsSourceAnalysis.test.ts && node scripts/write-workbench-ownership-inventory.mjs && node scripts/write-contract-caller-matrix.mjs && node scripts/write-canvas-import-matrix.mjs",
"build": "pnpm run lint && vite build",
"check:architecture": "pnpm run lint && pnpm run test:all && pnpm run test:performance:architecture && pnpm run test:project-files:browser",
"check:release": "pnpm run check:architecture && pnpm run test:accessibility:browser",
diff --git a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts
new file mode 100644
index 0000000000..3ee7985636
--- /dev/null
+++ b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts
@@ -0,0 +1,127 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { isProductionSourcePath, primeImportSources, resolveImportPath } from './dependencyPolicy';
+import { analyzeSource, closeSourceAnalysis } from './tsSourceAnalysis';
+
+const sources = import.meta.glob('../workbench/**/*.{ts,tsx}', {
+ eager: true,
+ import: 'default',
+ query: '?raw',
+}) as Record<string, string>;
+
+const productionSources = Object.entries(sources)
+ .map(([path, source]) => [path.replace(/^\.\.\//, ''), source] as const)
+ .filter(([path]) => isProductionSourcePath(path));
+
+beforeAll(() => primeImportSources(productionSources));
+afterAll(closeSourceAnalysis);
+
+/** Modules that may take part in stack order and selection repair: the reducer and the document seam. */
+const DOCUMENT_SEAM_OWNERS = [
+ /^workbench\/canvasProjectMutations\.ts$/,
+ /^workbench\/canvas-engine\/(?:api|capabilities)\.ts$/,
+ /^workbench\/canvas-engine\/document\//,
+ /^workbench\/canvas-engine\/document-model\//,
+];
+
+/** Modules whose namespace import would hide a seam-only symbol behind a qualifier. */
+const SEAM_MODULES = [
+ 'workbench/canvas-engine/api',
+ 'workbench/canvas-engine/capabilities',
+ 'workbench/canvas-engine/document/layerStacks',
+ 'workbench/canvas-engine/document/selectionRepair',
+];
+
+/**
+ * Mutations that restructure the layer list. Outside the engine and the reducer they may only be
+ * built by gallery import, which ingests into projects that have no mounted engine, and by the
+ * new-canvas confirmation, which swaps the whole document rather than editing layers. The engine
+ * grant covers every engine module: tools and raster controllers still dispatch some of these
+ * through the mutation port rather than the structural controller, which is engine-owned but not
+ * yet the single transaction module. The scan matches the formatted literal `type: '…'`.
+ */
+const STRUCTURAL_MUTATION_TYPES = [
+ 'addCanvasLayer',
+ 'applyCanvasLayerStackMutation',
+ 'convertCanvasLayer',
+ 'duplicateCanvasLayer',
+ 'mergeCanvasLayersDown',
+ 'removeCanvasLayers',
+ 'reorderCanvasLayerStacks',
+ 'replaceCanvasDocument',
+ 'replaceCanvasLayer',
+ 'restoreCanvasSnapshot',
+ 'setCanvasLayerPositions',
+ 'setCanvasLayersEnabled',
+ 'setCanvasLayersHidden',
+ 'updateCanvasLayerSource',
+];
+const STRUCTURAL_MUTATION_OWNERS = [
+ /^workbench\/canvasProjectMutations\.ts$/,
+ /^workbench\/canvas-engine\//,
+ /^workbench\/canvas-operations\/importGalleryImages\.ts$/,
+ /^workbench\/widgets\/canvas\/canvasHeaderCommands\.ts$/,
+];
+const structuralLiteral = new RegExp(`type: '(?:${STRUCTURAL_MUTATION_TYPES.join('|')})'`, 'g');
+
+const SEAM_ONLY_SYMBOLS = ['repairSelectedLayerId', 'moveLayersWithinStacks', 'reorderLayerStack'];
+
+/** Production planners that consume the document model; dropping the import would reopen an ad-hoc path. */
+const MODEL_CONSUMERS = [
+ 'workbench/canvas-engine/render/compositor.ts',
+ 'workbench/canvas-engine/render/frameDemand.ts',
+ 'workbench/canvas-engine/render/overlayFrame.ts',
+ 'workbench/canvas-engine/render/floatingSelectionFrame.ts',
+ 'workbench/canvas-engine/render/rasterComposite.ts',
+ 'workbench/canvas-engine/controllers/mergeLayerController.ts',
+ 'workbench/canvas-operations/generationCompositePlan.ts',
+];
+
+const MODEL_MODULE = 'workbench/canvas-engine/document-model/flatDocumentModel';
+
+describe('canvas document seam ownership', () => {
+ it('keeps stack mutation and selection repair inside the reducer and the document seam', () => {
+ const offenders: string[] = [];
+ for (const [path, source] of productionSources) {
+ if (DOCUMENT_SEAM_OWNERS.some((owner) => owner.test(path))) {
+ continue;
+ }
+ for (const reference of analyzeSource(path, source, { jsx: true }).moduleReferences) {
+ if (reference.kind === 'import-type') {
+ continue;
+ }
+ if (reference.namespace && SEAM_MODULES.includes(resolveImportPath(path, reference.specifier) ?? '')) {
+ offenders.push(`${path} imports ${reference.specifier} as a namespace`);
+ }
+ for (const symbol of reference.symbols) {
+ if (SEAM_ONLY_SYMBOLS.includes(symbol)) {
+ offenders.push(`${path} imports ${symbol} from ${reference.specifier}`);
+ }
+ }
+ }
+ }
+ expect(offenders).toEqual([]);
+ }, 60_000);
+
+ it('keeps structural mutations behind the engine transaction', () => {
+ const offenders: string[] = [];
+ for (const [path, source] of productionSources) {
+ if (STRUCTURAL_MUTATION_OWNERS.some((owner) => owner.test(path))) {
+ continue;
+ }
+ for (const match of source.matchAll(structuralLiteral)) {
+ offenders.push(`${path} builds ${match[0]}`);
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ it.each(MODEL_CONSUMERS)('%s consumes the document model', (path) => {
+ const source = productionSources.find(([candidate]) => candidate === path)?.[1];
+ expect(source, `${path} is missing`).toBeDefined();
+ const targets = analyzeSource(path, source!, { jsx: true }).moduleReferences.map((reference) =>
+ resolveImportPath(path, reference.specifier)
+ );
+ expect(targets).toContain(MODEL_MODULE);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index c1d46b4854..f7a64e7ede 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -7,6 +7,7 @@ import {
formatViolation,
getModuleOwner,
isExcepted,
+ isProductionSourcePath,
primeImportSources,
resolveImportPath,
} from './dependencyPolicy';
@@ -21,7 +22,7 @@ const sources = import.meta.glob('../**/*.{ts,tsx}', {
}) as Record<string, string>;
const toSourcePath = (path: string): string => path.replace(/^\.\.\//, '');
-const isProduction = (path: string): boolean => !/\.(?:test|browser\.test)\.[^.]+$/.test(path);
+const isProduction = isProductionSourcePath;
afterAll(closeSourceAnalysis);
@@ -124,6 +125,34 @@ describe('dependency policy rules', () => {
);
});
+ it.each([
+ 'react',
+ '@chakra-ui/react',
+ 'i18next',
+ '@platform/ui',
+ '@workbench/canvas-engine/render/compositor',
+ '@workbench/canvas-engine/history/documentPatch',
+ '@workbench/canvas-engine/engine',
+ '@workbench/canvasProjectMutations',
+ '@workbench/widgets/layers/layerOps',
+ '@workbench/canvas-engine/document/sources',
+ '@workbench/canvas-engine/document/bitmapStore',
+ ])('keeps the pure document model free of engine, screen and framework imports: %s', (specifier) => {
+ expect(checkDependency('workbench/canvas-engine/document-model/flatDocumentModel.ts', specifier)).toContainEqual(
+ expect.objectContaining({ rule: 'document-model-purity' })
+ );
+ });
+
+ it('permits the pure document model to read document facts, math and contracts', () => {
+ const source = 'workbench/canvas-engine/document-model/flatDocumentModel.ts';
+ expect(checkDependency(source, './semanticLeaf')).toEqual([]);
+ expect(checkDependency(source, '@workbench/canvas-engine/document/layerStacks')).toEqual([]);
+ expect(checkDependency(source, '@workbench/canvas-engine/math/mat2d')).toEqual([]);
+ expect(checkDependency(source, '@workbench/canvas-engine/contracts')).toEqual([]);
+ expect(checkDependency(source, '@workbench/canvas-engine/mutationContracts')).toEqual([]);
+ expect(checkDependency('workbench/canvas-engine/document-model/flatDocumentModel.test.ts', 'vitest')).toEqual([]);
+ });
+
it('permits feature Core to depend on other pure Core and Platform State modules', () => {
expect(checkDependency('features/queue/core/policy.ts', './types')).toEqual([]);
expect(checkDependency('features/queue/core/policy.ts', '@platform/state/selectorCore')).toEqual([]);
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
index d314faf6d7..0bb7e17ef0 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
@@ -154,6 +154,29 @@ const isFeatureCoreForbiddenDependency = (specifier: string, target: string | nu
/\/(?:data|ui)(?:\/|$)/.test(target))
);
+const DOCUMENT_MODEL_ROOT = 'workbench/canvas-engine/document-model/';
+const DOCUMENT_MODEL_DEPENDENCY_ROOTS = [DOCUMENT_MODEL_ROOT, 'workbench/canvas-engine/math/'];
+const DOCUMENT_MODEL_DEPENDENCY_MODULES = [
+ 'workbench/canvas-engine/contracts',
+ 'workbench/canvas-engine/types',
+ 'workbench/canvas-engine/mutationContracts',
+ 'workbench/canvas-engine/document/commandRefusal',
+ 'workbench/canvas-engine/document/insertionAnchors',
+ 'workbench/canvas-engine/document/layerEligibility',
+ 'workbench/canvas-engine/document/layerStacks',
+ 'workbench/canvas-engine/document/selectionRepair',
+];
+
+/** Production sources: everything the architecture rules scan; tests, type tests and stories are not. */
+export const isProductionSourcePath = (path: string): boolean =>
+ !/\.(?:test|browser\.test|type-test|stories)\.[^.]+$/.test(path);
+
+/** The pure document model may only reach pure document facts, math, and contracts. */
+const isDocumentModelDependency = (target: string | null): boolean =>
+ target !== null &&
+ (DOCUMENT_MODEL_DEPENDENCY_ROOTS.some((root) => target.startsWith(root)) ||
+ DOCUMENT_MODEL_DEPENDENCY_MODULES.includes(target));
+
export const checkDependency = (source: string, specifier: string): DependencyViolation[] => {
const sourcePath = normalizePath(source).replace(/^src\//, '');
const target = resolveImportPath(source, specifier);
@@ -170,6 +193,14 @@ export const checkDependency = (source: string, specifier: string): DependencyVi
add('feature-core-purity');
}
+ if (
+ sourcePath.startsWith(DOCUMENT_MODEL_ROOT) &&
+ isProductionSourcePath(sourcePath) &&
+ !isDocumentModelDependency(target)
+ ) {
+ add('document-model-purity');
+ }
+
if (!target) {
return violations;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 57bc72a0c9..2ccf7a7669 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -302,12 +302,18 @@ export interface StructuralCommitOptions {
}
/** The narrowest engine surface a structural edit needs. */
+/** The only mutations a widget may preview live; every other structural edit is prepared and committed. */
+export type CanvasLayerPreviewMutation = Extract<
+ CanvasProjectMutation,
+ { type: 'updateCanvasLayer' | 'updateCanvasLayerConfig' }
+>;
+
export interface CanvasStructuralEngine {
readonly layers: CanvasLayerCapability;
}
export interface CanvasLayerCapability {
- applyStructuralPreview(action: CanvasProjectMutation): boolean;
+ applyStructuralPreview(action: CanvasLayerPreviewMutation): boolean;
canCommitStructural(): boolean;
commitGeneratedImageResult(options: CommitGeneratedImageOptions): Promise<CommitGeneratedImageResult>;
commitStagedImage(options: CommitStagedImageOptions): CommitStagedImageResult;
@@ -588,12 +594,12 @@ export {
LAYER_STACK_ORDER,
LAYER_STACKS_TOP_FIRST,
layerStackOf,
- moveLayersWithinStacks,
- reorderLayerStack,
type LayerStackKind,
type LayerStackMoveKind,
+ reorderLayerStack,
type ReorderFlatStackCommand,
} from './document/layerStacks';
+export { repairSelectedLayerId } from './document/selectionRepair';
export {
type HideableLayer,
isHideableLayer,
@@ -605,7 +611,6 @@ export {
isLayerTransparencyLocked,
isPixelBackedLayer,
} from './document/layerEligibility';
-export { repairSelectedLayerId } from './document/selectionRepair';
export {
type FlatDocumentCommand,
type FlatDocumentRefusal,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
index 16cbc3463e..14ee4ce554 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
@@ -1,3 +1,4 @@
+import type { CanvasLayerPreviewMutation } from '@workbench/canvas-engine/capabilities';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
@@ -181,7 +182,9 @@ describe('LayerController', () => {
};
const controller = new LayerController(deps);
- expect(controller.layers.applyStructuralPreview(forward)).toBe(true);
+ expect(
+ controller.layers.applyStructuralPreview({ id: 'layer', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' })
+ ).toBe(true);
controller.layers.commitStructural('edit', forward, inverse);
expect(controller.previews.drawLayerThumbnail('layer', {} as HTMLCanvasElement, 96)).toBe(false);
await expect(controller.previews.requestLayerThumbnail('layer')).resolves.toBe('stale');
@@ -205,7 +208,7 @@ describe('LayerController', () => {
controller.dispose();
controller.dispose();
- expect(controller.layers.applyStructuralPreview({} as CanvasProjectMutation)).toBe(false);
+ expect(controller.layers.applyStructuralPreview({} as CanvasLayerPreviewMutation)).toBe(false);
controller.layers.commitStructural('late', {} as CanvasProjectMutation, {} as CanvasProjectMutation);
expect(controller.previews.drawLayerThumbnail('layer', {} as HTMLCanvasElement, 96)).toBe(false);
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
index 7a957f9ef5..6d89e0467a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
@@ -74,6 +74,7 @@ export interface PreparedFlatEdit {
readonly expectedRevision: number;
readonly selectionBefore: string | null;
readonly selectionAfter: string | null;
+ /** Layers the edit changes, including neighbours whose stack position it displaces. */
readonly touchedIds: readonly string[];
readonly touchedStacks: readonly LayerStackKind[];
readonly postconditions: readonly FlatEditPostcondition[];
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.budget.test.ts
new file mode 100644
index 0000000000..680a1938d5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.budget.test.ts
@@ -0,0 +1,166 @@
+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
+
+import { getStackOrder, layerStackOf } from '@workbench/canvas-engine/document/layerStacks';
+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import type { FlatDocumentCommand, PreparedFlatEdit } from './flatDocumentCommands';
+
+import { createLargeFlatDocument } from './documentFixtures.testStub';
+import {
+ compileDocumentLeaves,
+ createFlatDocumentModel,
+ flatDocumentModelCounters,
+ resetLatestLeafCompilation,
+} from './flatDocumentModel';
+import { ALL_OVERLAY_STACKS_SHOWN, planScreenComposition } from './screenComposition';
+
+const LAYER_COUNT = 2_000;
+const context = { editRevision: 0, projectId: 'budget' };
+
+const resetCounters = (): void => {
+ flatDocumentModelCounters.indexBuilds = 0;
+ flatDocumentModelCounters.leafCompilations = 0;
+ flatDocumentModelCounters.leavesCompiled = 0;
+};
+
+/** Runs the reducer over a fixture so the next document is the one production consumers see. */
+const reduce = (document: CanvasDocumentContractV2, command: FlatDocumentCommand) => {
+ const initial = createInitialWorkbenchState().projects[0]!;
+ const project = applyCanvasProjectMutation(initial, {
+ document,
+ type: 'replaceCanvasDocument',
+ });
+ const accepted = project.canvas.document;
+ const model = createFlatDocumentModel(accepted, context);
+ const result = model.prepare(command);
+ if (result.status !== 'prepared') {
+ throw new Error(`expected a prepared edit, got ${result.status}`);
+ }
+ return { edit: result.edit, model, next: applyCanvasProjectMutation(project, result.edit.forward).canvas.document };
+};
+
+type Annotate = (message: string) => unknown;
+
+/** Timing is informational: it is annotated on the test, never asserted. */
+const timed = <T>(annotate: Annotate, label: string, run: () => T): T => {
+ const start = performance.now();
+ const value = run();
+ annotate(`${label}: ${(performance.now() - start).toFixed(2)}ms`);
+ return value;
+};
+
+describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {
+ beforeEach(() => {
+ resetLatestLeafCompilation();
+ resetCounters();
+ });
+
+ it('builds one index per layer array and none for selection-only changes', ({ annotate }) => {
+ const project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {
+ document: createLargeFlatDocument(LAYER_COUNT),
+ type: 'replaceCanvasDocument',
+ });
+ const document = project.canvas.document;
+ const model = timed(annotate, 'model construction', () => createFlatDocumentModel(document, context));
+ createFlatDocumentModel(document, context);
+ model.getLayer('l1999');
+ model.getStack('control');
+ expect(model.prepare({ id: 'l7', type: 'select' }).status).toBe('prepared');
+ expect(model.prepare({ id: 'l0', type: 'select' })).toEqual({ status: 'unchanged' });
+ const leaves = compileDocumentLeaves(document);
+
+ const reselected = applyCanvasProjectMutation(project, { id: 'l7', type: 'setCanvasSelectedLayer' }).canvas
+ .document;
+ expect(reselected).not.toBe(document);
+ expect(reselected.selectedLayerId).toBe('l7');
+ expect(createFlatDocumentModel(reselected, context, model).compileLeaves()).toBe(leaves);
+ expect(compileDocumentLeaves(reselected)).toBe(leaves);
+ expect(flatDocumentModelCounters.indexBuilds).toBe(1);
+ expect(flatDocumentModelCounters.leafCompilations).toBe(1);
+ });
+
+ it('compiles leaves once per document and plans the screen from them', ({ annotate }) => {
+ const document = createLargeFlatDocument(LAYER_COUNT);
+ const leaves = timed(annotate, 'leaf compilation', () => compileDocumentLeaves(document));
+ expect(compileDocumentLeaves(document)).toBe(leaves);
+ expect(createFlatDocumentModel(document, context).compileLeaves()).toBe(leaves);
+ expect(flatDocumentModelCounters.leafCompilations).toBe(1);
+ expect(flatDocumentModelCounters.leavesCompiled).toBe(LAYER_COUNT);
+
+ const plan = timed(annotate, 'screen plan', () =>
+ planScreenComposition(leaves, { isolationLayerId: null, showOverlayStacks: ALL_OVERLAY_STACKS_SHOWN })
+ );
+ expect(plan.leaves).toHaveLength(LAYER_COUNT);
+ expect(plan.leaves.at(-1)?.stack).toBe('inpaint_mask');
+ });
+
+ it('recompiles only the patched leaf after a reducer edit', ({ annotate }) => {
+ const { model, next } = reduce(createLargeFlatDocument(LAYER_COUNT), {
+ id: 'l5',
+ patch: { opacity: 0.5 },
+ type: 'patch',
+ });
+ const before = model.compileLeaves();
+ resetCounters();
+ const after = timed(annotate, 'representative edit recompile', () => compileDocumentLeaves(next, model.document));
+ expect(flatDocumentModelCounters.leafCompilations).toBe(1);
+ expect(flatDocumentModelCounters.leavesCompiled).toBe(1);
+ after.forEach((leaf, index) => {
+ if (leaf.id === 'l5') {
+ expect(leaf).not.toBe(before[index]);
+ expect(leaf.layer.opacity).toBe(0.5);
+ } else {
+ expect(leaf).toBe(before[index]);
+ }
+ });
+ });
+
+ it('reuses the latest compilation when a consumer has no previous document to offer', () => {
+ const { model, next } = reduce(createLargeFlatDocument(LAYER_COUNT), {
+ id: 'l5',
+ patch: { name: 'x' },
+ type: 'patch',
+ });
+ const before = compileDocumentLeaves(model.document);
+ resetCounters();
+ const after = compileDocumentLeaves(next);
+ expect(flatDocumentModelCounters.leavesCompiled).toBe(1);
+ expect(after[6]).toBe(before[6]);
+ });
+
+ it('recompiles exactly the leaves whose stack position moved', () => {
+ const { model, next } = reduce(createLargeFlatDocument(LAYER_COUNT), { ids: ['l0'], kind: 'back', type: 'move' });
+ model.compileLeaves();
+ resetCounters();
+ compileDocumentLeaves(next, model.document);
+ const movedStack = layerStackOf(model.getLayer('l0')!);
+ expect(flatDocumentModelCounters.leavesCompiled).toBe(getStackOrder(next.layers, movedStack).orderedIds.length);
+ });
+
+ it.each<[string, FlatDocumentCommand, { ids: number; stacks: number }]>([
+ ['select', { id: 'l9', type: 'select' }, { ids: 0, stacks: 0 }],
+ ['lock', { type: 'set-locked', updates: [{ id: 'l1', isLocked: true }] }, { ids: 1, stacks: 1 }],
+ [
+ 'enable',
+ {
+ type: 'set-enabled',
+ updates: Array.from({ length: 10 }, (_, index) => ({ id: `l${index}`, isEnabled: false })),
+ },
+ { ids: 10, stacks: 4 },
+ ],
+ ['hide', { type: 'set-hidden', updates: [{ id: 'l1', isHidden: true }] }, { ids: 1, stacks: 1 }],
+ ['move', { ids: ['l8', 'l12', 'l16'], kind: 'forward', type: 'move' }, { ids: 4, stacks: 1 }],
+ ['remove', { ids: ['l1', 'l2'], type: 'remove' }, { ids: 2, stacks: 2 }],
+ ])('prepares a %s edit with exact touched ids and stacks', (_label, command, expected) => {
+ const model = createFlatDocumentModel(createLargeFlatDocument(LAYER_COUNT), context);
+ const result = model.prepare(command);
+ expect(result.status).toBe('prepared');
+ const edit = (result as { edit: PreparedFlatEdit }).edit;
+ expect(edit.touchedIds).toHaveLength(expected.ids);
+ expect(edit.touchedStacks).toHaveLength(expected.stacks);
+ expect(flatDocumentModelCounters.indexBuilds).toBe(1);
+ expect(flatDocumentModelCounters.leafCompilations).toBe(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
index 4c38d07886..8c9732be6d 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
@@ -76,7 +76,9 @@ interface DocumentIndex {
/** 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>();
+type LayerArray = CanvasDocumentContractV2['layers'];
+
+const indexes = new WeakMap<LayerArray, DocumentIndex>();
/** The most recent compilation, reused when a caller has no previous document to offer. */
let latestLeaves: {
@@ -84,7 +86,12 @@ let latestLeaves: {
readonly leaves: readonly SemanticLeafV2[];
} | null = null;
-const buildIndex = (document: CanvasDocumentContractV2): DocumentIndex => {
+/** Test seam: forgets the latest compilation so budgets measure one document chain at a time. */
+export const resetLatestLeafCompilation = (): void => {
+ latestLeaves = null;
+};
+
+const buildIndex = (layers: LayerArray): DocumentIndex => {
flatDocumentModelCounters.indexBuilds += 1;
const byId = new Map<string, LayerIndexEntry>();
const stacks: Record<LayerStackKind, CanvasLayerContract[]> = {
@@ -93,7 +100,7 @@ const buildIndex = (document: CanvasDocumentContractV2): DocumentIndex => {
raster: [],
regional_guidance: [],
};
- document.layers.forEach((layer, index) => {
+ layers.forEach((layer, index) => {
const stack = layerStackOf(layer);
byId.set(layer.id, { index, layer, stack, stackIndex: stacks[stack].length });
stacks[stack].push(layer);
@@ -101,13 +108,14 @@ const buildIndex = (document: CanvasDocumentContractV2): DocumentIndex => {
return { byId, leaves: null, stacks };
};
+/** Indexes are keyed on the layer array, so a selection-only document change reuses them. */
const indexOf = (document: CanvasDocumentContractV2): DocumentIndex => {
- const existing = indexes.get(document);
+ const existing = indexes.get(document.layers);
if (existing) {
return existing;
}
- const built = buildIndex(document);
- indexes.set(document, built);
+ const built = buildIndex(document.layers);
+ indexes.set(document.layers, built);
return built;
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.test.ts
index e78aa4beb8..3a5f64f20f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/selectionRepair.test.ts
@@ -1,5 +1,8 @@
import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import { flatDocument, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { applyCanvasProjectMutation, type CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { describe, expect, it } from 'vitest';
import { repairSelectedLayerId } from './selectionRepair';
@@ -32,3 +35,72 @@ describe('repairSelectedLayerId', () => {
expect(repairSelectedLayerId([mixed[0]!, mixed[2]!], 'r1', mixed)).toBe('c1');
});
});
+
+describe('selection repair through the reducer', () => {
+ const layers = () => [
+ layerContract('i1', 'inpaint_mask'),
+ layerContract('r1'),
+ layerContract('c1', 'control'),
+ layerContract('r2'),
+ layerContract('r3'),
+ ];
+ const reduce = (selectedLayerId: string | null, mutation: CanvasProjectMutation, initialLayers = layers()) => {
+ const project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {
+ document: flatDocument(initialLayers, selectedLayerId),
+ type: 'replaceCanvasDocument',
+ });
+ return applyCanvasProjectMutation(project, mutation).canvas.document.selectedLayerId;
+ };
+ const paint = { bitmap: null, type: 'paint' as const };
+
+ it.each<[string, string | null, CanvasProjectMutation, string | null]>([
+ ['remove keeps a surviving selection', 'r2', { ids: ['r1'], type: 'removeCanvasLayers' }, 'r2'],
+ ['remove moves to the same-stack neighbour below', 'r1', { ids: ['r1'], type: 'removeCanvasLayers' }, 'r2'],
+ [
+ 'remove moves above within the stack when nothing survives below',
+ 'r3',
+ { ids: ['r3'], type: 'removeCanvasLayers' },
+ 'r2',
+ ],
+ ['remove falls back across stacks when the stack empties', 'c1', { ids: ['c1'], type: 'removeCanvasLayers' }, 'r2'],
+ ['duplicate selects the copy', 'r1', { newId: 'r1-copy', sourceId: 'r1', type: 'duplicateCanvasLayer' }, 'r1-copy'],
+ [
+ 'merge down moves the selection onto the merged layer',
+ 'r2',
+ { source: paint, type: 'mergeCanvasLayersDown', upperLayerId: 'r2' },
+ 'r3',
+ ],
+ [
+ 'merge down keeps a selection elsewhere',
+ 'i1',
+ { source: paint, type: 'mergeCanvasLayersDown', upperLayerId: 'r2' },
+ 'i1',
+ ],
+ [
+ 'replacement keeps a selection the new document holds',
+ 'r1',
+ { document: flatDocument([layerContract('r1')], 'r1'), type: 'replaceCanvasDocument' },
+ 'r1',
+ ],
+ [
+ 'replacement selects the top when its selection is absent',
+ 'r1',
+ { document: flatDocument([layerContract('x'), layerContract('y')], 'nope'), type: 'replaceCanvasDocument' },
+ 'x',
+ ],
+ [
+ 'an emptied document clears the selection',
+ 'r1',
+ { ids: ['i1', 'r1', 'c1', 'r2', 'r3'], type: 'removeCanvasLayers' },
+ null,
+ ],
+ [
+ 'an empty replacement clears the selection',
+ 'r1',
+ { document: flatDocument([], 'r1'), type: 'replaceCanvasDocument' },
+ null,
+ ],
+ ])('%s', (_label, selected, mutation, expected) => {
+ expect(reduce(selected, mutation)).toBe(expected);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
index dd01c37876..1a2f9e5008 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
@@ -16,11 +16,11 @@ import type {
CanvasMaskFillContract,
CanvasRasterLayerContractV2,
CanvasRegionalGuidanceLayerContract,
+ CanvasLayerPreviewMutation,
CanvasStructuralEngine,
RegionalGuidanceReferenceImage,
Rect,
} from '@workbench/canvas-engine/api';
-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
export type { CanvasStructuralEngine } from '@workbench/canvas-engine/api';
@@ -614,5 +614,7 @@ export const canMergeLayerDown = (document: CanvasDocumentContractV2, layerId: s
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 =>
- engine?.layers.applyStructuralPreview(action) ?? false;
+export const applyStructuralPreview = (
+ engine: CanvasStructuralEngine | null,
+ action: CanvasLayerPreviewMutation
+): boolean => engine?.layers.applyStructuralPreview(action) ?? false;