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.

125 KB
Raw Blame

Canvas Engine Architecture

Paths are relative to src/workbench/canvas-engine/, except those starting with widgets/ or canvas-operations/ (relative to src/workbench/) and src/, scripts/, or vitest.* files (relative to the webv2 package).

Ownership invariant

Workbench reducer owns serializable canvas contract. Per-project canvas engine owns pixels, decoded images, rendering, interaction, history, transient editing state, caller-owned raster snapshots. Engine-owned objects never enter reducer actions or persisted project state. Brush, eraser, shape and text options belong to the account: canvas-operations/toolMemory.ts seeds a new engine's option stores from the account's preferences (normalized against the engine defaults), takes in what another engine stores later except for its own unsaved changes, and writes only the tools it changed, merged into the stored record, after half a second of quiet and on disposal, never once the account changed; so a warm engine and the one opened meanwhile never overwrite each other with stale options. Brush color stays the project's color pair. The active tool and the quick-switch bookmark belong to the engine lifetime and survive cooldown while the registry retains that engine; disposal hands them, with the number of undo steps it dropped, to the project's next engine in the session (canvas-operations/engineRegistry.ts), whose History pane says those steps were cleared. A project with no carry starts on Brush when its canvas is blank (no layer but empty inpaint masks) and nothing is selected, else on View, so an older project's selected empty mask is never painted by a first stroke. Quick-switch memory updates its return target only on explicit non-null selection changes outside engine edits; deselection, temporary engine selections, and removed targets do not overwrite it. The next explicit switch records the layer actually being left, including an automatic selection after an edit.

Canvas mutations are explicitly project-addressed. CanvasProjectMutation is the complete reducer mutation vocabulary; the only WorkbenchAction carrying one is:

{
  type: 'applyCanvasProjectMutation';
  projectId: string;
  mutation: CanvasProjectMutation;
  origin?: 'user' | 'system';
}

Reducer handles this envelope only through updateProjectById. No canvas action infers its target from active project.

Each engine gets a CanvasProjectMutationPort bound to its immutable projectId. Port exposes getCanvasState(), subscribe(), dispatch(mutation, origin?), commitEdit(intent). It neither exposes global workbench dispatcher nor follows active-project changes. Widgets use useCanvasProjectMutationDispatch, which captures current project ID and emits same envelope. So project switches and colliding layer IDs cannot redirect a delayed engine mutation to another project.

Port dispatch() returns whether named project's canvas identity changed. User-origin mutations may auto-route invocation controller; history replay, synchronization, rollback, bitmap persistence dispatch as system. Prepared transactions dispatch their document mutation as system, verify reducer and mirror postconditions, then call commitEdit() exactly once for a successful user edit. Paint calls commitEdit({ kind: 'paint' }) synchronously at stroke commit, so delayed persistence upload can never steal a later manual route.

Paint persistence clears dirty result only after intended layer accepts bitmap reference. Rejected update keeps dirty pixels for retry; layer or project deletion is terminal and discards obsolete persistence work. Rule applies equally to raster/control paint sources and paint-backed masks.

Vector runtime

vectorRuntime.ts is a static engine dependency. Its editing controller, vector Shape sessions, guide rendering and Trace/Fill geometry are initialized with the engine, so the first vector action is synchronous. canvas-operations/useCanvasEngine.ts exposes one stable engine for its registry lease; selecting Spline or creating a vector layer does not suspend the Canvas or its panels. Vector Properties, path menus and Spline settings are static dependencies of their owning widgets.

Document contract and hierarchy

Triangle and Star creation share their vertex geometry with raster Shapes in math/shapeGeometry.ts. Shape creation overlays share dashed styling and polyline vertex/closure markers through render/rasterizers/shapeRasterizer.ts; completed vector guides remain solid blue.

Shapes on a selected vector layer use tools/vectorShapeTool.ts; other targets keep the raster Shapes behavior. Vector Rect/Oval drags commit closed Bezier paths, Polygon clicks continue until explicit open/closed completion, and Freehand fits an open path with the v6 geometry math. Selected/New target chooses appending a path or creating another vector layer. Previews remain engine-local until completion; a completed edit records one structural history entry through the vector config patch. render/overlayFrame.ts supplies committed, visible vector paths and creation previews to render/vectorGuides.ts, which projects control points into CSS space before drawing constant-width blue guides. Layer changes, document replacement, cancellation and real tool switches drop stale creation sessions. Tool-owned modifier hooks let Space move a box or pan during an unfinished polyline/freehand, and Alt center a box without selecting the color picker.

Vector guide layers use type: 'vector' in the optional document.stacks.vector forest, between control and regional guidance in bottom-first order. Their paths contain named, explicitly open/closed Bezier paths with layer-local anchors and handles. They have no raster source or pixel extent and do not enter generation or raster exports. Creating a vector stack adopts Canvas schema 7; documents that have never used it omit the forest and retain their existing schema. Layer creation, selection, flags, grouping, duplication and removal use the same structural commands and history as other stacks; duplication also rekeys path IDs.

CanvasDocumentContractV3 holds stack forests, document.stacks.{raster, control, vector, regional_guidance, inpaint_mask} (the vector forest is optional). Each forest: top-first tree of leaves (unchanged v2 leaf contracts) and pass-through groups (type: 'group' with id, name, isEnabled, isLocked, optional overlay-only isHidden, children). Node belongs to exactly one stack, ids unique across document, groups nest at most ten levels deep, document holds at most 10,000 nodes. selectedLayerId may name leaf or group; leaf-only tools refuse a group rather than guess a descendant. Groups carry no opacity, blend mode, transform, or raster surface: they only organise leaves and gate their effective state. Loader refuses older document versions; nothing migrates them.

document/documentIndex.ts builds one index per stacks identity (parent, path, sibling index, document order, ancestor-effective enabled/locked/hidden per node). Selection and bbox edits keep stacks and cost no index. Value edit (transform, opacity, blend, name, source, config, or a flag) goes through updateNodeValues, which finds each edited node via index and copies only sibling arrays on its path (cost: sibling counts along edited paths, never the forest), so stacks changes; it then registers a derived index for new forests extending previous one, and records the edit's replaced nodes (before and after; ancestors rebuilt only for a new child array are not listed) against new forests: byId is a layered map reading through to previous index for every untouched id, nodes and leaves materialize only when a consumer reads them (leaves keeps identity when no leaf object changed), and only entries constructed are edited path plus subtree under a group whose flags changed. After eight derivations chain flattens onto its plain root: one override layer holding newest entry of every id chain touched, still pointing consumers at root's cached compile so flattening recompiles only what chain changed; only when overrides cover more than a quarter of root is a plain index rebuilt. So lookups read through at most nine layers; nothing older than root is retained. document-model/documentModel.budget.test.ts pins this at 10,000 nodes: leaf edit revisits and constructs depth + 1 entries, compiles depth + 1 semantic nodes (ancestors keep counts without walking subtrees) and one leaf, answers lookupDocumentLeaf/lookupDocumentNodeState without materializing node list; complete reducer → mirror value edit does same with no forest diff.

document-model/documentModel.ts compiles SemanticLeafs and SemanticNodes from that index: contributionEnabled, effectiveLocked, documentHidden fold in every ancestor; leaf or node keeps identity while its contract object, place, and ancestor-effective state are unchanged. Every consumer deciding visibility, contribution, editability, export, or what a panel row shows reads these (or isLeaf* predicates), not node's own flags; model.refusalFor(command) is the single eligibility authority for enabling a command before it runs; for reparent, group, ungroup, remove, duplicate it runs same validator prepare uses without materializing an edit (editsMaterialized stays zero), so drag hover or 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. Duplicate inserts its copy beside the source, so only a locked ancestor refuses it: a locked node, or a group holding one, copies with its locks. The engine's duplicate commits its own pixel copies rather than the model's prepared edit, and asks the same check of the document it commits, so a group locked while source pixels load still refuses it.

Model prepares structural edits (insert, remove, duplicate, move, reorder, reparent, group, ungroup, patch*, set-*, translate, select); commitPrepared commits them. Restructuring lands as one applyCanvasLayerStackMutation; reducer applies it as add, then move, then removeIds, then flag and selection updates, refusing whole mutation when any step is invalid or result exceeds limits. Insertion anchors are exact: before a surviving sibling under its current parent, after a surviving sibling, top of captured parent, nearest surviving group on captured path, then stack top. Inverses restore removed or moved nodes as maximal sibling runs anchored to their unmoved neighbours, so undo reproduces previous structure exactly.

Document mirror reports in leaf terms, in document order. For value edit it folds recorded edits since its last document (valueEditBetween, at most sixteen; record holds its predecessor weakly so superseded forests are never retained) and touches only those nodes: edited leaf is changed, and source-changed when its raster source or mask bitmap changed; group flag flip reports as changed the descendant leaves whose ancestor-effective state actually moved (never source-changed); group adjustment, opacity or blend edit sends its descendant leaves down non-destructive recomposite channel; group rename reports nothing. Only a structural edit, an unrecorded step or a wholesale replacement diffs 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 forests were restructured, so engine prunes group surfaces only then, and invalidates each changed layer once.

Layers panel

widgets/layers consumes the seam and owns nothing about the document. widgets/layers/layerTreeRows.ts turns compileDocumentNodes plus per-project panel state (expansion, name filter) into LayerTreeRows keyed on forests, so selection or bbox change rebuilds no row, and row keeps identity while its node, place, effective state, sibling position and expansion are unchanged; widgets/layers/layerPanelRows.ts flattens four stacks into one list with a header per non-empty stack. widgets/layers/LayersTree.tsx virtualizes that list (fixed row heights per density, 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 whole tree is a single tab stop with roving focus that survives focused item unmounting; selection toolbar above it is likewise one tab stop with arrow keys between its buttons. Keyboard: arrows, Home/End, Left to 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 focused row is part of it, as a drag would), F2 to rename (rename committed by clicking elsewhere leaves focus where the click put it), Shift+F10 for row or stack menu, which carries every pointer action including hide-on-canvas. 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; 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 scrolls into view, after which panel's scroll position is its own. Above 2,000 nodes panel degrades explicitly: thumbnails and drag reordering switch off, every command stays. widgets/layers/layersPanel.budget.test.ts pins 2,000-node facts (exact row counts, one node visit per build, row identity across selection and a local expand, linear drop projection); widgets/layers/LayersTree.browser.test.tsx pins mounted-row window, per-row commit counts (layerPanelDiagnostics) for selection and scroll, thumbnail requests, drag validation counts, tab stop, degraded mode on a real 2,001-node document, external reveal, edge auto-scroll, keyboard journeys in Chromium; scripts/run-accessibility-journeys.mjs runs Axe over panel on representative project.

Properties and Transform

Tool and operation settings live off the surface, as editor panes of Layers panel (widgets/layers/panes). Properties pane renders running operation first, then active tool, each as ToolPropertyForm / OperationPropertyForm (widgets/canvas/tool-presentation): named, collapsible groups of typed rows (optional preview card on top), each ending with its form's actions row inline in its section — no sticky footer. A running operation's row (OperationActions: Reset, Cancel, the manual run while auto-update is off, Apply with its save-as menu; while auto-update is on, Filter and Select Object also offer it as the retry after a failed run) follows its groups; the transform form's Apply/Cancel close the Tool section. An operation form's useStatus hook feeds its section: the busy phase sits beside the section title in a live region mounted for the operation's lifetime, the error comes last, after the actions, so no control moves, and the source layer is the subtitle's tooltip. Group ids are global so tools sharing a group's component keep its DOM and collapse state across the switch. Transform pane edits selected layer's transform without a tool, with the same rows as the Move and Transform tool forms (widgets/canvas/tool-options/layerTransformFields.tsx) — each field commits one undoable patch, and while Transform tool holds a session same fields drive its preview and Apply / Cancel land or drop it. Forms read engine's option stores and document transactions directly: no state mirror. A running operation locks the tool section, its actions included, in place (inert) and takes focus to its own Cancel, scrolled into view, keeping its own controls live; a generation or staged results lock nothing (see "Editing during generation"). Panes are fixed parts of panel — LayerEditorPanes owns their tabs, preferred height and collapse, persisted through Layers widget's project state — not movable widgets. Same blocks host Color/Swatches workspace (project foreground/background pair), History pane (engine's labeled undo/redo stack via history.getEntries()/stepBy: a Start row stands for the canvas before the oldest kept step and notes evicted steps or the dropped ones a previous engine of the project was disposed with (the registry hands their count, evictions and cooldown trims included, to the next engine's history), both until the history is next cleared; jumps wait while documentEditingLocked; Clear history asks first; below the steps, the project's restore points), and Overview navigator (previews.drawDocumentOverview plus live viewport handle).

