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
fix(canvas): derive indexes for value edits and freeze locked subtrees
Josh Corbettd92c60b03e43
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 1116dc916b..592f056513 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -27,7 +27,9 @@ Paint persistence clears a dirty result only after the intended layer accepts th`CanvasDocumentContractV3` holds four stack forests, `document.stacks.{raster, control, regional_guidance, inpaint_mask}`. Each forest is a top-first tree of leaves (the unchanged v2 leaf contracts) and pass-through groups (`type: 'group'` with `id`, `name`, `isEnabled`, `isLocked`, optional overlay-only `isHidden`, and `children`). A node belongs to exactly one stack, ids are unique across the document, groups nest at most ten levels deep, and a document holds at most 10,000 nodes. `selectedLayerId` may name a leaf or a group; leaf-only tools refuse a group rather than guessing a descendant. Groups carry no opacity, blend mode, transform, or raster surface: they only organise leaves and gate their effective state. Older document versions are refused by the loader; nothing migrates them.-`document/documentIndex.ts` builds one index per `stacks` identity (parent, path, sibling index, document order, and ancestor-effective enabled/locked/hidden per node). The reducer preserves `stacks` identity across selection, bbox and geometry-only edits, so those changes cost no index. `document-model/documentModel.ts` compiles `SemanticLeaf`s from that index: a leaf's `contributionEnabled`, `effectiveLocked`, and `documentHidden` fold in every ancestor, and a leaf keeps its identity while its layer object, ancestor path, and ancestor-effective state are unchanged. Every consumer that decides visibility, contribution, editability, or export reads leaves (or `isLeaf*` predicates) rather than a layer's own flags.+`document/documentIndex.ts` builds one index per `stacks` identity (parent, path, sibling index, document order, and ancestor-effective enabled/locked/hidden per node). Selection and bbox edits keep `stacks` and cost no index. A value edit (transform, opacity, blend, name, source, config, or a flag) rewrites the edited nodes and their ancestors through structural sharing, so `stacks` changes; the reducer then registers a derived index for the new forests (`deriveIndexForValueEdit`) instead of letting the next lookup rebuild one: no forest is walked, every unaffected entry keeps its identity, the leaves array keeps its identity when no leaf changed, and only the subtree under a group whose flags changed re-derives its ancestor-effective flags. `documentModel.budget.test.ts` pins this: a geometry edit over 2,000 nodes performs zero index builds, one derivation, and recompiles exactly one semantic leaf and node.++`document-model/documentModel.ts` compiles `SemanticLeaf`s and `SemanticNode`s from that index: `contributionEnabled`, `effectiveLocked`, and `documentHidden` fold in every ancestor, and a leaf or node keeps its identity while its contract object, place, and ancestor-effective state are unchanged. Every consumer that decides visibility, contribution, editability, export, or what a panel row shows reads these (or the `isLeaf*` predicates) rather than a node's own flags; `model.refusalFor(command)` is the single eligibility authority for enabling a command before it runs. Locks are all-or-nothing over subtrees: no command edits, moves, groups, ungroups, or inserts into a subtree that holds a locked node or sits under one, while name, enablement, and lock flips stay open so a locked node can be unlocked.Structural edits are prepared by the model (`insert`, `remove`, `duplicate`, `move`, `reorder`, `reparent`, `group`, `ungroup`, `patch*`, `set-*`, `translate`, `select`) and committed through `commitPrepared`. Restructuring lands as one `applyCanvasLayerStackMutation` that the reducer applies as `add`, then `move`, then `removeIds`, then flag and selection updates, refusing the whole mutation when any step is invalid or the result exceeds the limits. Insertion anchors are exact: before a surviving sibling under its current parent, after a surviving sibling, the top of the captured parent, the nearest surviving group on the captured path, then the stack top. Inverses restore removed or moved nodes as maximal sibling runs anchored to their unmoved neighbours, so undo reproduces the previous structure exactly.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex ec2426094a..cb3b1cecc5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -653,6 +653,8 @@ export {} from './document-model/documentCommands';export {compileContributingLayers,+ compileDocumentNodes,+ lookupDocumentNodeState,compileDocumentLeaves,createDocumentModel,type CanvasDocumentModel,@@ -670,6 +672,7 @@ export {type ScreenCompositionPlan,} from './document-model/screenComposition';export { type SemanticLeaf } from './document-model/semanticLeaf';+export { type SemanticNode } from './document-model/semanticNode';export {captureInsertionAnchor,captureRestoreAnchor,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.tsindex 61283e18d2..b14c9e6c00 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts@@ -292,6 +292,17 @@ export type CanvasNodeContract = CanvasLayerContract | CanvasGroupContract;/** One top-first forest per stack; a node's stack is the forest it lives in. */export type CanvasStackForests = Record<CanvasLayerStackKind, CanvasNodeContract[]>;+/** The composition order, bottom stack first; the one table every consumer reads. */+export const LAYER_STACK_ORDER: readonly CanvasLayerStackKind[] = [+ 'raster',+ 'control',+ 'regional_guidance',+ 'inpaint_mask',+];++/** The same stacks as the panel lists them, top first. */+export const LAYER_STACKS_TOP_FIRST: readonly CanvasLayerStackKind[] = [...LAYER_STACK_ORDER].reverse();+export const CANVAS_MAX_NODE_DEPTH = 10;export const CANVAS_MAX_NODE_COUNT = 10_000;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.tsindex fadd4ed117..664f2656e8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts@@ -3,6 +3,7 @@ import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contractimport {getDocumentIndex,getDocumentIndexBuildCount,+ getDocumentIndexDerivationCount,resetDocumentIndexBuildCount,} from '@workbench/canvas-engine/document/documentIndex';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -14,6 +15,7 @@ import type { DocumentCommand, PreparedDocumentEdit } from './documentCommands';import { createLargeFlatDocument, createLargeTreeDocument } from './documentFixtures.testStub';import {compileDocumentLeaves,+ compileDocumentNodes,createDocumentModel,getDocumentModelDiagnostics,resetDocumentModelDiagnostics,@@ -28,7 +30,11 @@ const resetCounters = (): void => {resetDocumentIndexBuildCount();};-const counters = () => ({ ...getDocumentModelDiagnostics(), indexBuilds: getDocumentIndexBuildCount() });+const counters = () => ({+ ...getDocumentModelDiagnostics(),+ indexBuilds: getDocumentIndexBuildCount(),+ indexDerivations: getDocumentIndexDerivationCount(),+});/** Runs the reducer over a fixture so the next document is the one production consumers see. */const reduce = (document: CanvasDocumentContractV3, command: DocumentCommand) => {@@ -105,7 +111,7 @@ describe(`document model budgets over ${NODE_COUNT} nodes`, () => {const before = model.compileLeaves();resetCounters();const after = timed(annotate, 'representative edit recompile', () => compileDocumentLeaves(next));- expect(counters()).toMatchObject({ indexBuilds: 1, leafCompilations: 1, leavesCompiled: 1 });+ expect(counters()).toMatchObject({ indexBuilds: 0, leafCompilations: 1, leavesCompiled: 1 });after.forEach((leaf, index) => {if (leaf.id === 'l5') {expect(leaf).not.toBe(before[index]);@@ -121,7 +127,7 @@ describe(`document model budgets over ${NODE_COUNT} nodes`, () => {const before = renamed.model.compileLeaves();resetCounters();expect(compileDocumentLeaves(renamed.next)).toEqual(before);- expect(counters()).toMatchObject({ indexBuilds: 1, leavesCompiled: 0 });+ expect(counters()).toMatchObject({ indexBuilds: 0, leavesCompiled: 0 });const gated = reduce(createLargeTreeDocument(NODE_COUNT), {type: 'set-enabled',@@ -200,3 +206,70 @@ describe(`document model budgets over ${NODE_COUNT} nodes`, () => {expect(counters()).toMatchObject({ indexBuilds: 1, leafCompilations: 0 });});});++describe(`value edits over ${NODE_COUNT} nodes`, () => {+ beforeEach(resetCounters);++ it('derives the index for a geometry edit instead of rebuilding it, keeping every other leaf and node', ({+ annotate,+ }) => {+ const fixture = createLargeTreeDocument(NODE_COUNT);+ resetCounters();+ const { model, next } = reduce(fixture, { id: 'l5', patch: { transform: { x: 40 } }, type: 'patch' });+ const leavesBefore = model.compileLeaves();+ const nodesBefore = compileDocumentNodes(model.document);+ // One build for the accepted fixture, one derivation for the edit, and nothing on lookup.+ const index = timed(annotate, 'derived index lookup', () => getDocumentIndex(next));+ expect(counters()).toMatchObject({ indexBuilds: 1, indexDerivations: 1 });+ expect(index.byId.get('l5')!.node).not.toBe(model.getLayer('l5'));+ expect(model.getLayer('l5')).not.toBeNull();+ expect((index.byId.get('l5')!.node as { transform: { x: number } }).transform).toMatchObject({ x: 40 });+ expect(index.byId.get('l6')).toBe(model.getEntry('l6'));++ resetCounters();+ const leavesAfter = compileDocumentLeaves(next);+ const nodesAfter = compileDocumentNodes(next);+ // The leaf and the ancestors rebuilt along its path are new contract objects; nothing else is.+ expect(counters()).toMatchObject({+ indexBuilds: 0,+ indexDerivations: 0,+ leavesCompiled: 1,+ nodesCompiled: 1 + index.byId.get('l5')!.path.length,+ });+ const path = new Set(index.byId.get('l5')!.path);+ expect(leavesAfter.filter((leaf) => leaf.id !== 'l5').every((leaf) => leavesBefore.includes(leaf))).toBe(true);+ expect(+ nodesAfter.filter((node) => node.id !== 'l5' && !path.has(node.id)).every((node) => nodesBefore.includes(node))+ ).toBe(true);+ });++ it('re-derives only the subtree under a group whose flags change', () => {+ resetCounters();+ const { model, next } = reduce(createLargeTreeDocument(NODE_COUNT), {+ type: 'set-locked',+ updates: [{ id: 'g0', isLocked: true }],+ });+ const before = getDocumentIndex(model.document);+ const after = getDocumentIndex(next);+ expect(counters()).toMatchObject({ indexBuilds: 1, indexDerivations: 1 });+ const subtree = before.nodes.filter((entry) => entry.path.includes('g0'));+ expect(subtree.length).toBeGreaterThan(0);+ expect(subtree.every((entry) => after.byId.get(entry.node.id)!.ancestorsLocked)).toBe(true);+ const untouched = before.nodes.filter((entry) => !entry.path.includes('g0') && entry.node.id !== 'g0');+ expect(untouched.every((entry) => after.byId.get(entry.node.id) === entry)).toBe(true);+ expect(after.leaves).toBe(before.leaves);+ });++ it('keeps the leaves array identity when a group is renamed', () => {+ const { model, next } = reduce(createLargeTreeDocument(NODE_COUNT), {+ id: 'g0',+ patch: { name: 'renamed' },+ type: 'patch',+ });+ const before = compileDocumentLeaves(model.document);+ resetCounters();+ expect(getDocumentIndex(next).leaves).toBe(getDocumentIndex(model.document).leaves);+ compileDocumentLeaves(next).forEach((leaf, position) => expect(leaf).toBe(before[position]));+ expect(counters()).toMatchObject({ indexBuilds: 0, indexDerivations: 0, leavesCompiled: 0 });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.tsnew file mode 100644index 0000000000..5f7f9dcc9a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts@@ -0,0 +1,371 @@+import type { CanvasDocumentContractV3, CanvasNodeContract } from '@workbench/canvas-engine/contracts';+import type { Project } from '@workbench/projectContracts';++import { CANVAS_MAX_NODE_DEPTH, LAYER_STACK_ORDER } from '@workbench/canvas-engine/contracts';+import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';+import { collectSubtree, isGroupNode } from '@workbench/canvas-engine/document/documentTree';+import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';+import { createEmptyCanvasDocument, normalizeCanvasDocumentContract } from '@workbench/canvasMigration';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { describe, expect, it } from 'vitest';++import type { DocumentCommand } from './documentCommands';++import { groupContract, layerContract, stacksFrom } from './documentFixtures.testStub';+import { createDocumentModel } from './documentModel';+import { checkEditPostconditions } from './postconditions';++/** Deterministic 32-bit generator so a failing seed reproduces exactly. */+const rng = (seed: number) => {+ let state = seed >>> 0;+ return (): number => {+ state = (state + 0x6d2b79f5) >>> 0;+ let t = state;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+};++const pick = <T>(random: () => number, items: readonly T[]): T => items[Math.floor(random() * items.length)]!;+const sample = <T>(random: () => number, items: readonly T[], max: number): T[] => {+ const pool = [...items];+ const out: T[] = [];+ const count = 1 + Math.floor(random() * Math.min(max, pool.length));+ while (out.length < count && pool.length > 0) {+ out.push(pool.splice(Math.floor(random() * pool.length), 1)[0]!);+ }+ return out;+};++let created = 0;+const nextId = (): string => `n${created++}`;++/** A random forest: every stack gets a few leaves, some wrapped in groups up to `depth`. */+const randomTree = (random: () => number, depth: number, budget: { left: number }): CanvasNodeContract[] => {+ const nodes: CanvasNodeContract[] = [];+ const count = 1 + Math.floor(random() * 3);+ for (let index = 0; index < count && budget.left > 0; index += 1) {+ budget.left -= 1;+ if (depth > 0 && random() < 0.55) {+ nodes.push(+ groupContract(nextId(), randomTree(random, depth - 1, budget), {+ isEnabled: random() < 0.85,+ isLocked: random() < 0.15,+ })+ );+ } else {+ nodes.push(layerContract(nextId(), 'raster', { isEnabled: random() < 0.85, isLocked: random() < 0.1 }));+ }+ }+ return nodes;+};++const randomDocument = (random: () => number, depth: number): CanvasDocumentContractV3 => {+ const stacks = stacksFrom([]);+ for (const stack of LAYER_STACK_ORDER) {+ const budget = { left: 4 + Math.floor(random() * 8) };+ stacks[stack] = randomTree(random, depth, budget).map((node) => retype(node, stack, random));+ }+ const ids = Object.values(stacks).flatMap((roots) => roots.flatMap((root) => collectSubtree(root).map((n) => n.id)));+ return { ...createEmptyCanvasDocument(), selectedLayerId: ids[0] ?? null, stacks };+};++/** Rebuilds a raster fixture subtree for `stack`; overlay groups may start display-hidden. */+const retype = (+ node: CanvasNodeContract,+ stack: (typeof LAYER_STACK_ORDER)[number],+ random: () => number+): CanvasNodeContract =>+ isGroupNode(node)+ ? {+ ...node,+ children: node.children.map((child) => retype(child, stack, random)),+ ...(stack !== 'raster' && random() < 0.2 ? { isHidden: true } : {}),+ }+ : { ...layerContract(node.id, stack, { isEnabled: node.isEnabled, isLocked: node.isLocked }) };++const randomCommand = (random: () => number, document: CanvasDocumentContractV3): DocumentCommand => {+ const index = getDocumentIndex(document);+ const ids = index.nodes.map((entry) => entry.node.id);+ const groups = index.nodes.filter((entry) => isGroupNode(entry.node));+ const groupIds = groups.map((entry) => entry.node.id);+ const overlayIds = index.nodes.filter((entry) => entry.stack !== 'raster').map((entry) => entry.node.id);+ const kind = pick(random, [+ 'insert',+ 'insert',+ 'remove',+ 'duplicate',+ 'duplicate',+ 'move',+ 'reparent',+ 'reparent',+ 'reparent',+ 'group',+ 'group',+ 'ungroup',+ 'ungroup',+ 'flags',+ 'hidden',+ 'patch',+ 'translate',+ ] as const);+ switch (kind) {+ case 'insert': {+ const anchor = pick(random, [...ids, null]);+ const stack = anchor ? index.byId.get(anchor)!.stack : pick(random, LAYER_STACK_ORDER);+ const nodes: CanvasNodeContract[] = [];+ const roll = random();+ if (roll < 0.25) {+ nodes.push(groupContract(nextId()));+ } else if (roll < 0.5) {+ nodes.push(+ groupContract(nextId(), [+ layerContract(nextId(), stack),+ groupContract(nextId(), [layerContract(nextId(), stack)]),+ ])+ );+ } else if (roll < 0.7) {+ nodes.push(layerContract(nextId(), stack), layerContract(nextId(), stack));+ } else {+ nodes.push(layerContract(nextId(), stack));+ }+ const inside = groups.filter((entry) => entry.stack === stack);+ return random() < 0.5 && inside.length > 0+ ? {+ aboveId: null,+ insideId: pick(random, inside).node.id,+ nodes,+ selectId: random() < 0.3 ? null : undefined,+ stack,+ type: 'insert',+ }+ : { aboveId: anchor, nodes, stack, type: 'insert' };+ }+ case 'remove':+ return { ids: sample(random, ids, 3), type: 'remove' };+ case 'duplicate': {+ // Half the time pick a group and something inside it, so nested selections fold.+ const nested = groups.length > 0 && random() < 0.5 ? pick(random, groups) : null;+ const inner = nested ? index.nodes.filter((entry) => entry.path.includes(nested.node.id)) : [];+ const chosen =+ nested && inner.length > 0 ? [nested.node.id, pick(random, inner).node.id] : sample(random, ids, 2);+ return { createId: nextId, ids: chosen, type: 'duplicate' };+ }+ case 'move':+ return {+ ids: sample(random, ids, 3),+ kind: pick(random, ['front', 'forward', 'backward', 'back'] as const),+ type: 'move',+ };+ case 'reparent': {+ // Parent and moving ids come from one stack, so the stack rule is not what usually refuses.+ const stack = pick(random, LAYER_STACK_ORDER);+ const inStack = index.nodes.filter((entry) => entry.stack === stack);+ if (inStack.length === 0) {+ return { ids: sample(random, ids, 1), kind: 'front', type: 'move' };+ }+ const parents = inStack.filter((entry) => isGroupNode(entry.node));+ const parentId = random() < 0.7 && parents.length > 0 ? pick(random, parents).node.id : null;+ const siblings = inStack.filter((entry) => entry.parentId === parentId).map((entry) => entry.node.id);+ return {+ beforeId: random() < 0.5 && siblings.length > 0 ? pick(random, siblings) : null,+ ids: sample(+ random,+ inStack.map((entry) => entry.node.id),+ 3+ ),+ parentId,+ type: 'reparent',+ };+ }+ case 'group': {+ // Siblings most of the time, so the depth and lock rules get exercised, not just not-siblings.+ const anchor = pick(random, index.nodes);+ const siblings = index.nodes+ .filter((entry) => entry.stack === anchor.stack && entry.parentId === anchor.parentId)+ .map((entry) => entry.node.id);+ return {+ groupId: nextId(),+ ids: random() < 0.8 ? sample(random, siblings, 3) : sample(random, ids, 3),+ name: 'fuzz',+ type: 'group',+ };+ }+ case 'ungroup':+ return { ids: groupIds.length > 0 ? sample(random, groupIds, 3) : [ids[0]!], type: 'ungroup' };+ case 'flags': {+ const type = pick(random, ['set-enabled', 'set-locked'] as const);+ const flag = random() < 0.5;+ const updates = sample(random, ids, 3);+ return type === 'set-enabled'+ ? { type, updates: updates.map((id) => ({ id, isEnabled: flag })) }+ : { type, updates: updates.map((id) => ({ id, isLocked: flag })) };+ }+ case 'hidden': {+ const targets = overlayIds.length > 0 ? sample(random, overlayIds, 3) : sample(random, ids, 1);+ const isHidden = random() < 0.5;+ return { type: 'set-hidden', updates: targets.map((id) => ({ id, isHidden })) };+ }+ case 'patch': {+ const id = pick(random, ids);+ const roll = random();+ const patch =+ roll < 0.4+ ? { name: `n${Math.floor(random() * 100)}` }+ : roll < 0.7+ ? { opacity: random() }+ : { transform: { x: Math.round(random() * 50) } };+ return { id, patch, type: 'patch' };+ }+ case 'translate':+ return {+ dx: Math.round(random() * 20) - 10,+ dy: Math.round(random() * 20) - 10,+ ids: sample(random, ids, 2),+ type: 'translate',+ };+ }+};++/** Every invariant the definition of done names for a document at rest. */+const assertInvariants = (document: CanvasDocumentContractV3): void => {+ const index = getDocumentIndex(document);+ expect(index.byId.size).toBe(index.nodes.length);+ expect(index.maxDepth).toBeLessThanOrEqual(CANVAS_MAX_NODE_DEPTH);+ for (const entry of index.nodes) {+ if (!isGroupNode(entry.node)) {+ expect(entry.node.type).toBe(entry.stack);+ }+ expect(entry.path.includes(entry.node.id)).toBe(false);+ }+ if (document.selectedLayerId !== null) {+ expect(index.byId.has(document.selectedLayerId)).toBe(true);+ }+ expect(normalizeCanvasDocumentContract(document)).not.toBeNull();+};++const projectFor = (document: CanvasDocumentContractV3): Project =>+ applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, { document, type: 'replaceCanvasDocument' });++const outcomes = { locked: 0, nestedDuplicate: 0, nestedUngroup: 0, reparentInside: 0 };++describe('document model fuzzing', () => {+ it.each(Array.from({ length: 160 }, (_, seed) => seed + 1))(+ 'keeps every invariant and round-trips undo through random edits (seed %i)',+ (seed) => {+ const random = rng(seed);+ created = 0;+ let project = projectFor(randomDocument(random, seed % 9));+ assertInvariants(project.canvas.document);+ let applied = 0;+ for (let step = 0; step < 16; step += 1) {+ const before = project;+ const model = createDocumentModel(before.canvas.document, { editRevision: step, projectId: before.id });+ const command = randomCommand(random, before.canvas.document);+ const result = model.prepare(command);+ expect(model.refusalFor(command)).toEqual(+ result.status === 'prepared' || result.status === 'unchanged' ? null : result+ );+ if (result.status === 'locked') {+ outcomes.locked += 1;+ }+ if (result.status !== 'prepared') {+ continue;+ }+ const preIndex = getDocumentIndex(before.canvas.document);+ const nestedSelection = (selected: readonly string[]): boolean =>+ selected.some((id) => preIndex.byId.get(id)!.path.some((ancestor) => selected.includes(ancestor)));+ if (command.type === 'duplicate' && nestedSelection(command.ids)) {+ outcomes.nestedDuplicate += 1;+ }+ if (command.type === 'ungroup' && nestedSelection(command.ids)) {+ outcomes.nestedUngroup += 1;+ }+ if (command.type === 'reparent' && command.parentId !== null) {+ outcomes.reparentInside += 1;+ }+ const after = applyCanvasProjectMutation(before, result.edit.forward);+ expect(after.canvas.document, `${JSON.stringify(command)} was prepared but the reducer refused it`).not.toBe(+ before.canvas.document+ );+ assertInvariants(after.canvas.document);+ expect(checkEditPostconditions(after.canvas.document, result.edit.postconditions)).toBe(true);+ expect(after.canvas.document.selectedLayerId).toBe(result.edit.selectionAfter);+ const restored = applyCanvasProjectMutation(after, result.edit.inverse).canvas.document;+ expect(haveSameStructure(restored.stacks, before.canvas.document.stacks)).toBe(true);+ expect(getDocumentIndex(restored).nodes.map((entry) => entry.node)).toEqual(+ getDocumentIndex(before.canvas.document).nodes.map((entry) => entry.node)+ );+ expect(restored.selectedLayerId).toBe(before.canvas.document.selectedLayerId);+ const redone = applyCanvasProjectMutation(+ { ...before, canvas: { ...before.canvas, document: restored } },+ result.edit.forward+ ).canvas.document;+ expect(+ haveSameStructure(redone.stacks, after.canvas.document.stacks),+ `redo of ${JSON.stringify(command)}`+ ).toBe(true);+ project = after;+ applied += 1;+ }+ expect(applied).toBeGreaterThan(0);+ }+ );++ it('reached every outcome the generator is meant to produce', () => {+ expect(outcomes.locked).toBeGreaterThan(20);+ expect(outcomes.nestedDuplicate).toBeGreaterThan(5);+ expect(outcomes.nestedUngroup).toBeGreaterThan(5);+ expect(outcomes.reparentInside).toBeGreaterThan(50);+ });++ it('holds the depth boundary under random reparenting, grouping, inserting and duplicating', () => {+ const random = rng(99);+ created = 0;+ const chain = (depth: number): CanvasNodeContract =>+ depth === 0 ? layerContract(nextId(), 'raster') : groupContract(nextId(), [chain(depth - 1)]);+ let project = projectFor({+ ...createEmptyCanvasDocument(),+ selectedLayerId: null,+ stacks: stacksFrom([chain(CANVAS_MAX_NODE_DEPTH - 1), groupContract('spare', [layerContract('leaf', 'raster')])]),+ });+ const refusals = { duplicate: 0, group: 0, insert: 0, reparent: 0 };+ for (let step = 0; step < 120; step += 1) {+ const model = createDocumentModel(project.canvas.document, { editRevision: step, projectId: project.id });+ const groups = model.compileNodes().filter((node) => node.kind === 'group');+ const target = pick(random, groups);+ const roll = random();+ const command: DocumentCommand =+ roll < 0.25+ ? { beforeId: null, ids: ['spare'], parentId: target.id, type: 'reparent' }+ : roll < 0.5+ ? { groupId: nextId(), ids: [target.id], name: 'g', type: 'group' }+ : roll < 0.75+ ? {+ aboveId: null,+ insideId: target.id,+ nodes: [groupContract(nextId(), [groupContract(nextId(), [layerContract(nextId(), 'raster')])])],+ type: 'insert',+ }+ : { createId: nextId, ids: [target.id], type: 'duplicate' };+ const result = model.prepare(command);+ if (result.status === 'invalid-target' && result.reason === 'depth-exceeded') {+ refusals[command.type as keyof typeof refusals] += 1;+ continue;+ }+ if (result.status !== 'prepared') {+ continue;+ }+ project = applyCanvasProjectMutation(project, result.edit.forward);+ expect(project.canvas.document, `${command.type} was prepared but the reducer refused it`).not.toBe(+ model.document+ );+ assertInvariants(project.canvas.document);+ }+ expect(refusals.reparent).toBeGreaterThan(0);+ expect(refusals.group).toBeGreaterThan(0);+ expect(refusals.insert).toBeGreaterThan(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.tsindex 85d3be6e63..08eb0676f1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts@@ -1042,7 +1042,7 @@ describe('lock coherence and limits', () => {expect(model.prepare({ id: 'L', patch: { isLocked: false }, type: 'patch' }).status).toBe('prepared');});- it('refuses inserting into or reordering inside a locked group, but moves a locked node among free siblings', () => {+ it('refuses inserting into a locked group and every structural move that touches a locked subtree', () => {const model = modelOf(projectWith(lockedTree(), 'r2'));expect(model.prepare({ aboveId: 'r2', nodes: [layer('new')], type: 'insert' })).toEqual({ids: ['L'],@@ -1053,8 +1053,21 @@ describe('lock coherence and limits', () => {status: 'locked',});expect(model.prepare({ ids: ['r2'], kind: 'back', type: 'move' })).toEqual({ ids: ['L'], status: 'locked' });- expect(model.prepare({ ids: ['r4'], kind: 'front', type: 'move' }).status).toBe('prepared');+ expect(model.prepare({ ids: ['r4'], kind: 'front', type: 'move' })).toEqual({ ids: ['r4'], status: 'locked' });+ // A locked sibling may be passed; only the moving subtree has to be free.+ expect(model.prepare({ ids: ['r1'], kind: 'back', type: 'move' }).status).toBe('prepared');+ expect(model.prepare({ beforeId: null, ids: ['L'], parentId: null, type: 'reparent' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ expect(model.prepare({ groupId: 'N', ids: ['r1', 'L'], name: 'n', type: 'group' })).toEqual({+ ids: ['L'],+ status: 'locked',+ });+ expect(model.prepare({ ids: ['L'], type: 'ungroup' })).toEqual({ ids: ['L'], status: 'locked' });expect(model.prepare({ aboveId: 'r1', nodes: [layer('new')], type: 'insert' }).status).toBe('prepared');+ expect(model.refusalFor({ ids: ['r1'], kind: 'front', type: 'move' })).toBeNull();+ expect(model.refusalFor({ ids: ['r4'], kind: 'front', type: 'move' })).toEqual({ ids: ['r4'], status: 'locked' });});it('counts every node of a multi-stack insert and a multi-root duplicate against the node limit', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.tsindex d123a061f3..9c44a92788 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts@@ -53,9 +53,11 @@ import type {} from './documentCommands';import type { EditPostcondition } from './postconditions';import type { SemanticLeaf } from './semanticLeaf';+import type { SemanticNode } from './semanticNode';import { isConfigApplied, isPatchApplied, sameValue } from './postconditions';import { compileSemanticLeaf, isSemanticLeafCurrent } from './semanticLeaf';+import { compileSemanticNode, isSemanticNodeCurrent } from './semanticNode';export interface DocumentModelContext {readonly projectId: string;@@ -76,16 +78,22 @@ export interface CanvasDocumentModel {getEntry(id: string): CanvasNodeEntry | null;getStack(kind: LayerStackKind): readonly CanvasNodeContract[];compileLeaves(): readonly SemanticLeaf[];+ /** Every node, leaf or group, stacks top first in preorder, with ancestor-effective state applied. */+ compileNodes(): readonly SemanticNode[];canMergeDown(upperId: string): MergeDownEligibility;prepare(command: DocumentCommand): PrepareEditResult;+ /** Why `command` would be refused, or `null` when it would prepare or change nothing: the one eligibility authority. */+ refusalFor(command: DocumentCommand): DocumentRefusal | null;}export interface DocumentModelDiagnostics {readonly leafCompilations: number;readonly leavesCompiled: number;+ /** Semantic nodes built rather than reused across compilations. */+ readonly nodesCompiled: number;}-const diagnostics = { leafCompilations: 0, leavesCompiled: 0 };+const diagnostics = { leafCompilations: 0, leavesCompiled: 0, nodesCompiled: 0 };/** Immutable snapshot for deterministic budget tests and diagnostics. */export const getDocumentModelDiagnostics = (): DocumentModelDiagnostics => ({ ...diagnostics });@@ -93,11 +101,34 @@ export const getDocumentModelDiagnostics = (): DocumentModelDiagnostics => ({ ..export const resetDocumentModelDiagnostics = (): void => {diagnostics.leafCompilations = 0;diagnostics.leavesCompiled = 0;+ diagnostics.nodesCompiled = 0;};const leavesByIndex = new WeakMap<CanvasDocumentIndex, readonly SemanticLeaf[]>();const leavesByLayer = new WeakMap<CanvasLayerContract, SemanticLeaf>();const leafByIdByIndex = new WeakMap<CanvasDocumentIndex, ReadonlyMap<string, SemanticLeaf>>();+const nodesByIndex = new WeakMap<CanvasDocumentIndex, readonly SemanticNode[]>();+const nodeByContract = new WeakMap<CanvasNodeContract, SemanticNode>();+const nodeByIdByIndex = new WeakMap<CanvasDocumentIndex, ReadonlyMap<string, SemanticNode>>();++const compileNodes = (index: CanvasDocumentIndex): readonly SemanticNode[] => {+ const cached = nodesByIndex.get(index);+ if (cached) {+ return cached;+ }+ const nodes = index.nodes.map((entry) => {+ const previous = nodeByContract.get(entry.node);+ if (previous && isSemanticNodeCurrent(previous, entry)) {+ return previous;+ }+ diagnostics.nodesCompiled += 1;+ const semantic = compileSemanticNode(entry);+ nodeByContract.set(entry.node, semantic);+ return semantic;+ });+ nodesByIndex.set(index, nodes);+ return nodes;+};const contributingByIndex = new WeakMap<CanvasDocumentIndex, readonly CanvasLayerContract[]>();const compileLeaves = (index: CanvasDocumentIndex): readonly SemanticLeaf[] => {@@ -142,6 +173,24 @@ export const lookupDocumentLayer = (document: DocumentView, id: string): CanvasLexport const compileDocumentLeaves = (document: CanvasDocumentContractV3): readonly SemanticLeaf[] =>compileLeaves(getDocumentIndex(document));+/** Every node with ancestor-effective state applied; the same array while the forests are unchanged. */+export const compileDocumentNodes = (document: Pick<CanvasDocumentContractV3, 'stacks'>): readonly SemanticNode[] =>+ compileNodes(getDocumentIndex(document));++/** The semantic node for `id`, or `null` when absent. */+export const lookupDocumentNodeState = (document: DocumentView, id: string): SemanticNode | null => {+ if (!document) {+ return null;+ }+ const index = getDocumentIndex(document);+ let byId = nodeByIdByIndex.get(index);+ if (!byId) {+ byId = new Map(compileNodes(index).map((semantic) => [semantic.id, semantic]));+ nodeByIdByIndex.set(index, byId);+ }+ return byId.get(id) ?? null;+};+/** The layers of every contributing leaf, in leaf order; the same array while the forests are unchanged. */export const compileContributingLayers = (document: CanvasDocumentContractV3): readonly CanvasLayerContract[] => {const index = getDocumentIndex(document);@@ -551,10 +600,19 @@ export const createDocumentModel = (return found;}const outer = outermostNodes(index, ids);- const locked = unique(outer.flatMap((entry) => lockedAlong(index, entry.path)));+ const locked = unique(outer.flatMap((entry) => lockedWithin(index, entry)));if (locked.length > 0) {return { ids: locked, status: 'locked' };}+ // Every refusal is decided before an id is minted, so asking is free of side effects.+ let budgeted = 0;+ for (const entry of outer) {+ const refusal = limits([entry.node], entry.path.length, budgeted);+ if (refusal) {+ return refusal;+ }+ budgeted += collectSubtree(entry.node).length;+ }const add: CanvasNodeInsertion[] = [];const createdIds: string[] = [];const rootIds: string[] = [];@@ -566,10 +624,6 @@ export const createDocumentModel = (if (clash) {return { reason: 'id-exists', status: 'invalid-target', targetId: clash.id };}- const refusal = limits([clone], entry.path.length, createdIds.length);- if (refusal) {- return refusal;- }const anchor = captureInsertionAnchor(expected, {aboveId: entry.node.id,editRevision: context.editRevision,@@ -598,7 +652,11 @@ export const createDocumentModel = ();};- const prepareReorder = (orders: readonly ReorderSiblingsCommand[]): PrepareEditResult => {+ /** `movingIds` names the nodes a move selected; a raw reorder treats every displaced node as moved. */+ const prepareReorder = (+ orders: readonly ReorderSiblingsCommand[],+ movingIds?: ReadonlySet<string>+ ): PrepareEditResult => {if (orders.length === 0) {return { operation: 'reorder nothing', status: 'unsupported' };}@@ -646,6 +704,11 @@ export const createDocumentModel = (if (touchedIds.length === 0) {return { status: 'unchanged' };}+ const moving = movingIds ? touchedIds.filter((id) => movingIds.has(id)) : touchedIds;+ const lockedMoving = unique(moving.flatMap((id) => lockedWithin(index, index.byId.get(id)!)));+ if (lockedMoving.length > 0) {+ return { ids: lockedMoving, status: 'locked' };+ }return prepared({orders: orders.map((order) => ({ ...order, orderedIds: [...order.orderedIds] })),@@ -674,7 +737,7 @@ export const createDocumentModel = (return found;}const orders = moveNodesWithinSiblings(index, ids, command.kind);- return orders.length === 0 ? { status: 'unchanged' } : prepareReorder(orders);+ return orders.length === 0 ? { status: 'unchanged' } : prepareReorder(orders, new Set(ids));};const prepareReparent = (command: Extract<DocumentCommand, { type: 'reparent' }>): PrepareEditResult => {@@ -707,7 +770,7 @@ export const createDocumentModel = (return { reason: 'cycle', status: 'invalid-target', targetId: parent.node.id };}const locked = unique([- ...outer.flatMap((entry) => lockedAlong(index, entry.path)),+ ...outer.flatMap((entry) => lockedWithin(index, entry)),...(parent ? frozenBy(index, parent) : []),]);if (locked.length > 0) {@@ -797,7 +860,7 @@ export const createDocumentModel = (if (stranger) {return { reason: 'not-siblings', status: 'invalid-target', targetId: stranger.node.id };}- const locked = lockedAlong(index, first.path);+ const locked = unique([...lockedAlong(index, first.path), ...outer.flatMap((entry) => lockedWithin(index, entry))]);if (locked.length > 0) {return { ids: locked, status: 'locked' };}@@ -871,7 +934,7 @@ export const createDocumentModel = (}const named = new Set(ids);const groups = index.nodes.filter((entry) => named.has(entry.node.id));- const locked = unique(groups.flatMap((entry) => frozenBy(index, entry)));+ const locked = unique(groups.flatMap((entry) => [...frozenBy(index, entry), ...lockedWithin(index, entry)]));if (locked.length > 0) {return { ids: locked, status: 'locked' };}@@ -1252,9 +1315,10 @@ export const createDocumentModel = ();};- return {+ const model: CanvasDocumentModel = {canMergeDown: (upperId) => mergeDownEligibility(document, upperId),compileLeaves: () => compileLeaves(index),+ compileNodes: () => compileNodes(index),document,getEntry: (id) => index.byId.get(id) ?? null,getLayer: (id) => {@@ -1297,7 +1361,12 @@ export const createDocumentModel = (return prepareSelect(command);}},+ refusalFor: (command) => {+ const result = model.prepare(command);+ return result.status === 'prepared' || result.status === 'unchanged' ? null : result;+ },};+ return model;};const stripRemoved = (node: CanvasNodeContract, removed: ReadonlySet<string>): CanvasNodeContract =>diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.tsnew file mode 100644index 0000000000..be6b0fb2d1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts@@ -0,0 +1,72 @@+import type { CanvasNodeContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeEntry } from '@workbench/canvas-engine/document/documentIndex';+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';++import { collectSubtreeLeaves, isGroupNode, subtreeDepth } from '@workbench/canvas-engine/document/documentTree';+import { isNodeHidden } from '@workbench/canvas-engine/document/layerEligibility';++/**+ * Document facts about one node, leaf or group, with its ancestors already applied: what a row,+ * a toolbar or a planner may show or refuse without recomputing any rule. Nothing about the+ * screen, the panel or the session.+ */+export interface SemanticNode {+ readonly id: string;+ readonly kind: 'group' | 'leaf';+ readonly stack: LayerStackKind;+ readonly node: CanvasNodeContract;+ readonly parentId: string | null;+ /** Ancestor group ids, root first. */+ readonly parentIds: readonly string[];+ readonly depth: number;+ readonly siblingIndex: number;+ /** The node and every ancestor are enabled. */+ readonly contributionEnabled: boolean;+ /** The node or an ancestor is display-hidden. */+ readonly documentHidden: boolean;+ /** The node or an ancestor is locked; edits refuse on this. */+ readonly effectiveLocked: boolean;+ readonly ancestorsEnabled: boolean;+ readonly ancestorsHidden: boolean;+ readonly ancestorsLocked: boolean;+ readonly childCount: number;+ readonly leafCount: number;+ /** Levels the node's child lists reach below it; a group always opens one. */+ readonly subtreeDepth: number;+}++export const compileSemanticNode = (entry: CanvasNodeEntry): SemanticNode => {+ const { node } = entry;+ const group = isGroupNode(node);+ return {+ ancestorsEnabled: entry.ancestorsEnabled,+ ancestorsHidden: entry.ancestorsHidden,+ ancestorsLocked: entry.ancestorsLocked,+ childCount: group ? node.children.length : 0,+ contributionEnabled: entry.ancestorsEnabled && node.isEnabled,+ depth: entry.path.length,+ documentHidden: entry.ancestorsHidden || isNodeHidden(node),+ effectiveLocked: entry.ancestorsLocked || node.isLocked,+ id: node.id,+ kind: group ? 'group' : 'leaf',+ leafCount: group ? collectSubtreeLeaves(node).length : 1,+ node,+ parentId: entry.parentId,+ parentIds: entry.path,+ siblingIndex: entry.siblingIndex,+ stack: entry.stack,+ subtreeDepth: group ? Math.max(1, subtreeDepth(node)) : 0,+ };+};++/** Whether a cached node still describes `entry`'s node in the place `entry` gives it. */+export const isSemanticNodeCurrent = (semantic: SemanticNode, entry: CanvasNodeEntry): boolean =>+ semantic.node === entry.node &&+ semantic.parentId === entry.parentId &&+ semantic.siblingIndex === entry.siblingIndex &&+ semantic.stack === entry.stack &&+ semantic.ancestorsEnabled === entry.ancestorsEnabled &&+ semantic.ancestorsHidden === entry.ancestorsHidden &&+ semantic.ancestorsLocked === entry.ancestorsLocked &&+ semantic.parentIds.length === entry.path.length &&+ semantic.parentIds.every((id, index) => id === entry.path[index]);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.tsindex 84480d5c17..21a04f7e8e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts@@ -7,6 +7,8 @@ import type {CanvasStackForests,} from '@workbench/canvas-engine/contracts';+import { LAYER_STACKS_TOP_FIRST } from '@workbench/canvas-engine/contracts';+import { isGroupNode } from './documentTree';/** Document facts about one node's place in its forest. */@@ -39,14 +41,16 @@ export interface CanvasDocumentIndex {readonly maxDepth: number;}-const STACKS_TOP_FIRST: readonly CanvasLayerStackKind[] = ['inpaint_mask', 'regional_guidance', 'control', 'raster'];--const diagnostics = { indexBuilds: 0 };+const diagnostics = { indexBuilds: 0, indexDerivations: 0 };export const getDocumentIndexBuildCount = (): number => diagnostics.indexBuilds;+/** Indexes derived from a previous one after a value edit, without walking the forests. */+export const getDocumentIndexDerivationCount = (): number => diagnostics.indexDerivations;+export const resetDocumentIndexBuildCount = (): void => {diagnostics.indexBuilds = 0;+ diagnostics.indexDerivations = 0;};type DocumentView = Pick<CanvasDocumentContractV3, 'stacks'> | null | undefined;@@ -100,12 +104,102 @@ const build = (stacks: CanvasStackForests): CanvasDocumentIndex => {}});};- for (const stack of STACKS_TOP_FIRST) {+ for (const stack of LAYER_STACKS_TOP_FIRST) {visit(stacks[stack], stack, null, [], true, false, false);}return { byId, leaves, maxDepth, nodes, stacks };};+const flagsChanged = (previous: CanvasNodeContract, next: CanvasNodeContract): boolean =>+ isGroupNode(previous) &&+ isGroupNode(next) &&+ (previous.isEnabled !== next.isEnabled ||+ previous.isLocked !== next.isLocked ||+ (previous.isHidden === true) !== (next.isHidden === true));++/**+ * Registers the index of `nextStacks` as a derivation of `previousStacks`' index after a value edit+ * that rewrote exactly the nodes in `changed` (and, through structural sharing, their ancestors).+ * Structure is untouched, so every entry keeps its place and every unaffected entry, and the leaves+ * array when no leaf changed, keep their identity; only a group whose flags changed re-derives the+ * ancestor-effective flags of its subtree. Returns `null` when no previous index exists or the edit+ * was not a value edit, leaving the next lookup to build from scratch.+ */+export const deriveIndexForValueEdit = (+ previousStacks: CanvasStackForests,+ nextStacks: CanvasStackForests,+ changed: ReadonlyMap<string, CanvasNodeContract>+): CanvasDocumentIndex | null => {+ const existing = indexes.get(nextStacks);+ if (existing) {+ return existing;+ }+ const previous = indexes.get(previousStacks);+ if (!previous || previousStacks === nextStacks) {+ return null;+ }+ const replaced = new Map<string, CanvasNodeContract>();+ const reflagged = new Set<string>();+ for (const [id, node] of changed) {+ const entry = previous.byId.get(id);+ if (!entry || entry.node.id !== node.id || isGroupNode(entry.node) !== isGroupNode(node)) {+ return null;+ }+ replaced.set(id, node);+ if (flagsChanged(entry.node, node)) {+ reflagged.add(id);+ }+ }+ // Ancestors were rebuilt along each changed path; find their new objects from the new roots.+ for (const id of changed.keys()) {+ const entry = previous.byId.get(id)!;+ let siblings: readonly CanvasNodeContract[] = nextStacks[entry.stack];+ for (const ancestorId of entry.path) {+ const known = replaced.get(ancestorId);+ const ancestor = known ?? siblings.find((node) => node.id === ancestorId);+ if (!ancestor || !isGroupNode(ancestor)) {+ return null;+ }+ replaced.set(ancestorId, ancestor);+ siblings = ancestor.children;+ }+ }+ diagnostics.indexDerivations += 1;+ const nodeOf = (id: string): CanvasNodeContract => replaced.get(id) ?? previous.byId.get(id)!.node;+ let leafChanged = false;+ const nodes = previous.nodes.map((entry) => {+ const node = replaced.get(entry.node.id);+ const underReflagged = reflagged.size > 0 && entry.path.some((ancestorId) => reflagged.has(ancestorId));+ if (!node && !underReflagged) {+ return entry;+ }+ if (node && !isGroupNode(node)) {+ leafChanged = true;+ }+ const ancestors = underReflagged ? entry.path.map(nodeOf) : null;+ return {+ ...entry,+ ancestorsEnabled: ancestors ? ancestors.every((ancestor) => ancestor.isEnabled) : entry.ancestorsEnabled,+ ancestorsHidden: ancestors+ ? ancestors.some((ancestor) => isGroupNode(ancestor) && ancestor.isHidden === true)+ : entry.ancestorsHidden,+ ancestorsLocked: ancestors ? ancestors.some((ancestor) => ancestor.isLocked) : entry.ancestorsLocked,+ node: node ?? entry.node,+ };+ });+ const derived: CanvasDocumentIndex = {+ byId: new Map(nodes.map((entry) => [entry.node.id, entry])),+ leaves: leafChanged+ ? previous.leaves.map((leaf) => (replaced.get(leaf.id) as CanvasLayerContract | undefined) ?? leaf)+ : previous.leaves,+ maxDepth: previous.maxDepth,+ nodes,+ stacks: nextStacks,+ };+ indexes.set(nextStacks, derived);+ return derived;+};+export const indexStacks = (stacks: CanvasStackForests): CanvasDocumentIndex => {const existing = indexes.get(stacks);if (existing) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.tsindex 95ed0210c7..bdea6b27c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts@@ -118,16 +118,18 @@ export const replaceChildren = (/*** Rewrites every node named by `updates` in place, sharing every untouched node. Groups are* rebuilt only along the paths to a changed node; the same forests come back when nothing changed.+ * `changed` holds the nodes an update actually replaced, keyed by id.*/-export const updateNodes = (+export const updateNodesTracked = (stacks: CanvasStackForests,updates: ReadonlyMap<string, (node: CanvasNodeContract) => CanvasNodeContract>-): CanvasStackForests => {+): { stacks: CanvasStackForests; changed: Map<string, CanvasNodeContract> } => {+ const changed = new Map<string, CanvasNodeContract>();if (updates.size === 0) {- return stacks;+ return { changed, stacks };}const visit = (nodes: readonly CanvasNodeContract[]): readonly CanvasNodeContract[] => {- let changed = false;+ let rebuilt = false;const next = nodes.map((node) => {let current = node;if (isGroupNode(current)) {@@ -138,12 +140,16 @@ export const updateNodes = (}const update = updates.get(current.id);if (update) {- current = update(current);+ const updated = update(current);+ if (updated !== current) {+ changed.set(updated.id, updated);+ current = updated;+ }}- changed ||= current !== node;+ rebuilt ||= current !== node;return current;});- return changed ? next : nodes;+ return rebuilt ? next : nodes;};let result = stacks;for (const stack of Object.keys(stacks) as CanvasLayerStackKind[]) {@@ -153,9 +159,14 @@ export const updateNodes = (result[stack] = [...roots];}}- return result;+ return { changed, stacks: result };};+export const updateNodes = (+ stacks: CanvasStackForests,+ updates: ReadonlyMap<string, (node: CanvasNodeContract) => CanvasNodeContract>+): CanvasStackForests => updateNodesTracked(stacks, updates).stacks;+/** Removes the subtrees rooted at `ids`, sharing every untouched node. */export const removeNodes = (stacks: CanvasStackForests, ids: ReadonlySet<string>): CanvasStackForests => {if (ids.size === 0) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.tsindex 23b9170920..5320920f6d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts@@ -17,9 +17,7 @@ export type LayerStackKind = CanvasLayerStackKind;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();+export { LAYER_STACK_ORDER, LAYER_STACKS_TOP_FIRST } from '@workbench/canvas-engine/contracts';export const layerStackOf = (layer: CanvasLayerContract): LayerStackKind => layer.type;diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.tsindex 91fe3c6f93..d653c4bb1d 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts@@ -490,7 +490,7 @@ const parseNode = (value: unknown, path: string, depth: number, context: ParseCocontext.diagnostics.push({ message: 'a raster group has no display-only hidden state', path: `${path}.isHidden` });return null;}- if (context.stack === 'raster') {+ if (context.stack === 'raster' || shell.data.isHidden === false) {delete shell.data.isHidden;}if (depth >= CANVAS_MAX_NODE_DEPTH) {diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex 057e1ebcac..d6df80849c 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -22,6 +22,7 @@ import {} from '@workbench/canvas-engine/api';import {childrenAt,+ deriveIndexForValueEdit,getDocumentIndex,getDocumentLayer,hasDocumentNode,@@ -36,6 +37,7 @@ import {isGroupNode,removeNodes,updateNodes,+ updateNodesTracked,} from '@workbench/canvas-engine/document/documentTree';import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { isOverlayStack, layerStackOf, reorderSiblings } from '@workbench/canvas-engine/document/layerStacks';@@ -130,11 +132,23 @@ const withinLimits = (stacks: CanvasStackForests): boolean => {return index.maxDepth <= CANVAS_MAX_NODE_DEPTH && index.nodes.length <= CANVAS_MAX_NODE_COUNT;};+/** Value edits keep the structure, so the next forests inherit the index instead of rebuilding it. */+const updateNodeValues = (+ stacks: CanvasStackForests,+ updates: Iterable<[string, (node: CanvasNodeContract) => CanvasNodeContract]>+): CanvasStackForests => {+ const next = updateNodesTracked(stacks, new Map(updates));+ if (next.stacks !== stacks) {+ deriveIndexForValueEdit(stacks, next.stacks, next.changed);+ }+ return next.stacks;+};+const mapNode = (document: CanvasDocumentContractV3,id: string,update: (node: CanvasNodeContract) => CanvasNodeContract-): CanvasDocumentContractV3 => withStacks(document, updateNodes(document.stacks, new Map([[id, update]])));+): CanvasDocumentContractV3 => withStacks(document, updateNodeValues(document.stacks, [[id, update]]));const mapLayer = (document: CanvasDocumentContractV3,@@ -145,7 +159,7 @@ const mapLayer = (const mapNodes = (document: CanvasDocumentContractV3,updates: Iterable<[string, (node: CanvasNodeContract) => CanvasNodeContract]>-): CanvasDocumentContractV3 => withStacks(document, updateNodes(document.stacks, new Map(updates)));+): CanvasDocumentContractV3 => withStacks(document, updateNodeValues(document.stacks, updates));const setCanvasLayersEnabled = (document: CanvasDocumentContractV3,@@ -169,7 +183,17 @@ const setCanvasLayersHidden = (document,updates.map(({ id, isHidden }) => [id,- (node) => (!isHideableNode(index, node) || isHidden === isNodeHidden(node) ? node : { ...node, isHidden }),+ (node) => {+ if (!isHideableNode(index, node) || isHidden === isNodeHidden(node)) {+ return node;+ }+ // Absence is the one spelling of "not hidden", so an undo restores the exact node.+ if (!isHidden) {+ const { isHidden: _hidden, ...shown } = node as CanvasNodeContract & { isHidden?: boolean };+ return shown as CanvasNodeContract;+ }+ return { ...node, isHidden };+ },]));};@@ -408,17 +432,17 @@ const applyLayerStackMutation = (}const enabledById = new Map(mutation.enabledUpdates.map((update) => [update.id, update.isEnabled]));const lockedById = new Map(mutation.lockedUpdates?.map((update) => [update.id, update.isLocked]) ?? []);- stacks = updateNodes(+ stacks = updateNodeValues(stacks,- new Map(- [...new Set([...enabledById.keys(), ...lockedById.keys()])].map((id) => [+ [...new Set([...enabledById.keys(), ...lockedById.keys()])].map(+ (id): [string, (node: CanvasNodeContract) => CanvasNodeContract] => [id,(node) => {const isEnabled = enabledById.get(id) ?? node.isEnabled;const isLocked = lockedById.get(id) ?? node.isLocked;return isEnabled === node.isEnabled && isLocked === node.isLocked ? node : { ...node, isEnabled, isLocked };},- ])+ ]));if (stacks !== document.stacks && !withinLimits(stacks)) {@@ -832,10 +856,10 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProstacks:offsetX === 0 && offsetY === 0? document.stacks- : updateNodes(+ : updateNodeValues(document.stacks,- new Map(- getDocumentIndex(document).leaves.map((leaf) => [+ getDocumentIndex(document).leaves.map(+ (leaf): [string, (node: CanvasNodeContract) => CanvasNodeContract] => [leaf.id,(node) =>isGroupNode(node)@@ -848,7 +872,7 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProy: node.transform.y + offsetY,},},- ])+ ])),width,