Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(canvas): close raster-ownership review gaps
Josh Corbett3fc8b61f754f
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex dad61ac8c9..f221e324a7 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -450,6 +450,7 @@"allSavedAlreadyOpen": "All saved projects are already open.","activeRunsMustFinish": "Wait for active queue runs to finish first.","closeProjectLabel": "Close {{name}}",+ "canvasPixelsNotSaved": "Unsaved canvas changes could not be uploaded, so the project stays open with them. {{reason}}","closeBlocked": "Project not closed","couldNotOpen": "Could not open project","couldNotOpenDescription": "\"{{name}}\" could not be loaded from the server.",diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex d58654c42b..587eeadc7c 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -10,8 +10,6 @@ import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from 'import { createContext, use, useEffect, useSyncExternalStore, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';-import type { ProjectPushOutcome } from './projects/projectFlush';-import { WorkbenchSplashScreen } from './components/WorkbenchSplashScreen';import { WorkbenchUnavailableScreen } from './components/WorkbenchUnavailableScreen';import { createExtensionRegistry, type ExtensionRegistry } from './extensions/extensionRegistry';@@ -19,9 +17,9 @@ import { clearLayerPanelStates } from './layerPanelState';import { createWorkbenchPersistenceRuntime } from './persistenceRuntime';import { createOpenProjectBroker } from './projects/openProjectBroker';import {- createCanvasHeldMediaSources,+ createLiveCanvasEngines,createOpenProjectsHeldMediaReader,- type CanvasHeldMediaSources,+ type LiveCanvasEngines,} from './projects/projectAssets';import { describeRefusedProjects } from './projects/projectLoadRefusal';import {@@ -45,7 +43,7 @@ type WorkbenchSelector<T> = (snapshot: WorkbenchSnapshot) => T;const WorkbenchStoreContext = createContext<WorkbenchInternalStore | null>(null);const WorkbenchPersistenceContext = createContext<SyncedWorkbenchPersistence | null>(null);const WorkbenchExtensionsContext = createContext<ExtensionRegistry | null>(null);-const WorkbenchCanvasHeldMediaContext = createContext<CanvasHeldMediaSources | null>(null);+const WorkbenchLiveCanvasEnginesContext = createContext<LiveCanvasEngines | null>(null);const subscribeToNothing = (): (() => void) => () => {};const getNullSnapshot = (): null => null;@@ -64,7 +62,7 @@ export const WorkbenchProvider = ({const { t } = useTranslation();const [persistence] = useState(() => createSyncedWorkbenchPersistence(owner));const [extensions] = useState(createExtensionRegistry);- const [canvasHeldMedia] = useState(createCanvasHeldMediaSources);+ const [liveCanvasEngines] = useState(createLiveCanvasEngines);const [loadUnavailable, setLoadUnavailable] = useState<{ message: string; retry(): void } | null>(null);const hasHydrated = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot).hasHydrated;@@ -120,13 +118,15 @@ export const WorkbenchProvider = ({}},deleteProject: (projectId) => persistence.deleteProjectOnServer(projectId),- flushProject: (projectId) => {+ flushProject: async (projectId) => {+ // Unsaved canvas pixels reach the document before it is pushed; a failure rejects the flush.+ await liveCanvasEngines.flushPendingPixels(projectId);const project = store.getSnapshot().projects.find((candidate) => candidate.id === projectId);// Unopened projects have no local edits; their ids reflect server acknowledgements.return project? persistence.flushProjectToServer(project)- : Promise.resolve<ProjectPushOutcome>({ documentJson: '', kind: 'acknowledged' });+ : { documentJson: '', kind: 'acknowledged' as const };},getOpenProjectIds: () => store.getSnapshot().projects.map((project) => project.id),markProjectDeleted: (projectId) => {@@ -144,7 +144,7 @@ export const WorkbenchProvider = ({persistenceRuntime.start();const releaseIntermediateHold = startIntermediatesHoldLease({owner,- read: createOpenProjectsHeldMediaReader(() => store.getSnapshot().projects, canvasHeldMedia.read),+ read: createOpenProjectsHeldMediaReader(() => store.getSnapshot().projects, liveCanvasEngines.heldAssets),subscribe: (onChange) => {let projects = store.getSnapshot().projects;const unsubscribeProjects = store.subscribe(() => {@@ -154,7 +154,7 @@ export const WorkbenchProvider = ({onChange();}});- const unsubscribeCanvas = canvasHeldMedia.subscribe(onChange);+ const unsubscribeCanvas = liveCanvasEngines.subscribe(onChange);return () => {unsubscribeProjects();unsubscribeCanvas();@@ -173,7 +173,7 @@ export const WorkbenchProvider = ({return (<WorkbenchPersistenceContext value={persistence}>- <WorkbenchCanvasHeldMediaContext value={canvasHeldMedia}>+ <WorkbenchLiveCanvasEnginesContext value={liveCanvasEngines}><WorkbenchExtensionsContext value={extensions}><WorkbenchStoreContext value={store}>{loadUnavailable ? (@@ -189,7 +189,7 @@ export const WorkbenchProvider = ({)}</WorkbenchStoreContext></WorkbenchExtensionsContext>- </WorkbenchCanvasHeldMediaContext>+ </WorkbenchLiveCanvasEnginesContext></WorkbenchPersistenceContext>);};@@ -316,12 +316,12 @@ export const useOptionalWorkbenchPersistenceService = (): SyncedWorkbenchPersistuse(WorkbenchPersistenceContext);/** Where live Canvas engines register the undo state the hold lease must keep. */-export const useWorkbenchCanvasHeldMedia = (): CanvasHeldMediaSources => {- const heldMedia = use(WorkbenchCanvasHeldMediaContext);- if (!heldMedia) {- throw new Error('useWorkbenchCanvasHeldMedia must be used within a WorkbenchProvider.');+export const useWorkbenchLiveCanvasEngines = (): LiveCanvasEngines => {+ const liveEngines = use(WorkbenchLiveCanvasEnginesContext);+ if (!liveEngines) {+ throw new Error('useWorkbenchLiveCanvasEngines must be used within a WorkbenchProvider.');}- return heldMedia;+ return liveEngines;};export const useWorkbenchExtensions = (): ExtensionRegistry => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 49b6b56e8d..4aa426aab4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -83,7 +83,7 @@ Controller-local tests instantiate these boundaries with fakes. Integration test`CanvasExportCapability.captureRasterSnapshot(snapshot, layerIds, options)` requests exactly the required layer caches, temporarily pins them, reserves detached-surface capacity, and copies their pixels into independent surfaces. It returns a typed `ok`, `stale`, `aborted`, `not-ready`, or `over-budget` result. Freshness is checked before and after every asynchronous rasterization boundary and once after all copies are detached.-An `ok` result contains a `CanvasRasterSnapshot`: the cloned canvas contract, its document generation, a map of detached layer surfaces, and an idempotent `release()`. The snapshot is caller-owned. Its surfaces do not read live caches and remain valid while the engine cools down; cooldown releases generation-scoped reservations and pins but does not invalidate detached snapshots. The caller must release the snapshot in `finally`. Engine disposal releases any snapshots still outstanding.+An `ok` result contains a `CanvasRasterSnapshot`: the cloned canvas contract, its document generation, a map of detached layer surfaces, and an idempotent `release()`. The snapshot is caller-owned. Its surfaces do not read live caches and remain valid while the engine cools down; cooldown releases generation-scoped reservations but does not invalidate detached snapshots. The caller must release the snapshot in `finally`. Engine disposal releases any snapshots still outstanding.This creates a deliberate transaction boundary:@@ -106,7 +106,7 @@ The frame's demanded layers form its working set. After drawing, `RasterControll1. derived and group artifacts the frame did not read (obsolete parameter variants, inactive groups);2. least-recently-used base caches that are outside the working set and unprotected.-A layer is protected while an operation pins it (`RasterController.pin`, held by every read lease, snapshot capture, export and duplicate) or while it is held: its pixels are not yet persisted (`BitmapStore.hasPendingWork`) or an edit session (transform, text, float, pixel edit, operation lock) owns them. Whatever the working set and protected layers still need stays resident; the bytes above the 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, and re-rasterization.+A 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 are not yet persisted (`BitmapStore.hasPendingWork`) or an edit session (transform, text, float, pixel edit, operation lock) owns them. Whatever the working set and protected layers still need stays resident; the bytes above the 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, and re-rasterization.## Raster resource ownership and memory policy@@ -124,7 +124,7 @@ The raster soft limit is 512 MiB. The memory snapshot reports:Background snapshots, thumbnails, raster exports, transformed/adjusted copies, and PSD exports reserve sufficient available bytes before allocating and return typed `over-budget` outcomes when they cannot.-Asynchronous raster reads return a `RasterReadLease` (`rasterTransactions.ts`): the pixels, their layer-local extent, a freshness guard and an idempotent `release`. The lease pins its source layer from before rasterization until release, so neither eviction nor paint trimming can reshape pixels an operation is still reading; the guard still rejects pixels a later edit replaced. Extraction, merges, crops, copies, filters, snapshots and composite exports all read through leases and release them in `finally`.+Asynchronous raster reads return a `RasterReadLease` (`rasterTransactions.ts`): the pixels, their layer-local extent, a freshness guard and an idempotent `release`. The 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); the guard still rejects pixels a later edit replaced. Leases on detached copies (adjusted or baked pixels) release the source pin as soon as the 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 the normal `finally` path has not already done so. Once an asynchronous 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 is still able to resume. Pins are always operation-owned. Detached snapshot accounting follows the snapshot and is released only by `CanvasRasterSnapshot.release()` or engine disposal.@@ -162,9 +162,9 @@ The capability returns `exported`, `nothing`, `too-large`, `not-ready`, `over-bu## Lifecycle-Lifecycle states are `active`, `cooling`, `cool`, and `disposed`. Losing the final registry reference immediately detaches input/render targets, cancels background PSD work and rasterization, releases the old generation's reservations and pins, and starts a dirty-pixel flush. Successful, still-current flushes release every reconstructible raster surface (base, derived and group) and trim history. Failed flushes retain dirty pixels and remain retryable; the registry retains the engine and retries after another grace period, disposing it only after a `cooled` result. Reacquisition increments the lifecycle generation so late flush or grace-period work cannot clean up or dispose a live engine. Operation-owned composite leases survive these generation transitions until their owning operation settles.+Lifecycle states are `active`, `cooling`, `cool`, and `disposed`. Losing the final registry reference immediately detaches input/render targets, cancels background PSD work and rasterization, releases the old generation's reservations, and 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 retain dirty pixels and remain retryable; the registry retains the engine and retries after another grace period, disposing it only after a `cooled` result. Reacquisition increments the 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.-Closing a project first crosses the engine's paint barrier; if unsaved pixels cannot be persisted the project stays open with its engine state intact. Disposal cancels outstanding work and releases every resource category: caches, decoded bitmaps, reservations, pins and outstanding snapshots.+Pushing an open project's document (close, export, copy, rename) first crosses its engine's paint barrier through the Workbench's `LiveCanvasEngines` registry, and close crosses it again after the push so pixels painted meanwhile are not lost; if unsaved pixels cannot be persisted the project stays open with its engine state intact. Disposal cancels outstanding work and releases every resource category: caches, decoded bitmaps, reservations, pins and outstanding snapshots.Caller-owned `CanvasRasterSnapshot` objects are not reconstructible lifecycle caches. They remain usable through cooldown and continue to count against detached bytes until released. Final engine disposal force-releases them.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 5728405ac1..1934cb37a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -475,7 +475,7 @@ export interface CanvasDiagnosticsSnapshot {readonly layersDrawn: number;readonly compositeFrames: number;readonly overlayFrames: number;- readonly overBudgetVisibleBaseBytes: number;+ readonly rasterOverageBytes: number;}export interface CanvasEngineToolCapability extends CanvasToolCapability {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.tsindex 88cbc10199..2c597eecfb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts@@ -152,17 +152,7 @@ export class PixelEditController {return null;}}- const original = originalEntry- ? {- hasPublishedPixels: originalEntry.hasPublishedPixels,- lastUsed: originalEntry.lastUsed,- pixels: originalPixels,- rect: { ...originalEntry.rect },- stale: originalEntry.stale,- surface: originalEntry.surface,- version: originalEntry.version,- }- : null;+ const original = o.layers.captureState(layerId);const releasePersistence = o.bitmapStore.suspendLayer(layerId);let closed = false;let owner: { cancel: () => void; layerId: string };@@ -176,23 +166,14 @@ export class PixelEditController {};const restore = (): void => {try {- if (!original) {- o.layers.delete(layerId);- } else {+ if (original) {original.surface.resize(original.rect.width, original.rect.height);- if (original.pixels) {- original.surface.ctx.putImageData(original.pixels, 0, 0);+ if (originalPixels) {+ original.surface.ctx.putImageData(originalPixels, 0, 0);}- const current = o.layers.get(layerId) ?? o.layers.getOrCreateRect(layerId, original.rect);- Object.assign(current, {- hasPublishedPixels: original.hasPublishedPixels,- lastUsed: original.lastUsed,- rect: { ...original.rect },- stale: original.stale,- surface: original.surface,- version: original.version,- });}+ // An exact rollback; the store re-accounts the reinstated surface.+ o.layers.restoreState(layerId, original);} finally {o.deleteDerived(layerId);o.invalidate(layerId);@@ -297,17 +278,8 @@ export class PixelEditController {): PixelEditTransaction | null {const o = this.options;const originalEntry = o.layers.get(layerId);- const original = originalEntry- ? {- hasPublishedPixels: originalEntry.hasPublishedPixels,- lastUsed: originalEntry.lastUsed,- rect: { ...originalEntry.rect },- stale: originalEntry.stale,- surface: originalEntry.surface,- version: originalEntry.version,- }- : null;- const beforeRect = original?.rect ?? { ...contentRect };+ const original = o.layers.captureState(layerId);+ const beforeRect = original ? { ...original.rect } : { ...contentRect };let beforePixels: ImageData | null = null;if (!isEmpty(beforeRect)) {if (!originalEntry) {@@ -342,14 +314,7 @@ export class PixelEditController {const before: LayerPixelSnapshot = { layer: structuredClone(layer), pixels: beforePixels, rect: beforeRect };const restore = (): void => {try {- if (original) {- const current = o.layers.get(layerId);- if (current) {- Object.assign(current, { ...original, rect: { ...original.rect } });- }- } else {- o.layers.delete(layerId);- }+ o.layers.restoreState(layerId, original);} finally {o.deleteDerived(layerId);o.setTransformOverride(layerId, null);@@ -365,14 +330,7 @@ export class PixelEditController {}};try {- const preview = originalEntry ?? o.layers.getOrCreateRect(layerId, prepared.rect);- Object.assign(preview, {- surface: prepared.surface,- rect: { ...prepared.rect },- hasPublishedPixels: true,- stale: false,- });- preview.version += 1;+ o.layers.installReplacement(prepared);o.deleteDerived(layerId);o.setTransformOverride(layerId, { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });o.invalidate(layerId, true);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex 95cd902119..abe951b3c5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@ -92,7 +92,9 @@ export class MergeLayerController {type: 'mergeCanvasLayersDown',upperLayerId,});+ // An empty live cache, not a missing one: the paint barrier treats a dirty layer without a cache as lost.this.deps.layers.delete(below.id);+ this.deps.layers.getOrCreateRect(below.id, { height: 0, width: 0, x: 0, y: 0 }).stale = false;this.deps.notifyPainted(below.id);this.deps.markDirty(below.id);return true;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.tsindex 6c077415c0..9950d1b719 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts@@ -117,7 +117,7 @@ describe('RasterController', () => {publish(controller, 'dirty');publish(controller, 'pinned');publish(controller, 'hidden');- const pin = controller.pin('pinned');+ const pin = controller.memory.pin('pinned');const result = controller.enforceBudget(new Set(), controller.beginFrame());@@ -128,6 +128,43 @@ describe('RasterController', () => {expect(controller.enforceBudget(new Set(), controller.beginFrame()).evictedBaseLayerIds).toEqual(['pinned']);});+ it('keeps a drawn group composite across frames instead of rebuilding it under pressure', () => {+ const backend = createTestStubRasterBackend();+ const createSurface = vi.fn((width: number, height: number) => backend.createSurface(width, height));+ const controller = new RasterController({+ backend: { ...backend, createSurface },+ budgetBytes: SURFACE_BYTES,+ diagnostics: createCanvasDiagnostics(true),+ });+ publish(controller, 'member');+ const members = [+ { id: 'member', layer: { ...adjustedLayer('member'), adjustments: [] } } as unknown as SemanticLeaf,+ ];+ const builds = (): number => createSurface.mock.calls.filter(([width]) => width === 10).length;+ const before = builds();++ for (let frame = 0; frame < 5; frame += 1) {+ const usage = controller.beginFrame();+ controller.groups.get(groupScope, members, [identity()], new Set());+ expect(controller.enforceBudget(new Set(['member']), usage).overageBytes).toBe(SURFACE_BYTES);+ }++ expect(builds() - before).toBe(1);+ });++ it('counts reserved and detached bytes when deciding what to reclaim', () => {+ const controller = createController(SURFACE_BYTES * 2);+ publish(controller, 'hidden');+ const reservation = controller.memory.reserveOperation(1, { purpose: 'thumbnail' });+ const detached = controller.memory.trackDetached(SURFACE_BYTES);++ expect(controller.enforceBudget(new Set(), controller.beginFrame()).evictedBaseLayerIds).toEqual(['hidden']);+ detached.release();+ if (reservation.status === 'ok') {+ reservation.lease.release();+ }+ });+it('evicts inactive group composites and releases them with the reconstructible caches', () => {const controller = createController(SURFACE_BYTES);publish(controller, 'member');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.tsindex cda630af22..40b4e86a26 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts@@ -3,7 +3,6 @@ import type {CanvasImageRef,CanvasLayerContract,CanvasLayerSourceContract,- CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -34,7 +33,7 @@ import {import { createGroupSurfaceCache, type GroupSurfaceCache } from '@workbench/canvas-engine/render/groupSurfaceCache';import { createLayerCacheStore, DEFAULT_CACHE_BUDGET_BYTES } from '@workbench/canvas-engine/render/layerCache';-import { RasterMemoryBudgetController, type RasterMemoryLease } from './rasterMemoryBudgetController';+import { RasterMemoryBudgetController } from './rasterMemoryBudgetController';export interface RasterControllerOptions {readonly backend: RasterBackend;@@ -46,8 +45,8 @@ export interface RasterControllerOptions {readonly imageResolver?: (imageName: string, signal?: AbortSignal) => Promise<Blob>;/** Layers whose live pixels nothing else can reconstruct: unpersisted paint and open edit sessions. */readonly isLayerHeld?: (layerId: string) => boolean;- /** A group member's display pixels; defaults to its adjusted surface. */- readonly getGroupMemberSurface?: (layer: CanvasRasterLayerContractV2, entry: LayerCacheEntry) => RasterSurface | null;+ /** Layers whose live cache already includes their adjustments (an open pixel transaction), drawn raw. */+ readonly isAdjustmentBaked?: (layerId: string) => boolean;}/** Access clocks captured before a frame draws; artifacts read after them are that frame's working set. */@@ -71,6 +70,7 @@ export class RasterController {readonly bitmaps: DecodedBitmapPool;private readonly diagnostics: CanvasDiagnostics;private readonly isLayerHeld: (layerId: string) => boolean;+ private readonly isAdjustmentBaked: (layerId: string) => boolean;private readonly jobs = new Map<string, RasterizationJob>();private readonly activeJobs = new Set<RasterizationJob>();private readonly trackedImages = new Map<string, string>();@@ -87,6 +87,7 @@ export class RasterController {this.backend = options.backend;this.diagnostics = options.diagnostics;this.isLayerHeld = options.isLayerHeld ?? (() => false);+ this.isAdjustmentBaked = options.isAdjustmentBaked ?? (() => false);const memory = new RasterMemoryBudgetController({ budgetBytes: options.budgetBytes ?? DEFAULT_CACHE_BUDGET_BYTES });this.memory = memory;this.bitmaps = createDecodedBitmapPool({ onBytesChange: (bytes) => memory.setCategoryBytes('decoded', bytes) });@@ -101,21 +102,14 @@ export class RasterController {this.adjustments = createAdjustedSurfaceCache(options.backend, this.derived, (layerId, version) =>this.layers.damageSince(layerId, version));- const getGroupMemberSurface =- options.getGroupMemberSurface ?? ((layer, entry) => this.getAdjustedSurface(layer, entry));this.groups = createGroupSurfaceCache({createSurface: (width, height) => options.backend.createSurface(width, height),- getAdjustedSurface: (layer, entry) => getGroupMemberSurface(layer, entry),+ getAdjustedSurface: (layer, entry) => this.getAdjustedSurface(layer, entry),getCacheEntry: (layerId) => this.layers.get(layerId),onBytesChange: (bytes) => memory.setCategoryBytes('group', bytes),});}- /** Keeps a layer's cache resident and untrimmed until the lease is released. */- pin(layerId: string): RasterMemoryLease {- return this.memory.pin(layerId);- }-/** Pinned or held layers survive eviction; their bytes become accounted overage instead. */isProtected(layerId: string): boolean {return this.memory.isPinned(layerId) || this.isLayerHeld(layerId);@@ -131,11 +125,13 @@ export class RasterController {*/enforceBudget(workingSetLayerIds: ReadonlySet<string>, usage: RasterFrameUsage): RasterBudgetResult {const excess = (): number => this.memory.snapshot().overageBytes;- if (excess() > 0) {- this.derived.evict(Math.max(0, this.derived.byteSize() - excess()), (_layerId, lastUsed) => {- return lastUsed > usage.derivedTick;- });+ if (excess() === 0) {+ return { evictedBaseLayerIds: [], overageBytes: 0 };}+ this.derived.evict(+ Math.max(0, this.derived.byteSize() - excess()),+ (_layerId, lastUsed) => lastUsed > usage.derivedTick+ );if (excess() > 0) {this.groups.evict(Math.max(0, this.groups.byteSize() - excess()), usage.groupTick);}@@ -151,16 +147,18 @@ export class RasterController {}const overageBytes = excess();if (overageBytes > 0) {- this.diagnostics.add('overBudgetVisibleBaseBytes', overageBytes);+ this.diagnostics.add('rasterOverageBytes', overageBytes);}return { evictedBaseLayerIds, overageBytes };}- /** Drops every reconstructible surface; callers first prove nothing unpersisted remains. */+ /** Drops every derived and group surface and each base cache nothing pins or holds. */releaseReconstructible(): void {- this.layers.dispose();this.derived.dispose();this.groups.clear();+ for (const layerId of this.layers.evict((candidate) => this.isProtected(candidate), 0)) {+ this.deleteDerivedSurfaces(layerId);+ }}async decodeImage(@@ -229,7 +227,9 @@ export class RasterController {}getAdjustedSurface(layer: CanvasLayerContract, entry: LayerCacheEntry): RasterSurface | null {- return layer.type === 'raster' ? this.adjustments.get(layer.id, entry, layer.adjustments) : null;+ return layer.type === 'raster' && !this.isAdjustmentBaked(layer.id)+ ? this.adjustments.get(layer.id, entry, layer.adjustments)+ : null;}deleteDerivedSurfaces(layerId: string): void {@@ -380,7 +380,9 @@ export class RasterController {this.clearTrackedImages();this.clearMirroredImages();this.clearThumbnailKeys();- this.releaseReconstructible();+ this.layers.dispose();+ this.derived.dispose();+ this.groups.clear();this.bitmaps.dispose();this.memory.dispose();}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.tsindex 0757d494de..89f430b56d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.test.ts@@ -389,4 +389,120 @@ describe('RasterExportController budget', () => {}expect(memory.isPinned('layer')).toBe(false);});++ it.each([+ ['aborted', 'aborted', { height: 10, width: 10, x: 0, y: 0 }],+ ['stale', 'not-ready', { height: 10, width: 10, x: 0, y: 0 }],+ ['published', 'empty', { height: 0, width: 0, x: 0, y: 0 }],+ ] as const)('releases the pin when a %s rasterization reads as %s', async (outcome, status, publishedRect) => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ const memory = new RasterMemoryBudgetController();+ const layer = {+ blendMode: 'normal' as const,+ id: 'layer',+ isEnabled: true,+ isLocked: false,+ name: 'Layer',+ opacity: 1,+ source: { image: { height: 10, imageName: 'layer.png', width: 10 }, type: 'image' as const },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster' as const,+ };+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 10, width: 10, x: 0, y: 0 },+ height: 10,+ stacks: stacksFrom([layer]),+ selectedLayerId: null,+ version: 3,+ width: 10,+ };+ const controller = new RasterExportController({+ backend,+ captureGuard: (captured, entry) => ({+ cacheVersion: entry.version,+ documentGeneration: 1,+ layer: captured,+ layerId: captured.id,+ projectId: 'p',+ }),+ getDocument: () => document,+ getOrStartRasterization: () => {+ layers.publishRasterized(+ 'layer',+ publishedRect,+ backend.createSurface(publishedRect.width, publishedRect.height)+ );+ return Promise.resolve(outcome);+ },+ isGuardCurrent: () => true,+ isRasterizing: () => false,+ isSupportedSource: () => true,+ layers,+ pin: (layerId) => memory.pin(layerId),+ });++ await expect(controller.rasterize('layer')).resolves.toEqual({ status });+ expect(memory.isPinned('layer')).toBe(false);+ });++ it('releases the source pin once an adjusted copy is made, keeping its reservation until release', async () => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ const memory = new RasterMemoryBudgetController();+ const layer = {+ adjustments: [+ { brightness: 0.1, contrast: 0, id: 'adj-bc', isEnabled: true, type: 'brightness-contrast' as const },+ ],+ blendMode: 'normal' as const,+ id: 'layer',+ isEnabled: true,+ isLocked: false,+ name: 'Layer',+ opacity: 1,+ source: { image: { height: 10, imageName: 'layer.png', width: 10 }, type: 'image' as const },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster' as const,+ };+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 10, width: 10, x: 0, y: 0 },+ height: 10,+ stacks: stacksFrom([layer]),+ selectedLayerId: null,+ version: 3,+ width: 10,+ };+ layers.publishRasterized('layer', { height: 10, width: 10, x: 0, y: 0 }, backend.createSurface(10, 10));+ const controller = new RasterExportController({+ backend,+ captureGuard: (captured, entry) => ({+ cacheVersion: entry.version,+ documentGeneration: 1,+ layer: captured,+ layerId: captured.id,+ projectId: 'p',+ }),+ getDocument: () => document,+ getOrStartRasterization: () => Promise.resolve('published'),+ isGuardCurrent: () => true,+ isRasterizing: () => false,+ isSupportedSource: () => true,+ layers,+ pin: (layerId) => memory.pin(layerId),+ reserve: (bytes) => memory.reserveOperation(bytes, { purpose: 'raster-export' }),+ });++ const adjusted = await controller.rasterize('layer', { applyAdjustments: true });++ expect(adjusted.status).toBe('ok');+ expect(memory.isPinned('layer')).toBe(false);+ expect(memory.snapshot().reservedBytes).toBe(800);+ if (adjusted.status === 'ok') {+ expect(adjusted.surface).not.toBe(layers.peek('layer')?.surface);+ adjusted.release();+ }+ expect(memory.snapshot().reservedBytes).toBe(0);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.tsindex 430220e59e..400bb20585 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts@@ -84,7 +84,6 @@ export class RasterExportController {return;}released = true;- result.release();if (reservation?.status === 'ok') {reservation.lease.release();}@@ -102,6 +101,9 @@ export class RasterExportController {} catch (error) {release();throw error;+ } finally {+ // The owned copy no longer reads the live cache; only its guard still describes it.+ result.release();}}@@ -141,10 +143,7 @@ export class RasterExportController {}const liveEntry = this.options.layers.get(layerId);if (liveEntry && !liveEntry.stale && !this.options.isRasterizing(layer) && !isEmpty(liveEntry.rect)) {- return this.applyAdjustments(- this.lease(layer, liveEntry, this.options.pin(layerId)),- options.applyAdjustments === true- );+ return this.applyAdjustments(this.lease(layer, liveEntry), options.applyAdjustments === true);}const contentRect = getSourceContentRect(layer, document);if (isEmpty(contentRect)) {@@ -193,18 +192,15 @@ export class RasterExportController {}}+ /** A lease on the live cache; the pin is taken last so nothing can fail while it is unowned. */private lease(layer: CanvasLayerContract,entry: LayerCacheEntry,- pin: { release(): void }+ pin?: { release(): void }): Extract<ExportLayerPixelsResult, { status: 'ok' }> {- return {- guard: this.options.captureGuard(layer, entry),- rect: { ...entry.rect },- release: () => pin.release(),- status: 'ok',- surface: entry.surface,- };+ const guard = this.options.captureGuard(layer, entry);+ const held = pin ?? this.options.pin(layer.id);+ return { guard, rect: { ...entry.rect }, release: () => held.release(), status: 'ok', surface: entry.surface };}private async reserveBaked(@@ -243,7 +239,6 @@ export class RasterExportController {if (reservation?.status === 'ok') {reservation.lease.release();}- raw.release();};try {const surface = this.options.backend.createSurface(rect.width, rect.height);@@ -261,6 +256,8 @@ export class RasterExportController {} catch (error) {release();throw error;+ } finally {+ raw.release();}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.tsindex 5e9e14ab4d..de009f5921 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts@@ -61,13 +61,8 @@ export class RasterizeLayerController {return;}const contentRect = getSourceContentRect(liveLayer, liveDocument);- const entry = this.deps.layers.getOrCreateRect(layerId, contentRect);- entry.rect = contentRect;- entry.stale = true;- void rasterizeSource(liveSource, this.deps.rasterizeDeps(liveDocument), entry.surface).then((result) => {- entry.rect = result.rect;- });- entry.stale = false;+ const scratch = this.deps.backend.createSurface(contentRect.width, contentRect.height);+ void rasterizeSource(liveSource, this.deps.rasterizeDeps(liveDocument), scratch);const matrix = bakeMatrix(liveLayer.transform);const bakedRect = roundOut(transformBounds(matrix, contentRect));const baked = this.deps.backend.createSurface(bakedRect.width, bakedRect.height);@@ -75,7 +70,7 @@ export class RasterizeLayerController {baked.ctx.clearRect(0, 0, bakedRect.width, bakedRect.height);baked.ctx.imageSmoothingEnabled = true;baked.ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - bakedRect.x, matrix.f - bakedRect.y);- baked.ctx.drawImage(entry.surface.canvas, contentRect.x, contentRect.y);+ baked.ctx.drawImage(scratch.canvas, contentRect.x, contentRect.y);baked.ctx.setTransform(1, 0, 0, 1, 0, 0);const paintLayer: CanvasLayerContract = {...liveLayer,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.tsindex 5216966127..83186fe396 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts@@ -1,7 +1,7 @@import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';-import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import type { LayerCacheEntryState, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { PixelEditTransaction } from '@workbench/canvas-engine/tools/tool';@@ -121,18 +121,7 @@ export class SelectionPixelController {let editSurface: RasterSurface | null = null;let commitStarted = false;let rollbackStarted = false;- let growthSnapshot:- | {- hasPublishedPixels: boolean;- lastUsed: number;- pixels: ImageData | null;- rect: Rect;- stale: boolean;- surface: RasterSurface;- version: number;- }- | null- | undefined;+ let growthSnapshot: { pixels: ImageData | null; state: LayerCacheEntryState } | null | undefined;const rollback = (): void => {if (target.kind !== 'control' || rollbackStarted) {return;@@ -140,23 +129,15 @@ export class SelectionPixelController {rollbackStarted = true;try {if (growthSnapshot !== undefined) {- if (growthSnapshot === null) {- this.deps.layers.delete(layerId);- } else {- const current = this.deps.layers.get(layerId);- if (current) {- growthSnapshot.surface.resize(growthSnapshot.rect.width, growthSnapshot.rect.height);- if (growthSnapshot.pixels) {- growthSnapshot.surface.ctx.putImageData(growthSnapshot.pixels, 0, 0);- }- current.hasPublishedPixels = growthSnapshot.hasPublishedPixels;- current.lastUsed = growthSnapshot.lastUsed;- current.rect = { ...growthSnapshot.rect };- current.stale = growthSnapshot.stale;- current.surface = growthSnapshot.surface;- current.version = growthSnapshot.version;+ if (growthSnapshot) {+ const { pixels, state } = growthSnapshot;+ state.surface.resize(state.rect.width, state.rect.height);+ if (pixels) {+ state.surface.ctx.putImageData(pixels, 0, 0);}}+ // An exact rollback; the store re-accounts the reinstated surface.+ this.deps.layers.restoreState(layerId, growthSnapshot?.state ?? null);this.deps.deleteDerived(layerId);this.deps.invalidateLayer(layerId);} else if (before && editOrigin && editRect && editSurface) {@@ -179,19 +160,16 @@ export class SelectionPixelController {selectionRect.x + selectionRect.width > existing.rect.x + existing.rect.width ||selectionRect.y + selectionRect.height > existing.rect.y + existing.rect.height;if (needsGrowth) {- growthSnapshot = existing- ? {- hasPublishedPixels: existing.hasPublishedPixels,- lastUsed: existing.lastUsed,- pixels: isEmpty(existing.rect)- ? null- : existing.surface.ctx.getImageData(0, 0, existing.rect.width, existing.rect.height),- rect: { ...existing.rect },- stale: existing.stale,- surface: existing.surface,- version: existing.version,- }- : null;+ const state = this.deps.layers.captureState(layerId);+ growthSnapshot =+ existing && state+ ? {+ pixels: isEmpty(existing.rect)+ ? null+ : existing.surface.ctx.getImageData(0, 0, existing.rect.width, existing.rect.height),+ state,+ }+ : null;}}let rect: Rect | null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.tsindex 18952c4ce1..a4c8df534e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/diagnostics.ts@@ -26,7 +26,7 @@ const zeroSnapshot = (): MutableCanvasDiagnosticsSnapshot => ({layersCulled: 0,layersDrawn: 0,overlayFrames: 0,- overBudgetVisibleBaseBytes: 0,+ rasterOverageBytes: 0,surfaceCreations: 0,surfaceResizes: 0,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.tsindex 3c77672337..87262b81fd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts@@ -205,11 +205,15 @@ describe('image-layer erasing with real browser pixels', () => {getLayerSource: () => currentSource,getLayerSurface: (layerId) => {const entry = layers.get(layerId);- return entry && entry.rect.width > 0 && entry.rect.height > 0+ if (!entry) {+ return null;+ }+ return entry.rect.width > 0 && entry.rect.height > 0? { offset: { x: entry.rect.x, y: entry.rect.y }, surface: entry.surface }- : null;+ : 'empty';},- trimLayerPixels: (layerId) => trimPaintCacheToAlpha({ isLayerBusy: () => false, layers }, layerId),+ trimLayerPixels: (layerId) =>+ trimPaintCacheToAlpha({ isLayerBusy: () => false, isLayerPinned: () => false, layers }, layerId),uploadImage,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.tsindex 9ce0a4ed12..7e7738e9eb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts@@ -30,6 +30,20 @@ vi.mock('./controllers/rasterController', async (importOriginal) => {});const RECT = { height: 10, width: 10, x: 0, y: 0 };+// Stub surfaces record calls without allocating, so a cache this size only exceeds the 512 MiB budget on paper.+const OVER_BUDGET_RECT = { height: 12_000, width: 12_000, x: 0, y: 0 };++const fakeCanvas = (): HTMLCanvasElement => {+ const surface = createTestStubRasterBackend().createSurface(100, 100);+ return {+ addEventListener: () => undefined,+ getBoundingClientRect: () => ({ height: 100, left: 0, top: 0, width: 100 }),+ getContext: () => surface.ctx,+ height: 100,+ removeEventListener: () => undefined,+ width: 100,+ } as unknown as HTMLCanvasElement;+};const createEngine = (bitmapStore?: BitmapStore) => {const document = documentFrom([groupContract('group', [layerContract('layer')], { opacity: 0.5 })]);@@ -64,6 +78,71 @@ const createEngine = (bitmapStore?: BitmapStore) => {return { engine, raster };};+const offscreenDocument = () =>+ documentFrom(+ ['visible', 'dirty', 'held', 'hidden'].map((id, index) =>+ layerContract(id, 'raster', { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: index * 100_000, y: 0 } })+ )+ );++const createFramedEngine = (pendingLayerIds: ReadonlySet<string>) => {+ const document = offscreenDocument();+ const canvas = { document, documentRevision: 0, snapshots: [], version: 3 };+ const store = {+ discardLayer: vi.fn(),+ dispose: vi.fn(),+ flushPendingUploads: () => Promise.resolve(),+ hasPendingClear: () => false,+ hasPendingWork: (layerId: string) => pendingLayerIds.has(layerId),+ isSelfEcho: () => false,+ markLayerDirty: vi.fn(),+ reset: vi.fn(),+ suspendLayer: () => () => undefined,+ } satisfies BitmapStore;+ const { engine } = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: store,+ fonts: null,+ imageResolver: () => Promise.resolve(new Blob()),+ mutationPort: {+ commitEdit: () => undefined,+ dispatch: () => false,+ getCanvasState: () => canvas,+ subscribe: () => () => undefined,+ } as unknown as CanvasProjectMutationPort,+ projectId: 'project',+ reportError: () => undefined,+ uploadImage: () => Promise.resolve({ height: 10, imageName: 'unused', width: 10 }),+ uploadIntermediateImage: () => Promise.resolve({ height: 10, imageName: 'unused', width: 10 }),+ });+ const raster = owners.raster!;+ for (const layerId of ['dirty', 'held', 'hidden']) {+ raster.layers.getOrCreateRect(layerId, OVER_BUDGET_RECT);+ raster.layers.publishPixels(layerId);+ }+ return { engine, raster };+};++describe('engine working-set protection', () => {+ it('keeps unsaved and session-held offscreen pixels when a frame enforces the budget', () => {+ const { engine, raster } = createFramedEngine(new Set(['dirty']));+ engine.stores.transformSession.set({+ layerId: 'held',+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 100_000 * 2, y: 0 },+ } as Parameters<typeof engine.stores.transformSession.set>[0]);++ engine.surface.attach(fakeCanvas(), fakeCanvas());+ engine.surface.resize(100, 100, 1);++ expect(raster.layers.peek('hidden')).toBeUndefined();+ expect(raster.layers.peek('dirty')).toBeDefined();+ expect(raster.layers.peek('held')).toBeDefined();+ expect(raster.memory.snapshot().overageBytes).toBeGreaterThan(0);+ engine.stores.transformSession.set(null);+ engine.lifecycle.dispose();+ });+});+describe('engine raster resource lifecycle', () => {it('releases base, derived and group surfaces after a successful cooldown', async () => {const { engine, raster } = createEngine();@@ -96,12 +175,15 @@ describe('engine raster resource lifecycle', () => {engine.lifecycle.dispose();});- it('releases every resource category deterministically on disposal', () => {+ it('releases every resource category deterministically on disposal', async () => {const { engine, raster } = createEngine();+ const bitmap = { close: vi.fn(), height: 10, width: 10 } as unknown as ImageBitmap;+ await raster.bitmaps.acquire('decoded', () => Promise.resolve(bitmap));+ expect(raster.memory.snapshot().decodedBytes).toBe(400);raster.memory.reserve(100, { generation: 0, purpose: 'thumbnail' });raster.memory.reserveOperation(100, { purpose: 'layer-operation' });raster.memory.trackDetached(100);- raster.pin('layer');+ raster.memory.pin('layer');engine.lifecycle.dispose();@@ -116,5 +198,6 @@ describe('engine raster resource lifecycle', () => {totalBytes: 0,});expect(raster.isProtected('layer')).toBe(false);+ expect(bitmap.close).toHaveBeenCalledOnce();});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 9cd148ea07..fc0e9f22e2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -5532,8 +5532,11 @@ describe('mergeLayerDown', () => {expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(true);- // No pixels require allocation; zero-sized union canvases would throw.- expect(surfaces.length).toBe(surfacesBeforeMerge);+ // Only the merged layer's empty cache is allocated; zero-sized union canvases would throw.+ expect(surfaces.length).toBe(surfacesBeforeMerge + 1);+ expect(surfaces.at(-1)).toMatchObject({ height: 0, width: 0 });+ // The merged layer is empty, not lost: the paint barrier succeeds.+ await expect(engine.lifecycle.flushPendingUploads()).resolves.toBeUndefined();engine.lifecycle.dispose();});@@ -7927,11 +7930,12 @@ describe('rasterizeLayer (parametric → paint)', () => {}}- const baked = surfaces[before];+ const baked = surfaces+ .slice(before)+ .find(+ (surface) => surface.width === 60 && surface.height === 40 && surface.callLog.some((e) => e.op === 'drawImage')+ );expect(baked).toBeDefined();- expect(baked?.width).toBe(60);- expect(baked?.height).toBe(40);- expect(baked?.callLog.some((e) => e.op === 'drawImage')).toBe(true);engine.lifecycle.dispose();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 868cd1bc0e..f30bcad574 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -347,11 +347,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbackend,diagnostics,getDocument: () => mirror.getDocument(),- // Pixel transactions already bake adjustments into the live cache; drawing them through the group again would- // apply them twice.- getGroupMemberSurface: (layer, entry) => getAdjustedSurface(layer, entry),getLayerImageName: layerImageName,imageResolver,+ // A raster-image pixel transaction replaces the live cache with pixels that already include adjustments while+ // the contract keeps them until commit; applying them again would double them and snap back on pointer-up.+ isAdjustmentBaked: (layerId) => pixelEditController?.isOpenFor([layerId]) === true,isLayerHeld: (layerId) => isLayerHeldBySession(layerId) || bitmapStore.hasPendingWork(layerId),onVersionChange: (layerId) => editingController?.invalidateLayer(layerId),});@@ -465,16 +465,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// Adjusted raster surfaces rebuild on cache-version or adjustment changes, not each frame.const derivedSurfaceCache = rasterController.derived;const deleteDerivedSurfaces = (layerId: string): void => rasterController.deleteDerivedSurfaces(layerId);- const getAdjustedSurface = (layer: CanvasLayerContract, entry: LayerCacheEntry): RasterSurface | null => {- if (layer.type === 'raster' && pixelEditController?.isOpenFor([layer.id])) {- // A raster-image pixel transaction replaces the live cache with pixels- // that already include adjustments while leaving the reducer contract- // untouched until commit. Drawing that preview through the contract's- // adjustments would apply them twice and snap back on pointer-up.- return null;- }- return rasterController.getAdjustedSurface(layer, entry);- };+ const getAdjustedSurface = (layer: CanvasLayerContract, entry: LayerCacheEntry): RasterSurface | null =>+ rasterController.getAdjustedSurface(layer, entry);const groupSurfaces = rasterController.groups;const getGroupSurface: NonNullable<CompositeOptions['groupSurface']> = (scope, members, matrices, excludeIds) =>@@ -574,9 +566,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC);}- /** Defer trim while a gesture, session, pinned read or rasterization depends on the cache bounds. */+ /** Defer trim while a gesture, session or rasterization depends on the cache bounds. */const isLayerBusyForTrim = (layerId: string): boolean => {- if (pipeline.isGestureActive() || isLayerHeldBySession(layerId) || rasterController.memory.isPinned(layerId)) {+ if (pipeline.isGestureActive() || isLayerHeldBySession(layerId)) {return true;}const layer = getDocumentLayer(mirror.getDocument(), layerId);@@ -591,7 +583,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCdispatchBitmap: (layerId, bitmap, offset) => dispatchLayerBitmap(layerId, bitmap, offset),encodeSurface: (surface) => backend.encodeSurface(surface),trimLayerPixels: (layerId) => {- const result = trimPaintCacheToAlpha({ isLayerBusy: isLayerBusyForTrim, layers: layerCache }, layerId);+ const result = trimPaintCacheToAlpha(+ {+ isLayerBusy: isLayerBusyForTrim,+ isLayerPinned: (candidate) => rasterController.memory.isPinned(candidate),+ layers: layerCache,+ },+ layerId+ );if (result === 'emptied' || result === 'trimmed') {// Derived surfaces are keyed on the old extent; both calls are synchronous,// so they land before the clear dispatch and no frame sees a mismatch.@@ -1187,7 +1186,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCisSupportedSource: isSupportedExportSource,layers: layerCache,invalidateLayerCache,- pin: (layerId) => rasterController.pin(layerId),+ pin: (layerId) => rasterController.memory.pin(layerId),reserve: (bytes) =>rasterController.memory.reserve(bytes, { generation: lifecycleGeneration, purpose: 'raster-export' }),waitForFont: fontLoader.waitForReady,@@ -2148,7 +2147,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCpreparePixels: prepareGeneratedPaintCache,prepareDuplicateRasterSource: prepareLayerRasterCache,pinDuplicateRasterSources: (layerIds) => {- const leases = layerIds.map((layerId) => rasterController.pin(layerId));+ const leases = layerIds.map((layerId) => rasterController.memory.pin(layerId));return {release: () => {for (const lease of leases) {@@ -2513,7 +2512,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCsnapshot.documentGeneration === rasterController.getDocumentGeneration() &&snapshot.lifecycleGeneration === lifecycleGeneration,pin: (layerIds) => {- const leases = layerIds.map((layerId) => rasterController.pin(layerId));+ const leases = layerIds.map((layerId) => rasterController.memory.pin(layerId));return {release: () => {for (const lease of leases) {@@ -2694,7 +2693,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetMaskPattern: getMaskPatternTile,isDisposed: () => disposed,isSupportedSource: isSupportedExportSource,- pin: (layerId) => rasterController.pin(layerId),+ pin: (layerId) => rasterController.memory.pin(layerId),projectId,rasterize: rasterizeLayerForThumbnail,reportError: (layerId, error) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.tsindex eb1fcbd12a..93fe95bd74 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts@@ -58,11 +58,7 @@ export const createDerivedSurfaceCache = (return;}totalBytes += delta;- try {- onBytesChange?.(totalBytes);- } catch {- // Accounting observers cannot veto an allocation that already happened.- }+ onBytesChange?.(totalBytes);};const remove = (key: string, entry: CacheEntry): void => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.tsindex b223c58d33..bd929475cb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts@@ -75,11 +75,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacreturn;}totalBytes += delta;- try {- deps.onBytesChange?.(totalBytes);- } catch {- // Accounting observers cannot veto an allocation that already happened.- }+ deps.onBytesChange?.(totalBytes);};const dropSlots = (slots: readonly GroupSlot[]): void => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.tsindex caaf92a449..455d416f9c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts@@ -213,6 +213,8 @@ describe('createLayerCacheStore', () => {expect(store.byteSize()).toBe(64);store.restoreState('a', before);expect(store.byteSize()).toBe(400);+ // An exact rollback: guards captured before the replacement describe the reinstated entry again.+ expect(store.peek('a')).toMatchObject({ rect: before!.rect, surface: before!.surface, version: before!.version });store.publishRasterized('b', { height: 2, width: 3, x: 0, y: 0 }, backend.createSurface(3, 2));store.delete('a');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.tsindex 23326d4277..05627ed524 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts@@ -112,7 +112,10 @@ export interface LayerCacheStore {publishRasterized(layerId: string, rect: Rect, pixels: RasterSurface, renderedFontFamily?: string): LayerCacheEntry;/** The entry's current state, or null when absent; the surface is shared, not copied. */captureState(layerId: string): LayerCacheEntryState | null;- /** Reinstates a captured state (null deletes the entry), keeping byte accounting exact. */+ /**+ * Reinstates a captured state exactly (null deletes the entry), version included, so guards captured before a+ * rolled-back transaction stay current. The caller discards artifacts derived from versions issued since.+ */restoreState(layerId: string, state: LayerCacheEntryState | null): void;/*** Publish direct writes as current, bump version and notify. Optional surface-local damage enables partial@@ -151,13 +154,7 @@ export const createLayerCacheStore = (const accountedBytes = new Map<string, number>();let totalBytes = 0;- const reportBytes = (): void => {- try {- options.onBytesChange?.(totalBytes);- } catch {- // Accounting observers cannot veto an allocation that already happened.- }- };+ const reportBytes = (): void => options.onBytesChange?.(totalBytes);/** Brings the running total in line with the entry's current surface. */const account = (entry: LayerCacheEntry): void => {@@ -496,17 +493,15 @@ export const createLayerCacheStore = (del(layerId);return;}- const entry = entries.get(layerId);- if (entry) {- Object.assign(entry, { ...state, rect: { ...state.rect } });- touch(entry);- damageTrails.delete(layerId);- account(entry);- notifyVersionChange(layerId);- return;- }- const restored: LayerCacheEntry = { ...state, lastUsed: 0, layerId, rect: { ...state.rect } };+ const restored: LayerCacheEntry = entries.get(layerId) ?? {+ ...state,+ lastUsed: 0,+ layerId,+ rect: { ...state.rect },+ };+ Object.assign(restored, { ...state, rect: { ...state.rect } });touch(restored);+ damageTrails.delete(layerId);entries.set(layerId, restored);account(restored);notifyVersionChange(layerId);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.tsindex 6b62d90294..2fc298f817 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts@@ -18,7 +18,7 @@ const published = () => {const store = createLayerCacheStore(createDomRasterBackend());const entry = store.growToRect('L', START);store.publishPixels('L');- return { deps: { isLayerBusy: () => false, layers: store }, entry, store };+ return { deps: { isLayerBusy: () => false, isLayerPinned: () => false, layers: store }, entry, store };};/** Fills a 10x10 mark addressed in LAYER-LOCAL space. */diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.tsindex 51d41cb001..972d83e04d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts@@ -6,10 +6,10 @@ import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/rasimport { describe, expect, it, vi } from 'vitest';/** Zero-alpha stub readbacks exercise empty-cache verdicts and guards; browser tests verify actual cropping. */-const harness = (options: { busy?: boolean } = {}) => {+const harness = (options: { busy?: boolean; pinned?: boolean } = {}) => {const store = createLayerCacheStore(createTestStubRasterBackend({ readbackAlpha: 0 }));const isLayerBusy = vi.fn(() => options.busy ?? false);- return { deps: { isLayerBusy, layers: store }, isLayerBusy, store };+ return { deps: { isLayerBusy, isLayerPinned: () => options.pinned ?? false, layers: store }, isLayerBusy, store };};/** A published 40x40 cache at (10,10) — the shape a chunk-padded stroke leaves. */@@ -65,6 +65,15 @@ describe('trimPaintCacheToAlpha', () => {expect((entry.surface as StubRasterSurface).callLog.map((e) => e.op)).not.toContain('getImageData');});+ it('KEEPS a pinned cache untrimmed so persistence never waits on a read lease', () => {+ const { deps, store } = harness({ pinned: true });+ const entry = publish(store);++ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('kept');+ expect(entry.rect).toEqual({ height: 40, width: 40, x: 10, y: 10 });+ expect((entry.surface as StubRasterSurface).callLog.map((e) => e.op)).not.toContain('getImageData');+ });+it('EMPTIES a published cache holding no visible alpha, collapsing it to a zero rect', () => {const { deps, store } = harness();const entry = publish(store);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.tsindex a42bb9ebf2..dc126bb843 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts@@ -18,8 +18,10 @@ export type PaintCacheTrim = 'deferred' | 'emptied' | 'kept' | 'trimmed';export interface TrimPaintCacheDeps {readonly layers: LayerCacheStore;- /** Injected by the engine, so this module stays free of engine knowledge. */+ /** A gesture, session or rasterization owns the pixels; persistence retries once it ends. */readonly isLayerBusy: (layerId: string) => boolean;+ /** A read lease holds the surface; persist it untrimmed rather than reshaping pixels it reads. */+ readonly isLayerPinned: (layerId: string) => boolean;}export const trimPaintCacheToAlpha = (deps: TrimPaintCacheDeps, layerId: string): PaintCacheTrim => {@@ -34,6 +36,9 @@ export const trimPaintCacheToAlpha = (deps: TrimPaintCacheDeps, layerId: string)if (!entry.hasPublishedPixels || entry.stale || deps.isLayerBusy(layerId)) {return 'deferred';}+ if (deps.isLayerPinned(layerId)) {+ return 'kept';+ }const bounds = alphaBounds(entry.surface.ctx.getImageData(0, 0, entry.rect.width, entry.rect.height));if (isEmpty(bounds)) {deps.layers.shrinkToRect(layerId, { height: 0, width: 0, x: entry.rect.x, y: entry.rect.y });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.tsindex 1e02da4f89..3532ee0984 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts@@ -21,7 +21,7 @@ import {} from '@workbench/canvas-operations/generationCompositePlan';import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { createCanvasHeldMediaSources } from '@workbench/projects/projectAssets';+import { createLiveCanvasEngines } from '@workbench/projects/projectAssets';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';@@ -147,39 +147,39 @@ const createFakeTimers = (): { timers: RegistryTimers; flush: () => void; pendindescribe('createEngineRegistry', () => {it('disposes the process registry synchronously when its account expires', () => {accountLifecycle.activate('user-a');- const heldMedia = createCanvasHeldMediaSources();- const engine = getOrCreateEngine('shared-project-id', { ...createFakeDeps(), heldMedia });+ const liveEngines = createLiveCanvasEngines();+ const engine = getOrCreateEngine('shared-project-id', { ...createFakeDeps(), liveEngines });const dispose = vi.spyOn(engine.lifecycle, 'dispose');- expect(heldMedia.read('shared-project-id')).toEqual({ images: [], videos: [] });+ expect(liveEngines.heldAssets('shared-project-id')).toEqual({ images: [], videos: [] });accountLifecycle.invalidate();expect(getCanvasEngine('shared-project-id')).toBeUndefined();- expect(heldMedia.read('shared-project-id')).toBeUndefined();+ expect(liveEngines.heldAssets('shared-project-id')).toBeUndefined();expect(dispose).toHaveBeenCalledOnce();});it('keeps a released engine for its own Workbench but replaces it for a remounted one', () => {const { flush, timers } = createFakeTimers();const registry = createEngineRegistry({ timers });- const first = createCanvasHeldMediaSources();- const second = createCanvasHeldMediaSources();+ const first = createLiveCanvasEngines();+ const second = createLiveCanvasEngines();const onHeldChange = vi.fn();first.subscribe(onHeldChange);- const engine = registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: first });+ const engine = registry.getOrCreateEngine('p1', { ...createFakeDeps(), liveEngines: first });registry.releaseEngine('p1');- expect(registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: first })).toBe(engine);+ expect(registry.getOrCreateEngine('p1', { ...createFakeDeps(), liveEngines: first })).toBe(engine);registry.releaseEngine('p1');const dispose = vi.spyOn(engine.lifecycle, 'dispose');onHeldChange.mockClear();- const replacement = registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: second });+ const replacement = registry.getOrCreateEngine('p1', { ...createFakeDeps(), liveEngines: second });expect(replacement).not.toBe(engine);expect(dispose).toHaveBeenCalledOnce();- expect(first.read('p1')).toBeUndefined();+ expect(first.heldAssets('p1')).toBeUndefined();expect(onHeldChange).toHaveBeenCalled();- expect(second.read('p1')).toEqual({ images: [], videos: [] });+ expect(second.heldAssets('p1')).toEqual({ images: [], videos: [] });flush();expect(registry.getEngine('p1')).toBe(replacement);registry.disposeAll();@@ -187,14 +187,14 @@ describe('createEngineRegistry', () => {it('refuses an engine another Workbench still uses instead of sharing or replacing it', () => {const registry = createEngineRegistry();- const first = createCanvasHeldMediaSources();- const engine = registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: first });+ const first = createLiveCanvasEngines();+ const engine = registry.getOrCreateEngine('p1', { ...createFakeDeps(), liveEngines: first });expect(() =>- registry.getOrCreateEngine('p1', { ...createFakeDeps(), heldMedia: createCanvasHeldMediaSources() })+ registry.getOrCreateEngine('p1', { ...createFakeDeps(), liveEngines: createLiveCanvasEngines() })).toThrow(/another Workbench/);expect(registry.getEngine('p1')).toBe(engine);- expect(first.read('p1')).toEqual({ images: [], videos: [] });+ expect(first.heldAssets('p1')).toEqual({ images: [], videos: [] });registry.disposeAll();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.tsindex f54851e681..42df80249a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts@@ -4,7 +4,7 @@*/import type { CanvasEngine as PublicCanvasEngine } from '@workbench/canvas-engine/api';-import type { CanvasHeldMediaSources } from '@workbench/projects/projectAssets';+import type { LiveCanvasEngines } from '@workbench/projects/projectAssets';import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import {@@ -19,7 +19,7 @@ export type EngineDeps = Omit<CanvasEngineOptions, 'projectId'> & {* The mounted Workbench's held-media registry. It also identifies that Workbench: an engine is bound to the one* that created it, so a released engine is replaced rather than reused by the next Workbench.*/- heldMedia?: CanvasHeldMediaSources;+ liveEngines?: LiveCanvasEngines;};/** Default grace period before a released engine is disposed (30s). */@@ -45,8 +45,8 @@ export interface EngineRegistry {interface RegistryEntry {engine: CanvasEngine;- heldMedia: CanvasHeldMediaSources | undefined;- releaseHeldMedia: () => void;+ liveEngines: LiveCanvasEngines | undefined;+ releaseLiveEngine: () => void;refCount: number;disposeHandle: number | null;generation: number;@@ -89,7 +89,7 @@ export const createEngineRegistry = (return;}entries.delete(projectId);- entry.releaseHeldMedia();+ entry.releaseLiveEngine();entry.engine.lifecycle.dispose();});}, gracePeriodMs);@@ -103,7 +103,7 @@ export const createEngineRegistry = (entries.clear();for (const entry of ownedEntries) {cancelDisposal(entry);- entry.releaseHeldMedia();+ entry.releaseLiveEngine();try {entry.engine.lifecycle.dispose();} catch (error) {@@ -118,13 +118,13 @@ export const createEngineRegistry = (}},getEngine: (projectId) => entries.get(projectId)?.engine,- getOrCreateEngine: (projectId, { heldMedia, ...deps }) => {+ getOrCreateEngine: (projectId, { liveEngines, ...deps }) => {const existing = entries.get(projectId);- if (existing && existing.heldMedia !== heldMedia && existing.refCount > 0) {+ if (existing && existing.liveEngines !== liveEngines && existing.refCount > 0) {// Its edits and held media belong to the Workbench still using it; sharing it would cross that boundary.throw new Error(`The canvas engine for project ${projectId} is still in use by another Workbench.`);}- if (existing && existing.heldMedia === heldMedia) {+ if (existing && existing.liveEngines === liveEngines) {cancelDisposal(existing);existing.generation += 1;existing.refCount += 1;@@ -136,14 +136,14 @@ export const createEngineRegistry = (// A released engine still writes through the Workbench that created it; a new Workbench gets its own.entries.delete(projectId);cancelDisposal(existing);- existing.releaseHeldMedia();+ existing.releaseLiveEngine();existing.engine.lifecycle.dispose();}const engine = createCanvasEngine({ projectId, ...deps });- const releaseHeldMedia =- heldMedia?.register(projectId, {+ const releaseLiveEngine =+ liveEngines?.register(projectId, {flushPendingPixels: () => engine.lifecycle.flushPendingUploads(),- read: () => engine.history.getHeldAssetRefs(),+ heldAssets: () => engine.history.getHeldAssetRefs(),subscribe: (listener) => engine.interaction.subscribe('historyEpoch', listener),}) ?? (() => undefined);entries.set(projectId, {@@ -151,9 +151,9 @@ export const createEngineRegistry = (disposeHandle: null,engine,generation: 0,- heldMedia,+ liveEngines,refCount: 1,- releaseHeldMedia,+ releaseLiveEngine,});return engine;},diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.tsindex 99b5754394..1d82499ae7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts@@ -9,7 +9,7 @@ import { resolveDefaultControlModelForBase } from '@workbench/widgets/layers/conimport { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';import {useActiveProjectId,- useWorkbenchCanvasHeldMedia,+ useWorkbenchLiveCanvasEngines,useWorkbenchCommands,useWorkbenchInternalStore,useWorkbenchPersistenceService,@@ -69,7 +69,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {const fonts = useFontRuntime();const store = useWorkbenchInternalStore();const persistence = useWorkbenchPersistenceService();- const heldMedia = useWorkbenchCanvasHeldMedia();+ const liveEngines = useWorkbenchLiveCanvasEngines();const { notifications } = useWorkbenchCommands();const projectId = useActiveProjectId();const resource = useMemo(@@ -85,7 +85,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {throw new DOMException('The canvas project is no longer open.', 'AbortError');}},- heldMedia,+ liveEngines,getDefaultControlModel: (base) => resolveDefaultControlModelForBase(getModelsSnapshot().models, base),getMainModelBase: () => {const project = store.getState().projects.find((candidate) => candidate.id === projectId);@@ -102,7 +102,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {mutationPort: createCanvasProjectMutationPort(store, projectId),reportError: notifications.reportError,}),- [fonts, heldMedia, notifications.reportError, persistence, projectId, store]+ [fonts, liveEngines, notifications.reportError, persistence, projectId, store]);return useSyncExternalStore(resource.subscribe, resource.getSnapshot, resource.getSnapshot);diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.tsindex 794cf786be..b674bf1e16 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from 'vitest';import {collectHeldAssetRefs,collectLiveAssetRefs,- createCanvasHeldMediaSources,+ createLiveCanvasEngines,createOpenProjectsHeldMediaReader,remapAssetRefs,selectCoverImageName,@@ -136,31 +136,31 @@ it('rescans only the workflow an edit touched, sharing the documents its history});it('announces engines registering and releasing their held media', () => {- const sources = createCanvasHeldMediaSources();+ const sources = createLiveCanvasEngines();const onChange = vi.fn();sources.subscribe(onChange);let notifyEngine = () => undefined as void;const release = sources.register('project-1', {flushPendingPixels: () => Promise.resolve(),- read: () => ({ images: ['undo.png'], videos: [] }),+ heldAssets: () => ({ images: ['undo.png'], videos: [] }),subscribe: (listener) => {notifyEngine = listener;return () => undefined;},});- expect(sources.read('project-1')).toEqual({ images: ['undo.png'], videos: [] });+ expect(sources.heldAssets('project-1')).toEqual({ images: ['undo.png'], videos: [] });notifyEngine();release();- expect(sources.read('project-1')).toBeUndefined();+ expect(sources.heldAssets('project-1')).toBeUndefined();expect(onChange).toHaveBeenCalledTimes(3);});it("crosses a registered engine's paint barrier and treats an unregistered project as saved", async () => {- const sources = createCanvasHeldMediaSources();+ const sources = createLiveCanvasEngines();const flushPendingPixels = vi.fn(() => Promise.reject(new Error('upload failed')));sources.register('project-1', {flushPendingPixels,- read: () => ({ images: [], videos: [] }),+ heldAssets: () => ({ images: [], videos: [] }),subscribe: () => () => undefined,});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.tsindex 20d250afff..5ed7a2b4d8 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts@@ -48,29 +48,29 @@ export interface CanvasHeldAssetRefs {}/** What a live Canvas engine holds beyond the document: media its undo state retains, and unsaved pixels. */-export interface CanvasHeldMediaSource {- read(): CanvasHeldAssetRefs;+export interface LiveCanvasEngine {+ heldAssets(): CanvasHeldAssetRefs;subscribe(listener: () => void): () => void;/** Persists the engine's unsaved pixels into the document; rejects when they cannot be saved. */flushPendingPixels(): Promise<void>;}/** One mounted Workbench's live Canvas engines, each registered for as long as its undo state survives. */-export interface CanvasHeldMediaSources {- read(projectId: string): CanvasHeldAssetRefs | undefined;- register(projectId: string, source: CanvasHeldMediaSource): () => void;+export interface LiveCanvasEngines {+ heldAssets(projectId: string): CanvasHeldAssetRefs | undefined;+ register(projectId: string, source: LiveCanvasEngine): () => void;subscribe(listener: () => void): () => void;/** Crosses the project's paint barrier; a project without a live engine has nothing unsaved. */flushPendingPixels(projectId: string): Promise<void>;}-export const createCanvasHeldMediaSources = (): CanvasHeldMediaSources => {- const sources = new Map<string, CanvasHeldMediaSource>();+export const createLiveCanvasEngines = (): LiveCanvasEngines => {+ const sources = new Map<string, LiveCanvasEngine>();const listeners = new Set<() => void>();const notify = (): void => listeners.forEach((listener) => listener());return {flushPendingPixels: (projectId) => sources.get(projectId)?.flushPendingPixels() ?? Promise.resolve(),- read: (projectId) => sources.get(projectId)?.read(),+ heldAssets: (projectId) => sources.get(projectId)?.heldAssets(),register: (projectId, source) => {sources.set(projectId, source);const unsubscribe = source.subscribe(notify);diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsxindex aca02a757c..cbb637fa6d 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx@@ -30,7 +30,7 @@ vi.mock('./library', () => ({vi.mock('@tanstack/react-router', () => ({ useNavigate: () => harness.navigate }));vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: harness.notifyError }) }));vi.mock('@workbench/WorkbenchContext', () => ({- useWorkbenchCanvasHeldMedia: () => ({ flushPendingPixels: harness.flushCanvasPixels }),+ useWorkbenchLiveCanvasEngines: () => ({ flushPendingPixels: harness.flushCanvasPixels }),useWorkbenchCommands: () => ({ projects: { close: harness.close } }),useWorkbenchPersistenceAdapter: () => ({ getState: () => ({ projects: [harness.project] }) }),useWorkbenchPersistenceService: () => ({@@ -118,7 +118,7 @@ describe('useProjectActions', () => {await act(() => userEvent.click(document.querySelector('button')!));await vi.waitFor(() => expect(harness.notifyError).toHaveBeenCalledOnce());- expect(harness.notifyError).toHaveBeenCalledWith('projects.closeBlocked', 'projects.file.notSynced');+ expect(harness.notifyError).toHaveBeenCalledWith('projects.closeBlocked', 'projects.canvasPixelsNotSaved');expect(harness.flush).not.toHaveBeenCalled();expect(harness.close).not.toHaveBeenCalled();});@@ -136,6 +136,10 @@ describe('useProjectActions', () => {expect(harness.flushCanvasPixels.mock.invocationCallOrder[0]).toBeLessThan(harness.flush.mock.invocationCallOrder[0]!);+ // Pixels painted while the document was being pushed are persisted before the tab closes.+ expect(harness.flushCanvasPixels.mock.invocationCallOrder[1]).toBeGreaterThan(+ harness.flush.mock.invocationCallOrder[0]!+ );});it('reports a rejected close flush and keeps the tab open', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.tsindex 5813aca7b0..c523b6de80 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts@@ -11,7 +11,7 @@ import { useNavigate } from '@tanstack/react-router';import { hasActiveQueueRuns } from '@workbench/queue-integration/activeQueueRuns';import { useNotify } from '@workbench/useNotify';import {- useWorkbenchCanvasHeldMedia,+ useWorkbenchLiveCanvasEngines,useWorkbenchCommands,useWorkbenchPersistenceAdapter,useWorkbenchPersistenceService,@@ -38,7 +38,7 @@ export const useProjectActions = (): {const persistence = useWorkbenchPersistenceAdapter();const persistenceService = useWorkbenchPersistenceService();const commands = useWorkbenchCommands();- const canvasEngines = useWorkbenchCanvasHeldMedia();+ const canvasEngines = useWorkbenchLiveCanvasEngines();const navigate = useNavigate();const notify = useNotify();const { t } = useTranslation();@@ -126,18 +126,28 @@ export const useProjectActions = (): {return;}+ /** Crosses the canvas paint barrier; false (with a notice) when unsaved pixels cannot be persisted. */+ const persistCanvasPixels = async (): Promise<boolean> => {+ try {+ await canvasEngines.flushPendingPixels(project.id);+ return true;+ } catch (error) {+ assertAccountScopeCurrent(owner);+ notify.error(+ t('projects.closeBlocked'),+ t('projects.canvasPixelsNotSaved', { reason: getApiErrorMessage(error, t('projects.file.notSynced')) })+ );+ return false;+ }+ };+void (async () => {for (let attempt = 0; attempt < CLOSE_FLUSH_ATTEMPTS; attempt += 1) {const current = queries.getProject(project.id);if (!current) {return;}- // Unsaved canvas pixels must reach the document before it is flushed; otherwise the engine keeps them open.- try {- await canvasEngines.flushPendingPixels(project.id);- } catch {- assertAccountScopeCurrent(owner);- notify.error(t('projects.closeBlocked'), t('projects.file.notSynced'));+ if (!(await persistCanvasPixels())) {return;}assertAccountScopeCurrent(owner);@@ -152,6 +162,10 @@ export const useProjectActions = (): {notify.error(t('projects.closeBlocked'), t('projects.file.notSynced'));return;}+ // Pixels painted while the document was pushed change it again, so the comparison below retries.+ if (!(await persistCanvasPixels())) {+ return;+ }if (outcome.kind === 'acknowledged' &&serializeProjectDocumentV3Json(queries.getProject(project.id) ?? current).documentJson !==