The Transform tool's Smoothing, resampling kernel, Contain/Cover/Fill fit choice, aspect link and reference point belong to the engine's transient options. Typed position, size and rotation act on the reference point of the content box the handles frame (hittableLayerRect): X/Y show and place that point (a placed origin stays on whole pixels), the rest hold it fixed, and a layer without a content box falls back to its origin with Size disabled; gestures keep their own pivots. Size is the layer's own box (rect × |scale|), not its rotated bounds. The aspect link governs the numeric size fields (the other axis' magnitude follows by the same factor; they also take N%, *N and /N of the current size) and every scale handle, layer sessions and floats alike; Shift inverts it for one drag. Flip horizontal and vertical mirror the layer in document space about its content-box centre, whatever the reference point. layers.flipLayer(layerId, direction, label) (TransformEditingController.flip) is the one write path the shared rows, the layer menu's Flip submenu and the canvas.flipHorizontal / canvas.flipVertical commands use: inside a transform session on that layer it flips the session preview, and with a floating selection lifted from that layer it flips the float's own layer-local transform about the float's centre (so along the layer's axes), Cancel restoring it (both previewed); otherwise it commits one structural transform step under the caller's label. It refuses a missing layer, a locked one and one without a content box as missing, locked and empty, which every entry point reports with the layer-action copy; locked document editing or a processing session is busy. Its Resampling group appears above Position in the Tool form. Fit to Frame and numeric edits update the tool's existing preview session; they stay disabled while that session is pending or processing. The separate layer Transform pane contains only its ordinary geometry fields and Apply/Cancel. Image and paint sources Apply through a 2x raster and the application's img_resize adapter using Bilinear, Bicubic, Hamming or Lanczos, then publish one paint conversion and undo step. Shape, gradient and text sources retain their editable types and do not expose smoothing; floating selections use their own Apply/Cancel and do not expose these options. The fit action resets rotation and centers the source content (including its local offset) in the generation frame; Cover preserves aspect ratio while extending beyond it, Fill stretches each axis.

A paint bake, with or without smoothing, evaluates the whole adjustment stack in layer-local space before transforming whenever Noise or a spatial adjustment contributes, and removes that baked stack; color-only adjustments stay editable. Undo restores the raw pixels and stack. The transform controller snapshots its source and reserves supersample, decode and undo/output pixel buffers before awaiting the application adapter; no edit transaction spans the network wait. Cancel, disposal, replay and document replacement abort the request; publication additionally requires the same selected layer, editable state, session and cache version. Refused or failed resampling keeps the preview open for retry. The application adapter owns encoding, upload, the utility graph, account/engine lifetime cancellation and decoded-bitmap disposal. The core owns memory admission and atomic history publication. Each initial publication or history replay prepares its cache replacement before changing the contract, so allocation failure keeps the previous layer and pixels intact. The application resize node is intermediate and requests front-of-queue execution. The session keeps its transform preview throughout preparation, queue waiting and resampling. Waiting for processing follows an observed pending item, and Resampling follows observed execution or decoding the returned result; preparation stays neutral while the queue state is unknown. Cancel remains live. A failed apply retains the transform and exposes Retry; a new edit or retry clears the failed marker. Request identity, abort, layer and cache freshness guard every progress callback as well as pixel publication, so an abandoned attempt cannot update its replacement's status.

Package and capability boundaries

canvas-engine/ is rendering and editing core. May import engine-internal modules and shared canvas contracts, mutations, and project mutation port. Must not import React, widgets, application canvas operations, generation graphs, socket infrastructure, or backend networking. canvas-engine-independence rule in src/architecture/dependencyPolicy.ts enforces widget, canvas-operation, and generation boundaries through pnpm architecture:check; review must catch React, socket, and networking imports.

canvas-operations/ owns application workflows such as Filter and Select Object. Coordinators may depend on queues, uploads, model selection, narrow engine capabilities. Their stores are React-free and useSyncExternalStore-compatible; React adapters stay under widgets/.

Non-owning engine lookup lives in canvas-operations/engineRegistry.ts. Gallery actions and invocation preparation query the process-wide default registry without constructing an engine or acquiring a lease. The React engine resource supplies the constructor on acquisition, so lookup callers do not load the engine implementation. The registry owns leases, cooldown, disposal and account cleanup; isolated registries never replace the public lookup. canvas-operations/operationAccess.ts binds application operation capabilities to engines through a weak map.

Public engine handle splits into capability groups such as CanvasDocumentCapability, CanvasExportCapability, CanvasLayerCapability, CanvasLifecycleCapability, and interaction/store capabilities. Production consumers request smallest aggregate they need. canvas-construction-private rule in src/architecture/dependencyPolicy.ts limits full CanvasEngine type to canvas-operations/createCanvasEngine.ts and canvas-operations/engineRegistry.ts; tests may construct full-engine fakes. Unused fflate dependency removed.

CanvasCoreStores holds interaction state only. canvas-operations creates and owns Filter and Select Object snapshots; application-session state cannot leak into core store contract.

Controllers talk through constructor-injected ports or public capabilities. They do not reach into another controller's private maps, and core engine never receives global workbench dispatcher.

Controllers

engine.ts is core composition root and document-event router. New behavior goes in a focused controller with explicit dependencies and idempotent dispose().

