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
perf(canvas): apply value edits through the document index
Josh Corbett2f9134a21855
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 92628740ea..49b6b56e8d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -27,13 +27,13 @@ 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). 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`) that extends the previous one: `byId` is a layered map that reads through to the previous index for every untouched id, `nodes` and `leaves` materialize only when a consumer reads them (and `leaves` keeps its identity when no leaf object changed), and the only entries constructed are the edited path plus the subtree under a group whose flags changed. After eight derivations the chain flattens onto its plain root: one override layer holding the newest entry of every id the chain touched, still pointing consumers at the root's cached compile so the flattening step recompiles only what the chain changed; only when overrides cover more than a quarter of the root is a plain index rebuilt. Lookups therefore read through at most nine layers, and nothing older than the root is retained. `documentModel.budget.test.ts` pins this at 10,000 nodes: a leaf edit constructs `depth + 1` entries, compiles `depth + 1` semantic nodes (ancestors keep their counts without walking their subtrees) and one leaf, and answers `lookupDocumentLeaf`/`lookupDocumentNodeState` without materializing the node list.+`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) goes through `updateNodeValues`, which finds each edited node through the index and copies only the sibling arrays on its path (cost: the sibling counts along the edited paths, never the forest), so `stacks` changes; it then registers a derived index for the new forests that extends the previous one, and records the edit's replaced nodes (before and after; ancestors rebuilt only for a new child array are not listed) against the new forests: `byId` is a layered map that reads through to the previous index for every untouched id, `nodes` and `leaves` materialize only when a consumer reads them (and `leaves` keeps its identity when no leaf object changed), and the only entries constructed are the edited path plus the subtree under a group whose flags changed. After eight derivations the chain flattens onto its plain root: one override layer holding the newest entry of every id the chain touched, still pointing consumers at the root's cached compile so the flattening step recompiles only what the chain changed; only when overrides cover more than a quarter of the root is a plain index rebuilt. Lookups therefore read through at most nine layers, and nothing older than the root is retained. `documentModel.budget.test.ts` pins this at 10,000 nodes: a leaf edit revisits and constructs `depth + 1` entries, compiles `depth + 1` semantic nodes (ancestors keep their counts without walking their subtrees) and one leaf, and answers `lookupDocumentLeaf`/`lookupDocumentNodeState` without materializing the node list; a complete reducer → mirror value edit does the same with no forest diff.`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; for `reparent`, `group`, `ungroup` and `remove` it runs the same validator `prepare` uses without materializing an edit (`editsMaterialized` stays at zero), so a drag hover or a toolbar render never builds an inverse or postconditions. 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.-The document mirror diffs forests by leaf identity and ancestor-effective state: a group flag flip reports every descendant leaf as changed (never source-changed), a group rename reports nothing, and a reparent that changes no leaf's effective state reports an order change only.+The document mirror reports in leaf terms, in document order. For a value edit it folds the recorded edits since its last document (`valueEditBetween`, at most sixteen; the record holds its predecessor weakly so superseded forests are never retained) and touches only those nodes: an edited leaf is changed, and source-changed when its raster source or mask bitmap changed; a group flag flip reports the descendant leaves whose ancestor-effective state actually moved as changed (never source-changed); a group adjustment, opacity or blend edit sends its descendant leaves down the non-destructive recomposite channel; a group rename reports nothing. Only a structural edit, an unrecorded step or a wholesale replacement diffs the forests by leaf identity and ancestor-effective state, where a reparent that changes no leaf's effective state reports an order change only. `onLayersChanged` says whether the forests were restructured, so the engine prunes group surfaces only then, and invalidates each changed layer once.### Layers paneldiff --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 2770654fdc..2172dc701c 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@@ -6,11 +6,17 @@ import {getDocumentIndexDerivationCount,getDocumentIndexMaterializationCount,getDocumentIndexVisitCount,+ getValueEditVisitCount,resetDocumentIndexBuildCount,} from '@workbench/canvas-engine/document/documentIndex';+import {+ createDocumentMirror,+ getForestDiffCount,+ resetForestDiffCount,+} from '@workbench/canvas-engine/document/documentMirror';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';import { createInitialWorkbenchState } from '@workbench/workbenchState';-import { beforeEach, describe, expect, it } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import type { DocumentCommand, PreparedDocumentEdit } from './documentCommands';@@ -32,11 +38,14 @@ const context = { editRevision: 0, projectId: 'budget' };const resetCounters = (): void => {resetDocumentModelDiagnostics();resetDocumentIndexBuildCount();+ resetForestDiffCount();};const counters = () => ({...getDocumentModelDiagnostics(),entriesVisited: getDocumentIndexVisitCount(),+ forestDiffs: getForestDiffCount(),+ forestNodesVisited: getValueEditVisitCount(),indexBuilds: getDocumentIndexBuildCount(),indexDerivations: getDocumentIndexDerivationCount(),nodesMaterialized: getDocumentIndexMaterializationCount(),@@ -300,7 +309,12 @@ describe('value edits at the 10,000-node limit', () => {patch: { transform: { x: 40 } },type: 'updateCanvasLayer',}).canvas.document;- expect(counters()).toMatchObject({ entriesVisited: depth + 1, indexBuilds: 0, indexDerivations: 1 });+ expect(counters()).toMatchObject({+ entriesVisited: depth + 1,+ forestNodesVisited: depth + 1,+ indexBuilds: 0,+ indexDerivations: 1,+ });expect(lookupDocumentLeaf(next, 'l5')?.layer.transform.x).toBe(40);expect(lookupDocumentNodeState(next, 'l5')?.node).toBe(getDocumentIndex(next).byId.get('l5')!.node);expect(lookupDocumentNodeState(next, 'l6')).toBe(lookupDocumentNodeState(before, 'l6'));@@ -324,7 +338,12 @@ describe('value edits at the 10,000-node limit', () => {type: 'setCanvasLayersEnabled',updates: [{ id: 'g0', isEnabled: false }],}).canvas.document;- expect(counters()).toMatchObject({ entriesVisited: subtree + 1, indexBuilds: 0, indexDerivations: 1 });+ expect(counters()).toMatchObject({+ entriesVisited: subtree + 1,+ forestNodesVisited: 1,+ indexBuilds: 0,+ indexDerivations: 1,+ });expect(getDocumentIndex(next).leaves).toBe(getDocumentIndex(before).leaves);compileDocumentNodes(next);expect(counters()).toMatchObject({ nodesCompiled: subtree + 1, nodesMaterialized: 0 });@@ -364,6 +383,47 @@ describe('value edits at the 10,000-node limit', () => {});});+describe('reducer → mirror value edits at the 10,000-node limit', () => {+ beforeEach(resetCounters);++ it.for([+ ['flat', createLargeFlatDocument],+ ['tree', createLargeTreeDocument],+ ] as const)('touches only the edited path end to end on a %s document', ([, create], { annotate }) => {+ let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {+ document: create(10_000),+ type: 'replaceCanvasDocument',+ });+ const onLayersChanged = vi.fn();+ const mirror = createDocumentMirror(+ { getCanvasState: () => project.canvas, subscribe: () => () => undefined },+ {+ onBboxChanged: () => undefined,+ onDocumentReplaced: () => undefined,+ onLayerOrderChanged: () => undefined,+ onLayersChanged,+ onStagingChanged: () => undefined,+ }+ );+ const depth = getDocumentIndex(project.canvas.document).byId.get('l0')!.path.length;+ resetCounters();++ timed(annotate, 'reducer + mirror', () => {+ project = applyCanvasProjectMutation(project, { id: 'l0', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' });+ mirror.refresh();+ });+ expect(onLayersChanged).toHaveBeenCalledWith(['l0'], [], false);+ expect(counters()).toMatchObject({+ forestDiffs: 0,+ forestNodesVisited: depth + 1,+ indexBuilds: 0,+ indexDerivations: 1,+ nodesMaterialized: 0,+ });+ mirror.dispose();+ });+});+describe('eligibility without materialization', () => {beforeEach(resetCounters);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.tsindex df036326b7..f639e8293c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts@@ -40,7 +40,13 @@ export interface CanvasDocumentIndex {readonly derivedFrom?: { readonly previous: CanvasDocumentIndex; readonly changedIds: ReadonlySet<string> };}-const diagnostics = { entriesVisited: 0, indexBuilds: 0, indexDerivations: 0, nodesMaterialized: 0 };+const diagnostics = {+ entriesVisited: 0,+ forestNodesVisited: 0,+ indexBuilds: 0,+ indexDerivations: 0,+ nodesMaterialized: 0,+};export const getDocumentIndexBuildCount = (): number => diagnostics.indexBuilds;@@ -53,8 +59,12 @@ export const getDocumentIndexVisitCount = (): number => diagnostics.entriesVisit/** Times a derived index had to materialize its full `nodes` array for a consumer. */export const getDocumentIndexMaterializationCount = (): number => diagnostics.nodesMaterialized;+/** Forest nodes a value edit revisited: the edited nodes and their ancestors, never the whole forest. */+export const getValueEditVisitCount = (): number => diagnostics.forestNodesVisited;+export const resetDocumentIndexBuildCount = (): void => {diagnostics.entriesVisited = 0;+ diagnostics.forestNodesVisited = 0;diagnostics.indexBuilds = 0;diagnostics.indexDerivations = 0;diagnostics.nodesMaterialized = 0;@@ -279,7 +289,7 @@ const flagsChanged = (previous: CanvasNodeContract, next: CanvasNodeContract): b* flags. Unchanged entries read through. Returns null without a prior index or when structure changed, deferring a* full build.*/-export const deriveIndexForValueEdit = (+const deriveIndexForValueEdit = (previousStacks: CanvasStackForests,nextStacks: CanvasStackForests,changed: ReadonlyMap<string, CanvasNodeContract>@@ -309,9 +319,8 @@ export const deriveIndexForValueEdit = (const entry = previous.byId.get(id)!;let siblings: readonly CanvasNodeContract[] = nextStacks[entry.stack];for (const ancestorId of entry.path) {- const known = replacedNodes.get(ancestorId);- const ancestor = known ?? siblings.find((node) => node.id === ancestorId);- if (!ancestor || !isGroupNode(ancestor)) {+ const ancestor = replacedNodes.get(ancestorId) ?? siblings[previous.byId.get(ancestorId)!.siblingIndex];+ if (!ancestor || ancestor.id !== ancestorId || !isGroupNode(ancestor)) {return null;}replacedNodes.set(ancestorId, ancestor);@@ -359,6 +368,140 @@ export const deriveIndexForValueEdit = (return registered;};+/** One node a value edit replaced; ancestors rebuilt only for a new child array are not listed. */+export interface CanvasNodeValueChange {+ readonly before: CanvasNodeContract;+ readonly after: CanvasNodeContract;+}++/** The nodes value edits replaced between two forests that share one structure. */+export type CanvasValueEdit = ReadonlyMap<string, CanvasNodeValueChange>;++interface ValueEditRecord {+ /** Weak, so a chain of edits never retains every superseded forest. */+ readonly from: WeakRef<CanvasStackForests>;+ readonly changes: CanvasValueEdit;+}++const valueEdits = new WeakMap<CanvasStackForests, ValueEditRecord>();++/** How many consecutive value edits a consumer that fell behind may still fold instead of diffing forests. */+const MAX_FOLDED_VALUE_EDITS = 16;++/**+ * The value edits that lead from `previous` to `next`, folded oldest first, or null when any step between them+ * restructured the forests or was not recorded.+ */+export const valueEditBetween = (previous: CanvasStackForests, next: CanvasStackForests): CanvasValueEdit | null => {+ const steps: CanvasValueEdit[] = [];+ let current = next;+ while (current !== previous) {+ const record = valueEdits.get(current);+ const from = record?.from.deref();+ if (!record || !from || steps.length === MAX_FOLDED_VALUE_EDITS) {+ return null;+ }+ steps.push(record.changes);+ current = from;+ }+ if (steps.length <= 1) {+ return steps[0] ?? new Map();+ }+ const folded = new Map<string, CanvasNodeValueChange>();+ for (let step = steps.length - 1; step >= 0; step -= 1) {+ for (const [id, change] of steps[step]!) {+ const earlier = folded.get(id);+ folded.set(id, earlier ? { after: change.after, before: earlier.before } : change);+ }+ }+ return folded;+};++const rootKey = (stack: CanvasLayerStackKind): string => `\0${stack}`;++/**+ * Rewrites named nodes in place of their old objects, locating them through the index. Only the sibling arrays on+ * each edited path are copied, so cost is the edited paths' sibling counts, not the forest. The next forests inherit+ * a derived index and record which nodes changed for incremental consumers. Returns `stacks` when nothing changed.+ */+export const updateNodeValues = (+ stacks: CanvasStackForests,+ updates: ReadonlyMap<string, (node: CanvasNodeContract) => CanvasNodeContract>+): CanvasStackForests => {+ if (updates.size === 0) {+ return stacks;+ }+ const index = indexStacks(stacks);+ // Sibling positions to revisit, keyed by parent group id or a stack's root key.+ const touched = new Map<string, Set<number>>();+ const mark = (entry: CanvasNodeEntry): boolean => {+ const key = entry.parentId ?? rootKey(entry.stack);+ const positions = touched.get(key) ?? new Set<number>();+ const added = !positions.has(entry.siblingIndex);+ positions.add(entry.siblingIndex);+ touched.set(key, positions);+ return added;+ };+ for (const id of updates.keys()) {+ const entry = index.byId.get(id);+ if (!entry || !mark(entry)) {+ continue;+ }+ for (let depth = entry.path.length - 1; depth >= 0; depth -= 1) {+ if (!mark(index.byId.get(entry.path[depth]!)!)) {+ break;+ }+ }+ }+ const changes = new Map<string, CanvasNodeValueChange>();+ const rebuild = (key: string, list: readonly CanvasNodeContract[]): readonly CanvasNodeContract[] => {+ const positions = touched.get(key);+ if (!positions) {+ return list;+ }+ let next: CanvasNodeContract[] | null = null;+ for (const position of positions) {+ const node = list[position]!;+ diagnostics.forestNodesVisited += 1;+ let current = node;+ if (isGroupNode(current)) {+ const children = rebuild(current.id, current.children);+ if (children !== current.children) {+ current = { ...current, children: children as CanvasNodeContract[] };+ }+ }+ const update = updates.get(node.id);+ if (update) {+ const updated = update(current);+ if (updated !== current) {+ changes.set(node.id, { after: updated, before: node });+ current = updated;+ }+ }+ if (current !== node) {+ next ??= list.slice();+ next[position] = current;+ }+ }+ return next ?? list;+ };+ let result = stacks;+ for (const stack of LAYER_STACKS_TOP_FIRST) {+ const roots = rebuild(rootKey(stack), stacks[stack]);+ if (roots !== stacks[stack]) {+ result = result === stacks ? { ...stacks } : result;+ result[stack] = roots as CanvasNodeContract[];+ }+ }+ if (result !== stacks) {+ const changed = new Map([...changes].map(([id, change]) => [id, change.after]));+ if (deriveIndexForValueEdit(stacks, result, changed)) {+ valueEdits.set(result, { changes, from: new WeakRef(stacks) });+ }+ }+ return result;+};+export const indexStacks = (stacks: CanvasStackForests): CanvasDocumentIndex => {const existing = indexes.get(stacks);if (existing) {@@ -396,16 +539,17 @@ export const isNodeAbsent = (document: DocumentView, id: string): boolean =>export const isSelfOrAncestor = (index: CanvasDocumentIndex, id: string, ancestorId: string): boolean =>id === ancestorId || (index.byId.get(id)?.path.includes(ancestorId) ?? false);-/** Drops every id whose ancestor is also listed, keeping document order. */+/** Drops every id whose ancestor is also listed, in document order; absent ids are skipped. */export const outermostNodes = (index: CanvasDocumentIndex, ids: Iterable<string>): CanvasNodeEntry[] => {const selected = new Set(ids);const outer: CanvasNodeEntry[] = [];- for (const entry of index.nodes) {- if (selected.has(entry.node.id) && !entry.path.some((ancestor) => selected.has(ancestor))) {+ for (const id of selected) {+ const entry = index.byId.get(id);+ if (entry && !entry.path.some((ancestor) => selected.has(ancestor))) {outer.push(entry);}}- return outer;+ return outer.sort((left, right) => left.order - right.order);};/** The child list `parentId` names, read through the index; `null` when the parent is not a group of `stack`. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.tsindex 8cb4cfe493..59131b51ed 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts@@ -7,14 +7,17 @@ import type {CanvasStateContractV3,CanvasNodeContract,} from '@workbench/canvas-engine/contracts';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';import type { DocumentMirrorCallbacks } from './documentMirror';import { getDocumentLeaves } from './documentIndex';-import { createDocumentMirror } from './documentMirror';+import { createDocumentMirror, getForestDiffCount, resetForestDiffCount } from './documentMirror';const rasterLayer = (id: string, overrides: Partial<CanvasRasterLayerContractV2> = {}): CanvasLayerContract => ({blendMode: 'normal',@@ -189,7 +192,7 @@ describe('createDocumentMirror', () => {mirror.refresh();expect(mirror.getDocument()).toBe(updated);- expect(callbacks.onLayersChanged).toHaveBeenCalledWith(['a'], []);+ expect(callbacks.onLayersChanged).toHaveBeenCalledWith(['a'], [], false);});it('reports exactly the edited layer id when one layer changes by reference', () => {@@ -206,7 +209,7 @@ describe('createDocumentMirror', () => {store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });expect(callbacks.onLayersChanged).toHaveBeenCalledTimes(1);- expect(callbacks.onLayersChanged).toHaveBeenCalledWith(['a'], []);+ expect(callbacks.onLayersChanged).toHaveBeenCalledWith(['a'], [], false);expect(callbacks.onDocumentReplaced).not.toHaveBeenCalled();expect(callbacks.onBboxChanged).not.toHaveBeenCalled();});@@ -222,7 +225,7 @@ describe('createDocumentMirror', () => {// Opacity changes preserve source identity; rerasterization would erase unflushed paint.const opacityEdit: CanvasDocumentContractV3 = { ...doc, stacks: stacksFrom([{ ...a, opacity: 0.5 }]) };store.setState({ projects: [{ canvas: { ...canvas, document: opacityEdit }, id: 'p1' }] });- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], []);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], [], false);// Genuine source swap (new `source` object): reported as source-changed.const swapped = getDocumentLeaves(store.getState().projects[0]!.canvas.document)[0] as CanvasRasterLayerContractV2;@@ -233,7 +236,7 @@ describe('createDocumentMirror', () => {]),};store.setState({ projects: [{ canvas: { ...canvas, document: sourceSwap }, id: 'p1' }] });- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], ['a']);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], ['a'], false);});it('for a mask: a fill-only change is NOT source-changed, a bitmap swap IS (protects unflushed strokes)', () => {@@ -261,7 +264,7 @@ describe('createDocumentMirror', () => {stacks: stacksFrom([{ ...mask, mask: { bitmap: null, fill: { color: '#00ff00', style: 'grid' as const } } }]),};store.setState({ projects: [{ canvas: { ...canvas, document: fillEdit }, id: 'p1' }] });- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['m'], []);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['m'], [], false);// A bitmap swap (persistence round-trip / undo): reported as source-changed.const current = getDocumentLeaves(@@ -274,7 +277,7 @@ describe('createDocumentMirror', () => {]),};store.setState({ projects: [{ canvas: { ...canvas, document: bitmapSwap }, id: 'p1' }] });- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['m'], ['m']);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['m'], ['m'], false);});it('reports added and removed layer ids', () => {@@ -290,11 +293,11 @@ describe('createDocumentMirror', () => {store.setState({projects: [{ canvas: { ...canvas, document: { ...doc, stacks: stacksFrom([b, a]) } }, id: 'p1' }],});- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['b'], ['b']);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['b'], ['b'], true);// A removal is a change but not a source change (the id has no incoming source).store.setState({ projects: [{ canvas: { ...canvas, document: { ...doc, stacks: stacksFrom([b]) } }, id: 'p1' }] });- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], []);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], [], true);});it('fires onLayerOrderChanged exactly once on a pure reorder, with no layer ids reported', () => {@@ -378,7 +381,7 @@ describe('createDocumentMirror', () => {store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });expect(callbacks.onDocumentReplaced).not.toHaveBeenCalled();- expect(callbacks.onLayersChanged).toHaveBeenCalledWith(['a'], []);+ expect(callbacks.onLayersChanged).toHaveBeenCalledWith(['a'], [], false);});it('fires onBboxChanged when only the bbox moves', () => {@@ -485,7 +488,7 @@ describe('createDocumentMirror: groups', () => {const { callbacks, set } = setup(doc);set({ ...doc, stacks: stacksFrom([groupContract('g', [a, groupContract('h', [b])], { isEnabled: false }), c]) });- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a', 'b'], []);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a', 'b'], [], false);expect(callbacks.onLayerOrderChanged).not.toHaveBeenCalled();});@@ -556,7 +559,7 @@ describe('createDocumentMirror: groups', () => {const { callbacks, set } = setup(doc);set({ ...doc, stacks: stacksFrom([groupContract('g', [a, b], { isEnabled: false })]) });- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['b'], []);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['b'], [], true);});it('reports the leaves of a removed group as removed, never the group id', () => {@@ -566,6 +569,74 @@ describe('createDocumentMirror: groups', () => {const { callbacks, set } = setup(doc);set({ ...doc, stacks: stacksFrom([b]) });- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], []);+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], [], true);+ });+});++describe('createDocumentMirror: value edits through the reducer', () => {+ const setup = (doc: CanvasDocumentContractV3) => {+ let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {+ document: doc,+ type: 'replaceCanvasDocument',+ });+ const store = createFakeStore([project]);+ const callbacks = spyCallbacks();+ const mirror = createDocumentMirror(store, project.id, callbacks);+ resetForestDiffCount();+ const apply = (mutation: CanvasProjectMutation, notify = true): void => {+ project = applyCanvasProjectMutation(project, mutation);+ (notify ? store.setState : store.replaceStateSilently)({ projects: [project] });+ };+ return { apply, callbacks, mirror };+ };++ it('reports leaf property and source edits from the recorded changes without diffing the forests', () => {+ const { apply, callbacks } = setup(makeDoc([rasterLayer('a'), rasterLayer('b')]));++ apply({ id: 'b', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['b'], [], false);+ apply({ id: 'a', source: { bitmap: null, type: 'paint' }, type: 'updateCanvasLayerSource' });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], ['a'], false);+ expect(getForestDiffCount()).toBe(0);+ });++ it('reports only the descendants whose inherited flags moved when a group flag flips', () => {+ const doc = makeDoc([+ groupContract('g', [rasterLayer('a'), groupContract('h', [rasterLayer('b')], { isEnabled: false })]),+ rasterLayer('c'),+ ]);+ const { apply, callbacks } = setup(doc);++ apply({ type: 'setCanvasLayersEnabled', updates: [{ id: 'g', isEnabled: false }] });+ // b was already disabled through h, so only a changes.+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a'], [], false);+ expect(getForestDiffCount()).toBe(0);+ });++ it('fans group appearance edits out on the recomposite channel and stays silent on a rename', () => {+ const { apply, callbacks } = setup(+ makeDoc([groupContract('g', [rasterLayer('a'), rasterLayer('b')]), rasterLayer('c')])+ );++ apply({ id: 'g', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' });+ expect(callbacks.onLayersRecomposite).toHaveBeenLastCalledWith(['a', 'b']);+ apply({ id: 'g', patch: { name: 'Folder' }, type: 'updateCanvasLayer' });+ expect(callbacks.onLayersChanged).not.toHaveBeenCalled();+ expect(callbacks.onLayersRecomposite).toHaveBeenCalledTimes(1);+ expect(getForestDiffCount()).toBe(0);+ });++ it('folds value edits a missed notification skipped, and diffs forests only across a structural edit', () => {+ const { apply, callbacks, mirror } = setup(makeDoc([rasterLayer('a'), rasterLayer('b'), rasterLayer('c')]));++ apply({ id: 'a', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' }, false);+ apply({ id: 'c', source: { bitmap: null, type: 'paint' }, type: 'updateCanvasLayerSource' }, false);+ mirror.refresh();+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a', 'c'], ['c'], false);+ expect(getForestDiffCount()).toBe(0);++ apply({ ids: ['b'], type: 'removeCanvasLayers' });+ expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['b'], [], true);+ expect(getForestDiffCount()).toBe(1);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.tsindex 663404d954..1b7d89ff41 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts@@ -1,12 +1,19 @@import type {CanvasDocumentContractV3,+ CanvasGroupContract,CanvasLayerContract,CanvasStagingAreaContractV2,CanvasStateContractV3,} from '@workbench/canvas-engine/contracts';-import { getDocumentIndex, type CanvasDocumentIndex, type CanvasNodeEntry } from './documentIndex';-import { isGroupNode } from './documentTree';+import {+ getDocumentIndex,+ valueEditBetween,+ type CanvasDocumentIndex,+ type CanvasNodeEntry,+ type CanvasValueEdit,+} from './documentIndex';+import { collectSubtreeLeaves, isGroupNode } from './documentTree';/** The minimal store shape the mirror depends on (a superset of `WorkbenchStore`). */export interface DocumentMirrorStore {@@ -18,11 +25,11 @@ export interface DocumentMirrorStore {/** Callbacks fired when the mirrored document changes. */export interface DocumentMirrorCallbacks {/**- * Reports leaf or ancestor-effective changes. `sourceChanged` contains added leaves and changed raster/control- * sources or mask bitmaps whose caches are stale. Property, transform and ancestor-flag changes retain cached- * pixels.+ * Reports leaf or ancestor-effective changes in document order. `sourceChanged` contains added leaves and changed+ * raster/control sources or mask bitmaps whose caches are stale. Property, transform and ancestor-flag changes+ * retain cached pixels. `restructured` is false for value edits, which add, remove and move nothing.*/- onLayersChanged(changed: string[], sourceChanged: string[]): void;+ onLayersChanged(changed: string[], sourceChanged: string[], restructured: boolean): void;/*** Leaves changed ONLY by an ancestor group's adjustment stack: recomposite* without `onLayersChanged`'s destructive reactions (float and pixel-edit@@ -69,6 +76,15 @@ const rasterSourceRef = (layer: CanvasLayerContract): unknown =>const effectiveKey = (entry: CanvasNodeEntry): string =>`${entry.ancestorsEnabled ? 1 : 0}${entry.ancestorsLocked ? 1 : 0}${entry.ancestorsHidden ? 1 : 0}`;+const diagnostics = { forestDiffs: 0 };++/** Whole-forest diffs: structural edits and replacements; value edits never cost one. */+export const getForestDiffCount = (): number => diagnostics.forestDiffs;++export const resetForestDiffCount = (): void => {+ diagnostics.forestDiffs = 0;+};+interface ForestDiff {changed: string[];sourceChanged: string[];@@ -82,6 +98,7 @@ interface ForestDiff {* by ancestors.*/const diffForests = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex): ForestDiff => {+ diagnostics.forestDiffs += 1;const changed = new Set<string>();const sourceChanged = new Set<string>();const recompositeOnly = new Set<string>();@@ -140,6 +157,64 @@ const diffForests = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex): Fore};};+const groupFlagsChanged = (before: CanvasGroupContract, after: CanvasGroupContract): boolean =>+ before.isEnabled !== after.isEnabled ||+ before.isLocked !== after.isLocked ||+ (before.isHidden === true) !== (after.isHidden === true);++/**+ * Diffs a value edit from its recorded node changes: changed leaves, the subtree leaves whose inherited flags+ * moved, and the subtree leaves of groups whose adjustments, opacity or blend changed. Structure is unchanged.+ */+const diffValueEdit = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex, edit: CanvasValueEdit): ForestDiff => {+ const changed = new Set<string>();+ const sourceChanged = new Set<string>();+ const reflagged: string[] = [];+ const adjusted: string[] = [];+ for (const [id, { after, before }] of edit) {+ if (isGroupNode(after) && isGroupNode(before)) {+ if (groupFlagsChanged(before, after)) {+ reflagged.push(id);+ }+ if (+ before.adjustments !== after.adjustments ||+ before.opacity !== after.opacity ||+ before.blendMode !== after.blendMode+ ) {+ adjusted.push(id);+ }+ } else if (!isGroupNode(after) && !isGroupNode(before)) {+ changed.add(id);+ if (rasterSourceRef(before) !== rasterSourceRef(after)) {+ sourceChanged.add(id);+ }+ }+ }+ for (const groupId of reflagged) {+ for (const leaf of collectSubtreeLeaves(next.byId.get(groupId)!.node)) {+ if (!changed.has(leaf.id) && effectiveKey(prev.byId.get(leaf.id)!) !== effectiveKey(next.byId.get(leaf.id)!)) {+ changed.add(leaf.id);+ }+ }+ }+ const recompositeOnly = new Set<string>();+ for (const groupId of adjusted) {+ for (const leaf of collectSubtreeLeaves(next.byId.get(groupId)!.node)) {+ if (!changed.has(leaf.id)) {+ recompositeOnly.add(leaf.id);+ }+ }+ }+ const inDocumentOrder = (ids: Set<string>): string[] =>+ [...ids].sort((left, right) => next.byId.get(left)!.order - next.byId.get(right)!.order);+ return {+ changed: inDocumentOrder(changed),+ recompositeOnly: inDocumentOrder(recompositeOnly),+ restructured: false,+ sourceChanged: inDocumentOrder(sourceChanged),+ };+};+/*** Creates a document mirror bound to `projectId`. Subscribes immediately and seeds the last-seen* references from the current state, so no spurious callback fires on creation.@@ -188,9 +263,12 @@ export const createDocumentMirror = (callbacks.onDocumentReplaced();} else {if (prevDoc.stacks !== doc.stacks) {- const diff = diffForests(getDocumentIndex(prevDoc), getDocumentIndex(doc));+ const edit = valueEditBetween(prevDoc.stacks, doc.stacks);+ const prevIndex = getDocumentIndex(prevDoc);+ const nextIndex = getDocumentIndex(doc);+ const diff = edit ? diffValueEdit(prevIndex, nextIndex, edit) : diffForests(prevIndex, nextIndex);if (diff.changed.length > 0) {- callbacks.onLayersChanged(diff.changed, diff.sourceChanged);+ callbacks.onLayersChanged(diff.changed, diff.sourceChanged, diff.restructured);} else if (diff.restructured) {callbacks.onLayerOrderChanged();}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.tsindex 976dff7c6f..1d0cedde7c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.test.ts@@ -7,7 +7,15 @@ import {} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';-import { getDocumentIndex, isSelfOrAncestor, outermostNodes } from './documentIndex';+import {+ getDocumentIndex,+ getValueEditVisitCount,+ isSelfOrAncestor,+ outermostNodes,+ resetDocumentIndexBuildCount,+ updateNodeValues,+ valueEditBetween,+} from './documentIndex';import {cloneSubtree,collectSubtree,@@ -15,7 +23,6 @@ import {insertNodes,removeNodes,subtreeDepth,- updateNodes,} from './documentTree';const layer = layerContract;@@ -44,7 +51,11 @@ describe('document tree', () => {it('updates nodes in place while sharing every untouched node, and returns the same forests for a no-op', () => {const before = stacks();- const after = updateNodes(before, new Map([['r3', (node) => ({ ...node, name: 'renamed' })]]));+ getDocumentIndex({ stacks: before });+ resetDocumentIndexBuildCount();+ const after = updateNodeValues(before, new Map([['r3', (node) => ({ ...node, name: 'renamed' })]]));+ // r3 and its two ancestors; r1, r2, r4 and c1 are never visited.+ expect(getValueEditVisitCount()).toBe(3);expect(after).not.toBe(before);expect(after.control).toBe(before.control);@@ -53,8 +64,32 @@ describe('document tree', () => {expect(g1(after)).not.toBe(g1(before));expect(g1(after).children[0]).toBe(g1(before).children[0]);expect(collectSubtreeLeaves(g1(after))[1]?.name).toBe('renamed');- expect(updateNodes(before, new Map([['r3', (node) => node]]))).toBe(before);- expect(updateNodes(before, new Map([['ghost', (node) => ({ ...node, name: 'x' })]]))).toBe(before);+ expect(updateNodeValues(before, new Map([['r3', (node) => node]]))).toBe(before);+ expect(updateNodeValues(before, new Map([['ghost', (node) => ({ ...node, name: 'x' })]]))).toBe(before);+ });++ it('records the replaced nodes of each value edit and folds consecutive edits for a consumer that fell behind', () => {+ const before = stacks();+ const renamed = updateNodeValues(+ before,+ new Map([+ ['g2', (node) => ({ ...node, isEnabled: false })],+ ['r3', (node) => ({ ...node, name: 'renamed' })],+ ])+ );+ const edit = valueEditBetween(before, renamed)!;+ // Only the updated nodes are listed: g1 was rebuilt for a new child array, not edited.+ expect([...edit.keys()]).toEqual(['r3', 'g2']);+ expect(edit.get('r3')!.before).toBe(collectSubtreeLeaves(g1(before))[1]);+ expect((edit.get('g2')!.after as CanvasGroupContract).children[0]).toBe(edit.get('r3')!.after);++ const moved = updateNodeValues(renamed, new Map([['r3', (node) => ({ ...node, opacity: 0.5 })]]));+ const folded = valueEditBetween(before, moved)!;+ expect(folded.get('r3')!.before).toBe(edit.get('r3')!.before);+ expect(folded.get('r3')!.after).toMatchObject({ name: 'renamed', opacity: 0.5 });+ expect(folded.has('g2')).toBe(true);+ // Structural edits are not value edits: nothing connects the forests across a removal.+ expect(valueEditBetween(before, removeNodes(moved, new Set(['r4'])))).toBeNull();});it('removes subtrees and shares the untouched forests', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.tsindex 31163afe36..8f75dce5f9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentTree.ts@@ -115,57 +115,6 @@ export const replaceChildren = (return roots === stacks[stack] ? stacks : { ...stacks, [stack]: [...roots] };};-/**- * Rewrites named nodes with structural sharing along changed paths. Returns the same forests if unchanged;- * `changed` records replaced nodes by id.- */-export const updateNodesTracked = (- stacks: CanvasStackForests,- updates: ReadonlyMap<string, (node: CanvasNodeContract) => CanvasNodeContract>-): { stacks: CanvasStackForests; changed: Map<string, CanvasNodeContract> } => {- const changed = new Map<string, CanvasNodeContract>();- if (updates.size === 0) {- return { changed, stacks };- }- const visit = (nodes: readonly CanvasNodeContract[]): readonly CanvasNodeContract[] => {- let rebuilt = false;- const next = nodes.map((node) => {- let current = node;- if (isGroupNode(current)) {- const children = visit(current.children);- if (children !== current.children) {- current = { ...current, children: [...children] };- }- }- const update = updates.get(current.id);- if (update) {- const updated = update(current);- if (updated !== current) {- changed.set(updated.id, updated);- current = updated;- }- }- rebuilt ||= current !== node;- return current;- });- return rebuilt ? next : nodes;- };- let result = stacks;- for (const stack of Object.keys(stacks) as CanvasLayerStackKind[]) {- const roots = visit(stacks[stack]);- if (roots !== stacks[stack]) {- result = result === stacks ? { ...stacks } : result;- result[stack] = [...roots];- }- }- return { 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/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 3b8640679f..ed06a89cdb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -1447,10 +1447,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreConLayersRecomposite: (ids) => {scheduler.invalidate({ layers: ids });},- onLayersChanged: (ids, sourceChangedIds) => {+ onLayersChanged: (ids, sourceChangedIds, restructured) => {const cleanup = createCleanupAccumulator();- // A group deleted with its leaves reports here, not onLayerOrderChanged.- {+ // A group deleted with its leaves reports here, not onLayerOrderChanged; value edits remove no group.+ if (restructured) {const doc = mirror.getDocument();cleanup.run(() => groupSurfaces.prune(doc ? new Set(getDocumentIndex(doc).byId.keys()) : new Set()));}@@ -1466,9 +1466,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(cancelOpenPixelEdit);}const doc = mirror.getDocument();- for (const id of sourceChangedIds) {- cleanup.run(() => editingController.invalidateLayer(id));- }+ // `sourceChangedIds` is a subset of `ids`, so each changed layer invalidates once.for (const id of ids) {cleanup.run(() => editingController.invalidateLayer(id));}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.tsindex 991e2a794e..25647c8234 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { SamPreviewState } from '@workbench/canvas-engine/controllers/previewStateController';import type { EngineStores } from '@workbench/canvas-engine/engineStores';import type {@@ -10,11 +10,9 @@ import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatimport type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { Mat2d, ToolId, Vec2 } from '@workbench/canvas-engine/types';-import {- compileDocumentLeaves,- lookupDocumentLayer,- lookupDocumentLeaf,-} from '@workbench/canvas-engine/document-model/documentModel';+import { lookupDocumentLayer, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+import { getDocumentIndex, type CanvasNodeEntry } from '@workbench/canvas-engine/document/documentIndex';+import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';import { hittableLayerRect, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';import { transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';@@ -66,6 +64,19 @@ export interface OverlayFrame {export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame => {const { getActiveToolId, selection, stores, transformOverrides } = deps;+ /** The topmost leaf carrying a live override, resolved from the override ids rather than a leaf scan. */+ const firstOverriddenLayer = (doc: CanvasDocumentContractV3): CanvasLayerContract | null => {+ let first: CanvasNodeEntry | null = null;+ const index = getDocumentIndex(doc);+ for (const id of transformOverrides.keys()) {+ const entry = index.byId.get(id);+ if (entry && !isGroupNode(entry.node) && (first === null || entry.order < first.order)) {+ first = entry;+ }+ }+ return first ? (first.node as CanvasLayerContract) : null;+ };+/*** The selected layer's bounds outline for the move tool. A layer mid-drag* (carrying a live override) wins over the committed selection so the marquee@@ -75,8 +86,8 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =if (getActiveToolId() !== 'move') {return null;}- const overridden = compileDocumentLeaves(doc).find((leaf) => transformOverrides.has(leaf.id))?.layer;- const target = overridden ?? (doc.selectedLayerId ? lookupDocumentLayer(doc, doc.selectedLayerId) : null);+ const target =+ firstOverriddenLayer(doc) ?? (doc.selectedLayerId ? lookupDocumentLayer(doc, doc.selectedLayerId) : null);if (!target) {return null;}diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex 2ab6f834e4..73073e345a 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -23,13 +23,13 @@ import {} from '@workbench/canvas-engine/api';import {childrenAt,- deriveIndexForValueEdit,getDocumentIndex,getDocumentLayer,getDocumentNode,hasDocumentNode,indexStacks,outermostNodes,+ updateNodeValues,type CanvasDocumentIndex,type CanvasNodeEntry,} from '@workbench/canvas-engine/document/documentIndex';@@ -38,8 +38,6 @@ import {collectSubtreeLeaves,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';@@ -147,23 +145,11 @@ const withinLimits = (stacks: CanvasStackForests): boolean => {return index.maxDepth <= CANVAS_MAX_NODE_DEPTH && index.byId.size <= 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, updateNodeValues(document.stacks, [[id, update]]));+): CanvasDocumentContractV3 => withStacks(document, updateNodeValues(document.stacks, new Map([[id, update]])));const mapLayer = (document: CanvasDocumentContractV3,@@ -174,7 +160,7 @@ const mapLayer = (const mapNodes = (document: CanvasDocumentContractV3,updates: Iterable<[string, (node: CanvasNodeContract) => CanvasNodeContract]>-): CanvasDocumentContractV3 => withStacks(document, updateNodeValues(document.stacks, updates));+): CanvasDocumentContractV3 => withStacks(document, updateNodeValues(document.stacks, new Map(updates)));const setCanvasLayersEnabled = (document: CanvasDocumentContractV3,@@ -446,15 +432,17 @@ const applyLayerStackMutation = (const lockedById = new Map(mutation.lockedUpdates?.map((update) => [update.id, update.isLocked]) ?? []);stacks = updateNodeValues(stacks,- [...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 };- },- ]+ new Map(+ [...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)) {@@ -638,7 +626,7 @@ const mergeLayersDown = (type: 'raster',};const stacks = removeNodes(- updateNodes(document.stacks, new Map([[below.id, () => merged]])),+ updateNodeValues(document.stacks, new Map([[below.id, () => merged]])),new Set([upper.node.id]));return {@@ -933,21 +921,23 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro? document.stacks: updateNodeValues(document.stacks,- getDocumentIndex(document).leaves.map(- (leaf): [string, (node: CanvasNodeContract) => CanvasNodeContract] => [- leaf.id,- (node) =>- isGroupNode(node)- ? node- : {- ...node,- transform: {- ...node.transform,- x: node.transform.x + offsetX,- y: node.transform.y + offsetY,+ new Map(+ getDocumentIndex(document).leaves.map(+ (leaf): [string, (node: CanvasNodeContract) => CanvasNodeContract] => [+ leaf.id,+ (node) =>+ isGroupNode(node)+ ? node+ : {+ ...node,+ transform: {+ ...node.transform,+ x: node.transform.x + offsetX,+ y: node.transform.y + offsetY,+ },},- },- ]+ ]+ ))),width,