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): make layer duplication reliable
Josh Corbettc887a34824fb
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 0497d42329..d0ea2c8306 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -312,10 +312,9 @@ export interface FilterPreviewInput {* fewer than two eligible rasters have content.*/export type MergeVisibleResult = 'merged' | 'not-ready' | 'over-budget' | 'busy' | 'nothing';-export interface DuplicateLayersResult {- readonly duplicateIds: readonly string[];- readonly selectedLayerId: string;-}+export type DuplicateLayersResult =+ | { readonly status: 'duplicated'; readonly duplicateIds: readonly string[]; readonly selectedLayerId: string }+ | { readonly status: 'busy' | 'nothing' | 'not-ready' | 'over-budget' | 'stale' };export type BooleanRasterResult = 'merged' | 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty';export type ExtractMaskedAreaResult =| { status: 'extracted'; layerId: string }@@ -381,7 +380,7 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {commitTextEdit(content: string, styleChanges?: Partial<TextToolOptions>): void;copyLayerToRaster(layerId: string): Promise<string | null>;cropLayerToBbox(layerId: string): Promise<CropLayerResult>;- duplicateLayers(layerIds: readonly string[]): DuplicateLayersResult | null;+ duplicateLayers(layerIds: readonly string[]): Promise<DuplicateLayersResult>;mergeLayerDown(upperLayerId: string): boolean;mergeSelectedRasterLayers(layerIds: readonly string[]): Promise<MergeVisibleResult>;mergeVisibleRasterLayers(): Promise<MergeVisibleResult>;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.tsindex a57006b4ca..e1d2bba192 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts@@ -56,10 +56,12 @@ const createSelectionPixelOptions = () => ({getFillColor: () => '#000',history: {} as never,invalidateLayer: vi.fn(),+ isRasterCacheReady: () => true,isGestureActive: () => false,layers: {} as never,markDirty: vi.fn(),notifyPainted: vi.fn(),+ requestRasterization: vi.fn(),});const createFloatingSelectionOptions = () => ({diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.tsindex b857d57a1f..38d7b5e802 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts@@ -9,8 +9,25 @@ import type { Rect } from '@workbench/canvas-engine/types';export type CapturedLayerCache = { pixels: RasterSurface; rect: Rect } | null | 'not-ready';-export interface LayerMutationControllerOptions {+export type DuplicateLayerRasterPlan =+ | {+ readonly captureBytes: number;+ readonly initialReserveBytes: number;+ readonly replayReserveBytes: number;+ readonly retainForHistory: boolean;+ readonly type: 'capture';+ }+ | { readonly type: 'empty' }+ | { readonly type: 'reference' }+ | { readonly type: 'not-ready' };++type DuplicateRasterPreparationResult =+ | { readonly status: 'ready'; readonly layer: CanvasLayerContract }+ | { readonly status: 'not-ready' | 'over-budget' };++export interface LayerMutationControllerOptions<Permit> {readonly canEdit: () => boolean;+ readonly capturePermit: () => Permit | null;readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;readonly createLayerId: () => string;readonly discardPersisted: (layerId: string) => void;@@ -20,61 +37,130 @@ export interface LayerMutationControllerOptions {mirrorAccepted: () => boolean) => void;readonly endBurst: () => void;- readonly estimateCacheBytes: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => number | 'not-ready';+ readonly getDuplicateRasterPlan: (+ layer: CanvasLayerContract,+ document: CanvasDocumentContractV2+ ) => DuplicateLayerRasterPlan;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getReducerDocument: () => CanvasDocumentContractV2 | null;readonly getSelectedLayerIds: (document: CanvasDocumentContractV2) => readonly string[];readonly history: History;+ readonly hasPendingPixelWork: (layerId: string) => boolean;readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;readonly isGestureActive: () => boolean;+ readonly isPermitCurrent: (permit: Permit) => boolean;readonly needsPixelPersistence: (layer: CanvasLayerContract) => boolean;readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;readonly publishSelectedLayerIds: (primaryId: string | null, selectedIds: readonly string[]) => void;+ readonly prepareDuplicateRasterSource: (layerId: string) => Promise<DuplicateRasterPreparationResult>;+ readonly pinDuplicateRasterSources: (layerIds: readonly string[]) => { release(): void };readonly reserve: (bytes: number) => RasterMemoryReservationResult;+ readonly scheduleDuplicateRasterization: (layerIds: readonly string[]) => void;readonly sameContract: (document: CanvasDocumentContractV2 | null, layer: CanvasLayerContract) => boolean;+ readonly trackDetached: (bytes: number) => { release(): void };}/** Owns failure-atomic copy and cross-type conversion mutations. */-export class LayerMutationController {- constructor(private readonly options: LayerMutationControllerOptions) {}+export class LayerMutationController<Permit> {+ private duplicateInFlight = false;++ constructor(private readonly options: LayerMutationControllerOptions<Permit>) {}++ async duplicate(layerIds: readonly string[]): Promise<DuplicateLayersResult> {+ const o = this.options;+ const permit = o.capturePermit();+ if (this.duplicateInFlight || !permit || !o.canEdit() || o.isGestureActive()) {+ return { status: 'busy' };+ }+ const document = o.getDocument();+ if (!document) {+ return { status: 'nothing' };+ }+ const requested = new Set(layerIds);+ const sources = document.layers.filter((layer) => requested.has(layer.id));+ if (sources.length === 0 || sources.length !== requested.size) {+ return { status: 'nothing' };+ }+ const plans = sources.map((source) => o.getDuplicateRasterPlan(source, document));+ const notReadySources = sources.filter((_source, index) => plans[index]?.type === 'not-ready');+ if (notReadySources.length === 0) {+ return this.commitDuplicate(layerIds);+ }++ this.duplicateInFlight = true;+ const pinLease = o.pinDuplicateRasterSources(sources.map((source) => source.id));+ try {+ for (const source of notReadySources) {+ if (o.hasPendingPixelWork(source.id)) {+ return { status: 'not-ready' };+ }+ const prepared = await o.prepareDuplicateRasterSource(source.id);+ if (prepared.status !== 'ready') {+ return { status: prepared.status };+ }+ if (prepared.layer !== source) {+ return { status: 'stale' };+ }+ }+ if (!o.isPermitCurrent(permit) || o.isGestureActive() || o.getDocument() !== document) {+ return { status: 'stale' };+ }+ return this.commitDuplicate(layerIds);+ } finally {+ pinLease.release();+ this.duplicateInFlight = false;+ }+ }- duplicate(layerIds: readonly string[]): DuplicateLayersResult | null {+ private commitDuplicate(layerIds: readonly string[]): DuplicateLayersResult {const o = this.options;if (!o.canEdit() || o.isGestureActive()) {- return null;+ return { status: 'busy' };}o.endBurst();const document = o.getDocument();if (!document) {- return null;+ return { status: 'nothing' };}const requested = new Set(layerIds);const sources = document.layers.filter((layer) => requested.has(layer.id));if (sources.length === 0 || sources.length !== requested.size) {- return null;+ return { status: 'nothing' };}- const estimates = sources.map((source) => o.estimateCacheBytes(source, document));- let capturedBytes = 0;- for (const estimate of estimates) {- if (estimate === 'not-ready') {- return null;+ const plans = sources.map((source) => o.getDuplicateRasterPlan(source, document));+ let retainedBytes = 0;+ let reserveBytes = 0;+ for (const plan of plans) {+ if (plan.type === 'not-ready') {+ return { status: 'not-ready' };+ }+ if (plan.type === 'capture') {+ if (plan.retainForHistory) {+ retainedBytes += plan.captureBytes;+ }+ reserveBytes += plan.initialReserveBytes;}- capturedBytes += estimate;}- const historyBytes = capturedBytes + sources.length * 256;+ const historyBytes = retainedBytes + sources.length * 256;if (!o.history.canRetain(historyBytes)) {- return null;+ return { status: 'over-budget' };}- // The initial transaction owns one immutable history capture and one- // prepared replacement per populated source at its allocation peak.- const reservation = o.reserve(capturedBytes * 2);+ // Durable layer sources are immutable, so their one prepared cache is used+ // only for the initial insertion and can be reconstructed from the source+ // on redo. Live paint/mask pixels that have not reached a durable source+ // retain a separate immutable history capture and therefore need a second+ // live cache. This makes the common path one full-size copy while keeping+ // dirty pixels exact and every allocation inside the raster reservation.+ const reservation = o.reserve(reserveBytes);if (reservation.status === 'over-budget') {- return null;+ return { status: 'over-budget' };}try {- const captures = sources.map((source) => o.captureCache(source, document));+ const captures = sources.map((source, index) =>+ plans[index]?.type === 'capture' ? o.captureCache(source, document) : null+ );if (captures.some((capture) => capture === 'not-ready')) {- return null;+ return { status: 'not-ready' };}const existingIds = new Set(document.layers.map((layer) => layer.id));const duplicates = sources.map((source) => {@@ -83,11 +169,23 @@ export class LayerMutationController {duplicate.name = `${source.name} copy`;return duplicate;});+ for (const [index, duplicate] of duplicates.entries()) {+ if (plans[index]?.type !== 'empty') {+ continue;+ }+ if (duplicate.type === 'raster' || duplicate.type === 'control') {+ if (duplicate.source.type === 'paint') {+ duplicate.source = { bitmap: null, type: 'paint' };+ }+ } else if (duplicate.type === 'regional_guidance' || duplicate.type === 'inpaint_mask') {+ duplicate.mask = { ...duplicate.mask, bitmap: null, offset: { x: 0, y: 0 } };+ }+ }if (duplicates.some((layer) => existingIds.has(layer.id)) ||new Set(duplicates.map((layer) => layer.id)).size !== duplicates.length) {- return null;+ return { status: 'stale' };}const duplicateBySource = new Map(sources.map((source, index) => [source.id, duplicates[index]!]));const orderedIds = document.layers.flatMap((layer) => {@@ -108,14 +206,9 @@ export class LayerMutationController {candidate?.selectedLayerId === previousSelectedLayerId &&candidate.layers.length === originalIds.length &&candidate.layers.every((layer, index) => layer.id === originalIds[index]);- const applyPrepared = (): void => {- const prepared = captures.flatMap((capture, index) => {- if (!capture || capture === 'not-ready') {- return [];- }- const duplicate = duplicates[index]!;- return [{ duplicate, replacement: o.preparePixels(duplicate.id, capture.rect, capture.pixels) }];- });+ const applyPrepared = (+ prepared: readonly { duplicate: CanvasLayerContract; replacement: PreparedLayerCacheReplacement }[]+ ): void => {o.dispatchPrepared({add: { index: 0, layers: duplicates },@@ -132,20 +225,84 @@ export class LayerMutationController {});o.publishSelectedLayerIds(selectedLayerId, duplicateIds);};+ const retainedCaptures = captures.map((capture, index) =>+ plans[index]?.type === 'capture' && plans[index].retainForHistory ? capture : null+ );+ const initialPrepared = captures.flatMap((capture, index) => {+ if (!capture || capture === 'not-ready') {+ return [];+ }+ const duplicate = duplicates[index]!;+ const plan = plans[index]!;+ return [+ {+ duplicate,+ replacement:+ plan.type === 'capture' && plan.retainForHistory+ ? o.preparePixels(duplicate.id, capture.rect, capture.pixels)+ : { layerId: duplicate.id, rect: capture.rect, surface: capture.pixels },+ },+ ];+ });+ applyPrepared(initialPrepared);+ initialPrepared.length = 0;+ captures.forEach((_capture, index) => {+ const plan = plans[index];+ if (plan?.type !== 'capture' || !plan.retainForHistory) {+ captures[index] = null;+ }+ });+ const detachedLease = retainedBytes > 0 ? o.trackDetached(retainedBytes) : null;const redo = (): void => {- const replayReservation = o.reserve(capturedBytes);+ const current = o.getDocument();+ if (!current) {+ throw new Error('Canvas document is not ready to restore duplicated layers');+ }+ const replayPlans = sources.map((_source, index) => {+ const originalPlan = plans[index]!;+ if (originalPlan.type === 'capture' && originalPlan.retainForHistory) {+ return originalPlan;+ }+ return originalPlan.type === 'capture' ? ({ type: 'reference' } as const) : originalPlan;+ });+ const replayBytes = replayPlans.reduce(+ (total, plan) => total + (plan.type === 'capture' ? plan.replayReserveBytes : 0),+ 0+ );+ const replayReservation = o.reserve(replayBytes);if (replayReservation.status === 'over-budget') {throw new Error('Not enough raster memory to restore duplicated layers');}try {- applyPrepared();+ const prepared = replayPlans.flatMap((plan, index) => {+ if (plan.type !== 'capture') {+ return [];+ }+ const duplicate = duplicates[index]!;+ const retained = retainedCaptures[index];+ if (!retained || retained === 'not-ready') {+ throw new Error('Layer pixels are not ready to restore duplicated layers');+ }+ return [+ {+ duplicate,+ replacement: o.preparePixels(duplicate.id, retained.rect, retained.pixels),+ },+ ];+ });+ applyPrepared(prepared);+ o.scheduleDuplicateRasterization(+ replayPlans.flatMap((plan, index) =>+ plan.type === 'reference' && plans[index]?.type === 'capture' ? [duplicates[index]!.id] : []+ )+ );} finally {replayReservation.lease.release();}};- applyPrepared();o.history.push({bytes: historyBytes,+ dispose: () => detachedLease?.release(),label: duplicates.length === 1 ? 'Duplicate layer' : 'Duplicate layers',redo,replayFailureAtomic: true,@@ -163,7 +320,7 @@ export class LayerMutationController {o.publishSelectedLayerIds(previousSelectedLayerId, previousSelectedIds);},});- return { duplicateIds, selectedLayerId };+ return { duplicateIds, selectedLayerId, status: 'duplicated' };} finally {reservation.lease.release();}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/persistenceController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/persistenceController.test.tsindex aebfee5c2a..43b3f6f4b0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/persistenceController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/persistenceController.test.ts@@ -8,6 +8,8 @@ const createStore = (): BitmapStore => ({discardLayer: vi.fn(),dispose: vi.fn(),flushPendingUploads: vi.fn(() => Promise.resolve()),+ hasPendingClear: vi.fn(() => false),+ hasPendingWork: vi.fn(() => false),isSelfEcho: vi.fn(() => false),markLayerDirty: vi.fn(),reset: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.tsindex eebe116ddd..52a615dfa1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts@@ -46,10 +46,12 @@ describe('SelectionPixelController', () => {getFillColor: () => '#f00',history,invalidateLayer: vi.fn(),+ isRasterCacheReady: () => true,isGestureActive: () => false,layers,markDirty,notifyPainted,+ requestRasterization: vi.fn(),selection,});@@ -59,4 +61,55 @@ describe('SelectionPixelController', () => {expect(notifyPainted).toHaveBeenCalledWith('paint');expect(history.canUndo()).toBe(true);});++ it('requests durable paint pixels instead of growing a transparent fill cache', () => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ const mask = backend.createSurface(2, 2);+ const selection = {+ bounds: () => ({ height: 2, width: 2, x: 0, y: 0 }),+ mask: () => ({ rect: { height: 2, width: 2, x: 0, y: 0 }, surface: mask }),+ } as unknown as SelectionState;+ const document = {+ layers: [+ {+ id: 'paint',+ isEnabled: true,+ isLocked: false,+ source: { bitmap: { height: 2, imageName: 'durable', width: 2 }, type: 'paint' },+ type: 'raster',+ },+ ],+ selectedLayerId: 'paint',+ } as CanvasDocumentContractV2;+ const markDirty = vi.fn();+ const requestRasterization = vi.fn();+ const history = createHistory();+ const controller = new SelectionPixelController({+ applyImagePatch: vi.fn(),+ backend,+ beginPixelEdit: () => null,+ canEdit: () => true,+ deleteDerived: vi.fn(),+ endBurst: vi.fn(),+ getDocument: () => document,+ getFillColor: () => '#f00',+ history,+ invalidateLayer: vi.fn(),+ isGestureActive: () => false,+ isRasterCacheReady: () => false,+ layers,+ markDirty,+ notifyPainted: vi.fn(),+ requestRasterization,+ selection,+ });++ controller.run('fill');++ expect(requestRasterization).toHaveBeenCalledWith('paint');+ expect(layers.peek('paint')).toBeUndefined();+ expect(markDirty).not.toHaveBeenCalled();+ expect(history.canUndo()).toBe(false);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.tsindex 9bdb527bbe..66a727a954 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts@@ -30,7 +30,12 @@ export interface SelectionPixelControllerOptions {readonly endBurst: () => void;readonly deleteDerived: (layerId: string) => void;readonly invalidateLayer: (layerId: string) => void;+ readonly isRasterCacheReady: (+ layer: CanvasDocumentContractV2['layers'][number],+ document: CanvasDocumentContractV2+ ) => boolean;readonly notifyPainted: (layerId: string) => void;+ readonly requestRasterization: (layerId: string) => void;readonly markDirty: (layerId: string) => void;}@@ -80,6 +85,14 @@ export class SelectionPixelController {}const selectionRect = roundOut(bounds);const selectedLayer = document.layers.find((candidate) => candidate.id === document.selectedLayerId);+ if (+ selectedLayer?.type === 'raster' &&+ selectedLayer.source.type === 'paint' &&+ !this.deps.isRasterCacheReady(selectedLayer, document)+ ) {+ this.deps.requestRasterization(selectedLayer.id);+ return;+ }if (kind === 'erase' &&selectedLayer?.type === 'control' &&diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.tsindex 99c9993a2f..e08a788783 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts@@ -176,6 +176,18 @@ afterEach(() => {});describe('createBitmapStore', () => {+ it('reports whether a layer still has pixels that are not represented by its persisted ref', async () => {+ const h = createHarness();++ expect(h.store.hasPendingWork(LAYER)).toBe(false);+ h.store.markLayerDirty(LAYER);+ expect(h.store.hasPendingWork(LAYER)).toBe(true);++ await h.store.flushPendingUploads();+ expect(h.store.hasPendingWork(LAYER)).toBe(false);+ h.store.dispose();+ });+it('debounces a burst of strokes into a single flush', async () => {const h = createHarness();@@ -1615,6 +1627,7 @@ describe('truthful extent: trimming and clearing', () => {h.store.markLayerDirty(LAYER);await vi.advanceTimersByTimeAsync(1500);await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ expect(h.store.hasPendingClear(LAYER)).toBe(true);h.store.dispose();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.tsindex c12e7be263..2730dd56bb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts@@ -155,6 +155,10 @@ export interface BitmapStoreDeps {/** The imperative bitmap-store handle. */export interface BitmapStore {+ /** Whether the live cache is empty but clearing the durable bitmap is still pending. */+ hasPendingClear(layerId: string): boolean;+ /** Whether this layer has pixels that are not yet represented by its persisted bitmap ref. */+ hasPendingWork(layerId: string): boolean;/** Marks a layer dirty and (re)arms its debounce timer. Called on each committed stroke. */markLayerDirty(layerId: string): void;/**@@ -872,5 +876,24 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {reportedStreaks.clear();};- return { discardLayer, dispose, flushPendingUploads, isSelfEcho, markLayerDirty, reset, suspendLayer };+ const hasPendingWork = (layerId: string): boolean =>+ dirty.has(layerId) ||+ pendingClears.has(layerId) ||+ debounceTimers.has(layerId) ||+ inFlight.has(layerId) ||+ isSuspended(layerId);++ const hasPendingClear = (layerId: string): boolean => pendingClears.has(layerId);++ return {+ discardLayer,+ dispose,+ flushPendingUploads,+ hasPendingClear,+ hasPendingWork,+ isSelfEcho,+ markLayerDirty,+ reset,+ suspendLayer,+ };};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 060ccc4af4..e61bdec71a 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@@ -35,6 +35,8 @@ const inertBitmapStore = (): BitmapStore => ({discardLayer: vi.fn(),dispose: vi.fn(),flushPendingUploads: vi.fn(() => Promise.resolve()),+ hasPendingClear: vi.fn(() => false),+ hasPendingWork: vi.fn(() => false),isSelfEcho: vi.fn(() => false),markLayerDirty: vi.fn(),reset: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 65a4390448..238081ad1c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -2913,6 +2913,8 @@ const createSpyBitmapStore = (): BitmapStore & {discardLayer: vi.fn(),dispose: vi.fn(),flushPendingUploads: vi.fn(() => Promise.resolve()),+ hasPendingClear: () => false,+ hasPendingWork: () => false,isSelfEcho: () => false,markLayerDirty: vi.fn<(layerId: string) => void>(),releaseSuspendedLayer,@@ -6812,7 +6814,11 @@ describe('mergeVisibleRasterLayers', () => {};};- const setup = (doc: CanvasDocumentContractV2) => {+ const setup = (+ doc: CanvasDocumentContractV2,+ pendingClearIds: ReadonlySet<string> = new Set(),+ pendingWorkIds: ReadonlySet<string> = new Set()+ ) => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -6835,8 +6841,12 @@ describe('mergeVisibleRasterLayers', () => {};let panelSelectedIds = doc.selectedLayerId ? [doc.selectedLayerId] : [];const selectionChanges: { primaryId: string | null; selectedIds: readonly string[] }[] = [];+ const bitmapStore = createSpyBitmapStore();+ bitmapStore.hasPendingClear = (layerId) => pendingClearIds.has(layerId);+ bitmapStore.hasPendingWork = (layerId) => pendingWorkIds.has(layerId);const engine = createCanvasEngine({backend,+ bitmapStore,getSelectedLayerIds: () => panelSelectedIds,imageResolver: () => Promise.resolve(new Blob()),mutationPort,@@ -6851,6 +6861,7 @@ describe('mergeVisibleRasterLayers', () => {const overlay = createFakeCanvas();engine.surface.attach(screen.element, overlay.element);return {+ bitmapStore,engine,getPanelSelectedIds: () => panelSelectedIds,raf,@@ -6873,9 +6884,12 @@ describe('mergeVisibleRasterLayers', () => {raf.flush();setPanelSelectedIds(['upper', 'below']);- const result = engine.layers.duplicateLayers(['upper', 'below']);- expect(result).not.toBeNull();- const [upperCopyId, belowCopyId] = result!.duplicateIds;+ const result = await engine.layers.duplicateLayers(['upper', 'below']);+ expect(result.status).toBe('duplicated');+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }+ const [upperCopyId, belowCopyId] = result.duplicateIds;expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([upperCopyId,'upper',@@ -6916,13 +6930,18 @@ describe('mergeVisibleRasterLayers', () => {setPanelSelectedIds(['upper', 'below']);setRejectMutations(true);- expect(() => engine.layers.duplicateLayers(['upper', 'below'])).toThrow('Canvas document mutation was rejected');+ await expect(engine.layers.duplicateLayers(['upper', 'below'])).rejects.toThrow(+ 'Canvas document mutation was rejected'+ );expect(getPanelSelectedIds()).toEqual(['upper', 'below']);expect(selectionChanges).toHaveLength(0);expect(engine.stores.canUndo.get()).toBe(false);setRejectMutations(false);- const result = engine.layers.duplicateLayers(['upper', 'below'])!;+ const result = await engine.layers.duplicateLayers(['upper', 'below']);+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }expect(getPanelSelectedIds()).toEqual(result.duplicateIds);expect(selectionChanges).toHaveLength(1);@@ -6945,6 +6964,107 @@ describe('mergeVisibleRasterLayers', () => {engine.lifecycle.dispose();});+ it('installs duplicate pixels before the new selected layer can be edited', async () => {+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );+ const { bitmapStore, engine, raf } = setup(twoPaintDoc());+ raf.flush();+ await flushMicrotasks();+ raf.flush();++ const result = await engine.layers.duplicateLayers(['upper']);+ expect(result.status).toBe('duplicated');+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }+ bitmapStore.markLayerDirty.mockClear();++ engine.selection.selectAll();+ engine.selection.fillSelection();++ expect(bitmapStore.markLayerDirty).toHaveBeenCalledWith(result.duplicateIds[0]);+ expect(bitmapStore.markLayerDirty).not.toHaveBeenCalledWith('upper');++ engine.history.undo();+ const restored = await engine.exports.exportLayerPixels(result.duplicateIds[0]!);+ expect(restored.status).toBe('ok');+ engine.history.undo();+ engine.history.redo();+ const redone = await engine.exports.exportLayerPixels(result.duplicateIds[0]!);+ expect(redone.status).toBe('ok');+ if (restored.status === 'ok' && redone.status === 'ok') {+ expect(redone.surface).not.toBe(restored.surface);+ expect(redone.rect).toEqual({ height: 40, width: 40, x: 0, y: 0 });+ }+ engine.lifecycle.dispose();+ });++ it('duplicates pending empty paint as empty instead of resurrecting its stale durable bitmap', async () => {+ const { engine } = setup(twoPaintDoc(), new Set(['upper']));++ const result = await engine.layers.duplicateLayers(['upper']);++ expect(result.status).toBe('duplicated');+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }+ const duplicate = engine.document.getDocument()!.layers.find((layer) => layer.id === result.duplicateIds[0]);+ expect(duplicate).toMatchObject({ source: { bitmap: null, type: 'paint' }, type: 'raster' });+ engine.lifecycle.dispose();+ });++ it('duplicates a pending empty mask without its stale durable bitmap', async () => {+ const mask = maskLayer('pending-mask');+ mask.mask = {+ ...mask.mask,+ bitmap: { height: 20, imageName: 'stale-mask', width: 20 },+ offset: { x: 4, y: 5 },+ };+ const doc = { ...twoPaintDoc(), layers: [mask], selectedLayerId: mask.id };+ const { engine } = setup(doc, new Set([mask.id]));++ const result = await engine.layers.duplicateLayers([mask.id]);++ expect(result.status).toBe('duplicated');+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }+ const duplicate = engine.document.getDocument()!.layers.find((layer) => layer.id === result.duplicateIds[0]);+ expect(duplicate).toMatchObject({+ mask: { bitmap: null, fill: mask.mask.fill, offset: { x: 0, y: 0 } },+ type: 'inpaint_mask',+ });+ engine.lifecycle.dispose();+ });++ it('duplicates a disabled persisted layer without waiting for a cache it cannot receive', async () => {+ const doc = twoPaintDoc();+ doc.layers = doc.layers.map((layer) => (layer.id === 'upper' ? { ...layer, isEnabled: false } : layer));+ const { engine, surfaces } = setup(doc);++ const result = await engine.layers.duplicateLayers(['upper']);++ expect(result.status).toBe('duplicated');+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }+ expect(surfaces).toHaveLength(0);+ const original = doc.layers.find((layer) => layer.id === 'upper');+ if (original?.type !== 'raster') {+ throw new Error('expected a raster source');+ }+ const duplicate = engine.document.getDocument()!.layers.find((layer) => layer.id === result.duplicateIds[0]);+ expect(duplicate).toMatchObject({ isEnabled: false, source: original.source, type: 'raster' });+ engine.lifecycle.dispose();+ });+it('merges rasters separated only by another layer group and restores them on undo', async () => {const { engine, getPanelSelectedIds, raf, setPanelSelectedIds } = setup(selectedMergeDoc());raf.flush();@@ -7049,7 +7169,7 @@ describe('mergeVisibleRasterLayers', () => {engine.lifecycle.dispose();});- it('declines oversized duplicate and merge batches before unbounded transaction copies', async () => {+ it('duplicates clean persisted layers with one immediately paintable cache copy each', async () => {const size = 4096;const layers = ['top', 'middle', 'bottom'].map((id): CanvasLayerContract => ({blendMode: 'normal',@@ -7070,12 +7190,135 @@ describe('mergeVisibleRasterLayers', () => {width: size,};const { engine, raf, surfaces } = setup(doc);++ const result = await engine.layers.duplicateLayers(layers.map((layer) => layer.id));+ expect(result.status).toBe('duplicated');+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }+ // Each first-use source allocates one cache and one rasterization scratch;+ // the transaction then allocates exactly one immediately-live copy.+ expect(surfaces).toHaveLength(layers.length * 3);+ expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(+ layers.flatMap((layer, index) => [result.duplicateIds[index], layer.id])+ );+ const afterDuplicate = surfaces.length;+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ // A reference-only copy would allocate both a visible cache and a+ // rasterization scratch surface here, after the transaction reservation was+ // gone. Prepared caches make this frame allocation-free.+ // The frame may lazily create its single checkerboard tile, but it must not+ // rebuild any of the already-prepared duplicate layer caches.+ expect(surfaces).toHaveLength(afterDuplicate + 1);+ expect(engine.stores.canUndo.get()).toBe(true);+ engine.lifecycle.dispose();+ });++ it('reports a concurrent duplicate as busy while first-use source preparation is in flight', async () => {+ const { engine } = setup(twoPaintDoc());++ const first = engine.layers.duplicateLayers(['upper']);+ expect(await engine.layers.duplicateLayers(['upper'])).toEqual({ status: 'busy' });+ expect((await first).status).toBe('duplicated');++ engine.lifecycle.dispose();+ });++ it('redoes a clean duplicate after cooldown evicts the original cache', async () => {+ const size = 4096;+ const layers = ['top', 'upper-middle', 'lower-middle', 'bottom'].map((id): CanvasLayerContract => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { bitmap: { height: size, imageName: `${id}-bmp`, width: size }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10_000, y: 10_000 },+ type: 'raster',+ }));+ const doc: CanvasDocumentContractV2 = {+ ...twoPaintDoc(),+ height: size,+ layers,+ selectedLayerId: 'top',+ width: size,+ };+ const { engine, surfaces } = setup(doc);+ const result = await engine.layers.duplicateLayers(layers.map((layer) => layer.id));+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }+ const duplicateId = result.duplicateIds[0]!;++ engine.history.undo();+ expect(await engine.lifecycle.beginCooldown()).toBe('cooled');+ engine.lifecycle.activate();+ const beforeRedo = surfaces.length;+ engine.history.redo();+ await flushMicrotasks();++ expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual(+ layers.flatMap((layer, index) => [result.duplicateIds[index], layer.id])+ );+ // Redo warms each offscreen reference sequentially: one cache plus one+ // scratch surface per duplicate, never four simultaneous 128 MiB reserves.+ expect(surfaces).toHaveLength(beforeRedo + layers.length * 2);+ expect(engine.document.getDocument()!.selectedLayerId).toBe(duplicateId);+ engine.lifecycle.dispose();+ });++ it('retains an immutable snapshot only for live pixels that are not durable yet', async () => {+ const { engine, raf, surfaces } = setup(twoPaintDoc(), new Set(), new Set(['upper']));+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ const beforeDuplicate = surfaces.length;++ const result = await engine.layers.duplicateLayers(['upper']);++ expect(result.status).toBe('duplicated');+ if (result.status !== 'duplicated') {+ throw new Error(`unexpected duplicate result: ${result.status}`);+ }+ expect(surfaces).toHaveLength(beforeDuplicate + 2);+ engine.history.undo();+ const beforeRedo = surfaces.length;+ engine.history.redo();+ expect(surfaces).toHaveLength(beforeRedo + 1);+ expect(engine.exports.hasExportableLayerContent(result.duplicateIds[0]!)).toBe(true);+ engine.lifecycle.dispose();+ });++ it('declines oversized duplicate and merge batches before unbounded transaction copies', async () => {+ const size = 4096;+ const layers = ['top', 'upper-middle', 'middle', 'lower-middle', 'bottom'].map((id): CanvasLayerContract => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { bitmap: { height: size, imageName: `${id}-bmp`, width: size }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ }));+ const doc: CanvasDocumentContractV2 = {+ ...twoPaintDoc(),+ height: size,+ layers,+ selectedLayerId: 'top',+ width: size,+ };+ const { engine, raf, surfaces } = setup(doc);raf.flush();await flushMicrotasks();raf.flush();const afterRasterization = surfaces.length;- expect(engine.layers.duplicateLayers(layers.map((layer) => layer.id))).toBeNull();+ expect(await engine.layers.duplicateLayers(layers.map((layer) => layer.id))).toEqual({ status: 'over-budget' });expect(surfaces).toHaveLength(afterRasterization);expect(await engine.layers.mergeSelectedRasterLayers(layers.map((layer) => layer.id))).toBe('over-budget');expect(engine.document.getDocument()!.layers).toEqual(layers);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex f8c2c50f2c..26abc2a775 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -87,7 +87,10 @@ import { GeneratedResultController } from '@workbench/canvas-engine/controllers/import { HistoryController } from '@workbench/canvas-engine/controllers/historyController';import { InteractionController } from '@workbench/canvas-engine/controllers/interactionController';import { LayerController } from '@workbench/canvas-engine/controllers/layerController';-import { LayerMutationController } from '@workbench/canvas-engine/controllers/layerMutationController';+import {+ type DuplicateLayerRasterPlan,+ LayerMutationController,+} from '@workbench/canvas-engine/controllers/layerMutationController';import { MaskResultController } from '@workbench/canvas-engine/controllers/maskResultController';import {createCanvasMutationContext,@@ -121,6 +124,7 @@ import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';import { isEmpty, union } from '@workbench/canvas-engine/math/rect';import { createCheckerboardTile } from '@workbench/canvas-engine/render/compositor';import { createFontLoader, domFontLoadApi } from '@workbench/canvas-engine/render/fontLoader';+import { hasLayerDisplayEffect } from '@workbench/canvas-engine/render/layerDisplayEffect';import { createMaskPatternTile } from '@workbench/canvas-engine/render/maskFill';import { renderOverlay } from '@workbench/canvas-engine/render/overlayRenderer';import { trimPaintCacheToAlpha } from '@workbench/canvas-engine/render/paintCacheTrim';@@ -886,10 +890,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetFillColor: () => stores.brushOptions.get().color,history,invalidateLayer: (layerId) => scheduler.invalidate({ layers: [layerId] }),+ isRasterCacheReady: (layer, document) => isLayerCacheReadyForOp(layer, document),isGestureActive: () => pipeline.isGestureActive(),layers: layerCache,markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),notifyPainted: notifyLayerPainted,+ requestRasterization: (layerId) => scheduleLayerRasterization([layerId]),},selectionImage: {capturePermit: (owner) => captureDocumentEditPermit(owner),@@ -1021,6 +1027,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCinvalidate: (payload) => scheduler.invalidate(payload),layers: layerCache,notifyLayerPainted,+ requestLayerRasterization: (layerId) => scheduleLayerRasterization([layerId]),getSamInteraction: () => stores.samInteraction.get(),openTextCreate: (docPoint) => openTextCreate(docPoint),openTextEdit: (layerId) => openTextEdit(layerId),@@ -1182,6 +1189,27 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},});const rasterizeLayerPixels = rasterExportController.rasterize.bind(rasterExportController);+ const prepareLayerRasterCache = async (layerId: string) => {+ const result = await rasterizeLayerPixels(layerId, { includeDisabled: true });+ if (result.status !== 'ok') {+ return { status: result.status === 'over-budget' ? ('over-budget' as const) : ('not-ready' as const) };+ }+ const layer = result.guard.layer;+ result.release();+ return { layer, status: 'ready' as const };+ };+ const scheduleLayerRasterization = (layerIds: readonly string[]): void => {+ void (async () => {+ for (const layerId of layerIds) {+ try {+ await prepareLayerRasterCache(layerId);+ } catch {+ // Each target can retry independently through its next paint/fill+ // gesture; one failed source must not starve the rest of the batch.+ }+ }+ })();+ };const exportBakedLayerPixels = rasterExportController.baked.bind(rasterExportController);const exportBakedLayerBlob = rasterExportController.blob.bind(rasterExportController);type StructuralExportLayerPixelsResult =@@ -2113,20 +2141,55 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCif (isCurrentRasterizationJob(layer) || (entry.stale && !isEmpty(getSourceContentRect(layer, doc)))) {return 'not-ready';}- const pixels = backend.createSurface(entry.rect.width, entry.rect.height);+ const pixels = backend.createSurface(entry.rect.width, entry.rect.height, { willReadFrequently: true });pixels.ctx.drawImage(entry.surface.canvas, 0, 0);return { pixels, rect: { ...entry.rect } };};- const estimateLayerCacheBytes = (layer: CanvasLayerContract, doc: CanvasDocumentContractV2): number | 'not-ready' => {+ const getDuplicateRasterPlan = (+ layer: CanvasLayerContract,+ doc: CanvasDocumentContractV2+ ): DuplicateLayerRasterPlan => {+ const source = renderableSourceOf(layer);+ if (!source) {+ return { type: 'empty' };+ }const entry = layerCache.get(layer.id);if (!entry || isEmpty(entry.rect)) {- return 0;+ // Persistence clearing is failure-tolerant: the live cache may already be+ // empty while the contract still names the old bitmap. The cache is the+ // pixel authority in that state, so the duplicate must explicitly start+ // empty rather than resurrecting the durable image.+ if (source.type === 'paint' && bitmapStore.hasPendingClear(layer.id)) {+ return { type: 'empty' };+ }+ if (isEmpty(getSourceContentRect(layer, doc))) {+ return { type: 'empty' };+ }+ if (source.type === 'paint' && bitmapStore.hasPendingWork(layer.id)) {+ return { type: 'not-ready' };+ }+ if (layer.isEnabled) {+ return { type: 'not-ready' };+ }+ return { type: 'reference' };}if (isCurrentRasterizationJob(layer) || (entry.stale && !isEmpty(getSourceContentRect(layer, doc)))) {- return 'not-ready';- }- return entry.rect.width * entry.rect.height * 4;+ return { type: 'not-ready' };+ }+ const captureBytes = entry.rect.width * entry.rect.height * 4;+ const createsDerivedSurface =+ layer.type === 'regional_guidance' || layer.type === 'inpaint_mask' || hasLayerDisplayEffect(layer);+ const retainForHistory =+ source.type === 'paint' && (source.bitmap === null || bitmapStore.hasPendingWork(layer.id));+ const derivedBytes = createsDerivedSurface ? captureBytes : 0;+ return {+ captureBytes,+ initialReserveBytes: captureBytes * (retainForHistory ? 2 : 1) + derivedBytes,+ replayReserveBytes: captureBytes + derivedBytes,+ retainForHistory,+ type: 'capture',+ };};const reserveLayerOperation = (bytes: number) => {@@ -2151,23 +2214,39 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst layerMutationController = new LayerMutationController({canEdit: () => canEditDocument(),+ capturePermit: () => captureDocumentEditPermit(),captureCache: captureLayerCache,createLayerId,discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),dispatchPrepared: dispatchPreparedMutation,endBurst: () => endNudgeBurst(),- estimateCacheBytes: estimateLayerCacheBytes,+ getDuplicateRasterPlan,getDocument: () => mirror.getDocument(),getReducerDocument,getSelectedLayerIds: resolveSelectedLayerIds,+ hasPendingPixelWork: (layerId) => bitmapStore.hasPendingWork(layerId),history,installPrepared: installGeneratedPaintCache,isGestureActive: () => pipeline.isGestureActive(),+ isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),needsPixelPersistence: layerNeedsPixelPersistence,preparePixels: prepareGeneratedPaintCache,+ prepareDuplicateRasterSource: prepareLayerRasterCache,+ pinDuplicateRasterSources: (layerIds) => {+ const leases = layerIds.map((layerId) => rasterController.memory.pinOperation(layerId));+ return {+ release: () => {+ for (const lease of leases) {+ lease.release();+ }+ },+ };+ },publishSelectedLayerIds: (primaryId, selectedIds) => opts.setSelectedLayerIds?.(primaryId, selectedIds),reserve: reserveLayerOperation,+ scheduleDuplicateRasterization: scheduleLayerRasterization,sameContract: documentHasLayerContract,+ trackDetached: (bytes) => rasterController.memory.trackDetached(bytes, lifecycleGeneration),});const commitLayerCopy = layerMutationController.copy.bind(layerMutationController);const commitLayerConversion = layerMutationController.convert.bind(layerMutationController);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.tsindex ee11ee1926..66b72dd931 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts@@ -507,4 +507,24 @@ describe('createHistory: failure-atomic replay', () => {history.undo();expect(log).toEqual(['undo:newest', 'undo:middle']);});++ it('disposes entries whenever stack ownership permanently ends', () => {+ const disposed: string[] = [];+ const entry = (label: string) => ({+ ...makeEntry(label, []),+ dispose: () => disposed.push(label),+ });+ const history = createHistory({ maxEntries: 1 });++ history.push(entry('evicted'));+ history.push(entry('redo-cleared'));+ expect(disposed).toEqual(['evicted']);+ history.undo();+ history.push(entry('amended'));+ expect(disposed).toEqual(['evicted', 'redo-cleared']);+ history.amendLast(entry('cleared'));+ expect(disposed).toEqual(['evicted', 'redo-cleared', 'amended']);+ history.clear();+ expect(disposed).toEqual(['evicted', 'redo-cleared', 'amended', 'cleared']);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.tsindex a227e886d6..41d3e067af 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts@@ -43,6 +43,8 @@ export interface HistoryEntry {* stack, preventing a retry from applying the same mutation twice.*/readonly replayFailureAtomic?: boolean;+ /** Releases resources retained only by this entry when it is permanently dropped. */+ readonly dispose?: () => void;/** Reverts the change. Must not push new history entries. */undo(): void;/** Re-applies the change. Must not push new history entries. */@@ -99,6 +101,15 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const redoStack: HistoryEntry[] = [];const listeners = new Set<() => void>();+ const disposeEntry = (entry: HistoryEntry): void => {+ try {+ entry.dispose?.();+ } catch {+ // Stack ownership has already ended. Resource cleanup cannot restore the+ // entry and must not prevent the remaining history from being released.+ }+ };+// Running byte totals, kept in sync with the stacks so eviction is O(1) per drop.let undoBytes = 0;let redoBytes = 0;@@ -120,7 +131,8 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {if (redoStack.length === 0) {return;}- redoStack.length = 0;+ const discarded = redoStack.splice(0);+ discarded.forEach(disposeEntry);redoBytes = 0;};@@ -130,12 +142,14 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const evicted = undoStack.shift();if (evicted) {undoBytes -= evicted.bytes;+ disposeEntry(evicted);}}while (undoBytes + redoBytes > byteBudget && undoStack.length > 0) {const evicted = undoStack.shift();if (evicted) {undoBytes -= evicted.bytes;+ disposeEntry(evicted);}}};@@ -143,6 +157,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const push = (entry: HistoryEntry): void => {// Replaying an entry must never record a new one; drop it defensively.if (applying) {+ disposeEntry(entry);return;}clearRedo();@@ -156,6 +171,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const amendLast = (entry: HistoryEntry): void => {if (applying) {+ disposeEntry(entry);return;}if (undoStack.length === 0) {@@ -166,6 +182,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const replaced = undoStack.pop();if (replaced) {undoBytes -= replaced.bytes;+ disposeEntry(replaced);}undoStack.push(entry);undoBytes += entry.bytes;@@ -286,8 +303,10 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {if (undoStack.length === 0 && redoStack.length === 0) {return;}+ const discarded = [...undoStack, ...redoStack];undoStack.length = 0;redoStack.length = 0;+ discarded.forEach(disposeEntry);undoBytes = 0;redoBytes = 0;notify();@@ -300,6 +319,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const evicted = undoStack.shift();if (evicted) {undoBytes -= evicted.bytes;+ disposeEntry(evicted);changed = true;}}@@ -307,6 +327,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const evicted = redoStack.shift();if (evicted) {redoBytes -= evicted.bytes;+ disposeEntry(evicted);changed = true;}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.tsindex f676d4d593..e5ede8ed2b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts@@ -122,6 +122,7 @@ interface Harness {dispatched: CanvasProjectMutation[];strokes: StrokeCommittedEvent[];painted: string[];+ requestLayerRasterization: ReturnType<typeof vi.fn>;createdIds: string[];}@@ -137,6 +138,7 @@ const createHarness = (const painted: string[] = [];const createdIds: string[] = [];const beginPixelEdit = transaction === undefined ? null : vi.fn(() => transaction);+ const requestLayerRasterization = vi.fn();let idCounter = 0;const ctx: ToolContext = {@@ -161,6 +163,7 @@ const createHarness = (invalidate: vi.fn(),layers,notifyLayerPainted: (layerId) => painted.push(layerId),+ requestLayerRasterization,setLayerTransformOverride: vi.fn(),setOverlayCursor: vi.fn(),stores,@@ -168,7 +171,7 @@ const createHarness = (viewport: null as never,};- return { backend, beginPixelEdit, createdIds, ctx, dispatched, layers, painted, strokes };+ return { backend, beginPixelEdit, createdIds, ctx, dispatched, layers, painted, requestLayerRasterization, strokes };};const cacheOps = (surface: StubRasterSurface): string[] => surface.callLog.map((entry) => entry.op);@@ -229,6 +232,29 @@ describe('brush tool: stroke into an existing paint layer', () => {expect(ops).toContain('drawImage');expect(lastCompositeOp(cacheSurface(h, 'paint1'))).toBe('source-over');});++ it('waits for a persisted paint source cache instead of painting over transparent pixels', () => {+ const layer = paintLayer('paint1');+ if (layer.type !== 'raster' || layer.source.type !== 'paint') {+ throw new Error('expected a raster paint layer');+ }+ layer.source.bitmap = { height: 10, imageName: 'persisted-paint', width: 10 };+ const h = createHarness(makeDoc([layer], layer.id));+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(5, 5));+ up(brush, h.ctx, pointer(5, 5, { buttons: 0 }));+ expect(h.strokes).toHaveLength(0);+ expect(h.layers.peek(layer.id)).toBeUndefined();+ expect(h.requestLayerRasterization).toHaveBeenCalledWith(layer.id);++ const entry = h.layers.getOrCreateRect(layer.id, { height: 10, width: 10, x: 0, y: 0 });+ h.layers.publishPixels(layer.id);+ expect(entry.stale).toBe(false);+ down(brush, h.ctx, pointer(5, 5));+ up(brush, h.ctx, pointer(5, 5, { buttons: 0 }));+ expect(h.strokes).toHaveLength(1);+ });});describe('eraser tool', () => {@@ -493,6 +519,28 @@ describe('transparency lock', () => {});describe('mask strokes are forced opaque', () => {+ it('waits for a persisted mask cache instead of replacing its coverage', () => {+ const layer = inpaintMaskLayer('mask1');+ if (layer.type !== 'inpaint_mask') {+ throw new Error('expected an inpaint mask');+ }+ layer.mask.bitmap = { height: 10, imageName: 'persisted-mask', width: 10 };+ const h = createHarness(makeDoc([layer], layer.id));+ const eraser = createEraserTool();++ down(eraser, h.ctx, pointer(5, 5));+ up(eraser, h.ctx, pointer(5, 5, { buttons: 0 }));+ expect(h.strokes).toHaveLength(0);+ expect(h.layers.peek(layer.id)).toBeUndefined();+ expect(h.requestLayerRasterization).toHaveBeenCalledWith(layer.id);++ h.layers.getOrCreateRect(layer.id, { height: 10, width: 10, x: 0, y: 0 });+ h.layers.publishPixels(layer.id);+ down(eraser, h.ctx, pointer(5, 5));+ up(eraser, h.ctx, pointer(5, 5, { buttons: 0 }));+ expect(h.strokes).toHaveLength(1);+ });+it('composites a mask stroke at globalAlpha 1 even when the brush opacity is 0.5', () => {const doc = makeDoc([inpaintMaskLayer('mask1')], 'mask1');const h = createHarness(doc);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex d7537e61e8..d48ea251be 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -72,7 +72,9 @@ interface PaintTarget {}/** True for a mask-bearing layer (inpaint mask / regional guidance) — a paintable alpha stencil. */-const isMaskLayer = (layer: CanvasLayerContract): boolean =>+const isMaskLayer = (+ layer: CanvasLayerContract+): layer is Extract<CanvasLayerContract, { type: 'inpaint_mask' | 'regional_guidance' }> =>layer.type === 'inpaint_mask' || layer.type === 'regional_guidance';/** Resolves (or auto-creates) the paint target for a gesture, or `null` to no-op. */@@ -89,6 +91,17 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetif (selected.isLocked || !selected.isEnabled) {return null;}+ if (selected.source.bitmap) {+ const entry = ctx.layers.get(selected.id);+ if (!entry || entry.stale) {+ // A durable paint source can legitimately have no cache while disabled+ // or outside the current frame. Never grow a transparent stroke-sized+ // cache over it; the compositor's rasterization pass will publish the+ // source first, and the next gesture can edit the complete pixels.+ ctx.requestLayerRasterization?.(selected.id);+ return null;+ }+ }// The cache (if any) keeps its current content extent; the stroke grows it.return {cancel: () => undefined,@@ -124,6 +137,13 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetif (selected.isLocked || !selected.isEnabled) {return null;}+ if (selected.mask.bitmap) {+ const entry = ctx.layers.get(selected.id);+ if (!entry || entry.stale) {+ ctx.requestLayerRasterization?.(selected.id);+ return null;+ }+ }return {cancel: () => undefined,color: MASK_STROKE_COLOR,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 98e8f9a932..997948ad58 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -114,6 +114,8 @@ export interface ToolContext {beginTransformSession?(layerId: string): void;/** Prepares direct or materializing pixel editing for a selected control or raster-image layer. */beginPixelEdit?(layerId: string): PixelEditTransaction | null;+ /** Starts reserved source materialization when an offscreen durable paint target is not ready yet. */+ requestLayerRasterization?(layerId: string): void;/** Updates the active transform session's live transform (drag or numeric edit). */updateTransformSession?(transform: LayerTransform): void;/**diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 8048457e32..954d7ef0b8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -375,6 +375,8 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {hasSelectedStagedCandidate: selectedCandidate !== undefined,hasStagingSlots,isInteractionLocked,+ notifyLayerDuplicateFailed: () =>+ notifications.add({ kind: 'error', title: t('widgets.layers.actions.copyFailed') }),pasteFromClipboard,selectedLayerIds,t,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex f5efa52263..4da7140058 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@ -58,7 +58,15 @@ const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {layers: {clearMask: vi.fn(),commitStructural: vi.fn(),- duplicateLayers: vi.fn(() => ({ duplicateIds: ['new-layer'], selectedLayerId: 'new-layer' })),+ duplicateLayers: vi.fn(() =>+ Promise.resolve<+ { status: 'duplicated'; duplicateIds: string[]; selectedLayerId: string } | { status: 'not-ready' }+ >({+ duplicateIds: ['new-layer'],+ selectedLayerId: 'new-layer',+ status: 'duplicated',+ })+ ),mergeLayerDown: vi.fn(),nudgeSelectedLayer: vi.fn(),},@@ -86,6 +94,7 @@ const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyCohasSelectedStagedCandidate: false,hasStagingSlots: false,isInteractionLocked: false,+ notifyLayerDuplicateFailed: vi.fn(),pasteFromClipboard,selectedLayerIds: ['a'],t: (key) => key,@@ -297,6 +306,20 @@ describe('duplicate: lift vs whole layer', () => {const engine = run('canvas.duplicateLayer', { selectedLayerIds: ['a', 'b'] });expect(engine.layers.duplicateLayers).toHaveBeenCalledWith(['a', 'b']);});++ it.each(['declines', 'throws'] as const)('reports when whole-layer duplication %s', async (failure) => {+ const engine = createEngine();+ if (failure === 'declines') {+ engine.layers.duplicateLayers.mockImplementation(() => Promise.resolve({ status: 'not-ready' }));+ } else {+ engine.layers.duplicateLayers.mockImplementation(() => Promise.reject(new Error('rejected')));+ }+ const notifyLayerDuplicateFailed = vi.fn();++ executeCanvasHotkeyCommand('canvas.duplicateLayer', contextOf({ engine, notifyLayerDuplicateFailed }));++ await vi.waitFor(() => expect(notifyLayerDuplicateFailed).toHaveBeenCalledOnce());+ });});describe('clipboard', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex 1b310bbbeb..fd068f8adf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@ -69,6 +69,7 @@ export interface CanvasHotkeyContext {readonly dispatch: CanvasProjectMutationDispatch;readonly copySelection: (cut: boolean) => void;readonly pasteFromClipboard: () => void;+ readonly notifyLayerDuplicateFailed: () => void;readonly t: (key: string) => string;}@@ -239,14 +240,27 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCif (engine?.interaction.get('hasSelection')) {engine.selection.liftSelectionToLayer();} else if (engine && selectedLayer) {- const result = engine.layers.duplicateLayers(ctx.selectedLayerIds);- if (result) {- publishLayerPanelSelection({- primaryId: result.selectedLayerId,- projectId: engine.projectId,- selectedIds: result.duplicateIds,+ void engine.layers+ .duplicateLayers(ctx.selectedLayerIds)+ .then((result) => {+ if (result.status === 'duplicated') {+ publishLayerPanelSelection({+ primaryId: result.selectedLayerId,+ projectId: engine.projectId,+ selectedIds: result.duplicateIds,+ });+ return;+ }+ if (result.status === 'busy') {+ return;+ }+ ctx.notifyLayerDuplicateFailed();+ })+ .catch(() => {+ // The engine keeps rejected transactions atomic; route both rejection+ // and preflight refusal through the same user-facing command feedback.+ ctx.notifyLayerDuplicateFailed();});- }}} else if (commandId === 'canvas.mergeDown') {// Gate on the SAME predicate the layers panel's context menu uses todiff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 239e5c2178..e5c406a49b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -330,23 +330,33 @@ const LayerMenu = ({[t]);- const handleDuplicate = useCallback(() => {+ const handleDuplicate = useCallback(async () => {if (engine) {const panelSelection = readLayerPanelSelection(projectId, document.selectedLayerId);const sourceIds = panelSelection.selectedIds.includes(layer.id) ? panelSelection.selectedIds : [layer.id];- const result = engine.layers.duplicateLayers(sourceIds);- if (result) {- publishLayerPanelSelection({- primaryId: result.selectedLayerId,- projectId,- selectedIds: result.duplicateIds,- });+ try {+ const result = await engine.layers.duplicateLayers(sourceIds);+ if (result.status === 'duplicated') {+ publishLayerPanelSelection({+ primaryId: result.selectedLayerId,+ projectId,+ selectedIds: result.duplicateIds,+ });+ return;+ }+ if (result.status === 'busy') {+ return;+ }+ } catch {+ // A rejected engine transaction leaves the document unchanged; report+ // the failure through the menu instead of leaking an event exception.}+ notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.copyFailed'));return;}const { forward, inverse } = duplicateLayerActions(layer.id, createLayerId());applyStructural(engine, dispatch, t('widgets.layers.actions.duplicate'), forward, inverse);- }, [dispatch, document.selectedLayerId, engine, layer.id, projectId, t]);+ }, [dispatch, document.selectedLayerId, engine, layer.id, notify, projectId, t]);const handleDelete = useCallback(() => {const { forward, inverse } = deleteLayerActions(layer, index);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsxindex 2238c30361..6ff2579ff6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx@@ -79,16 +79,28 @@ export const LayerMultiSelectionActions = ({engine.exports.hasExportableLayerContent(layerId));- const duplicateSelected = useCallback(() => {- const result = engine?.layers.duplicateLayers(selectedIds);- if (result) {- publishLayerPanelSelection({- primaryId: result.selectedLayerId,- projectId,- selectedIds: result.duplicateIds,- });+ const duplicateSelected = useCallback(async () => {+ try {+ const result = await engine?.layers.duplicateLayers(selectedIds);+ if (result?.status === 'duplicated') {+ publishLayerPanelSelection({+ primaryId: result.selectedLayerId,+ projectId,+ selectedIds: result.duplicateIds,+ });+ return;+ }+ if (result?.status === 'busy') {+ return;+ }+ } catch {+ // Reducer rejection is failure-atomic; surface the same actionable result+ // as a preflight refusal instead of leaking an event-handler exception.+ }+ if (engine) {+ toaster.create({ title: t('widgets.layers.actions.copyFailed'), type: 'warning' });}- }, [engine, projectId, selectedIds]);+ }, [engine, projectId, selectedIds, t]);const mergeSelected = useCallback(() => {if (!engine) {