Current extracted ownership includes:

  • RasterController: base layer caches, decoded bitmap leases, derived, adjusted and group surfaces, the spatial adjustment worker service, rasterization jobs, invalidation, residency pins, working-set eviction, unified raster-memory controller.
  • RasterMemoryBudgetController: base, derived, group, decoded, detached, reserved and overage byte accounting plus generation-scoped reservations and operation-owned reservations and pins.
  • RenderController: render targets, scheduler construction, previews, render lifecycle.
  • HistoryController: engine-owned history, guarded async replay with failure reporting, inactive byte trimming.
  • PersistenceController: dirty-bitmap flush barriers (whole document, or one layer through applicationHost.flushLayerUploads) and disposal.
  • EditingController: selection state and exclusive edit-lease lifecycle.
  • TransformEditingController (under EditingController): transform sessions, previews, parameter commits and paint bakes (an image, shape, gradient, text, mask or region keeps its transform, so Apply is one transform patch; paint pixels are baked), plus layers.beginTransform and the wait of a session requested before its layer's pixels persist. It alone decides when that wait opens a session or ends; engine.ts routes it document changes, tool switches, Escape, replays, document replacement and final upload failures.
  • ColorSampleController: one-shot color requests and the workbench color router, and which of them receives each pick.
  • PaintLineEndController: where the last brush or eraser stroke ended on each layer, followed through the layer's changes (see "Input ownership and frame scheduling").
  • InteractionController: public tool commands and their disposal boundary.
  • LayerController: guarded layer mutations and thumbnail capability ports.
  • RasterExportController: guarded layer rasterization, transformed copies, encoding, reservations, pin leases. A rasterization that failed because the source cannot be read reports a LayerUnreadable refusal (layerExportGuards.ts) carrying the layer's id and name, never not-ready: waiting cannot fix it, so every consumer (crop, merges, boolean merges, copies, conversion, extraction, duplicate, filter, Select Object, Run Workflow, snapshots for generation and PSD, composite export) refuses with it instead of asking the user to retry, and the message names the layer to disable, delete or replace. An operation reading several layers names the first that failed in its read order; crop all lists each one it skipped. Unreadable means the image resolver threw CanvasImageMissingError (the ImageResolver contract: the image is missing, or not readable by this user; the production resolver maps 403, 404 and 410 to it), the fetched image did not decode, or rendering threw. Any other resolver failure (network, server, an expired session) is wrapped as ImageUnavailableError and is transient: operations and readiness gates report not-ready, and crop all refuses the whole crop as not-ready instead of skipping the layer. The rasterizer remembers either failure per cache entry, keyed by cache version, document generation and source, with its kind, and a retry of the same source that fails again with the same kind raises no second error notice; a change of kind (a fetch outage that turns out to be a deleted image) is reported, with the ImageUnavailableError itself (naming the image, the resolver's error as its cause) for a transient one. Two questions read that record. getFailure (the kind recorded for the layer's current key) drives the readiness gates that never rasterize themselves (Merge Down, boolean merges, extraction): they answer unreadable for as long as an unreadable failure holds, and not-ready for an unavailable one. isBackingOff (either failure's retry backoff, 3 s doubling per repeated failure up to 60 s, is still running) drives the compositor, which skips the layer meanwhile instead of reading its image every frame; the backoff's end invalidates the layer, so a displayed layer retries on its own. A readiness gate asked about a layer also retries it in the background while it answers from the record (a layer off screen or disabled is never redrawn to do so): at once for an unavailable failure, so trying again after an outage ends fetches without waiting out the backoff, and only once the backoff is over for an unreadable one. A running job is joined, never duplicated. Explicit operations (crop, export, merges) always try again. A retry that fails again restarts the backoff without a second notice; a success or any change to the layer clears the failure. Thumbnails show error for both kinds.
  • PsdExportController: immutable PSD planning, snapshot capture, reservation, execution, cancellation.
  • StagedResultController: guarded staged-candidate acceptance and its history entry.
  • PixelEditController, SelectionImageController, LayerMutationController: atomic pixel/document publication at their respective boundaries. Pixel editor materializes control layers and raster-image layers in place before destructive edits (brush, eraser and selection Fill/Erase alike), keeping conversion plus pixels in one undoable transaction.
  • SelectionPixelController: selection Fill and Erase, on the layers the brush and eraser edit in place (paint, raster image, control, inpaint mask, regional guidance), refused as they refuse (editing/controlPixelEdit.ts selectionPixelEditRefusal, which also decides the Selection actions' disabled reasons). A paint layer or mask is edited in its local space, the document-space selection mapped through the inverse layer transform, one image-patch entry per edit; masks take opaque coverage. Control layers and raster images go through the pixel editor.
  • CropLayerController: crops one layer, or every leaf of every stack, to the frame; crop-all is one entry. Both paths share one eligibility rule: a leaf locked by itself or an ancestor, or with a source the export cannot bake, is never cropped. A single crop refuses such a leaf, an unreadable one, and one wholly outside the frame (outside-frame: the explicit crop would empty it). Crop all first crosses the paint-upload barrier (flushPendingPixels, not waiting for held pixels), so an acknowledgement replacing a just-painted leaf cannot land mid-read and refuse it as stale. It skips locked and unreadable leaves when their contract's content reaches past the frame, counting the locked ones (skippedLocked) and listing the unreadable ones in document order (skippedUnreadable), so the result can say what was left alone, by name, even when nothing was cropped, and one leaf that cannot be read never blocks the rest; a leaf already inside the frame, empty or unsupported is left alone; a leaf wholly outside is emptied in place, so ids, order, groups and flags never change. It reads one leaf at a time through a read lease, copies the cropped pixels into a surface under their own raster reservation and releases the lease before the next leaf, so the peak is the cropped set plus one export; it refuses stale when the stacks, frame or any pixel guard moved meanwhile, admits one history entry for every before and after snapshot, and publishes one replaceCanvasLayers (same-id, same-type leaves, refused whole when any entry is invalid). MergeLayerController merges selected leaves into a new one through one pipeline parameterized by eligibility, result stack, result leaf and label: merge-selected flattens a contiguous raster run into a paint layer, merge-masks unions any inpaint masks' coverage (each at full alpha, since a mask's opacity only tints it on screen) into a mask configured like the topmost source.
  • MaskResultController, FilterResultController, GeneratedResultController: guarded application-result adoption through narrow host ports.
  • ControlDerivationController: control-layer intent patches and detected-map commits (see "Control derivation").
  • ControlViewController: the display-only Original / Overlay view of one control layer (see "Control layer view").

Controller-local tests instantiate these boundaries with fakes. Integration tests in engine.test.ts cover composition, document routing, cross-controller invariants.

Immutable document and raster snapshots

CanvasDocumentCapability.captureSnapshot() returns CanvasDocumentSnapshot or null. Snapshot holds structured clone of exact CanvasStateContractV3 and engine's documentGeneration. Engine privately ties it to the reducer canvas identity it was captured from, so caller cannot manufacture a current snapshot by copying fields.

CanvasExportCapability.captureRasterSnapshot(snapshot, layerIds, options) requests exactly the required layer caches, temporarily pins them, reserves detached-surface capacity, copies their pixels into independent surfaces. Returns typed ok, stale, aborted, not-ready, over-budget, or LayerUnreadable (naming the first layer that could not be read) result. Freshness checked before and after every async rasterization boundary and once after all copies are detached.

ok result holds a CanvasRasterSnapshot: cloned canvas contract, its document generation, map of detached layer surfaces, idempotent release(). Snapshot is caller-owned. Its surfaces do not read live caches and stay valid while engine cools down; cooldown releases generation-scoped reservations but does not invalidate detached snapshots. Caller must release snapshot in finally. Engine disposal releases any snapshots still outstanding.

Snapshots create a deliberate transaction boundary:

  1. Before detachment completes, document change makes capture stale; no downstream submission may use a mix of generations.
  2. After successful invocation detachment, ordinary editing may continue. Composite, upload, graph compilation, queue submission read only frozen contract and detached surfaces.
  3. Wholesale canvas replacement stays a separate session, identified by documentRevision; completed results from an older session are dropped.

Canvas invocation first crosses paint-flush barrier, then captures post-flush document, plans every raster/control/regional composite, and detaches exactly the contributing layers. It passes the generation bbox as the capture's optional document-space region. For unrotated layers at native resolution (signed unit scales, including reflections), capture copies only intersecting source pixels plus one pixel of sampling margin, rounded outward on the source's pixel grid. render/rasterComposite.ts owns the capture extent through getRasterSnapshotCaptureRect: the same source-region policy drives actual adjustment drawing and scratch reservations, and the same whole-source requirement drives group frames and capture's indexed ancestor check. Capture owns leases and allocations; it does not reproduce inverse-transform, sampling-margin or spatial-context rules. The renderer first rounds the sampled region in layer-local coordinates, then capture's owner boundary rounds that region outward on the source pixel grid, so fractional paint origins cannot clip adjustment samples. Translation and paint offsets remain layer-local. The snapshot keeps each layer's actual whole-source sourceRect for content bounds and mode detection; its rect places the detached pixels. Disjoint sources keep a transparent one-pixel surface and an empty detached rect. Reservations estimate these bounded copies and top up actual extents before allocation, so a small frame on a resident large map does not require a second map-sized surface.

Rotation or rescaling retains whole-source capture: changing a Canvas2D source's origin can change transformed sampling, so these paths preserve the original source grid exactly. Spatial layer stacks and all members of a spatial raster group also retain whole sources because their adjustments depend on that context. Callers omitting region (including PSD) retain whole-layer capture. This bounds detached generation inputs, not initial source rasterization: an uncached large source, a transformed layer, or spatial adjustment work can still exceed the unchanged 512 MiB budget. Composite dedupe writes stage in transaction-local maps. They publish to persistent per-engine dedupe cache only after all frozen compositing, uploads, compilation, and queue dispatch complete; stale or failed captures leave no persistent dedupe entries.

submitCanvasInvocationSnapshot carries exact cloned canvas state used for compilation. enqueueCompiledSnapshot extracts its bounding box, dimensions, document revision instead of reading live project canvas. Generated candidates are placed from queueItem.snapshot.canvas.document.bbox, so later bbox edits do not move result. Progress frames land at the same rect: a placeholder slot carries the submitted bbox origin and the result's size there (src/workbench/canvasStagingView.ts), and StagedPreviewInput always carries an absolute placement, so neither a candidate nor a progress frame follows the live bbox, and a bbox change repaints only the overlay. documentRevision still keeps results from a replaced canvas session out of current staging.

The canvas paints only the selected slot: a candidate's image, or a placeholder's own latest frame. Staging auto-switch follows the policy Preview follows (getAutoSwitchFollowedLive, selectsLandedResult, pickAutoSwitch in @features/queue/contracts) and moves the real selection, so accept and discard act on what is shown. A landed result takes the selection by selectsLandedResult (latest and progress always, off only while no result is selected). After every reducer action, reconcileCanvasStagingFollow (workbenchState.ts) shows what the policy follows for each project whose staging, queue or follow state changed: under progress, the pinned placeholder while it remains, else the newest placeholder with a frame of its own; otherwise, under progress and latest, never a placeholder with nothing to show while a result is staged (the newest result takes the selection). That covers frames, results landing, a mode chosen from the menu, and a discard, accept or cancel that leaves a placeholder at the selected index. The follow state is the Workbench's transient canvasStagingFollow (placeholders that showed a first frame, from the coordinator's onFirstProgressFrame → noteQueueItemFirstProgressFrame; and the user's pin), never persisted, synced or undone; entries go with their placeholders and with closed projects, so a slot id a retry brings back starts fresh. Between images (model load, text encoding) the previous result stays selected and painted. A user pick (thumbnail click or right-click, an arrow key from the selected thumbnail, the bar's step buttons, the canvas stepping keys; not Tab focus, which the strip's roving tab stop keeps to the selected thumbnail) is pickAutoSwitch (pickStagedSlotAutoSwitch): a candidate turns the mode off; a placeholder turns it progress and pins it; a mode set from the menu releases the pin. The reducer cannot tell a placeholder waiting to start from one running, so every placeholder counts as running and a pin holds until its placeholder is gone. A followed placeholder that ends without a staged image (a single item canceled, or finished with none) hands the selection to the newest candidate rather than to the frameless placeholder that takes its index. The staging bar's Stop generating, first in the bar and apart from the result's actions, stops every run still generating for this canvas (getInFlightCanvasItems, one notice for all) while any placeholder remains, whatever kind of slot is selected.

Editing during generation

Nothing in the document freezes while a generation runs or its results wait for review: tools, Properties, layer menus, canvas keys and history stay live. Only each result's landing rect is fixed: a candidate's placement, or the submitted bbox for a result still generating. Moving or resizing the bbox mid-batch changes the next Invoke only. Painting under a staged area is allowed; the shown preview draws above the raster stack and below the overlay stacks, and the staging bar's eye hides it. Deleting, reordering or adding layers leaves staging alone, and accept inserts a new raster layer at the top of the raster stack at accept time. Undo past the submission is allowed and never re-stages or moves a result. What keeps this safe: documentRevision fences staging (Clear canvas drops the replaced session's results and offers to stop its queued work; restoring a canvas point waits while the session has pending results, see "Restore points"); an offset resizeCanvasDocument is refused while the session has pending results (hasPendingCanvasResults), since it would move every leaf but not the pinned rects; acceptance stays engine-guarded (permit, gesture, a live float or open transform landed first, candidate fingerprint; see "Edit leases and staged-result acceptance"). A new Invoke no longer interrupts Filter or Select Object; their own lease and guards hold. The canvas widget outlines where each pending result lands (previews.setStagedRegions, see "Composition, damage and overlays") and the staging bar announces the pending count in a role="status" pill. From the canvas, Alt+[ and Alt+] step through staged results while more than one slot exists (a placeholder shows its progress frame); with one slot or none there is nothing to step to and they walk the layers. Bare arrows always nudge. With focus in the staging bar, its own key handler owns the arrows and Delete/Backspace and keeps them from the canvas: the thumbnail strip is one Tab stop, on the selected thumbnail, so Tab passes it without picking; Left/Right on a thumbnail pick the neighbour and move focus with the pick, and from the bar's other controls step the selection, Delete or Backspace discards the selected result and leaves focus on the next thumbnail, a step button or the bar, and nothing acts while one of the bar's menus is open.

Frame demand before allocation

Each frame is described once by a CompositePreparation (render/compositor.ts): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). compositeFrame reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides. The overview composites the same extent fit-to-view fits (the frame joined with every enabled renderable layer's bounds), translated so that extent fills its target, and returns that document-space rect so the Overview pane maps its outline and pointer through it. The screen description also carries which overlay stacks it shows: while a staged or progress preview is shown it hides every overlay stack (control layers, inpaint masks, regional guidance) and the regenerate-region tint, so only raster layers draw and the result reads uncovered and untinted, whatever is selected. A selected candidate the staging bar's eye toggled off keeps hiding them (the widget publishes it as hidden: nothing decodes or draws), so comparing the result with the canvas under it shows the same raster-only canvas on both sides; hiding is canvas-wide, as it is under a shown result. Accept, discard and anything else that clears the preview (selecting a placeholder without a progress frame, cooldown, document replacement) show them again. They show again, drawn above the preview, only while an edit of a control layer, mask or region is under way (or of a group in those stacks; isInStagingHiddenStack), so the user never edits blind: a pointer gesture on the selected one, a transform session open on one, or a floating selection lifted from one. The regenerate tint then draws again too, with its raster layer and so under the preview: it shows only outside the result's rect, or everywhere while the eye hides the result. Whether a gesture edits is the active tool's Tool.editsSelectedLayer contract, asked once as the pointer pipeline reports the gesture starting (onGestureChange): a brush or eraser press that paints the selected leaf in place and is not refused up front; a box or freehand shape drag that draws into the selected leaf's pixels, or cuts out of them under the mod key whatever Place on says. A tool that knows only after it was asked calls ToolContext.beginSelectedLayerEdit, which runs the same reveal decision mid-gesture: the shape tool once its press shows the modifiers (the hook is asked before the press reaches the tool), or when the mod key turns a drag into a cutout; a move reveals once its drag crosses the drag threshold as a layer drag, so a click reveals nothing, nor does a drag that a locked or hidden layer refuses; a drag that lifts or moves a float reveals through the float itself. A locked or hidden layer reveals nothing, and a selected group reveals only for a move, since the brush and shapes paint a new layer instead and the eraser refuses it. Navigation, sampling, bbox, selection, gradient and Select Object gestures, Space and Alt holds included, never reveal, and a polygon's vertex presses do not either, since they write nothing until it closes. Edits that no revealing gesture or session carries, such as undoing a mask stroke, closing a polygon, an arrow-key nudge, or the selection commands (Fill, Erase, and the Delete and Cut that erase through eraseSelection) on a control layer, mask or region, change nothing visible while the preview hides the stacks: a reveal lasts as long as the gesture or session that carries it, and a one-shot command has none to end it. So that a gesture can edit at once, while its stack is hidden the frame keeps a selected control, mask or region leaf resident when the screen would otherwise draw it and its bounds meet the viewport (the rule drawn leaves follow): it stays demanded (protected from eviction) and rasterizes when stale; a selected group needs nothing up front. Transform sessions open on control layers, masks and regions; floating selections on control layers, never on masks or regions. The reveal follows the transformSession and hasFloatingSelection stores: it starts when a session opens on, or a float is lifted from, a layer in a hidden stack, and ends when the session is applied or cancelled or the float is banked or dropped. The staged preview always lands above the raster stack and below every overlay stack, so a revealed control layer, mask or region draws over it. Isolation targets and every non-screen composite are unaffected. The flag is derived per frame from that per-gesture decision and the session's, and joins the description's reuse key; publishing, hiding or clearing the preview repaints in full, and while a preview is shown or toggled off so do the reveal's start (the press, a move's threshold crossing, a session opening or a float lifting) and its end (release, cancel or reset; the session or float ending); its other pointer moves repaint only their own damage. The engine publishes whether the preview hides the overlay stacks as the stagingHidesOverlays interaction state (a reveal does not change it), so canvas chrome about a hidden layer, such as the control-view switch, can step aside. A progress frame decodes at its own (latent) size and the compositor scales it into its rect, so an upscale's large output rect costs no full-size decode.

calculateActiveFrameLayerIds is the pure pre-allocation pass over that description: intersects each drawable leaf's bounds with document-space viewport. Explicitly isolated operation target is the one exception to normal document visibility: stays demanded and drawable when disabled or display-hidden, because user acts on that named layer directly.

Render path computes this set before ensureLayerCaches. Only demanded layers rasterize for the frame. Offscreen enabled layers are not eagerly allocated; they stay on-demand and LRU-evictable, then rasterize again when panning or a transform reveals them.

