Skip to content

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

docs(canvas): describe index flattening and the layers tree contract

Josh Corbett73cd47bb6aee
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index ff912d7664..bd3259542c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -27,9 +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). 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/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-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.
+`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.
@@ -37,7 +37,7 @@ The document mirror diffs forests by leaf identity and ancestor-effective state:
### Layers panel
-`widgets/layers` consumes the seam and owns nothing about the document. `layerTreeRows.ts` turns `compileDocumentNodes` plus per-project panel state (expansion, a name filter) into `LayerTreeRow`s that keep their identity while their node, place, effective state, sibling position and expansion are unchanged; `layerPanelRows.ts` flattens the four stacks into one list with a header per non-empty stack. `LayersTree.tsx` virtualizes that list (fixed row heights per density, the focused row always mounted), holds the single drag context, the single menu/properties host (`LayerSurfaceHost`, addressed by node id), the roving tab stop and the WAI-ARIA tree keyboard model (arrows, Home/End, Left to the parent, Right into a group, Alt+arrows to reorder and reparent, F2 to rename), and every store subscription and commit; a row receives one view model and one stable command handle. Drop targets are projected in linear time (`layerTreeDrop.ts`) and asked of `model.refusalFor` before the drop, so a locked, cyclic or too-deep landing shows its refusal inline instead of failing after the fact. Above 2,000 nodes the panel degrades explicitly: thumbnails and drag reordering switch off, every command stays. `layersPanel.budget.test.ts` pins the 2,000-node facts (exact row counts, one node visit per build, row identity across selection and a local expand, linear drop projection) and `LayersTree.browser.test.tsx` pins the mounted-row window, the rows a selection commit touches, the tab stop, and the keyboard journeys in Chromium.
+`widgets/layers` consumes the seam and owns nothing about the document. `layerTreeRows.ts` turns `compileDocumentNodes` plus per-project panel state (expansion, a name filter) into `LayerTreeRow`s keyed on the forests, so a selection or bbox change rebuilds no row, and a row keeps its identity while its node, place, effective state, sibling position and expansion are unchanged; `layerPanelRows.ts` flattens the four stacks into one list with a header per non-empty stack. `LayersTree.tsx` virtualizes that list (fixed row heights per density, the focused item always mounted, each slot drawing the row its key names so a list change never relabels a mounted node) and is one WAI-ARIA tree: stack headers are level-one tree items that expand or collapse their stack, rows are tree items beneath them, every control inside an item is pointer-only (`tabIndex={-1}`) and hands focus back to its item when pressed, and the whole tree is a single tab stop with a roving focus that survives the focused item unmounting; the selection toolbar above it is likewise one tab stop with arrow keys between its buttons. Keyboard: arrows, Home/End, Left to the parent or header, Right into a stack or group, Enter/Space to select (with Shift/Ctrl), Alt+arrows to reorder and reparent (carrying the selection when the focused row is part of it, as a drag would), F2 to rename (a rename committed by clicking elsewhere leaves focus where the click put it), Shift+F10 for the row or stack menu, which carries every pointer action including hide-on-canvas. The tree holds the single drag context (pointer-within collision scoped to the stack, deterministic edge auto-scroll, hover-expand, indicator projected in linear time and checked with `model.refusalFor` so a locked, cyclic or too-deep landing shows its refusal inline), the single menu/properties host addressed by node id, and every store subscription and commit; a row receives one view model and one stable command handle, and a primary that changes outside the panel is revealed once: its collapsed stack and groups open and it is scrolled into view, after which the panel's scroll position is its own. Above 2,000 nodes the panel degrades explicitly: thumbnails and drag reordering switch off, every command stays. `layersPanel.budget.test.ts` pins the 2,000-node facts (exact row counts, one node visit per build, row identity across selection and a local expand, linear drop projection) and `LayersTree.browser.test.tsx` pins the mounted-row window, per-row commit counts (`layerPanelDiagnostics`) for selection and scroll, thumbnail requests, drag validation counts, the tab stop, degraded mode on a real 2,001-node document, external reveal, edge auto-scroll, and the keyboard journeys in Chromium; `scripts/run-accessibility-journeys.mjs` runs Axe over the panel on the representative project.
## Package and capability boundaries