Frame's demanded layers form its working set. After drawing, RasterController.enforceBudget reclaims memory in fixed order (bounded or empty repaint reads only part of working set, so its usage window stays open from last full repaint):

  1. derived and group artifacts the frame did not read (obsolete parameter variants, inactive groups);
  2. least-recently-used base caches outside working set and unprotected.

The main viewport fills patterned masks and regenerate regions in CSS space through a transformed alpha stencil. Patterned overlays of each style step their phase by one device pixel in compositing order, so consecutive overlays of the same style have different phases. The phase stays fixed during pan, zoom and partial repaint for the same overlay order. The attached RenderController keeps one scratch surface sized to cover the largest patterned areas it has repainted within the current viewport backing bounds, and accounts it as detached working-set memory. A viewport shrink bounds the retained surface again. Detach, document replacement, cache clear and a full frame with no patterned overlay release it. A bounded frame can miss an overlay that is still visible, so it keeps the scratch. The color picker and its loupe omit inpaint and regional guidance stacks from their shared sample composite so they read the image beneath mask overlays.

Layer is protected while an operation pins it (RasterMemoryBudgetController.pin, held by every read lease, snapshot capture, export and duplicate) or while it is held: its pixels not yet persisted (BitmapStore.hasPendingWork) or an edit session (transform, text, float, pixel edit, operation lock) owns them. Whatever working set and protected layers still need stays resident; bytes above budget are reported as overage and leave no room for background reservations. Export and thumbnail callers request and pin their own caches. Deterministic tests assert allocation counts and bytes for pan/reveal, rotated bounds, unflushed paint bounds, isolation, transient transforms, eviction, re-rasterization.

Raster resource ownership and memory policy

RasterController owns the raster caches and budget: base layer caches, derived and adjusted surfaces, group composites, decoded bitmaps, detached snapshot accounting, reservations and pins. RenderController owns the viewport's hatch scratch and tracks its bytes as detached working-set memory through the same budget. Each store keeps a running byte total, updated at every allocation, resize, transfer and release, and pushes it to RasterMemoryBudgetController; nothing resynchronizes totals by rescanning. Cache surfaces change only through LayerCacheStore (growth, trim, replacement, publishRasterized, captureState/restoreState), so accounting cannot drift from pixels.

Raster soft limit is 512 MiB. Memory snapshot reports:

  • baseBytes: layer cache surfaces;
  • derivedBytes: derived and adjusted display surfaces;
  • groupBytes: group composites;
  • decodedBytes: leased ImageBitmap instances;
  • detachedBytes: caller-owned raster snapshot surfaces, retained operation pixels and the viewport hatch scratch;
  • reservedBytes: capacity promised to background work but not yet represented by another class;
  • overageBytes: amount the protected working set holds above the limit.

Background snapshots, thumbnails, raster exports, transformed/adjusted copies, and PSD exports reserve enough available bytes before allocating and return typed over-budget outcomes when they cannot.

Async raster reads return a RasterReadLease (rasterTransactions.ts): pixels, their layer-local extent, a freshness guard, an idempotent release. Lease pins its source layer from before rasterization until release, so neither eviction nor paint trimming can reshape pixels an operation is still reading (persistence encodes a pinned layer untrimmed instead of waiting); guard still rejects pixels a later edit replaced. Leases on detached copies (adjusted or baked pixels) release source pin as soon as copy exists. Extraction, merges, crops, copies, filters, snapshots and composite exports all read through leases and release them in finally.

Reservations are idempotent leases. Cancellable preparation work uses lifecycle-generation reservations, which activation, cooldown, and disposal release if normal finally path has not released them. Once an async raster composite is in flight, it uses operation-owned reservations instead: lifecycle changes may make its result stale but cannot erase its accounting while a yielded allocation can still resume. Pins are always operation-owned. Detached snapshot accounting follows the snapshot; only CanvasRasterSnapshot.release() or engine disposal releases it.

Paint persistence protects dirty pixels until their latest generation is acknowledged: across encoding, upload failures, an open retry circuit and later strokes. Dirty paint layer whose cache is missing keeps its pending work and fails flush barrier; store never reports a save that uploaded nothing.

DecodedBitmapPool replaces permanent decoded-image caching. acquire(imageName, decode, signal) refuses an already-aborted request before any work starts, coalesces concurrent decodes for same image, returns a short-lived DecodedBitmapLease. Each rasterizer releases its lease in finally. Bitmap closes after final lease; pending decode aborts when all interested callers cancel and its late bitmap is closed; pool observes its own decode promise so an abandoned decode cannot surface an unhandled rejection; disposal aborts pending work and closes every resolved bitmap. Pool byte changes feed decodedBytes.

Staged results use a separate compressed-Blob cache instead of retaining a decoded surface for every candidate. Once a candidate's thumbnail settles, UI asks engine to prefetch its full-resolution bytes, at most two full-image requests in flight. Selecting a queued candidate promotes it immediately and preempts stale work; completed/in-flight requests and concurrent decodes of same image coalesce. Per-engine cache is LRU-bounded to 24 entries and 64 MiB, retries a failed selected request once as foreground demand, releases outstanding work on engine cooldown or disposal.

Composition, damage and overlays

Shape rasterization and direct Shape-tool pixel edits share render/rasterizers/shapeRasterizer.ts. Fill uses the original silhouette; an outline is a centered stroke at twice its configured width, masked to that silhouette so the visible stroke lies inside the shape without changing fill coverage or the source extent. Both callers provide isolated transparent targets: the parametric rasterizer clears its target, and the Shape tool allocates scratch pixels before selection or mask compositing. With an outline, fill color covers that target first, then stroke color composites over it, and one opaque destination-in fill applies silhouette coverage. Applying coverage once prevents antialiased exterior pixels from exposing the fill color. The drawing helper restores caller transform, alpha and composite state; its final mask must never act on existing layer pixels. The tool preview traces the same silhouette.

Damage is explicit: FrameDamage is full repaint, no visible repaint, or layer-local regions. Scheduler widens to full on any invalidation without a region, a viewport change or a forced repaint. Compositor resolves regions through frame's matrices into one padded screen rect: regions entirely off target draw nothing; bounded repaint clips to the rect and culls every leaf, group scope and staged preview whose screen bounds miss it. Unknown layers or non-finite geometry repaint everything.

Compositing always renders through canonical RasterBackend; no approximate backend-free path. Filter previews and floating selection of a grouped member compose inside group's isolated surface, under group's opacity, blend and adjustments, exactly as member's committed pixels would. Committed content composes with same semantics for display, sampling and export; previews and floats are display-only. Layer's own adjustments apply to its layer-local pixels before resampling: export draws display's memoized adjusted copy of a leased live cache when one is current and exact, never building one (a layer-sized copy would exceed the export's reservation), and otherwise adjusts only the layer region the output samples (plus one pixel of resampling margin). When a downscaled layer samples more pixels than output holds and its stack is position independent (color only), a detached copy of it is adjusted after resampling instead, keeping export work bounded by output size; composite reservations count each such scratch buffer at output size. A position-dependent stack (noise) never takes that shortcut: resampling must average its grain exactly as on screen, so its layer-local sampled region is adjusted and reserved even when larger than the output. Composite reservations plan that region from estimated content bounds; when a layer's rasterized pixels (measured text) sample more, rendering reserves the excess before allocating it and refuses as over-budget when it does not fit. World-space bakes (merges, boolean merges, crops, copies) and PSD always adjust the layer's own stack on a layer-local copy, or draw the display's exact adjusted copy, and then resample it. Merge Down bakes both layers' own stacks the same way before the upper layer resamples into the lower layer's space, so the merged layer carries no stack; its undo snapshots stay raw and undo restores both layers with their stacks. Control layers carry no stack, so a raster layer whose stack changes pixels reaches the control stack only baked: copy to control (CopyLayerController) and convert to control (LayerMutationController.convertToControl) draw the layer's exact baked export at an identity transform, conversion in place as one step whose undo restores the raster contract, its stack and its original cache; a layer whose stack changes nothing, or an empty layer with no pixels to bake, takes the plain contract clone of source and transform. Mask conversions read alpha alone, which no adjustment writes. Rasterize bakes a position-dependent or spatial stack (all of it) into the layer-local source render before the transform and drops it from the paint contract, since kept it would grain, or measure detail on, the baked pixel grid; a color-only stack stays on the contract. Thumbnails downscale the display's current adjusted copy when one exists.

Per-pixel adjustments (every type except the spatial ones below) are position dependent but region independent. applyAdjustments takes the pixel of its ImageData's top-left in the stack's reference space; adjusting any sub-rectangle at its own origin yields exactly the pixels a whole-surface pass gives there, which damage refreshes, sampled regions and group-region repaints rely on. Color entries ignore position. Noise adds a field that is a pure function of seed, integer pixel coordinate and channel (a stable integer hash into an equiprobable quantile table, no sequential state), scaled per pixel by a function of that pixel alone: 1 for flat response, 4·Y′·(1 − Y′) of the incoming Rec. 709 luma for midtones. Size 1 adds the white samples directly. Larger sizes blur them with a separable Gaussian of σ √(size² − 1)/2 truncated at 3σ (R taps each side), renormalized so squared taps sum to one (σ unchanged); a kernel whose outer taps all stay under 10⁻³ (sizes under about 1.14) runs as size 1. Samples beyond the ImageData come from the hash, never from pixels, and each output sums the same float64 values in the same order wherever the region starts, so region independence stays exact. The blur streams rows through a ring of 2R + 1 horizontally filtered rows: transient JS heap of O(R × width) per channel, not counted in the raster budget. Cost is O(pixels × R × channels) on the main thread, paid once per changed preview frame while a slider scrubs. Monochrome shares one field across R, G, B; color draws three; chroma draws two, added to OKLab a and b with lightness kept, then converts back to sRGB clamped in linear light. A layer's own stack works in layer-local pixels (cache surface (0,0) is entry.rect's origin, possibly negative) and is always applied before resampling when it contains noise, so display, generation, exports, bakes and PSD agree in grain pattern and strength, and the grain moves with the layer under transforms. A group stack works in document pixels: group surfaces, composite group buffers and PSD's baked group stacks all sit on the document grid at scale 1. The one exception is a floating selection: its display copy is baked at its lift origin and moves with the drag; committing recomputes the layer's grain at the new position. Thumbnails without a current display copy adjust their own downscaled pixels, shrinking grain to size × scale (at least 1) and scaling σ by min(1, scale × grain span) to approximate the averaging a downscale applies; span is (Σ taps)², 1 at size 1.

Spatial adjustments

Clarity, texture and dehaze are spatial: an output pixel depends on OKLab lightness across a neighborhood of the owner's source, so they are neither per-pixel, region independent, nor resample-commuting. Their domain is the source's alpha bounds, computed inside the kernel (render/spatial/evaluateSpatialSteps.ts): hidden pixels borrow the nearest visible pixel's lightness, and nothing outside the bounds, no hidden pixel and no alpha is written, so any buffer holding all the content gives identical pixels. They therefore evaluate only on the owner's full source in owner pixel space (a layer's cache surface before its transform, a group's document-resolution composite), never on a sampled, cropped or downscaled region. applyAdjustments skips them; toSpatialPlan splits a stack into ordered runs, per-pixel runs applied on the main thread at the owner's origin and each run of consecutive spatial entries sent as one job to SpatialAdjustmentService, a module worker evaluating one job at a time.

Display is asynchronous, run by one state machine per owner (render/spatialDisplay.ts) that layers (render/adjustedSurfaceCache.ts) and spatial group scopes (below) share. While a layer's job is pending its adjusted surface shows an interim: a parameter change keeps the shown pixels; a content edit with known damage re-patches that rect with the per-pixel part only; unknown damage, a new source or size, or a rebuild after eviction shows a whole per-pixel-only interim. A layer has at most one job in flight and a later target waits for it, so scrubbing reads the source once per landed result. A content change starts the next job after 120 ms of quiet, anything else as soon as the running job ends; a placeholder cache with no published pixels starts none. A result installs only onto the same source surface, from a version at or before the shown one whose later damage is known (re-patched per-pixel after the install), and only when newer than the result shown, so an older parameter's result can land as an interim while scrubbing. The copy is exact only when the installed result's version and key both match the current ones. peek returns exact copies only (export reuse, merges, control-pixel materialization, which refuses not-ready meanwhile); peekDisplayed returns whatever is shown (thumbnails). Installing calls the engine's settle handler, which recomposites the layer, steps its thumbnail display token and the pixel epoch (overview) and marks ancestor group surfaces for a full redraw, since no cache version changed; it never drops the surface that landed. A status leaving computing without a landing (failure, eviction) also redraws ancestor groups, which may be waiting on it. After too-large, over-budget or error the owner shows the target's per-pixel part only (repainted when that part differs from what is shown, then settled like a landing) and retries only after the target changes: too-large depends on the content's alpha bounds alone, so only new content retries it, never a parameter scrub; the others also retry on a parameter change. The keyed adjustmentStatus store (interaction.getLayerAdjustmentStatus) reports those and computing; absence means exact. Control-pixel materialization refuses not-ready while the owner computes and an AdjustmentRefusal naming it once it cannot run. A floating selection previews the per-pixel part only and committing re-evaluates the layer. Layer deletion, base-cache eviction and disposal abandon spatial work; the engine also drops the spatial state of layers and groups that no longer draw a spatial stack, drawn or not (retainSpatial, visiting only owners that hold such state), so no status outlives its stack. Cooldown abandons only the display's running and scheduled jobs, dropping their interims; exact copies and failures keep their state, and pixel-writing operations' jobs stay governed by their own signal, since their detached snapshots outlive cooldown.

Each job reserves its 4 B/px pixel buffer as an operation-owned spatial-adjustment reservation until the buffer returns from the worker; over-budget refuses the job. Worker scratch (up to SPATIAL_SCRATCH_BYTES_PER_PIXEL per alpha-bounds pixel, at most MAX_SPATIAL_PIXELS, about 400 MB at the cap) stays outside the raster budget: the budget accounts surfaces resident in the page's heap, while scratch lives in the worker's, one job at a time per engine (each engine owns its service and worker), freed when the job ends or the idle worker terminates after 30 s. Counting it would evict display caches for memory the page never holds.

Pixel-writing consumers evaluate spatial stacks exactly or refuse; none leaves a spatial entry out. render/exactAdjustments.ts applies a stack's per-pixel runs on the calling thread and sends its spatial runs to the shared service at now priority, one slot per job so consumers never supersede each other. too-large, over-budget or error becomes an AdjustmentRefusal naming the owner and cause, returned through each operation's result: generation (its notice), exports, layer bakes and everything built on them (filter and Select Object sources, crop, copy, boolean merges, Run Workflow, clipboard and board saves), Merge Down, Visible and Selected, Rasterize, conversion to a control layer, PSD and extraction. A consumer reuses a layer's display copy only when exact; groups have no exact peek, so a spatial group scope always runs its own job.

The raster composite (generation, export, extraction) evaluates a spatial leaf on all its leased pixels in layer-local space, then resamples it, never through the sampled-region or post-resample paths. A spatial group scope leases its members first, composites them over the union of their actual bounds (the display's group surface domain), unclipped by the bbox, evaluates its stack there in document pixels and lands at its offset; nested scopes draw into that frame. Pixels inside a bbox therefore do not depend on the bbox. Composite reservations count a spatial leaf's whole planned content and a spatial scope's planned member extent, each with its ImageData; the job's buffer is the service's reservation, and larger actual extents (measured text) reserve the excess while rendering. Extraction composites its leased contributors through this path instead of the display's providers, so it never reads an interim or takes a group slot.

Layer bakes (RasterExportController) adjust the whole layer-local copy and then recheck the lease guard, since a job yields. Merge Down and Rasterize are asynchronous: the transaction stays open across the job and lands only if the edit revision, the caches and their versions, and any display copy drawn are unchanged, otherwise not-ready. Merge Visible evaluates a spatial group stack on its merged-rect buffer, which holds every member, and lands only while every contributor's guard holds. Colour sampling, the overview and thumbnails mirror the display and may show an interim.

Group surface is keyed by everything except its members' pixels and float's placement (scope shape, member appearance and matrices, in-scope previews, float's surface). While that key and bounds hold, cache refreshes in place: it unions damage each member's cache recorded since the version it last drew, padded by one source pixel before member's matrix maps it (bilinear reach at any scale), plus old and new landing of a moved float, clears that region with one pixel of antialiasing margin and redraws every contributor there, then applies group's adjustments to the region alone, at the region's document origin. Unknown member damage, a member's landed spatial result (invalidate), changed member set or new bounds redraw whole surface, reallocating only when its size changed; new key reuses least-recently-used of a group's two slots once both are taken.

A scope whose own stack is spatial keeps its slot surface raw (its own stack key stays out of its shape key, so a parameter edit repaints nothing; a parent still keys it as a child). Each raw repaint bumps the slot's raw version and records its surface-local damage: unknown for a whole rebuild, and only member content damage for an invalidate redraw, so the adjusted copy keeps its pixels until the group's own result lands. It tracks each member's and nested group's look (stack, opacity, blend, matrix) apart from its shape: a look change repaints that look's old and new bounds in a same-shaped slot with the same bounds. A spatial stack edited into another spatial stack is redrawn only in the raw composite, not patched in the adjusted copy, since its shown pixels stay until it lands. A move that changes the group's bounds repaints the whole slot. A same-size adjusted surface, counted in group bytes and evicted with its slot, follows the layer rules on that raw composite: the domain is the document-resolution union of member bounds, whose transparent margin the kernel's alpha-bounds domain ignores, and per-pixel runs work at the slot's document origin. Each slot runs its own jobs; the group reports, under its id in adjustmentStatus, the status of the slot the canvas frame read last (else of its most recently read slot), so reads by the overview or picking under other keys never flip its row or redraw its ancestors. While a filter preview, float or transform session gives the frame and the overview different keys, each runs its own job on its own inputs: a known cost, not a correctness issue. A raw repaint trail longer than 16 entries folds its oldest entries together, so damage since an older version stays known, only coarser. A job waits (reporting computing) while any member's or nested group's displayed pixels are still pending; a member that cannot finish does not block it. Every read returns state, exact, pending or inexact, combining the group's own state with its inputs'. The group's settle handler steps the pixel epoch and redraws ancestor groups and the frame, never the landed group. The engine drops the spatial slots of groups that no longer draw a spatial stack (retainSpatial), clearing their status.

Overlay renders in CSS pixels. Receives document→CSS view, CSS viewport size and device-pixel ratio, clears backing store in device pixels, then draws every handle, nub, dash and cursor under a DPR base transform (nested image and path transforms compose with it), so chrome keeps its CSS size at any ratio and matches CSS-pixel hit tests. Viewport owns the ratio (capped at MAX_DPR, sub-one ratios kept); backing-store size and composite view matrix both derive from it. The generation frame and its handles draw in device space as filled axis-aligned rects on whole device pixels. Each dash is three bands one hairline wide (a whole number of device pixels, about one CSS pixel): navy outside, the accent core centred on the device pixels nearest the frame's edge, white inside. White contrasts with content up to about 0.30 relative luminance and navy with content from about 0.16, so some band of every dash keeps at least about 3.8:1 contrast (WCAG) with any solid content, both casings over the accent itself. Each edge fits a whole odd number of dashes and gaps (about 4 CSS px, varying by at most a device pixel) between its corners, so every corner is a whole L and every edge and dash end is crisp at any ratio; dashes beyond the backing store are not traced. Handles wrap the same bands around a white face. Snapping moves the frame by under one device pixel and never changes the rect it marks or hit testing.

Pending results are outlined by the overlay, not the compositor (which draws staged pixels without an outline). The canvas widget feeds previews.setStagedRegions from its staging slots (widgets/canvas/CanvasStagedRegionsFeed.tsx): each candidate's placement and each placeholder's submitted rect, the selected slot flagged. PreviewStateController keeps each distinct rect once, selected when any result there is, with the selected one last; the overlay draws them as dashed amber outlines over a dark halo, under the bbox frame, the selected one wider and opaque. An equal list invalidates nothing, a changed one only the overlay. The regions are project data, so the feed never clears them on unmount; another canvas on the engine may still show them. The staged preview itself is published by the canvas widget, which clears it when it unmounts; cooldown and document replacement clear it too, but detaching a surface does not, so a remounted surface (a layout change) shows it again without a republish.

Color picker shows a loupe of pixels under the pointer. Anchors to pipeline's last pointer position in screen space, so pans and zooms keep it under pointer, and shows as soon as picker activates over a still pointer. Each overlay frame composites the square around that point through same sampler, providers and coverage rules as a pick, so magnified center pixel and its RGB readout are exactly what a click picks; square holds fewer, larger pixels once canvas zoom passes loupe's own magnification. Hover chrome (loupe and brush ring) leaves canvas with pointer unless a gesture still owns it; input handlers are stable so detach removes every listener attach added.

Derived surfaces and invalidation

Cached display-only pixel effects use DerivedSurfaceCache. The viewport hatch instead uses the RenderController scratch because the pattern is composited in screen space on each repaint. Each cache slot is identified by layer ID and effect kind, guarded by source surface identity, monotonic source version, and a deterministic parameter key. Reuse safe only when every guard matches. So source replacement cannot publish or reuse a surface produced for an older preview. A spatial stack's adjusted surface also records whether its pixels are exact or an interim (see Spatial adjustments).

Invalidate only affected effect when parameters change. Delete every derived slot when a layer is removed, replaced, or its base cache evicted. Frame-demand culling happens before derived lookup or construction.

Edits, history and replay

Every recorded document and pixel edit goes through one protocol, CanvasMutationContext.begin, and is admitted before it mutates anything. Admission reserves undo entry's bytes in History without clearing redo or evicting older steps, so an edit whose entry could never be kept is refused as over-budget with document, pixels and history untouched. Two kinds of edit are admitted before they change anything but publish afterwards: live strokes paint as they are admitted (see below), and floating selection holds its admission from lift to landing. Selection-mask changes (selection/selectionHistory.ts) admit their step right after applying, because new mask's size is only known then, and roll back to exact prior selection when it cannot be kept. Resulting EditTransaction also reserves raster memory for its preparation (reserveRaster), holds leases and pins until end(), publishes once: publish(label, step, entry) applies an EditStep — optional document mutation with its postcondition and rollback, prepared pixels to install, ancillary notifications — verifies reducer and mirror, records the entry, then routes a user edit and notifies. Step that is rejected or fails its postconditions records nothing; failed postcondition dispatches step's rollback and reports when reducer or mirror could not return. Transactions refuse while permit is stale, a gesture runs (unless edit belongs to that gesture), a replay runs, or engine is disposed. Coalescing (nudges) names the entry it replaces by its HistoryEntryToken and is refused once anything else became newest step.

Layer controllers build their steps from controllers/editSteps.ts: byte accounting, replay reservations (replay whose preparation memory does not fit throws REPLAY_RASTER_REFUSAL and stays in place), steps that add, replace (one layer, or several as one replaceCanvasLayers, sharing the identity postcondition, rollback and pre-install hook) and remove layers with their prepared pixels, and new paint layers. It also names how a publication that did not land is reported: ordinary layer operations (merge, crop, copy, rasterize, insert) report reducer refusal or failed postcondition as failed (layerOperationStatus), while guarded result operations (generated, filter, mask and staged results, mask edits, duplicate) report it as stale (guardedResultRefusal), because their target moved on after the guard was taken.

Floating selection (FloatingSelectionController) computes its commit footprint from geometry before it copies or cuts anything: before and after pixels over union of hole and landing, selection alpha before and after, entry overhead. Admitted for that footprint as part of the drag that lifts it; keeps the transaction until it lands or is dropped. Every move, scale or rotation grows admission to the footprint at the new transform, from geometry alone; transform that does not fit keeps last accepted one and reports over-budget once per float, so an accepted transform always fits its undo entry while permit stays current; admission never shrinks, so a live float holds its largest accepted footprint until it lands or is dropped. Refused lift is reported and moves nothing (lift returns refused), including content whose cache is not rebuilt yet; only a lift with nothing to take (unavailable) lets Move tool fall back to moving the layer. Cut layer's persistence is suspended while float lives. Commit lands pixels and moved selection as one entry under retained admission, renewed once when its permit went stale (an operation locked and released the document meanwhile); commit that cannot be admitted or published puts pre-lift pixels and selection back. Cancellation refills hole before persistence resumes; hole that cannot be refilled keeps layer suspended rather than uploading it. Every terminal path ends the transaction: commit, cancel, Escape, undo/redo, layer's deletion or replacement, document replacement, cooldown (which banks the float before the flush), disposal, exceptions while cutting or landing.

Live pixel edits (brush, eraser, shapes on paint layers or as opaque mask coverage, pixel transactions on control and image layers) are admitted before their first pixel changes and grow their admission before the stroke's before/after footprint does; refused growth restores layer's pixels and extent and engine reports the refusal through tools.onEditRefused, which canvas widget turns into a notice. Tools and selection Fill/Erase report an edit the selected layer cannot take there too, as a CanvasLayerEditRefusal naming the layer: hidden (disabled, itself or through a group), hidden on the canvas only (layer-display-hidden: leafPaintRefusal refuses it to every edit that writes pixels, so nothing lands out of sight; moves and transforms still take it), locked, transparency-locked under the eraser, a shape cutout or Erase, its durable pixels not in the cache yet (the edit requests them and the next one can act; nothing is drawn over missing pixels), a control layer whose empty shape has no pixels (layer-unpaintable), a layer the eraser cannot erase in place (erase-unsupported: a group, text, shape or gradient) or one removing the selection's pixels cannot (selection-erase-unsupported, for Erase, Delete and Cut), a mask or region the Gradient tool never adds a raster layer for (gradient-unsupported), or an open transform session that selection Fill/Erase waits for (transform-session, naming the transformed layer). One predicate (editing/controlPixelEdit.ts editsPixelsInPlace) says which layers the brush, eraser and selection Fill/Erase edit in place. With no layer to act on, an eraser stroke, removing the selection's pixels and a shape cutout (the platform's mod key: ⌘ on macOS, where Ctrl-click opens the context menu, Ctrl elsewhere) each report a CanvasNoTargetRefusal (erase-no-target, selection-erase-no-target, cutout-no-target) and never add a layer. The Shape and Gradient tools report at the press when the press already decides the target, and Shape again at commit if the target changed meanwhile. The Brush never creates a layer above a locked or hidden image on its own; its refusal offers one, worded for its cause. Brush, eraser, shape, gradient and move cursors read not-allowed over a selection the press would refuse, the eraser's included when it has nothing to erase; the engine refreshes the cursor on every document change. Cut asks selection.admitSelectionErase before it writes the clipboard, so a refused Cut copies nothing. Widget previews of structural edits run in one owned StructuralPreviewSession (useStructuralPreview), which coalesces live dispatches to one per frame, captures the values its first preview of each field replaces (session's baseline) and records the gesture as a single step from it; refused commit or cancel restores that baseline, even while edits are locked. A commit from elsewhere, a history replay, a newer session or disposal ends an open session first, dropping pending previews and restoring baseline, so previewed values never land over a replayed document or inside another step: every engine edit starts from CanvasMutationContext.getDocument(), which ends it first (structural controller's commits and nudges, pixel and layer operations such as merge down and duplicate, result commits); widget-prepared edits (commitPreparedEdit, layers tree's child-row commands) end it before reading the model; HistoryController ends it (with any live float) before a replay that has a step to land, and a replay with nothing to land disturbs nothing; document replacement drops it without restoring, since the document it previewed on is gone. Widget's next preview starts a new session from changed document, and a commit after engine ended its session records from live values; its refusal as missing stays silent, since the document change that ended the gesture also unmounted the editor.

Undo and redo are async and failure-atomic: entry moves to the other stack only after its replay completes, replay that throws leaves it in place and is reported, and edits and new gestures are refused while one runs. Replays apply steps through same verified path (applyStep). Pixel replays land only on trustworthy pixels: evicted or stale cache is rasterized first under a read lease, and a layer that no longer exists moves the step as a no-op.

Edit leases and staged-result acceptance

Application operations acquire one exclusive lease from CanvasEditGate. Lease carries an AbortSignal, has explicit isCurrent() freshness check, is idempotently released. Release, document/project invalidation, cooldown, or disposal aborts and stales the lease. Expected cancellation and stale results use status unions; exceptions represent unexpected failures. Operation sessions publish typed error codes, not copy (FilterSessionError, SamSessionError): view translates the code when it renders, so a visible error follows a language change, and an unexpected failure shows a translated summary with its original message as technical detail.

Staged-result acceptance is engine-owned. UI enables Accept unless an operation holds the document, but StagedResultController stays authoritative. It captures a document-edit permit and rejects an active gesture first, so a held document refuses before anything lands; then it lands a live floating selection and applies an open transform session, each as its own step (Move selection, Transform layer), since the accept's selection change would otherwise drop them, and returns busy when either is refused; it verifies selected candidate's stable key immediately before dispatch. Edits since submission change nothing about where the result goes: its pinned placement, on top of the raster stack as it stands at accept time.

Initial commitStagedImage mutation atomically inserts new raster layer at top of raster stack, clears staging, records project event. It keeps a selected overlay leaf (inpaint or regional mask, control layer) as editing target while next stroke could edit it (leaf and every ancestor enabled and unlocked, as painting requires) and otherwise selects new layer: nothing, a group or a refusing leaf was selected, or raster work the result now covers; selectionAfterAcceptedResult (document/selectionRepair.ts) decides this once for controller's postcondition and history steps, the reducer, and its rollback. Controller verifies both reducer postcondition and document mirror before pushing exactly one engine-history entry. Returns busy, stale, or missing without changing staging or history when any guard fails.

Canvas widget stops candidate's originating batch only after an accept has committed (widgets/canvas/stagedAcceptance.ts), and only while that batch still has queued or running work the queue can cancel; action keeps its ordinary "Accept to layer" label. Request is Workbench reducer action cancelQueueItem (exposed as queue.cancel) with an accept-specific notice in place of the generic cancellation one, or none (notice: null) when the accept set other candidates aside: its own notice then says the batch stopped beside an Undo that re-stages those candidates (restoreStagedImages, fenced by documentRevision; widgets/canvas/useCanvasRecovery.ts). Discard, Discard all and Delete in the staging bar report the same way; Discard all also stops this canvas session's queued or running generations and keeps a restore point of the results. It marks batch cancelled at once, so it shows as cancelled in queue and siblings that finish before backend stops are dropped instead of re-staged; queue runtime then cancels by batch id, retries a failed request, reports the failure once per batch. Other batches untouched, continue-staging save never stops generation, undoing accepted layer re-enqueues nothing.

Continue-staging variant uses same guarded transaction but inserts candidate as a disabled raster layer, preserves exact staging-area state and current layer selection, keeps staged preview active. Lets users bank candidates without visually doubling preview or ending comparison. Undo and redo affect only the banked layer after initial transaction.

Undo removes accepted layer and restores prior selection. Redo restores identical layer and selection without recreating event or staging candidate. History entry replays failure-atomically; successful commit publishes through an admitted transaction, which clears any previous redo stack. Undo intentionally does not return accepted candidate to staging: staging is reducer data a later result may have changed, so an engine step never rewrites it; the accept's notice says so.

Restore points

canvas.snapshots are restore points, at most MAX_CANVAS_SNAPSHOTS (five) per kind and project, newest kept, so Discard all points never push a clear-canvas point out. Every document swap they drive (widgets/canvas/canvasRestorePoints.ts) crosses the paint barrier first and changes nothing when the flush fails: Clear canvas keeps a clear-canvas point of the document and its staged candidates (none for a blank canvas: no layer but empty masks, no candidates), then replaces the document and withdraws the point when replaceDocument refuses. Restoring a canvas point, from the History pane or a toast's Undo, waits while documentEditingLocked holds the document or the session has pending results (hasPendingCanvasResults: a staged candidate, or a generation queued or running for this revision; a swap would drop them) and says so. document.restoreSnapshot is the one restore path, a document swap like replaceDocument: restoreCanvasSnapshot bumps documentRevision, clears staging (restoring the point's candidates when it kept any) and so drops in-flight results of the replaced session, and engine history clears with the swap. keepCurrentAs saves the replaced canvas as a point in the restored one's place, so a restore is undoable without pushing an older point out; a blank replaced canvas is not kept and the restored point is deleted instead. The Undo of a Clear canvas or a restore runs only while the canvas is as that swap left it (isCanvasEditedSince: same documentRevision, size, background and layer stacks; selection and bbox do not count): it may run minutes later from the Notifications list. It looks before and again after the paint barrier, whose saved strokes land in the document only then, and after a later edit it says the canvas was not restored and leaves the point in History. Discard all keeps a discard-results point of the candidates only, its document an empty one of the canvas's size; restoring it neither waits nor flushes, re-stages the candidates on the current canvas through restoreStagedImages, leaves the document alone and is used up once one of them is back (when all already are, the point stays and nothing changes). A staging Undo re-stages through restoreStagedImages fenced by the discard's documentRevision; after a swap moved it, Discard all's Undo falls back to its point and the others say they could not bring the results back.

Metadata recall

Image and queue recall enter through canvas-operations/importGalleryImages.ts, the same structural ingestion owner as Gallery imports. The image-action parser validates records and resolves assets before commit; the import owner checks the captured project/document, rejects an editing lock and preserves a replaced canvas as a restore point. A partial or appended recall uses a structural history transaction when an engine is live. A canvas with staged or running results merges recalled layers, preserving that session and its pinned placements. A paint-persistence barrier runs before the final identity check. Metadata records and legacy raster conversion are application workflows, outside the engine; their wire format and recovery semantics are documented in src/workbench/projects/README.md.

Control derivation

A typed control layer can keep the pixels it was detected from (original, framed by originalTransform) beside the derived map in source. The invariants are documented on CanvasControlLayerContract; document/controlDerivation.ts owns them as pure rules, and every engine path that changes a control layer's pixels or frame applies one of them so no edit leaves a map paired with an original it no longer derives from:

Operation Rule
Materialize before a pixel edit (buildMaterializedPixelLayer) rebaseControlOriginal with the baked transform; a frame the bake would shear detaches
Transform Apply baking a paint map (TransformEditingController) the same rebase in the bake's own step, so undo restores the whole before-contract
Crop to bbox detach (the cropped pixels become the image)
Generated or Select Object result replacing a control layer detach and drop filter: the result is the image, not a filter's map
Filter result on a control layer refused unsupported: Filter runs on raster layers only; a control map comes from detection
Filter result copied from a raster layer to a new control layer a fresh control layer; controlCopy.controlType types the copy with detection: null
Paint on a map that needs no materialize only source changes; the map stays current

ControlDerivationController, reached through CanvasApplicationHost (captureControlDetectionGuard, commitControlLayerPatch, commitControlMap) like the Filter, Mask and Generated adoptions, is the only writer of derivation fields besides those rules. The application's detection coordinator calls commitControlLayerPatch for an intent (type, detector, settings, image) and commitControlMap for a detection result, guarded by captureControlDetectionGuard: same documentRevision and same controlDetectionInputKey, which ignores weight, name and paint on the map, so those never discard a running detection. Neither commit passes the operation edit owner. A detection runs in the background while the user keeps working, so its commit must yield to whatever holds the document: an operation's lease (Filter, Select Object, Transform), a gesture, a replay or a session holding the layer's pixels all refuse it busy, and the coordinator retries once the lock releases. The guard capture and the map commit's freshness checks (before decoding, after it, and once admitted) read the reducer document, so a background job never ends the user's structural preview; only an admitted commit does, and the map is built from the layer as it stands after that. A map whose input is the layer's own unpersisted paint is also busy until flushLayerUploads lands those strokes in the original it records. The commit promotes the map image through the caller's makeDurable only once its first check passes, just before decoding, and promotes it once across retries: promoted maps are exempt from server-side intermediate cleanup, so a result that is refused, superseded or dropped as stale before then stays collectible. A refusal after promotion (stale after decoding, over-budget, a history refusal, a busy timeout) still leaves that map durable and unreferenced; this is accepted because detector graphs cache their results, so a re-run can return a map the document or history still references and deleting a dropped one could remove a live map. A document change (undo, redo) that leaves a layer needing no detection, or changes its input other than by its own paint landing, cancels that layer's run and its backend queue item, except while that run's own map commit is in flight, whose publish reconciles synchronously.

History pairing keeps one undo per user intent. A patch with a coalesceKey replaces the newest entry while that is the controller's patch of the same layer and key, so a settings scrub is one step. A map replaces the newest entry while that is the controller's entry for the same layer that requested this input key (a patch that changed the detection input, or an earlier map), so one undo reverts "set type" and its map together; otherwise the map records its own "Detect " entry, and a weight or name patch in between is never undone together with a later map. The controller's record of its newest entry, including any unpersisted before-pixels, is dropped when that entry is disposed (evicted, cleared, discarded from redo or replaced), so it never outlives the entry. Patches route as user edits; maps publish as system so a background result never changes the invocation route. Undo restores the exact before-state: a contract whose source is persisted re-rasterizes from it, and unpersisted paint the step replaced is captured and replayed with the entry. A source change discards the outgoing source's pending persistence. Undo and redo never schedule detection; a restored stale map shows as needing detection until the user asks again.

Control layer view

previews.setControlLayerView(layerId, 'original' | 'map' | 'overlay') lets the user compare a control layer's map with the picture it was detected from. ControlViewController owns the one view that can exist. It refuses while an operation holds the document (documentEditingLocked); a generation or staged results do not affect it, though while a staged preview hides the control stack the view draws nothing and the canvas widget hides its switch. Otherwise it reserves raster memory for the original's decoded pixels, rasterizes the original source with the layer rasterizers, and once the surface exists accounts it as detached pixels until the view ends; the reservation ends with the decode. map ends the view and resolves shown.

Outcome Meaning
shown the view (or the map) is displayed
missing no control layer with a kept original that has pixels
locked an operation holds the document
stale a newer request, a reset below or an edit of the layer superseded the decode in flight
over-budget the original's pixels do not fit the raster budget; nothing was decoded
failed the original could not be fetched or decoded

The view records the contract it was built from and publishes { layerId, view } as the controlLayerView interaction state. It returns to the map (null, surface released, layer invalidated), ending any decode in flight, on:

  • any change to the layer's contract (every edit, undo, redo and detection commit) and its removal;
  • another selection;
  • a stroke or other pixel edit admitted on the layer (strokes paint the map live), a direct repaint of it, and its cache invalidation (including clearCaches);
  • the editing lock engaging;
  • document replacement, the project going away, cooldown and disposal.

The compositor draws the original as layer-local pixels, like a floating selection: through the layer matrix and originalTransform, at the layer's opacity and blend, without the control-transparency effect. original draws it in place of the map, even when the layer has no map; overlay draws the map over it at CONTROL_OVERLAY_MAP_ALPHA of the layer's opacity. The original's landing joins the leaf's bounds, so culling and bounded damage cover it. Control layers never sit in a composited group scope (only raster-stack groups composite in isolation), so group surfaces never see a view. Isolation suppresses it, and only screen frames pass it: history, persistence, thumbnails, exports and generation composites read the map.

PSD export

PSD export is a planner/executor transaction over immutable snapshots. PsdExportController captures one CanvasDocumentSnapshot, walks raster tree into planner inputs (groups as pass-through folders, exportable leaves with their captured content rects), then obtains a CanvasRasterSnapshot including disabled layers. planPsdExport reverses every level of top-first tree into ag-psd's bottom-to-top order, writes each node's own visibility flag (disabled group is a hidden folder), flattens merged preview from the leaves that contribute (enabled with every ancestor enabled), which is what Photoshop renders for the same flags. Folders whose subtree exports nothing are dropped. Execution reads only detached surfaces; cannot mix live layer caches from different document generations.

Each leaf bakes its own stack exactly (spatial entries included), layer-local, before the transform. PSD has no group adjustments, so each enclosing group's stack, innermost first and named per group for refusals, is baked into each leaf's world pixels: under member opacity and blending, and for spatial entries, which see that leaf alone instead of the group composite, this approximates the canvas.

Controller keeps the 30,000-pixel side cap and refuses more than 32,767 PSD records (a folder uses two records). Final freshness check and both memory admissions happen before executor allocations; once execution starts it uses only frozen pixels.

export/psdExport.ts owns the private serialization wire contract and creates one lazy export/psdSerialization.worker.ts module worker per execution. The worker imports that contract only as types, so its ag-psd writer stays outside the editor startup graph. After baking and preview composition, the executor resizes every temporary surface to zero and releases the snapshot and preparation reservation. It converts every export-owned readback into a plain { width, height, data } PixelData record before posting it with its buffer transferred: posting ImageData itself can clone its pixels despite transferring the backing buffer. No live cache, snapshot surface or spatial-service resource crosses this boundary. Input arrays detach on the sender and the receiver owns their full buffers; the exact output buffer transfers back. The default ag-psd 31 pixel-backed RLE path needs neither DOM canvas nor an OffscreenCanvas adapter. Thumbnail generation, trimming, masks and ZIP compression are not enabled. Success, writer/transport/startup failure, request or response deserialization failure, and abort settle the operation, remove listeners and terminate the worker. Termination interrupts the synchronous writer; there is no main-thread fallback. Retries use a fresh worker.

Allocation derivation for the installed ag-psd default writer (revisit when upgrading the dependency):

  • The existing 512 MiB raster budget still admits snapshot capture and preparation. getPsdRequiredBytes reserves eight bytes per pixel of transformed leaves and composite/isolation surfaces, plus the largest adjusted layer-local area. Existing decoded images, caches and detached snapshots count separately. Local adjustment surfaces are cleared after baking; all remaining executor surfaces are cleared before serialization and in finally on earlier failure. Spatial jobs keep their separate service-owned pixel-buffer reservations; kernel scratch stays outside raster accounting as described above.
  • Serialization has a separate 1280 MiB allowance per engine/controller, chosen to admit an ordinary single-layer 4096² export with conservative writer accounting. It is not charged against the reusable raster cache ceiling. One operation may run per controller, including capture, worker execution and download cleanup; another start returns busy. This is an operation/engine limit, not a process-wide browser memory limit.
  • Let C = width * height and A be the sum of transformed leaf areas. Each RGBA RLE result is bounded by 4 * height * (width + ceil(width / 128) + 3): full literal packets add one header per 128 samples; a short literal packet interrupted by a run has its header offset by that run's saving (at least three samples encoded in two bytes); a final one/two-sample packet can add one extra header. The remaining two bytes per row are the length table. Let L and M be those bounds for leaves and composite. Metadata allowance is 4096 bytes plus 1024 + 6 * name.length per record (two records per folder), covering fixed layer/resource records and Unicode/Pascal names. B = metadata + L + M bounds serialized output for this restricted document shape.
  • The worker allowance includes 4*(A+C) + L + M + 12*C + 2*height + 5*B: transferred input pixels; all retained encoded channels, including potentially uncollected layer channels during composite encoding; writer scratch (8*C + 2*height); composite pixel copy (4*C); every geometric writer growth buffer (<4*B, including obsolete allocations without assuming collection); and the exact writePsd output slice (B). Worker termination relinquishes this heap before download. Download needs at most 2*B for exact output and Blob, so admission uses the maximum of the worker and download phases, rather than summing disjoint phases. writePsdUint8Array would retain unused writer capacity; the exact final slice is used instead and its copy is budgeted.
  • A single 4096² layer needs about 1095 MiB of serialization allowance; its 256 MiB preparation plus 64 MiB each for decoded pixels, live cache and detached snapshot fits at 448 MiB of the unchanged raster budget. Unit admission tests also pin single 2048²/3840×2160 and three 1920×1080/1536² layers, plus an unsupported serialization size refused before executor allocation. PackBits adversarial fixtures and actual writePsd output tests check the bound independently.

Reservations describe known pixel/binary allocations, not a browser RSS ceiling: allocator/GC timing, module/JS object overhead, GPU/driver copies and browser download storage are outside this model. No obsolete writer allocation is assumed to have been collected; termination relinquishes worker ownership but browser reclamation timing is not observable. Capture and preparation leases release once on every exit, including cancellation and worker failure.

The engine publishes its phase in the psdExportStatus scalar interaction store. exports.cancelPsdExport() and lifecycle cooldown/disposal cancel preparation or the writer; widgets only render this store and invoke the capability. Layers header and keyboard stack menu disable export while busy, show the phase and offer Cancel. Download handoff is irreversible: cancellation is disabled in that phase and a successful initiated download returns exported even if the engine cools while URL cleanup settles. The Platform download helper appends its anchor for Firefox compatibility and keeps the URL through the next animation frame, with a one-second timer fallback for suspended background frames; the controller remains busy until cleanup settles.

Capability returns exported, busy, nothing, too-large (PSD format or serialization allowance), not-ready, over-budget (raster preparation), stale, aborted, a LayerUnreadable, or an AdjustmentRefusal. Layers widget maps non-success results to notices and leaves duplicate busy silent. The engine reports unexpected failures with their project identity through the existing Workbench error recorder and Platform Logging.

Input ownership and frame scheduling

Pointer pipeline (input/pointerPipeline.ts) owns gesture capture and temporary holds (Space → view, Alt → picker, C → bbox). Keyboard ownership is explicit. Widget passes its focusable keyboard root and a resolveKeyOwner judge to surface.attach; the judge names the workbench region that owns a keydown (surface, a companion widget acting on this canvas's layers, or elsewhere) and is asked only on keydown, after the pipeline's own refusals, so the engine imports nothing from Workbench focus and pointer paths never pay for it. No key acts over an editable field, a control reached by keyboard (pipeline records on focusin whether focus arrived by pointer: Chromium marks focused element :focus-visible at any keydown, so arrival is the only reliable signal), an open dialog, menu or listbox, or beneath a modal. Past those refusals: Enter applies a session only from the surface with focus on its root or nowhere, never on a control; the Escape ladder and C act from the surface or a companion. Escape first cancels the pointer gesture, then the engine ladder runs, most local first: a color pick, a defocused text edit, a transform session or pending transform, a float, the open session of the tool the user is on (the held tool under a Space, Alt or C hold: a polygon between clicks), an application operation (Filter, Select Object), and only then the selection. A tool's onKeyCommand('cancel') reports whether it dropped a session; one that did, or a gesture the Escape cancelled, keeps the committed selection; Space and Alt stay pointer-led, acting over the hovered canvas whatever the owner and otherwise only from the surface. Without a judge (tests, detached engines) focus alone decides: the root or no focus is the surface, and a control the pointer last clicked counts as a companion. Owned Space keydown is prevented, so a clicked control does not activate. An owned Alt keydown is prevented, and so is the release of an Alt the pipeline claimed, because Firefox and Windows otherwise activate the menu bar; that holds for a tool that reads Alt as a gesture modifier too (Marquee, Lasso, Move and the Frame tool's grid bypass, Transform's scale about the centre, Shape's draw from the centre), which keeps the key and only gets no picker hold, since pointer events still carry altKey; the Color picker tool (I) covers those tools. Every other release is observed, never consumed. Alt from the surface while the pointer is elsewhere arms a pending hold that the next pointerenter with Alt still held, or a pointerdown with Alt, begins before the press is routed, so a pen landing without hover samples on contact; release, tool switch, blur, reset and detach clear it. Genuine tool switch first cancels the gesture through outgoing tool and ends any hold, restoring held tool, so the switch leaves the tool the user was really on and a later key release restores nothing.

Wheel routing (input/wheel.ts) follows the scrollInput interaction setting. Mouse behavior: wheel zooms, resting on snap points, and Ctrl+wheel steps the brush or eraser size. Trackpad behavior: wheel pans on both axes and Ctrl+wheel, how browsers deliver a pinch, zooms continuously about the pointer. auto classifies each event (input/wheelDevice.ts, which reads deltaMode first, because Firefox otherwise reports a line-mode wheel in pixels, and normalizes deltas to CSS pixels for all routing). A notched wheel always gets mouse behavior. Smooth scrolling gets trackpad behavior once trackpadDetected is set and mouse behavior before, so a high-resolution mouse wheel keeps zooming; a sideways-only event, notched or smooth, pans either way. A two-axis event, or Ctrl+wheel while the physical Control key is known to be up, or, while that state is unknown, Ctrl+wheel carrying Chromium's pinch stamp (a whole-tick wheelDeltaY on a delta under 25px), proves a trackpad: the engine sets trackpadDetected before routing that event and never clears it, and the widget persists it per browser (widgets/canvas/CanvasScrollInputFeed.tsx). The pipeline tracks Control from capture-phase window key events, so a handler that stops propagation cannot hide them, and from pointer event modifiers and wheel events without ctrlKey, which show it up only while the document has focus; it is unknown until the first such event and again after window focus, blur or a hidden page, since a press made meanwhile is never seen. Safari's pinch arrives as gesturestart/gesturechange instead; in every mode it is prevented, so the page does not magnify, zooms by scale from the gesture's start and sets trackpadDetected. A pinch that starts during a pointer gesture is ignored: iPadOS sends the same events for a touch pinch, whose first finger is already drawing. A view change under a still pointer delivers a hover move (refreshHover) with hover pressure, so hover state such as the brush ring stays under the pointer; it is skipped during a gesture, where a synthesized move would paint a segment the user never drew.

ColorSampleController routes picks. A pick previews each sampled color to the one-shot request or the workbench router (setColorSampleRouter), then commits the last preview once on release or cancels it once when the press ends any other way (Escape, a tool change, a cancelled pointer); a declined preview falls back to the brush color. The sink that took a pick's first preview gets its commit or cancel, so a request armed or settled mid-pick never sends the router a stray phase, nor the reverse. Brush and eraser share an engine-lifetime memory (PaintLineEndController) of where the last committed stroke ended on each layer, kept in that layer's local space: a Shift press on a layer with a remembered end draws a straight segment from it, placed through the layer's current transform, as part of the one stroke. The engine routes every layer change to it. A change of transform alone (move, nudge, Fit to frame, a transform parameter) carries the end with the layer; a change that rewrites content and transform together (crop, conversion, a baked float or result) keeps its document position and re-expresses it in the new local space; an applied Transform on a paint layer, which redraws only the pixels, rebases it from the session's transform. It survives tool switches but forgets on replay, document replacement, the layer's removal and a transform it cannot invert. layers.beginTransform (TransformEditingController.request) selects a leaf, switches to transform and opens its session even when transform is already active, cancelling a session on another layer; it refuses a locked or ineligible leaf, a running gesture, a live float or locked edits without changing selection or tool. A leaf whose only content is a stroke persistence has not acknowledged yet (a new paint layer's first upload) has no persisted extent to frame, so the request waits in the pendingTransformLayerId interaction store and the session opens when the bitmap lands, while the leaf is still selected, transform is the tool the user is on (a Space, Alt or C hold over it counts) and no other session opened. The wait ends without a session on a genuine tool switch, a selection change, the leaf's removal, Escape, a history replay, a document replacement, disposal, or an upload of that leaf failing with no retry to follow (retried failures keep the wait), which also reports a not-ready refusal through tools.onEditRefused.

RenderScheduler.beforeNextFrame(task) runs tasks once before next frame takes its flags, so their invalidations join that frame. Tools reach it through required ToolContext.scheduleFrame; detached engine runs the task immediately because it produces no frames. Brush strokes append samples and decimate them incrementally per event, render accumulated stroke at most once per presented frame, render synchronously on commit.

Lifecycle

Lifecycle states: active, cooling, cool, disposed. Losing final registry reference immediately banks a live floating selection, detaches input/render targets, cancels background PSD work, rasterization and the display's spatial adjustment jobs, releases old generation's reservations, starts a dirty-pixel flush. Successful, still-current flushes release every derived and group surface and each base cache that no read lease pins and no session holds, then trim history. Failed flushes keep dirty pixels and stay retryable; registry keeps the engine and retries after another grace period, disposing it only after a cooled result. Reacquisition increments lifecycle generation so late flush or grace-period work cannot clean up or dispose a live engine. Operation-owned reservations and pins survive these generation transitions until their owning operation settles.

Operations that write an open project's document elsewhere (close, export, duplicate) first cross its engine's paint barrier through open-project handle and Workbench's LiveCanvasEngines registry; close crosses it again after the push so pixels painted meanwhile are not lost. These barriers do not wait on an edit that holds dirty pixels (session, gesture or suspension): they fail fast and ask user to finish or cancel it, and if unsaved pixels cannot be persisted the project stays open with its engine state intact. Rename keeps its tolerant flush. Invocation waits for short-lived holds. The same registry lets Workbench's frame-size sync (canvasDimsSync.ts) record a frame resize that Generate's size asked for as one canvas step (commitFrame), so canvas undo restores frame and size together; without a live engine it is a system write. Disposal cancels outstanding work and releases every resource category: caches, decoded bitmaps, reservations, pins, outstanding snapshots.

Caller-owned CanvasRasterSnapshot objects are not reconstructible lifecycle caches. They stay usable through cooldown and keep counting against detached bytes until released. Final engine disposal force-releases them.

Browser acceptance

Node and browser suites split by filename and config. vitest.config.mts excludes *.browser.test.ts(x); vitest.browser.config.mts runs those files through @vitest/browser-playwright in headless Chromium. test:browser runs browser suite; test:all runs Node, then browser tests. CI installs Chromium with pnpm exec playwright install chromium before browser job.

Real-Canvas2D suite verifies transformed composition, clipping, alpha and blend modes, browser text metrics, PNG blob encoding, createImageBitmap decoding, pixel undo/redo, small PSD write/read round trip. React StrictMode harness verifies surface attachment, ResizeObserver sizing, detachment, registry cooldown/reacquisition, grace-period safety, project switching.

Adding functionality

  • New tool: implement tool interface under tools/, keep durable state in CanvasProjectMutation, expose only required tool capability methods. Commit structural edits on pointer-up or from a key command with no press held, never on pointer-down: the pipeline's gesture is active from press to release, and commitStructural refuses it as gesture-active (the Shape tool's click-closed polygon commits on the release of its closing press for this reason). Pixel edits begun through beginStrokeEdit belong to the gesture and may start on the press.
  • New derived effect: add stable effect kind/parameter key, construct through DerivedSurfaceCache, test warm hits, precise invalidation, stale source guards, culling, byte accounting.
  • New layer operation: pure pixel/document math in core, orchestration in a controller; accept narrow ports, use project-bound mutations, reserve background allocations, return status unions for expected no-op/stale cases.
  • New background raster workflow: capture document snapshot, plan required layers, reserve and pin before allocation, detach immutable surfaces, release every lease in finally, define whether edits after detachment are allowed.
  • New application coordinator: place under canvas-operations/, acquire edit lease, capture through narrow document/export capabilities, own its session store and cancellation, publish through preview/layer capabilities.

Deterministic CI assertions use operation counters and byte totals. Wall-clock timing is informational only.

Vector point editing is owned by controllers/vectorEditingController.ts and the dedicated spline tool. The toolbar uses Lucide SplinePointer as its last button; the working cursor is a crosshair. vectorEditSession stores point/path selection and in-flight gesture geometry only. Each completed gesture or command writes a structural vector-config edit into global history; there is no Apply/Cancel session or separate local undo stack. Escape cancels the current gesture and clears point selection, without leaving the tool. Layer changes retarget the tool to the selected editable vector layer; other layer types expose no editable geometry. Properties renders point commands through layers.vectorEdit and never edits geometry itself.

Move always moves the whole selected layer. Shapes creates paths independently of the point tool. Whole vector layers use the existing Transform tool and Bezier content bounds: previews update the guide matrix, and Transform Apply records one layer-transform history step without rasterization. Switching away from the point tool cancels any unfinished gesture; completed edits are already saved.

Spline context menus resolve anchor/curve hits in CSS viewport coordinates through layers.vectorEdit.targetContextMenu. The UI checks its captured layer/path against the live point-tool selection before running commands. Path deletion is separate from Delete-selection semantics; both use global history.

Extract Path immediately copies the active spline into a new vector layer above the source, with a fresh path ID and preserved geometry/transform/appearance. Its stack-insertion command retains the selected source layer, active spline and selected points. It is one global history step, undoable without leaving the point tool.

Spline point/topology controls are presented by tool-options/SplineOptions.tsx as the spline tool form. Vector layer Properties owns path count, optional guideColor, and Trace/Fill appearance settings. This display property is parsed by Canvas migration and patched through vector config edits; missing colors resolve to DEFAULT_VECTOR_GUIDE_COLOR. The existing structural preview/commit seam supplies live color preview and one history step. Overlay guide descriptors carry the color independently of point-selection chrome and raster compositing. Extract and layer duplication preserve it.

The spline tool owns an optional active-path transform frame in vectorEditSession.pathTransform, reusing transformMath for hit testing and gestures. The controller holds immutable source geometry and applies the cumulative local transform to its anchors and handles. Frame chrome projects through the existing layer matrix; other contours and the layer contract transform stay unchanged. Completed gestures commit through ordinary vector-config history. Global document replays invalidate the frame; no separate transform tool or layer-level Apply/Cancel session is opened for a path.

Vector layer Properties owns Trace controls. Stroke color and width, Fill/Stroke switches and colors, and optional traceTaperEnds/traceTaper config properties persist per layer. New layers store black strokes at 50 pixels. Appearance edits use structural preview/commit and global undo/redo. vectorTraceController samples Bezier curves and renders ordinary round strokes or v6-style tapered pressure outlines into layer-local paint pixels. It uses the standard mutation transaction and publishAddedRasterLayer for reserved allocation, atomic insertion, pixel persistence and global replay. The new raster layer inherits the vector transform; source geometry and display guide color are unaffected.

Input reset releases tool-owned Space, Alt and Shift holds after restoring any temporary tool. This clears modifiers whose keyup was lost while the window was unfocused, including between polygon clicks.

Vector layer Trace/Fill and path-menu scope

Layer Properties exposes Shapes-style Appearance rows with independent Fill/Stroke toggles and colors, stroke width, taper settings, and one Trace/Fill action. Fill defaults off and Stroke defaults on. The required strokeColor and strokeWidth, and optional fillColor, fillEnabled, strokeEnabled, traceTaperEnds and traceTaper properties persist on the vector layer. Trace Path, Fill Path and layer-wide Trace/Fill read that layer snapshot. Brush changes do not change vector appearance. New layers store black strokes at 50 pixels.

Intersection-based filling belongs exclusively to the layer action. When Fill is enabled, math/vectorFillRegions.ts discovers bounded faces across all sampled paths in the active vector layer, including self-intersections and intersections between open paths. Free tails are excluded from filled areas; an isolated crossing does not create a region. Source paths are never closed, split or otherwise rewritten. Fill and optional strokes are published together into one raster layer with one global Undo/Redo step, preserving the selected vector layer on insertion and redo.

The path context menu deliberately has narrower semantics: Trace Path strokes only the targeted path, while Fill Path fills only the targeted explicitly closed path (at least three points), using the layer fill color regardless of the Appearance toggles. It does not discover regions involving other curves. There is no context-menu Fill Region or cursor-based region selection.

Region discovery runs only when the layer action executes, not when opening a context menu or moving points. It yields bounded work chunks to the browser and checks AbortSignal between chunks. Cancel or Escape interrupts it; document edits, engine cooldown and disposal abort pending work. Results are fenced against the captured document before admission and publication. The prototype uses 24 samples per Bezier segment, x-sorted bounding-box candidate rejection, segment splitting and directed planar-face traversal. Worst-case intersection work is quadratic, bounded by 24,000 input segments, 2,000,000 candidate comparisons and 120,000 directed edges. Exceeding a limit returns a distinct too-complex result instead of publishing partial output. Approximation can miss small features; gap snapping, coincident-segment repair, robust tangency handling and intentional holes are outside the current scope. Numerical endpoint coincidences may connect. Live Trace/Fill preview is not implemented.

Trace/Fill capabilities return Promise<VectorTraceResult> with distinct empty, canceled/stale, busy, memory-budget and complexity outcomes. Properties offers Cancel while its request runs; the path menu closes immediately and reports actionable failures. Raster bounds include the tension curve control-point hull and actual taper outline. Geometry preparation is browser-independent; Path2D construction can be injected for recording tests.

Spline editing reattaches to the selected vector layer when its engine activates after cooldown. Join eligibility and welding share viewport-distance semantics under non-uniform scales. The controller owns a bounded hit-test cache (50,000 retained samples, at most 64 path entries), invalidated by immutable path identity and projection; bounds reject distant curves before sampling, and per-segment sampling is capped at 128. Completed edit refusals restore committed geometry and notify; Shapes retains a refused draft for Enter retry, while Escape or a fresh press abandons it explicitly. The Move tool has no vector-editor delegation.