Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
perf(canvas): isolate PSD serialization and bound export memory (#10164)
Josh Corbett6d6549ac387f
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 7a415f966c..b90bd6563e 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -5357,13 +5357,20 @@"expand": "Expand group","exportNothing": "No raster layer content to export","exportNotReady": "Layers are still loading — try exporting again in a moment",- "exportOverBudget": "Not enough raster memory is available to export this PSD",+ "exportOverBudget": "Not enough raster memory is available to prepare this PSD","exportStale": "The canvas changed during export — try again","exportUnreadable": "“{{name}}” could not be read, so nothing was exported. Delete or replace that layer, then export again","exportAborted": "PSD export was canceled","exportFailed": "PSD export failed","exportPsd": "Export to PSD",- "exportTooLarge": "Canvas is too large to export to PSD",+ "cancelExportPsd": "Cancel PSD export",+ "psdExportStatus": {+ "preparing": "Preparing PSD…",+ "serializing": "Writing PSD…",+ "downloading": "Downloading PSD…",+ "cancelling": "Cancelling PSD…"+ },+ "exportTooLarge": "PSD export is too large. Reduce the canvas size or number of layers.","hideAll": "Hide all","mergeNotReady": "Layers are still loading — try merging again in a moment","mergeOverBudget": "Not enough canvas memory to merge these layers",diff --git a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.tsindex 6cb86e292d..439f3d300c 100644--- a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts+++ b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.browser.test.ts@@ -14,6 +14,7 @@ const capture = () => {afterEach(() => {vi.restoreAllMocks();+ vi.useRealTimers();});describe('downloadBlob', () => {@@ -69,3 +70,28 @@ describe('downloadBlob', () => {await expect(fetch(clicked[0]!.href).then((response) => response.text())).resolves.toBe('a,b\n1,2');});});++it('settles owned cleanup when a background tab never delivers animation frames', async () => {+ vi.useFakeTimers();+ capture();+ vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(123);+ const cancel = vi.spyOn(window, 'cancelAnimationFrame');+ const revoke = vi.spyOn(URL, 'revokeObjectURL');+ const pending = downloadBlob(new Blob(['background']), 'background.txt');+ expect(revoke).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1000);+ await pending;+ expect(revoke).toHaveBeenCalledOnce();+ expect(cancel).toHaveBeenCalledWith(123);+});++it('releases its anchor and URL immediately when the browser rejects the click', () => {+ capture();+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {+ throw new Error('click failed');+ });+ const revoke = vi.spyOn(URL, 'revokeObjectURL');+ expect(() => downloadBlob(new Blob(['failure']), 'failed.txt')).toThrow('click failed');+ expect(revoke).toHaveBeenCalledOnce();+ expect(document.querySelector('a[download="failed.txt"]')).toBeNull();+});diff --git a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.tsindex f4da774436..7ed6e4b414 100644--- a/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts+++ b/invokeai/frontend/webv2/src/platform/browser/downloadBlob.ts@@ -2,21 +2,32 @@* Append the download anchor for Firefox compatibility; defer URL revocation until the next frame to avoid racing* browser consumption.*/-export const downloadBlob = (blob: Blob, fileName: string): void => {+export const downloadBlob = (blob: Blob, fileName: string): Promise<void> => {const url = URL.createObjectURL(blob);const anchor = document.createElement('a');-- anchor.href = url;- anchor.download = fileName;- anchor.rel = 'noopener';- anchor.style.display = 'none';-- document.body.append(anchor);- anchor.click();- anchor.remove();-- requestAnimationFrame(() => {+ try {+ anchor.href = url;+ anchor.download = fileName;+ anchor.rel = 'noopener';+ anchor.style.display = 'none';+ document.body.append(anchor);+ anchor.click();+ } catch (error) {URL.revokeObjectURL(url);+ throw error;+ } finally {+ anchor.remove();+ }+ // Keep frame-delayed consumption; bound cleanup when background tabs suspend animation frames.+ return new Promise<void>((resolve) => {+ const done = (): void => {+ clearTimeout(timer);+ cancelAnimationFrame(frame);+ URL.revokeObjectURL(url);+ resolve();+ };+ const timer = setTimeout(done, 1000);+ const frame = requestAnimationFrame(done);});};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex eeabfa27e6..bf49523af3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -265,9 +265,23 @@ PSD export is a planner/executor transaction over immutable snapshots. `PsdExporEach leaf bakes its own stack exactly (spatial entries included), layer-local, before the transform. PSD has no group adjustments, so each enclosing group's stack, innermost first and named per group for refusals, is baked into each leaf's world pixels: under member opacity and blending, and for spatial entries, which see that leaf alone instead of the group composite, this approximates the canvas.-Controller keeps 30,000-pixel side cap and also derives a pixel-area limit from currently available reserved bytes. Accounts for flattened composite plus each transformed layer surface, budgets eight bytes per required pixel, reserves full execution allocation before creating PSD surfaces. Final freshness check happens before that reservation; once execution starts it uses only frozen pixels. Capture and execution reservations release in `finally`; cancellation aborts before next allocation or side effect.+Controller keeps the 30,000-pixel side cap and refuses more than 32,767 PSD records (a folder uses two records). Final freshness check and both memory admissions happen before executor allocations; once execution starts it uses only frozen pixels.-Capability returns `exported`, `nothing`, `too-large`, `not-ready`, `over-budget`, `stale`, `aborted`, a `LayerUnreadable`, or an `AdjustmentRefusal`. Layers widget awaits the promise and maps every non-success result to a user-visible notice.+`export/psdExport.ts` owns the private serialization wire contract and creates one lazy `export/psdSerialization.worker.ts` module worker per execution. The worker imports that contract only as types, so its ag-psd writer stays outside the editor startup graph. After baking and preview composition, the executor resizes every temporary surface to zero and releases the snapshot and preparation reservation. It converts every export-owned readback into a plain `{ width, height, data }` PixelData record before posting it with its buffer transferred: posting `ImageData` itself can clone its pixels despite transferring the backing buffer. No live cache, snapshot surface or spatial-service resource crosses this boundary. Input arrays detach on the sender and the receiver owns their full buffers; the exact output buffer transfers back. The default ag-psd 31 pixel-backed RLE path needs neither DOM canvas nor an OffscreenCanvas adapter. Thumbnail generation, trimming, masks and ZIP compression are not enabled. Success, writer/transport/startup failure, request or response deserialization failure, and abort settle the operation, remove listeners and terminate the worker. Termination interrupts the synchronous writer; there is no main-thread fallback. Retries use a fresh worker.++Allocation derivation for the installed ag-psd default writer (revisit when upgrading the dependency):++- The existing 512 MiB raster budget still admits snapshot capture and preparation. `getPsdRequiredBytes` reserves eight bytes per pixel of transformed leaves and composite/isolation surfaces, plus the largest adjusted layer-local area. Existing decoded images, caches and detached snapshots count separately. Local adjustment surfaces are cleared after baking; all remaining executor surfaces are cleared before serialization and in `finally` on earlier failure. Spatial jobs keep their separate service-owned pixel-buffer reservations; kernel scratch stays outside raster accounting as described above.+- Serialization has a separate **1280 MiB allowance per engine/controller**, chosen to admit an ordinary single-layer 4096² export with conservative writer accounting. It is not charged against the reusable raster cache ceiling. One operation may run per controller, including capture, worker execution and download cleanup; another start returns `busy`. This is an operation/engine limit, not a process-wide browser memory limit.+- Let `C = width * height` and `A` be the sum of transformed leaf areas. Each RGBA RLE result is bounded by `4 * height * (width + ceil(width / 128) + 3)`: full literal packets add one header per 128 samples; a short literal packet interrupted by a run has its header offset by that run's saving (at least three samples encoded in two bytes); a final one/two-sample packet can add one extra header. The remaining two bytes per row are the length table. Let `L` and `M` be those bounds for leaves and composite. Metadata allowance is 4096 bytes plus `1024 + 6 * name.length` per record (two records per folder), covering fixed layer/resource records and Unicode/Pascal names. `B = metadata + L + M` bounds serialized output for this restricted document shape.+- The worker allowance includes `4*(A+C) + L + M + 12*C + 2*height + 5*B`: transferred input pixels; all retained encoded channels, including potentially uncollected layer channels during composite encoding; writer scratch (`8*C + 2*height`); composite pixel copy (`4*C`); every geometric writer growth buffer (`<4*B`, including obsolete allocations without assuming collection); and the exact `writePsd` output slice (`B`). Worker termination relinquishes this heap before download. Download needs at most `2*B` for exact output and Blob, so admission uses the maximum of the worker and download phases, rather than summing disjoint phases. `writePsdUint8Array` would retain unused writer capacity; the exact final slice is used instead and its copy is budgeted.+- A single 4096² layer needs about 1095 MiB of serialization allowance; its 256 MiB preparation plus 64 MiB each for decoded pixels, live cache and detached snapshot fits at 448 MiB of the unchanged raster budget. Unit admission tests also pin single 2048²/3840×2160 and three 1920×1080/1536² layers, plus an unsupported serialization size refused before executor allocation. PackBits adversarial fixtures and actual `writePsd` output tests check the bound independently.++Reservations describe known pixel/binary allocations, not a browser RSS ceiling: allocator/GC timing, module/JS object overhead, GPU/driver copies and browser download storage are outside this model. No obsolete writer allocation is assumed to have been collected; termination relinquishes worker ownership but browser reclamation timing is not observable. Capture and preparation leases release once on every exit, including cancellation and worker failure.++The engine publishes its phase in the `psdExportStatus` scalar interaction store. `exports.cancelPsdExport()` and lifecycle cooldown/disposal cancel preparation or the writer; widgets only render this store and invoke the capability. Layers header and keyboard stack menu disable export while busy, show the phase and offer Cancel. Download handoff is irreversible: cancellation is disabled in that phase and a successful initiated download returns `exported` even if the engine cools while URL cleanup settles. The Platform download helper appends its anchor for Firefox compatibility and keeps the URL through the next animation frame, with a one-second timer fallback for suspended background frames; the controller remains busy until cleanup settles.++Capability returns `exported`, `busy`, `nothing`, `too-large` (PSD format or serialization allowance), `not-ready`, `over-budget` (raster preparation), `stale`, `aborted`, a `LayerUnreadable`, or an `AdjustmentRefusal`. Layers widget maps non-success results to notices and leaves duplicate `busy` silent. The engine reports unexpected failures with their project identity through the existing Workbench error recorder and Platform Logging.## Input ownership and frame schedulingdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 024f03bf46..6542091d4d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -186,7 +186,10 @@ export interface CommitMaskImageResultOptions {}export type CommitMaskImageResult = { status: 'committed'; layerId: string } | { status: GuardedMutationRefusal };+export type PsdExportStatus = 'idle' | 'preparing' | 'serializing' | 'downloading' | 'cancelling';+export interface CanvasInteractionState {+ psdExportStatus: PsdExportStatus;activeTool: ToolId;bboxGrid: number;bboxOptions: BboxToolOptions;@@ -353,6 +356,7 @@ export interface CanvasDocumentSnapshot {export type PsdExportResult =| AdjustmentRefusal| LayerUnreadable+ | 'busy'| 'exported'| 'nothing'| 'too-large'@@ -360,6 +364,7 @@ export type PsdExportResult =| SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'stale' | 'aborted'>;export interface CanvasPsdExportCapability {+ cancelPsdExport(): void;exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;}@@ -799,8 +804,7 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {updateTransformSession(transform: LayerTransform): void;}-export interface CanvasEngineExportCapability extends CanvasExportCapability {- exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;+export interface CanvasEngineExportCapability extends CanvasExportCapability, CanvasPsdExportCapability {extractMaskedArea(maskLayerId: string): Promise<ExtractMaskedAreaResult>;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.tsindex d6659b2282..a8208a7519 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts@@ -12,7 +12,7 @@ import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndimport { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';-import { derivePsdPixelAreaLimit, PSD_ALLOCATION_BYTES_PER_PIXEL, PsdExportController } from './psdExportController';+import { PsdExportController } from './psdExportController';const document: CanvasDocumentContractV3 = {background: 'transparent',@@ -57,11 +57,6 @@ const canvasWithDocument = (nextDocument: CanvasDocumentContractV3): CanvasState});describe('PsdExportController', () => {- it('derives the PSD allocation pixel-area limit from currently available reserved bytes', () => {- expect(derivePsdPixelAreaLimit(159_999)).toBe(19_999);- expect(derivePsdPixelAreaLimit(160_000)).toBe(20_000);- });-it('executes from one immutable raster snapshot instead of live layer pixels', async () => {const backend = createTestStubRasterBackend();const detached = backend.createSurface(100, 100);@@ -88,7 +83,7 @@ describe('PsdExportController', () => {captureDocumentSnapshot: () => documentSnapshot,captureRasterSnapshot,execute,- getAvailableBytes: () => 1_000_000,+ getAvailableBytes: () => 10_000_000,isDocumentSnapshotCurrent: () => true,reserve: () => ({ lease: { release: vi.fn() }, status: 'ok' }),});@@ -142,7 +137,7 @@ describe('PsdExportController', () => {status: 'ok',}),execute,- getAvailableBytes: () => 1_000_000,+ getAvailableBytes: () => 10_000_000,isDocumentSnapshotCurrent: () => true,reserve: () => ({ lease: { release: vi.fn() }, status: 'ok' }),});@@ -164,7 +159,7 @@ describe('PsdExportController', () => {const grownCanvas = canvasWithDocument(smallDocument);const documentSnapshot: CanvasDocumentSnapshot = { canvas: grownCanvas, documentGeneration: 7 };const grownRect = { height: 40, width: 30, x: -12, y: -8 };- const reserve = vi.fn(() => ({ lease: { release: vi.fn() }, status: 'ok' as const }));+ const reserve = vi.fn((_bytes: number) => ({ lease: { release: vi.fn() }, status: 'ok' as const }));const execute = vi.fn((plan) => {expect(plan).toMatchObject({ height: 40, status: 'ok', width: 30 });if (plan.status !== 'ok') {@@ -187,13 +182,15 @@ describe('PsdExportController', () => {status: 'ok',}),execute,- getAvailableBytes: () => 1_000_000,+ getAvailableBytes: () => 10_000_000,isDocumentSnapshotCurrent: () => true,reserve,});await expect(controller.export('grown.psd')).resolves.toBe('exported');- expect(reserve).toHaveBeenCalledWith(30 * 40 * 2 * PSD_ALLOCATION_BYTES_PER_PIXEL);+ const plan = execute.mock.calls[0]![0] as Extract<PsdExportPlan, { status: 'ok' }>;+ expect(reserve).toHaveBeenCalledWith(30 * 40 * 8 * 2);+ expect(plan.width).toBe(30);});it('exports valid captured pixels while skipping a confirmed-empty paint layer', async () => {@@ -236,7 +233,7 @@ describe('PsdExportController', () => {status: 'ok',}),execute,- getAvailableBytes: () => 1_000_000,+ getAvailableBytes: () => 10_000_000,isDocumentSnapshotCurrent: () => true,reserve: () => ({ lease: { release: vi.fn() }, status: 'ok' }),});@@ -270,7 +267,7 @@ describe('PsdExportController', () => {status: 'ok',}),execute: vi.fn(),- getAvailableBytes: () => 1_000_000,+ getAvailableBytes: () => 10_000_000,isDocumentSnapshotCurrent: () => true,reserve: vi.fn(),});@@ -279,7 +276,7 @@ describe('PsdExportController', () => {expect(release).toHaveBeenCalledOnce();});- it('derives the execution limit after detached capture and releases the snapshot when over budget', async () => {+ it('refuses writer allocations even when raster-only bytes fit, releasing the snapshot', async () => {const backend = createTestStubRasterBackend();const snapshotRelease = vi.fn();const reserve = vi.fn();@@ -304,7 +301,7 @@ describe('PsdExportController', () => {documentGeneration: 1,}),captureRasterSnapshot,- getAvailableBytes: () => 0,+ getAvailableBytes: () => 159_999,isDocumentSnapshotCurrent: () => true,reserve,});@@ -323,7 +320,7 @@ describe('PsdExportController', () => {documentGeneration: 1,}),captureRasterSnapshot: () => Promise.resolve({ status: 'over-budget' }),- getAvailableBytes: () => 1_000_000,+ getAvailableBytes: () => 10_000_000,isDocumentSnapshotCurrent: () => true,reserve: () => ({ lease: { release: vi.fn() }, status: 'ok' }),});@@ -353,7 +350,7 @@ describe('PsdExportController', () => {status: 'ok',}),execute: vi.fn(),- getAvailableBytes: () => 1_000_000,+ getAvailableBytes: () => 10_000_000,isDocumentSnapshotCurrent,reserve: vi.fn(),});@@ -394,7 +391,7 @@ describe('PsdExportController', () => {once: true,});}),- getAvailableBytes: () => 1_000_000,+ getAvailableBytes: () => 10_000_000,isDocumentSnapshotCurrent: () => true,reserve: () => ({ lease: { release: reservationRelease }, status: 'ok' }),});@@ -546,3 +543,59 @@ describe('PsdExportController — spatial adjustments', () => {expect(runSpatial).toHaveBeenCalledTimes(2);});});++describe('PSD operation lifetime', () => {+ it('rejects concurrent starts, releases on execute failure, rethrows and permits a fresh retry', async () => {+ const backend = createTestStubRasterBackend();+ const snapshotRelease = vi.fn();+ const leaseRelease = vi.fn();+ let fail!: (error: Error) => void;+ const execute = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise<void>((_resolve, reject) => {+ fail = reject;+ })+ )+ .mockResolvedValue(undefined);+ const onStatus = vi.fn();+ const capture = vi.fn(() =>+ Promise.resolve({+ status: 'ok' as const,+ snapshot: {+ canvas,+ documentGeneration: 1,+ emptyLayerIds: new Set<string>(),+ layerSurfaces: new Map([+ ['layer', { rect: { x: 0, y: 0, width: 100, height: 100 }, surface: backend.createSurface(100, 100) }],+ ]),+ release: snapshotRelease,+ },+ })+ );+ const controller = new PsdExportController({+ backend,+ captureDocumentSnapshot: () => ({ canvas, documentGeneration: 1 }),+ captureRasterSnapshot: capture,+ execute,+ onStatus,+ getAvailableBytes: () => 10_000_000,+ reserve: () => ({ status: 'ok', lease: { release: leaseRelease } }),+ isDocumentSnapshotCurrent: () => true,+ });+ const pending = controller.export('failure');+ await vi.waitFor(() => expect(execute).toHaveBeenCalledOnce());+ await expect(controller.export('duplicate')).resolves.toBe('busy');+ expect(capture).toHaveBeenCalledOnce();+ const failure = new Error('allocation failed');+ fail(failure);+ await expect(pending).rejects.toBe(failure);+ expect(snapshotRelease).toHaveBeenCalledOnce();+ expect(leaseRelease).toHaveBeenCalledOnce();+ expect(onStatus).toHaveBeenLastCalledWith('idle');+ await expect(controller.export('retry')).resolves.toBe('exported');+ expect(snapshotRelease).toHaveBeenCalledTimes(2);+ expect(leaseRelease).toHaveBeenCalledTimes(2);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.tsindex 9e8e98e260..ab1c894e69 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentSnapshot, PsdExportResult } from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentSnapshot, PsdExportResult, PsdExportStatus } from '@workbench/canvas-engine/capabilities';import type { CanvasNodeContract } from '@workbench/canvas-engine/contracts';import type {CanvasDetachedLayerSurface,@@ -31,6 +31,7 @@ type RasterMemoryReservationResult =export interface PsdExportControllerOptions {readonly backend: RasterBackend;+ readonly onStatus?: (status: PsdExportStatus) => void;readonly captureDocumentSnapshot: () => CanvasDocumentSnapshot | null;readonly captureRasterSnapshot: (snapshot: CanvasDocumentSnapshot,@@ -47,9 +48,6 @@ export interface PsdExportControllerOptions {export const PSD_ALLOCATION_BYTES_PER_PIXEL = 8;-export const derivePsdPixelAreaLimit = (availableBytes: number): number =>- Math.max(0, Math.floor(availableBytes / PSD_ALLOCATION_BYTES_PER_PIXEL));-const countIsolatedFolders = (nodes: readonly PsdPlanNode[]): number =>nodes.reduce((total, node) =>@@ -71,21 +69,74 @@ const getRequiredAllocationPixelArea = (plan: Extract<PsdExportPlan, { status: '0);+/** Raster preparation remains under the engine cache budget. Serialization has its own bounded lifetime. */+export const getPsdRequiredBytes = (plan: Extract<PsdExportPlan, { status: 'ok' }>): number =>+ getRequiredAllocationPixelArea(plan) * PSD_ALLOCATION_BYTES_PER_PIXEL;++/** One private worker per engine, including uncollected writer growth buffers; not a browser RSS limit. */+export const PSD_SERIALIZATION_ALLOWANCE_BYTES = 1280 * 1024 * 1024;++/**+ * Installed PackBits: full literal packets add one byte per 128 samples. An interrupted literal header is+ * paid for by the following >=3-sample run's saving. A final 1/2-sample packet can add one more header.+ * Add the two-byte row length table for each of four channels.+ */+export const getPsdRleBound = (width: number, height: number): number =>+ 4 * height * (width + Math.ceil(width / 128) + 3);++export const getPsdSerializationBudget = (plan: Extract<PsdExportPlan, { status: 'ok' }>) => {+ const compositeArea = plan.width * plan.height;+ const layerArea = plan.layers.reduce((sum, layer) => sum + layer.worldRect.width * layer.worldRect.height, 0);+ let encodedLayers = 0;+ let metadata = 4096;+ const visit = (nodes: readonly PsdPlanNode[]): void => {+ for (const node of nodes) {+ metadata += (node.kind === 'folder' ? 2 : 1) * (1024 + 6 * node.name.length);+ if (node.kind === 'folder') {+ visit(node.children);+ } else {+ encodedLayers += getPsdRleBound(node.worldRect.width, node.worldRect.height);+ }+ }+ };+ visit(plan.tree);+ const encodedComposite = getPsdRleBound(plan.width, plan.height);+ const outputBound = metadata + encodedLayers + encodedComposite;+ // Retain every geometric growth allocation (<4B), plus writePsd's exact slice (B): no GC assumption.+ const workerBytes =+ 4 * (layerArea + compositeArea) ++ encodedLayers ++ encodedComposite ++ 12 * compositeArea ++ 2 * plan.height ++ 5 * outputBound;+ // Worker terminates before download; exact bytes + Blob can overlap without any writer heap.+ return { outputBound, requiredBytes: Math.max(workerBytes, 2 * outputBound) };+};+/** Owns immutable PSD snapshot capture, budget reservation, execution, and cancellation. */export class PsdExportController {private disposed = false;- private readonly active = new Set<AbortController>();+ private active: AbortController | null = null;+ private status: PsdExportStatus = 'idle';++ private setStatus(status: PsdExportStatus): void {+ this.status = status;+ this.deps.onStatus?.(status);+ }constructor(private readonly deps: PsdExportControllerOptions) {}- async export(fileName: string, options: { signal?: AbortSignal } = {}): Promise<PsdExportResult> {- if (this.disposed || options.signal?.aborted) {+ async export(fileName: string): Promise<PsdExportResult> {+ if (this.disposed) {return 'aborted';}+ if (this.active) {+ return 'busy';+ }const abortController = new AbortController();- const abort = (): void => abortController.abort(options.signal?.reason);- options.signal?.addEventListener('abort', abort, { once: true });- this.active.add(abortController);+ this.active = abortController;+ this.setStatus('preparing');try {const documentSnapshot = this.deps.captureDocumentSnapshot();if (!documentSnapshot) {@@ -112,6 +163,13 @@ export class PsdExportController {return capture.status;}const rasterSnapshot = capture.snapshot;+ let snapshotReleased = false;+ const releaseSnapshot = (): void => {+ if (!snapshotReleased) {+ snapshotReleased = true;+ rasterSnapshot.release();+ }+ };try {if (abortController.signal.aborted) {return 'aborted';@@ -186,15 +244,25 @@ export class PsdExportController {if (plan.status === 'too-large') {return 'too-large';}- const requestedPixelArea = getRequiredAllocationPixelArea(plan);- const requestedBytes = requestedPixelArea * PSD_ALLOCATION_BYTES_PER_PIXEL;- if (requestedPixelArea > derivePsdPixelAreaLimit(this.deps.getAvailableBytes())) {+ if (getPsdSerializationBudget(plan).requiredBytes > PSD_SERIALIZATION_ALLOWANCE_BYTES) {+ return 'too-large';+ }+ const requestedBytes = getPsdRequiredBytes(plan);+ if (requestedBytes > this.deps.getAvailableBytes()) {return 'over-budget';}const reservation = this.deps.reserve(requestedBytes);if (reservation.status === 'over-budget') {return 'over-budget';}+ let reservationReleased = false;+ const releasePreparation = (): void => {+ if (!reservationReleased) {+ reservationReleased = true;+ reservation.lease.release();+ releaseSnapshot();+ }+ };try {const getLayerSurface = (layerId: string): Promise<CanvasDetachedLayerSurface> => {const detached = rasterSnapshot.layerSurfaces.get(layerId);@@ -209,6 +277,12 @@ export class PsdExportController {/\.psd$/i.test(fileName) ? fileName : `${fileName}.psd`,{backend: this.deps.backend,+ onStage: (stage) => {+ if (stage === 'serializing') {+ releasePreparation();+ }+ this.setStatus(abortController.signal.aborted ? 'cancelling' : stage);+ },getLayerSurface,runSpatial: this.deps.runSpatial,signal: abortController.signal,@@ -223,22 +297,23 @@ export class PsdExportController {}throw error;}- return abortController.signal.aborted ? 'aborted' : 'exported';+ return 'exported';} finally {- reservation.lease.release();+ releasePreparation();}} finally {- rasterSnapshot.release();+ releaseSnapshot();}} finally {- this.active.delete(abortController);- options.signal?.removeEventListener('abort', abort);+ this.active = null;+ this.setStatus('idle');}}cancel(): void {- for (const controller of this.active) {- controller.abort();+ if (this.active && this.status !== 'downloading') {+ this.setStatus('cancelling');+ this.active.abort();}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdMemoryPolicy.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdMemoryPolicy.test.tsnew file mode 100644index 0000000000..1328d6b8ec--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdMemoryPolicy.test.ts@@ -0,0 +1,211 @@+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { planPsdExport } from '@workbench/canvas-engine/export/psdExport';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { writePsd, type Psd } from 'ag-psd';+import { writeDataRLE } from 'ag-psd/dist/helpers';+import { describe, expect, it, vi } from 'vitest';++import {+ getPsdRequiredBytes,+ getPsdRleBound,+ getPsdSerializationBudget,+ PSD_SERIALIZATION_ALLOWANCE_BYTES,+ PsdExportController,+} from './psdExportController';+import { RasterMemoryBudgetController } from './rasterMemoryBudgetController';++const planFor = (width: number, height: number, count = 1) => {+ const plan = planPsdExport(+ Array.from({ length: count }, (_, i) => ({+ id: String(i),+ name: String(i),+ contentRect: { x: 0, y: 0, width, height },+ opacity: 1,+ blendMode: 'normal' as const,+ isEnabled: true,+ transform: { x: 0, y: 0, scaleX: 1, scaleY: 1, rotation: 0 },+ }))+ );+ if (plan.status !== 'ok') {+ throw new Error('Invalid test plan');+ }+ return plan;+};++const pixelRecord = (row: readonly number[], height = 1) => ({+ width: row.length,+ height,+ data: Uint8ClampedArray.from({ length: row.length * height * 4 }, (_, i) => row[Math.floor(i / 4) % row.length]!),+});++describe('installed ag-psd memory policy', () => {+ it('pins independent phase accounting, including all writer growth buffers and exact output slice', () => {+ const plan = planFor(2, 2);+ expect(getPsdRequiredBytes(plan)).toBe(64);+ expect(getPsdSerializationBudget(plan)).toEqual({ outputBound: 5222, requiredBytes: 26290 });+ });++ it('bounds PackBits across short runs, literal packet boundaries and adversarial transitions', () => {+ const check = (row: number[]) => {+ const pixels = pixelRecord(row);+ const encoded = writeDataRLE(new Uint8Array(8 * row.length + 8), pixels, [0, 1, 2, 3], false)!;+ expect(encoded.byteLength).toBeLessThanOrEqual(getPsdRleBound(row.length, 1));+ };+ for (let width = 1; width <= 12; width++) {+ for (let bits = 0; bits < 2 ** width; bits++) {+ check(Array.from({ length: width }, (_, i) => (bits >> i) & 1));+ }+ }+ for (const width of [127, 128, 129, 130, 131, 255, 256, 257, 2048, 4096, 30000]) {+ check(Array.from({ length: width }, (_, i) => i % 251));+ check(Array.from({ length: width }, (_, i) => Math.floor(i / 3) % 2));+ check(Array.from({ length: width }, (_, i) => (i % 131 < 128 ? i % 251 : 255)));+ }+ });++ it.each([1, 2, 127, 128, 129, 259, 2048])('bounds actual writePsd output for width %i', (width) => {+ const height = 17;+ const plan = planFor(width, height, 3);+ const imageData = pixelRecord(+ Array.from({ length: width }, (_, i) => i % 251),+ height+ );+ const psd: Psd = {+ width,+ height,+ imageData,+ children: plan.layers.map((layer) => ({+ name: layer.name,+ imageData,+ left: 0,+ top: 0,+ right: width,+ bottom: height,+ })),+ };+ expect(writePsd(psd).byteLength).toBeLessThanOrEqual(getPsdSerializationBudget(plan).outputBound);+ });++ it.each([+ [2048, 2048, 1],+ [4096, 4096, 1],+ [3840, 2160, 1],+ [1920, 1080, 3],+ [1536, 1536, 3],+ ])(+ 'admits %i×%i with %i layers, live caches and detached snapshots under the unchanged raster ceiling',+ async (width, height, count) => {+ const backend = createTestStubRasterBackend();+ const memory = new RasterMemoryBudgetController();+ const liveBytes = width * height * count * 4;+ memory.setCategoryBytes('base', liveBytes);+ memory.setCategoryBytes('decoded', liveBytes);+ const snapshot = memory.trackDetached(liveBytes);+ const plan = planFor(width, height, count);+ expect(getPsdSerializationBudget(plan).requiredBytes).toBeLessThan(PSD_SERIALIZATION_ALLOWANCE_BYTES);+ const canvas = {+ ...createInitialWorkbenchState().projects[0]!.canvas,+ document: documentFrom(Array.from({ length: count }, (_, i) => layerContract(String(i)))),+ };+ const execute = vi.fn((_plan, _name, deps) => {+ expect(memory.snapshot().totalBytes).toBeLessThanOrEqual(512 * 1024 * 1024);+ expect(memory.snapshot().reservedBytes).toBe(8 * width * height * (count + 1));+ deps.onStage('serializing');+ expect(memory.snapshot()).toMatchObject({ reservedBytes: 0, detachedBytes: 0, baseBytes: liveBytes });+ return Promise.resolve();+ });+ const controller = new PsdExportController({+ backend,+ captureDocumentSnapshot: () => ({ canvas, documentGeneration: 1 }),+ captureRasterSnapshot: () =>+ Promise.resolve({+ status: 'ok' as const,+ snapshot: {+ canvas,+ documentGeneration: 1,+ emptyLayerIds: new Set<string>(),+ release: snapshot.release,+ layerSurfaces: new Map(+ plan.layers.map((layer) => [+ layer.id,+ { rect: layer.contentRect, surface: backend.createSurface(width, height) },+ ])+ ),+ },+ }),+ getAvailableBytes: () => memory.getAvailableBytes(),+ isDocumentSnapshotCurrent: () => true,+ reserve: (bytes) => memory.reserveOperation(bytes, { purpose: 'psd-export' }),+ execute,+ });+ await expect(controller.export('representative')).resolves.toBe('exported');+ expect(execute).toHaveBeenCalledOnce();+ controller.dispose();+ memory.dispose();+ }+ );++ it.each([+ [4429, 1, 1, 1_342_003_772, 'exported'],+ [4430, 1, 1, 1_342_608_010, 'too-large'],+ [4608, 1, 1, 1_452_550_174, 'too-large'],+ [64, 2, 64, 1_620_973_628, 'too-large'],+ [8192, 1, 1, 4_589_790_238, 'too-large'],+ ] as const)(+ 'enforces the serialization ceiling for %i² content, %i layers at scale %i before executor allocation',+ async (size, count, scale, expectedBytes, result) => {+ const backend = createTestStubRasterBackend();+ const memory = new RasterMemoryBudgetController();+ const snapshot = memory.trackDetached(size * size * count * 4);+ const canvas = {+ ...createInitialWorkbenchState().projects[0]!.canvas,+ document: documentFrom(+ Array.from({ length: count }, (_, i) =>+ layerContract(String(i), 'raster', {+ name: String(i),+ transform: { x: 0, y: 0, scaleX: scale, scaleY: scale, rotation: 0 },+ })+ )+ ),+ };+ // These admission fixtures never read pixels; even the 8192² surface holds only dimensions and call logs.+ const surfaces = new Map(+ Array.from({ length: count }, (_, i) => [+ String(i),+ { rect: { x: 0, y: 0, width: size, height: size }, surface: backend.createSurface(size, size) },+ ])+ );+ const execute = vi.fn(() => Promise.resolve());+ const reserve = vi.fn((bytes: number) => memory.reserveOperation(bytes, { purpose: 'psd-export' }));+ const release = vi.fn(snapshot.release);+ const controller = new PsdExportController({+ backend,+ captureDocumentSnapshot: () => ({ canvas, documentGeneration: 1 }),+ captureRasterSnapshot: () =>+ Promise.resolve({+ status: 'ok' as const,+ snapshot: {+ canvas,+ documentGeneration: 1,+ emptyLayerIds: new Set<string>(),+ release,+ layerSurfaces: surfaces,+ },+ }),+ execute,+ reserve,+ getAvailableBytes: () => memory.getAvailableBytes(),+ isDocumentSnapshotCurrent: () => true,+ });+ expect(getPsdSerializationBudget(planFor(size * scale, size * scale, count)).requiredBytes).toBe(expectedBytes);+ await expect(controller.export('serialization-limit')).resolves.toBe(result);+ expect(execute).toHaveBeenCalledTimes(result === 'exported' ? 1 : 0);+ expect(reserve).toHaveBeenCalledTimes(result === 'exported' ? 1 : 0);+ expect(release).toHaveBeenCalledOnce();+ expect(memory.snapshot()).toMatchObject({ reservedBytes: 0, detachedBytes: 0 });+ controller.dispose();+ memory.dispose();+ }+ );+});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 f4df89e93d..39bc886622 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@@ -18,6 +18,7 @@ import type * as RasterControllerModule from './controllers/rasterController';import type { RasterController } from './controllers/rasterController';import { createCanvasEngine } from './engine';+import * as psdExport from './export/psdExport';const NO_GROUP_CONTENT: GroupSurfaceContent = { excludeIds: new Set(), float: null, previews: null };@@ -211,6 +212,111 @@ describe('engine raster resource lifecycle', () => {engine.lifecycle.dispose();});+ it('publishes PSD progress and cancels a single active export through the public API, then retries', async () => {+ const { engine, raster } = createEngine();+ const statuses: string[] = [];+ const unsubscribe = engine.interaction.subscribe('psdExportStatus', () =>+ statuses.push(engine.interaction.get('psdExportStatus'))+ );+ const download = vi.fn();+ let entered!: () => void;+ const serializing = new Promise<void>((resolve) => {+ entered = resolve;+ });+ let first = true;+ const execute = psdExport.executePsdExport;+ const execution = vi.spyOn(psdExport, 'executePsdExport').mockImplementation((plan, name, deps) =>+ execute(plan, name, {+ ...deps,+ download,+ writePsd: () => {+ if (!first) {+ return Promise.resolve(new ArrayBuffer(8));+ }+ first = false;+ entered();+ return new Promise((_resolve, reject) => {+ deps.signal?.addEventListener('abort', () => reject(new DOMException('Cancelled', 'AbortError')), {+ once: true,+ });+ });+ },+ })+ );+ try {+ const pending = engine.exports.exportRasterLayersToPsd('first');+ expect(engine.interaction.get('psdExportStatus')).toBe('preparing');+ await serializing;+ expect(engine.interaction.get('psdExportStatus')).toBe('serializing');+ await expect(engine.exports.exportRasterLayersToPsd('duplicate')).resolves.toBe('busy');+ engine.exports.cancelPsdExport();+ expect(engine.interaction.get('psdExportStatus')).toBe('cancelling');+ await expect(pending).resolves.toBe('aborted');+ expect(raster.memory.snapshot()).toMatchObject({ detachedBytes: 0, reservedBytes: 0 });+ expect(download).not.toHaveBeenCalled();+ await expect(engine.exports.exportRasterLayersToPsd('retry')).resolves.toBe('exported');+ expect(download).toHaveBeenCalledOnce();+ expect(statuses).toEqual([+ 'preparing',+ 'serializing',+ 'cancelling',+ 'idle',+ 'preparing',+ 'serializing',+ 'downloading',+ 'idle',+ ]);+ } finally {+ unsubscribe();+ execution.mockRestore();+ engine.lifecycle.dispose();+ }+ });++ it('releases PSD raster bytes before download and preserves the successful handoff across cooldown', async () => {+ const { engine, raster } = createEngine();+ let finishDownload!: () => void;+ let downloadStarted!: () => void;+ const downloading = new Promise<void>((resolve) => {+ downloadStarted = resolve;+ });+ const download = new Promise<void>((resolve) => {+ finishDownload = resolve;+ });+ const execute = psdExport.executePsdExport;+ const execution = vi.spyOn(psdExport, 'executePsdExport').mockImplementation((plan, fileName, deps) =>+ execute(plan, fileName, {+ ...deps,+ writePsd: () => Promise.resolve(new ArrayBuffer(8)),+ download: () => {+ downloadStarted();+ return download;+ },+ })+ );+ const pending = engine.exports.exportRasterLayersToPsd('pending.psd');+ try {+ await downloading;+ const reserved = raster.memory.snapshot().reservedBytes;+ expect(reserved).toBe(0);+ expect(raster.memory.snapshot().detachedBytes).toBe(0);++ await expect(engine.lifecycle.beginCooldown()).resolves.toBe('cooled');+ expect(raster.memory.snapshot().reservedBytes).toBe(reserved);+ engine.lifecycle.activate();+ expect(raster.memory.snapshot().reservedBytes).toBe(reserved);++ finishDownload();+ await expect(pending).resolves.toBe('exported');+ expect(raster.memory.snapshot()).toMatchObject({ reservedBytes: 0, detachedBytes: 0 });+ } finally {+ finishDownload();+ await pending;+ execution.mockRestore();+ engine.lifecycle.dispose();+ }+ });+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;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 3564be3c85..50df16bb20 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -256,6 +256,7 @@ export interface CanvasEngineErrorReport {/** The raw failure; notifications show its message and diagnostics keep its stack. */context: { error: unknown; layerId?: string; label?: string };message:+ | 'PSD export failed'| 'Layer thumbnail rasterization failed'| 'Bitmap persistence failed'| 'Bitmap persistence suspended'@@ -399,6 +400,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcolorPair: stores.colorPair,controlLayerView: stores.controlLayerView,documentEditingLocked: stores.documentEditingLocked,+ psdExportStatus: stores.psdExportStatus,eraserOptions: stores.eraserOptions,gradientOptions: stores.gradientOptions,hasFloatingSelection: stores.hasFloatingSelection,@@ -2508,15 +2510,28 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst psdExportController = new PsdExportController({backend,+ onStatus: (status) => stores.psdExportStatus.set(status),captureDocumentSnapshot,captureRasterSnapshot,getAvailableBytes: () => rasterController.memory.getAvailableBytes(),isDocumentSnapshotCurrent,- reserve: (bytes) =>- rasterController.memory.reserve(bytes, { generation: lifecycleGeneration, purpose: 'psd-export' }),+ reserve: (bytes) => rasterController.memory.reserveOperation(bytes, { purpose: 'psd-export' }),runSpatial: (request) => rasterController.spatial.run(request),});- const exportRasterLayersToPsd = (fileName: string): Promise<PsdExportResult> => psdExportController.export(fileName);+ const exportRasterLayersToPsd = async (fileName: string): Promise<PsdExportResult> => {+ try {+ return await psdExportController.export(fileName);+ } catch (error) {+ opts.reportError({+ namespace: 'canvas',+ area: 'canvas-engine',+ projectId,+ message: 'PSD export failed',+ context: { error },+ });+ throw error;+ }+ };const rasterizeLayer = (layerId: string): Promise<RasterizeLayerResult> =>layerController.rasterize.rasterize(layerId);@@ -2944,6 +2959,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCexportLayerPixels: rasterizeLayerPixels,exportRasterComposite,exportRasterLayersToPsd,+ cancelPsdExport: () => psdExportController.cancel(),extractMaskedArea,getCompositeExecutorDeps,hasExportableLayerContent,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex fa2b7d0078..5df6a54985 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -3,6 +3,7 @@* them to React without coupling the engine to UI.*/+import type { PsdExportStatus } from '@workbench/canvas-engine/capabilities';import type {CanvasLayerSourceContract,CanvasTextFontRef,@@ -539,6 +540,7 @@ export interface EngineStores {snapToGrid: ScalarStore<boolean>;/** Whether an engine-owned operation currently excludes ordinary document edits. */documentEditingLocked: ScalarStore<boolean>;+ psdExportStatus: ScalarStore<PsdExportStatus>;/** The layer targeted by that operation, or null when no operation is active. */documentEditingLayerId: ScalarStore<string | null>;/** The control layer displayed as its original (or original under map); null displays every map. */@@ -713,6 +715,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =eraserOptions: createScalarStore<EraserOptions>({ ...DEFAULT_ERASER_OPTIONS }, eraserOptionsEqual),documentEditingLayerId: createScalarStore<string | null>(null),documentEditingLocked: createScalarStore<boolean>(false),+ psdExportStatus: createScalarStore<PsdExportStatus>('idle'),hasFloatingSelection: createScalarStore<boolean>(false),hasSelection: createScalarStore<boolean>(false),invertBrushSizeScroll: createScalarStore<boolean>(false),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.browser.test.tsindex c8f64a129a..1b72219c03 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.browser.test.ts@@ -2,7 +2,6 @@import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import type { Psd } from 'ag-psd';import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';import { executePsdExport, planPsdExport } from '@workbench/canvas-engine/export/psdExport';@@ -11,6 +10,7 @@ import { createAdjustedSurfaceCache } from '@workbench/canvas-engine/render/adjuimport { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';import { createSpatialAdjustmentService } from '@workbench/canvas-engine/render/spatial/spatialAdjustmentService';+import { readPsd } from 'ag-psd';import { describe, expect, it, vi } from 'vitest';const CONTENT: Rect = { height: 30, width: 40, x: -6, y: -4 };@@ -59,17 +59,15 @@ describe('executePsdExport with a spatial stack', () => {},]);expect(plan.status).toBe('ok');- let written: Psd | null = null;+ let bytes: ArrayBuffer | null = null;await executePsdExport(plan, 'layer.psd', {backend,- download: () => undefined,+ download: (data) => {+ bytes = data;+ },getLayerSurface: () => Promise.resolve({ rect: entry.rect, surface: entry.surface }),runSpatial: (request) => service.run(request),- writePsd: (psd) => {- written = psd;- return Promise.resolve(new ArrayBuffer(0));- },});// What the canvas shows: the display's exact adjusted surface resampled through the transform.@@ -87,10 +85,78 @@ describe('executePsdExport with a spatial stack', () => {);reference.ctx.drawImage(display.peek('layer', entry, STACK)!.canvas, CONTENT.x, CONTENT.y);const expected = reference.ctx.getImageData(0, 0, worldRect.width, worldRect.height).data;- expect([...written!.children![0]!.imageData!.data]).toEqual([...expected]);+ const written = readPsd(bytes!, { useImageData: true });+ expect([...written.children![0]!.imageData!.data]).toEqual([...expected]);expect(memory.snapshot().reservedBytes).toBe(0);} finally {service.dispose();}});});++it('round-trips nested mixed visibility and a transformed leaf through the serialization worker', async () => {+ const backend = createDomRasterBackend();+ const rect = { x: 0, y: 0, width: 2, height: 2 };+ const fill = (color: string, width = 2, height = 2) => {+ const surface = backend.createSurface(width, height);+ surface.ctx.fillStyle = color;+ surface.ctx.fillRect(0, 0, width, height);+ return surface;+ };+ const sources = { red: fill('#ff0000'), blue: fill('#0000ff'), base: fill('#00ff00', 8, 4) };+ const leaf = (id: string) => ({+ id,+ name: id,+ contentRect: rect,+ blendMode: 'normal' as const,+ isEnabled: true,+ opacity: 1,+ transform: { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 },+ });+ const plan = planPsdExport([+ {+ type: 'group',+ id: 'outer',+ name: 'outer',+ isEnabled: true,+ opacity: 0.5,+ children: [+ { type: 'group', id: 'hidden', name: 'hidden', isEnabled: false, children: [leaf('blue')] },+ { ...leaf('red'), opacity: 0.5, transform: { x: 3, y: 1, rotation: 0, scaleX: 2, scaleY: 1 } },+ ],+ },+ { ...leaf('base'), contentRect: { x: 0, y: 0, width: 8, height: 4 } },+ ]);+ let bytes: ArrayBuffer | undefined;+ await executePsdExport(plan, 'nested.psd', {+ backend,+ getLayerSurface: (id) =>+ Promise.resolve({+ rect: id === 'base' ? { ...rect, width: 8, height: 4 } : rect,+ surface: sources[id as keyof typeof sources],+ }),+ download: (data) => {+ bytes = data;+ },+ });+ const psd = readPsd(bytes!, { useImageData: true });+ expect([psd.width, psd.height]).toEqual([8, 4]);+ expect(psd.children!.map((node) => node.name)).toEqual(['base', 'outer']);+ const outer = psd.children![1]!;+ expect(outer.hidden).toBe(false);+ expect(outer.opacity).toBeCloseTo(0.5, 2);+ expect(outer.children![0]!.opacity).toBeCloseTo(0.5, 2);+ expect(outer.children!.map((node) => node.name)).toEqual(['red', 'hidden']);+ expect(outer.children![0]).toMatchObject({ left: 3, top: 1, right: 7, bottom: 3, hidden: false });+ const hidden = outer.children![1]!;+ expect(hidden.hidden).toBe(true);+ expect(hidden.children![0]).toMatchObject({ name: 'blue', hidden: false });+ expect(Array.from(hidden.children![0]!.imageData!.data.subarray(0, 4))).toEqual([0, 0, 255, 255]);+ const expected: number[] = [];+ for (let y = 0; y < 4; y += 1) {+ for (let x = 0; x < 8; x += 1) {+ expected.push(...(x >= 3 && x < 7 && y >= 1 && y < 3 ? [64, 191, 0, 255] : [0, 255, 0, 255]));+ }+ }+ expect(Array.from(psd.imageData!.data)).toEqual(expected);+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.tsindex d8723a339c..15e2d8482b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts@@ -6,7 +6,7 @@ import type { Rect } from '@workbench/canvas-engine/types';import { applyAdjustments } from '@workbench/canvas-engine/render/adjustments';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { readPsd, writePsd } from 'ag-psd';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import type {PsdExportGroupInput,@@ -429,3 +429,61 @@ describe('executePsdExport — adjustments', () => {expect(drawn?.args[0]).toBe(local!.surface.canvas);});});++describe('PSD execution resource ownership', () => {+ it.each(['success', 'failure', 'abort'] as const)(+ 'clears temporary surfaces after %s without clearing snapshot pixels',+ async (outcome) => {+ const backend = createTestStubRasterBackend();+ const source = backend.createSurface(100, 50);+ const temporary: RasterSurface[] = [];+ const controller = new AbortController();+ const download = vi.fn();+ const operation = executePsdExport(planPsdExport([layer()]), 'owned.psd', {+ backend: {+ createSurface: (width, height) => {+ const surface = backend.createSurface(width, height);+ temporary.push(surface);+ return surface;+ },+ },+ signal: controller.signal,+ getLayerSurface: () => Promise.resolve({ rect: { x: 0, y: 0, width: 100, height: 50 }, surface: source }),+ readImageData: (_surface, rect) =>+ ({+ data: new Uint8ClampedArray(rect.width * rect.height * 4),+ width: rect.width,+ height: rect.height,+ }) as ImageData,+ writePsd: () => {+ expect(temporary.length).toBeGreaterThan(0);+ expect(temporary.every((surface) => surface.width === 0 && surface.height === 0)).toBe(true);+ if (outcome === 'failure') {+ throw new Error('writer failed');+ }+ if (outcome === 'abort') {+ controller.abort();+ }+ return Promise.resolve(new ArrayBuffer(0));+ },+ download,+ });+ if (outcome === 'success') {+ await operation;+ } else {+ await expect(operation).rejects.toThrow();+ }+ expect(download).toHaveBeenCalledTimes(outcome === 'success' ? 1 : 0);+ expect(temporary.length).toBeGreaterThan(0);+ expect(temporary.every((surface) => surface.width === 0 && surface.height === 0)).toBe(true);+ expect(source.width).toBe(100);+ expect(source.height).toBe(50);+ }+ );+ it('refuses records that cannot fit the signed PSD layer count, including folder markers', () => {+ const children = Array.from({ length: 32766 }, (_, i) => layer({ id: String(i) }));+ expect(planPsdExport([{ type: 'group', id: 'g', name: 'g', isEnabled: true, children }]).status).toBe('too-large');+ children.pop();+ expect(planPsdExport([{ type: 'group', id: 'g', name: 'g', isEnabled: true, children }]).status).toBe('ok');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.tsindex 9ece83eea5..733bd76320 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts@@ -1,5 +1,5 @@/**- * PSD export separates pure geometry planning from raster baking, lazy `ag-psd` serialization and download.+ * PSD export separates pure geometry planning from raster baking, worker `ag-psd` serialization and download.* Reverse every top-first tree level for ag-psd's bottom-first children; omit empty leaves/folders and size the* document to exported world bounds.*@@ -313,12 +313,18 @@ export const planPsdExport = (return out;};+ const tree = buildTree(inputs);+ const countRecords = (nodes: readonly PsdPlanNode[]): number =>+ nodes.reduce((total, node) => total + (node.kind === 'folder' ? 2 + countRecords(node.children) : 1), 0);+ if (countRecords(tree) > 32767) {+ return { status: 'too-large', width: canvasRect.width, height: canvasRect.height };+ }return {canvasRect,height: canvasRect.height,layers,status: 'ok',- tree: buildTree(inputs),+ tree,unmappedBlends: [...unmappedBlends],width: canvasRect.width,};@@ -326,6 +332,74 @@ export const planPsdExport = (// ---- Executor (impure) -----------------------------------------------------+/** Private export wire contract: only executor-owned pixels and PSD metadata, never engine resources. */+export interface PsdSerializationRequest {+ id: number;+ psd: Psd;+}+export type PsdSerializationResponse = { id: number; bytes: ArrayBuffer } | { id: number; error: string };++/** One operation, one worker: termination interrupts the synchronous writer and discards its entire heap. */+export const serializePsd = (psd: Psd, signal?: AbortSignal): Promise<ArrayBuffer> => {+ if (signal?.aborted) {+ return Promise.reject(new DOMException('PSD export was aborted.', 'AbortError'));+ }+ return new Promise((resolve, reject) => {+ const worker = new Worker(new URL('./psdSerialization.worker.ts', import.meta.url), { type: 'module' });+ const cleanup = (): void => {+ signal?.removeEventListener('abort', abort);+ worker.onmessage = null;+ worker.onerror = null;+ worker.onmessageerror = null;+ worker.terminate();+ };+ const fail = (error: Error): void => {+ cleanup();+ reject(error);+ };+ const abort = (): void => fail(new DOMException('PSD export was aborted.', 'AbortError'));+ // The worker is private to this call, so id 1 cannot collide with another operation or retry.+ worker.onmessage = ({ data }: MessageEvent<PsdSerializationResponse>) => {+ if (data.id !== 1) {+ return;+ }+ cleanup();+ if ('error' in data) {+ reject(new Error(data.error));+ } else {+ resolve(data.bytes);+ }+ };+ worker.onerror = (event) => {+ event.preventDefault();+ fail(new Error(event.message || 'PSD serialization worker failed.'));+ };+ worker.onmessageerror = () => fail(new Error('PSD serialization response could not be read.'));+ signal?.addEventListener('abort', abort, { once: true });+ try {+ const buffers: Transferable[] = [];+ const toWire = (node: AgPsdLayer): AgPsdLayer => {+ const { imageData, children, ...metadata } = node;+ // ImageData itself is cloned even with its buffer transferred. Transfer plain PixelData instead.+ if (imageData) {+ buffers.push(imageData.data.buffer);+ }+ return {+ ...metadata,+ ...(imageData+ ? { imageData: { width: imageData.width, height: imageData.height, data: imageData.data } }+ : {}),+ ...(children ? { children: children.map(toWire) } : {}),+ };+ };+ const wire = toWire(psd) as Psd;+ worker.postMessage({ id: 1, psd: wire } satisfies PsdSerializationRequest, buffers);+ } catch (error) {+ fail(error instanceof Error ? error : new Error(String(error)));+ }+ });+};+type Ctx = RasterSurface['ctx'];/** Reads a surface region's pixels (real DOM path; injectable for tests). */@@ -336,16 +410,9 @@ const defaultReadImageData = (surface: RasterSurface, rect: Rect): ImageData =>const defaultWriteImageData = (surface: RasterSurface, imageData: ImageData, x: number, y: number): void =>surface.ctx.putImageData(imageData, x, y);-/** Lazy-loads `ag-psd` only for serialization, keeping it out of the main bundle. */-const defaultWritePsd = async (psd: Psd): Promise<ArrayBuffer> => {- const { writePsd } = await import('ag-psd');- return writePsd(psd);-};-/** Triggers a browser download of the PSD bytes (Blob + anchor click). */-const defaultDownload = (data: ArrayBuffer, fileName: string): void => {- const blob = new Blob([data], { type: 'image/vnd.adobe.photoshop' });- downloadBlob(blob, fileName);+const defaultDownload = async (data: ArrayBuffer, fileName: string): Promise<void> => {+ await downloadBlob(new Blob([data], { type: 'image/vnd.adobe.photoshop' }), fileName);};/** Injected dependencies for {@link executePsdExport}. */@@ -354,6 +421,7 @@ export interface ExecutePsdExportDeps {backend: { createSurface(width: number, height: number): RasterSurface };/** Cancels before the next background allocation or side effect. */signal?: AbortSignal;+ onStage?(stage: 'serializing' | 'downloading'): void;/*** Evaluates spatial adjustment runs; without it a spatial stack throws {@link AdjustmentRefusedError} rather than* bake without its spatial entries.@@ -365,10 +433,10 @@ export interface ExecutePsdExportDeps {readImageData?(surface: RasterSurface, rect: Rect): ImageData;/** Writes pixels back to a surface (default `putImageData`). */writeImageData?(surface: RasterSurface, imageData: ImageData, x: number, y: number): void;- /** Serializes a PSD to bytes (default: lazy `ag-psd` `writePsd`). */+ /** Serializes a PSD to bytes (default: operation-owned worker). */writePsd?(psd: Psd): Promise<ArrayBuffer>;/** Triggers the download (default: Blob + anchor click). */- download?(data: ArrayBuffer, fileName: string): void;+ download?(data: ArrayBuffer, fileName: string): void | Promise<void>;}/** Sets a 2D context transform from a matrix. */@@ -439,6 +507,10 @@ const bakeLayer = async (ctx.drawImage(source.canvas, rect.x, rect.y);}+ if (source !== cache) {+ source.resize(0, 0);+ }+const fullRect: Rect = { height, width, x: 0, y: 0 };let imageData = read(surface, fullRect);if (planLayer.groupStacks && planLayer.groupStacks.length > 0) {@@ -464,96 +536,121 @@ export const executePsdExport = async (if (plan.status !== 'ok') {return;}- const read = deps.readImageData ?? defaultReadImageData;- const write = deps.writeImageData ?? defaultWriteImageData;- const writePsdFn = deps.writePsd ?? defaultWritePsd;- const download = deps.download ?? defaultDownload;-- const bakedById = new Map<string, AgPsdLayer>();- const baked: { planLayer: PsdPlanLayer; surface: RasterSurface }[] = [];-- for (const planLayer of plan.layers) {+ const surfaces: RasterSurface[] = [];+ const backend = deps.backend;+ deps = {+ ...deps,+ backend: {+ createSurface: (width, height) => {+ const surface = backend.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ },+ };+ try {+ const read = deps.readImageData ?? defaultReadImageData;+ const write = deps.writeImageData ?? defaultWriteImageData;+ const writePsdFn = deps.writePsd ?? ((psd: Psd) => serializePsd(psd, deps.signal));+ const download = deps.download ?? defaultDownload;++ const bakedById = new Map<string, AgPsdLayer>();+ const baked: { planLayer: PsdPlanLayer; surface: RasterSurface }[] = [];++ for (const planLayer of plan.layers) {+ throwIfAborted(deps.signal);+ const { imageData, surface } = await bakeLayer(planLayer, deps, read, write);+ baked.push({ planLayer, surface });+ bakedById.set(planLayer.id, {+ blendMode: planLayer.blendMode,+ bottom: planLayer.bottom,+ hidden: planLayer.hidden,+ imageData,+ left: planLayer.left,+ ...(planLayer.colorLabel ? { layerColor: planLayer.colorLabel } : {}),+ name: planLayer.name,+ opacity: planLayer.opacity,+ right: planLayer.right,+ top: planLayer.top,+ });+ }+ const toChildren = (nodes: readonly PsdPlanNode[]): AgPsdLayer[] =>+ nodes.map((node) =>+ node.kind === 'folder'+ ? {+ blendMode: node.blendMode,+ children: toChildren(node.children),+ hidden: node.hidden,+ ...(node.colorLabel ? { layerColor: node.colorLabel } : {}),+ name: node.name,+ opacity: node.opacity,+ opened: true,+ }+ : bakedById.get(node.id)!+ );+ const children = toChildren(plan.tree);++ // Flatten bottom-first. Isolate folders with opacity/blend so the merged preview matches readers' folder+ // compositing.throwIfAborted(deps.signal);- const { imageData, surface } = await bakeLayer(planLayer, deps, read, write);- baked.push({ planLayer, surface });- bakedById.set(planLayer.id, {- blendMode: planLayer.blendMode,- bottom: planLayer.bottom,- hidden: planLayer.hidden,- imageData,- left: planLayer.left,- ...(planLayer.colorLabel ? { layerColor: planLayer.colorLabel } : {}),- name: planLayer.name,- opacity: planLayer.opacity,- right: planLayer.right,- top: planLayer.top,- });- }- const toChildren = (nodes: readonly PsdPlanNode[]): AgPsdLayer[] =>- nodes.map((node) =>- node.kind === 'folder'- ? {- blendMode: node.blendMode,- children: toChildren(node.children),- hidden: node.hidden,- ...(node.colorLabel ? { layerColor: node.colorLabel } : {}),- name: node.name,- opacity: node.opacity,- opened: true,+ const surfaceById = new Map(baked.map(({ planLayer, surface }) => [planLayer.id, surface]));+ const drawPreview = (ctx: Ctx, nodes: readonly PsdPlanNode[]): void => {+ for (const node of nodes) {+ if (node.hidden) {+ continue;+ }+ if (node.kind === 'folder') {+ if (node.opacity === 1 && node.compositeBlend === 'source-over') {+ drawPreview(ctx, node.children);+ continue;}- : bakedById.get(node.id)!- );- const children = toChildren(plan.tree);-- // Flatten bottom-first. Isolate folders with opacity/blend so the merged preview matches readers' folder- // compositing.- throwIfAborted(deps.signal);- const surfaceById = new Map(baked.map(({ planLayer, surface }) => [planLayer.id, surface]));- const drawPreview = (ctx: Ctx, nodes: readonly PsdPlanNode[]): void => {- for (const node of nodes) {- if (node.hidden) {- continue;- }- if (node.kind === 'folder') {- if (node.opacity === 1 && node.compositeBlend === 'source-over') {- drawPreview(ctx, node.children);+ const buffer = deps.backend.createSurface(plan.width, plan.height);+ setTransform(buffer.ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });+ buffer.ctx.clearRect(0, 0, plan.width, plan.height);+ drawPreview(buffer.ctx, node.children);+ ctx.globalAlpha = node.opacity;+ ctx.globalCompositeOperation = node.compositeBlend;+ ctx.drawImage(buffer.canvas, 0, 0);+ continue;+ }+ const surface = surfaceById.get(node.id);+ if (!surface) {continue;}- const buffer = deps.backend.createSurface(plan.width, plan.height);- setTransform(buffer.ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });- buffer.ctx.clearRect(0, 0, plan.width, plan.height);- drawPreview(buffer.ctx, node.children);ctx.globalAlpha = node.opacity;ctx.globalCompositeOperation = node.compositeBlend;- ctx.drawImage(buffer.canvas, 0, 0);- continue;- }- const surface = surfaceById.get(node.id);- if (!surface) {- continue;+ ctx.drawImage(surface.canvas, node.left, node.top);}- ctx.globalAlpha = node.opacity;- ctx.globalCompositeOperation = node.compositeBlend;- ctx.drawImage(surface.canvas, node.left, node.top);- }- };- const composite = deps.backend.createSurface(plan.width, plan.height);- const cctx = composite.ctx;- setTransform(cctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });- cctx.clearRect(0, 0, plan.width, plan.height);- drawPreview(cctx, plan.tree);- cctx.globalAlpha = 1;- cctx.globalCompositeOperation = 'source-over';-- const psd: Psd = {- children,- height: plan.height,- imageData: read(composite, { height: plan.height, width: plan.width, x: 0, y: 0 }),- width: plan.width,- };+ };+ const composite = deps.backend.createSurface(plan.width, plan.height);+ const cctx = composite.ctx;+ setTransform(cctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });+ cctx.clearRect(0, 0, plan.width, plan.height);+ drawPreview(cctx, plan.tree);+ cctx.globalAlpha = 1;+ cctx.globalCompositeOperation = 'source-over';++ const psd: Psd = {+ children,+ height: plan.height,+ imageData: read(composite, { height: plan.height, width: plan.width, x: 0, y: 0 }),+ width: plan.width,+ };- throwIfAborted(deps.signal);- const bytes = await writePsdFn(psd);- throwIfAborted(deps.signal);- download(bytes, fileName);+ for (const surface of surfaces) {+ surface.resize(0, 0);+ }+ surfaces.length = 0;+ deps.onStage?.('serializing');+ throwIfAborted(deps.signal);+ const bytes = await writePsdFn(psd);+ throwIfAborted(deps.signal);+ // Once the browser accepts the click, cancellation cannot retract the download.+ deps.onStage?.('downloading');+ await download(bytes, fileName);+ } finally {+ for (const surface of surfaces) {+ surface.resize(0, 0);+ }+ }};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.browser.test.tsnew file mode 100644index 0000000000..afdf796095--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.browser.test.ts@@ -0,0 +1,304 @@+import { getPsdRequiredBytes, PsdExportController } from '@workbench/canvas-engine/controllers/psdExportController';+import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { readPsd, writePsd, type Psd } from 'ag-psd';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { executePsdExport, planPsdExport, serializePsd } from './psdExport';++const pixels = (side: number): ImageData => {+ const image = new ImageData(side, side);+ let seed = 7;+ for (let i = 0; i < image.data.length; i += 4) {+ seed = (Math.imul(seed, 1664525) + 1013904223) | 0;+ image.data[i] = seed & 255;+ image.data[i + 1] = (seed >>> 8) & 255;+ image.data[i + 2] = (seed >>> 16) & 255;+ image.data[i + 3] = 255;+ }+ return image;+};+const document = (side: number): Psd => ({+ width: side,+ height: side,+ imageData: pixels(side),+ children: [0, 1, 2].map((i) => ({ name: `Layer ${i}`, imageData: pixels(side) })),+});+afterEach(() => vi.unstubAllGlobals());++describe('real PSD serialization lifecycle', () => {+ it('releases workers after failure and repeated success; transfers only owned pixels', async () => {+ const NativeWorker = globalThis.Worker;+ const active = new Set<Worker>();+ const received: unknown[] = [];+ class TrackedWorker extends NativeWorker {+ constructor(url: string | URL, options?: WorkerOptions) {+ const bootstrap = URL.createObjectURL(+ new Blob(+ [+ `self.onmessage = async (event) => {+ await import(${JSON.stringify(new URL(url, location.href).href)});+ if (event.data.psd.imageData) self.postMessage({ id: 0, received: { plain: Object.getPrototypeOf(event.data.psd.imageData) === Object.prototype,+ bytes: event.data.psd.imageData.data.buffer.byteLength,+ first: Array.from(event.data.psd.imageData.data.subarray(0,4)) } });+ self.onmessage(event);+ };`,+ ],+ { type: 'text/javascript' }+ )+ );+ super(bootstrap, options);+ URL.revokeObjectURL(bootstrap);+ this.addEventListener('message', ({ data }) => {+ if (data.id === 0) {+ received.push(data.received);+ }+ });+ active.add(this);+ }+ override terminate(): void {+ super.terminate();+ active.delete(this);+ }+ }+ vi.stubGlobal('Worker', TrackedWorker);+ await expect(serializePsd({ width: 0, height: 1 })).rejects.toThrow('Invalid document size');+ expect(active.size).toBe(0);+ for (let i = 0; i < 2; i += 1) {+ const psd = document(8);+ const expected = new Uint8Array(writePsd(psd));+ const result = serializePsd(psd);+ expect(psd.imageData!.data.byteLength).toBe(0);+ const bytes = await result;+ expect(new Uint8Array(bytes)).toEqual(expected);+ const parsed = readPsd(bytes, { useImageData: true });+ expect(parsed.children).toHaveLength(3);+ expect(Array.from(parsed.imageData!.data.subarray(0, 4))).toEqual([186, 189, 32, 255]);+ expect(active.size).toBe(0);+ expect(received.at(-1)).toEqual({ plain: true, bytes: 8 * 8 * 4, first: [186, 189, 32, 255] });+ }+ });++ it('interrupts an entered production writer, releases its reservation without downloading, and retries', async () => {+ const NativeWorker = globalThis.Worker;+ const active = new Set<Worker>();+ let entered!: () => void;+ const writerEntered = new Promise<void>((resolve) => {+ entered = resolve;+ });+ let finished = false;+ class ObservedWorker extends NativeWorker {+ constructor(url: string | URL, options?: WorkerOptions) {+ // Import the production handler, then observe its synchronous call without delaying or replacing its work.+ const bootstrap = URL.createObjectURL(+ new Blob(+ [+ `self.onmessage = async (event) => {+ await import(${JSON.stringify(new URL(url, location.href).href)});+ const write = self.onmessage;+ self.onmessage = null;+ self.postMessage({ id: 0, phase: 'entered' });+ write.call(self, event);+ self.postMessage({ id: 0, phase: 'finished' });+ };`,+ ],+ { type: 'text/javascript' }+ )+ );+ super(bootstrap, options);+ URL.revokeObjectURL(bootstrap);+ active.add(this);+ this.addEventListener('message', ({ data }) => {+ if (data.id === 0 && data.phase === 'entered') {+ entered();+ }+ if (data.id === 0 && data.phase === 'finished') {+ finished = true;+ }+ });+ }+ override terminate(): void {+ super.terminate();+ active.delete(this);+ }+ }+ vi.stubGlobal('Worker', ObservedWorker);+ const backend = createDomRasterBackend();+ // Enough real pixel/RLE work to keep the writer occupied after its entry message reaches the page.+ const side = 1536;+ const rect = { x: 0, y: 0, width: side, height: side };+ const source = backend.createSurface(side, side);+ source.ctx.putImageData(pixels(side), 0, 0);+ const documentSnapshot = {+ canvas: {+ ...createInitialWorkbenchState().projects[0]!.canvas,+ document: documentFrom([layerContract('layer')]),+ },+ documentGeneration: 0,+ };+ const release = vi.fn();+ const download = vi.fn();+ const memory = new RasterMemoryBudgetController();+ const controller = new PsdExportController({+ backend,+ captureDocumentSnapshot: () => documentSnapshot,+ captureRasterSnapshot: () =>+ Promise.resolve({+ status: 'ok' as const,+ snapshot: {+ ...documentSnapshot,+ emptyLayerIds: new Set<string>(),+ layerSurfaces: new Map([['layer', { rect, surface: source }]]),+ release,+ },+ }),+ getAvailableBytes: () => memory.getAvailableBytes(),+ isDocumentSnapshotCurrent: () => true,+ reserve: (bytes) => memory.reserveOperation(bytes, { purpose: 'psd-export' }),+ execute: (plan, fileName, deps) => executePsdExport(plan, fileName, { ...deps, download }),+ });+ try {+ const pending = controller.export('cancelled.psd');+ await Promise.race([+ writerEntered,+ pending.then(() => {+ throw new Error('PSD export settled before the writer entered.');+ }),+ ]);+ expect(finished).toBe(false);+ expect(active.size).toBe(1);+ expect(memory.snapshot().reservedBytes).toBe(0);++ controller.cancel();+ expect(active.size).toBe(0);+ await expect(pending).resolves.toBe('aborted');+ expect(memory.snapshot().reservedBytes).toBe(0);+ expect(release).toHaveBeenCalledOnce();+ expect(download).not.toHaveBeenCalled();+ expect(finished).toBe(false);++ await expect(controller.export('retry.psd')).resolves.toBe('exported');+ expect(download).toHaveBeenCalledOnce();+ expect(release).toHaveBeenCalledTimes(2);+ expect(active.size).toBe(0);+ expect(memory.snapshot().reservedBytes).toBe(0);+ } finally {+ controller.dispose();+ for (const worker of active) {+ worker.terminate();+ }+ source.resize(0, 0);+ memory.dispose();+ }+ });+});++// Informational profile, deliberately outside timing gates. Run with VITE_PSD_PROFILE=1 on a quiet machine.+it.runIf(import.meta.env.VITE_PSD_PROFILE === '1')(+ 'profiles medium and large multilayer serialization',+ async ({ annotate, task }) => {+ for (const side of [512, 1024]) {+ const setupStart = performance.now();+ const backend = createDomRasterBackend();+ const source = backend.createSurface(side, side);+ source.ctx.putImageData(pixels(side), 0, 0);+ const sourceSetupMs = performance.now() - setupStart;+ const rect = { x: 0, y: 0, width: side, height: side };+ const plan = planPsdExport(+ [0, 1, 2].map((i) => ({+ id: String(i),+ name: `Layer ${i}`,+ contentRect: rect,+ blendMode: 'normal' as const,+ opacity: 1,+ isEnabled: true,+ transform: { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 },+ }))+ );+ if (plan.status !== 'ok') {+ throw new Error('Expected an executable profile fixture');+ }+ const pipeline = async (worker: boolean) => {+ let extractionMs = 0;+ let serializationMs = 0;+ let bytes: ArrayBuffer | undefined;+ const start = performance.now();+ await executePsdExport(plan, 'profile.psd', {+ backend,+ getLayerSurface: () => Promise.resolve({ rect, surface: source }),+ readImageData: (surface, region) => {+ const before = performance.now();+ const data = surface.ctx.getImageData(region.x, region.y, region.width, region.height);+ extractionMs += performance.now() - before;+ return data;+ },+ writePsd: async (psd) => {+ const before = performance.now();+ const result = worker ? await serializePsd(psd) : writePsd(psd);+ serializationMs = performance.now() - before;+ return result;+ },+ download: (data) => {+ bytes = data;+ },+ });+ const totalMs = performance.now() - start;+ Object.assign(task.meta, {+ [`pipeline${side}${worker ? 'Worker' : 'Baseline'}`]: {+ sourceSetupMs,+ extractionMs,+ serializationMs,+ totalMs,+ rasterAndCompositionMs: totalMs - extractionMs - serializationMs,+ reservedBytes: getPsdRequiredBytes(plan),+ captureAndDownload: 'fixture-owned source; no live snapshot capture or native download',+ },+ });+ return bytes!;+ };+ const measure = async (+ run: () => Promise<ArrayBuffer>+ ): Promise<{ bytes: ArrayBuffer; ms: number; maxTimerGap: number }> => {+ let last = performance.now();+ let maxTimerGap = 0;+ const timer = setInterval(() => {+ const now = performance.now();+ maxTimerGap = Math.max(maxTimerGap, now - last);+ last = now;+ }, 4);+ const start = performance.now();+ try {+ const bytes = await run();+ const ms = performance.now() - start;+ await new Promise((resolve) => {+ setTimeout(resolve, 20);+ });+ return { bytes, ms, maxTimerGap };+ } finally {+ clearInterval(timer);+ }+ };+ const baseline = await measure(() => pipeline(false));+ const worker = await measure(() => pipeline(true));+ const expected = new Uint8Array(baseline.bytes);+ expect(new Uint8Array(worker.bytes).every((value, i) => value === expected[i])).toBe(true);+ expect(worker.bytes.byteLength).toBe(expected.byteLength);+ const measurement = {+ side,+ layers: 3,+ outputBytes: expected.length,+ baselineMs: baseline.ms,+ baselineMaxTimerGap: baseline.maxTimerGap,+ workerMs: worker.ms,+ workerMaxTimerGap: worker.maxTimerGap,+ peakMemory: 'unavailable: page heap metrics exclude worker and canvas/native allocations',+ };+ Object.assign(task.meta, { [`psd${side}`]: measurement });+ await annotate(JSON.stringify(measurement));+ source.resize(0, 0);+ }+ },+ 30_000+);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.test.tsnew file mode 100644index 0000000000..892906791f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.test.ts@@ -0,0 +1,97 @@+import type { Psd } from 'ag-psd';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { serializePsd } from './psdExport';++class TestWorker {+ static instances: TestWorker[] = [];+ onmessage: ((event: { data: unknown }) => void) | null = null;+ onerror: ((event: { preventDefault(): void; message: string }) => void) | null = null;+ onmessageerror: (() => void) | null = null;+ terminate = vi.fn();+ postMessage = vi.fn();+ constructor() {+ TestWorker.instances.push(this);+ }+}+const document = (): Psd => ({+ width: 1,+ height: 1,+ imageData: { width: 1, height: 1, data: new Uint8ClampedArray([1, 2, 3, 255]) },+});+const worker = (): TestWorker => TestWorker.instances.at(-1)!;+afterEach(() => {+ vi.unstubAllGlobals();+ TestWorker.instances = [];+});++describe('operation-owned PSD serialization worker', () => {+ it('transfers inputs, ignores another request, and cleans up on success', async () => {+ vi.stubGlobal('Worker', TestWorker);+ const controller = new AbortController();+ const remove = vi.spyOn(controller.signal, 'removeEventListener');+ const psd = document();+ const result = serializePsd(psd, controller.signal);+ expect(worker().postMessage).toHaveBeenCalledWith({ id: 1, psd }, [psd.imageData!.data.buffer]);+ worker().onmessage!({ data: { id: 2, bytes: new ArrayBuffer(3) } });+ expect(worker().terminate).not.toHaveBeenCalled();+ const bytes = new ArrayBuffer(7);+ worker().onmessage!({ data: { id: 1, bytes } });+ await expect(result).resolves.toBe(bytes);+ expect(worker().terminate).toHaveBeenCalledOnce();+ expect(worker().onmessage).toBeNull();+ expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));+ });+ it('terminates on cancellation and can retry without stale completion', async () => {+ vi.stubGlobal('Worker', TestWorker);+ const controller = new AbortController();+ const result = serializePsd(document(), controller.signal);+ controller.abort();+ await expect(result).rejects.toMatchObject({ name: 'AbortError' });+ expect(worker().terminate).toHaveBeenCalledOnce();+ expect(worker().onmessage).toBeNull();+ const retry = serializePsd(document());+ worker().onmessage!({ data: { id: 1, bytes: new ArrayBuffer(1) } });+ await expect(retry).resolves.toHaveProperty('byteLength', 1);+ expect(TestWorker.instances).toHaveLength(2);+ });+ it.each(['error', 'messageerror', 'writer', 'transfer'] as const)('cleans up after %s failure', async (kind) => {+ vi.stubGlobal('Worker', TestWorker);+ const psd = document();+ if (kind === 'transfer') {+ Object.defineProperty(psd, 'imageData', {+ get: () => {+ throw new Error('transfer failed');+ },+ });+ }+ const result = serializePsd(psd);+ if (kind === 'error') {+ worker().onerror!({ message: 'load failed', preventDefault: vi.fn() });+ }+ if (kind === 'messageerror') {+ worker().onmessageerror!();+ }+ if (kind === 'writer') {+ worker().onmessage!({ data: { id: 1, error: 'writer failed' } });+ }+ await expect(result).rejects.toThrow();+ expect(worker().terminate).toHaveBeenCalledOnce();+ expect(worker().onerror).toBeNull();+ expect(worker().onmessageerror).toBeNull();+ });+ it('does not allocate for an already aborted operation', async () => {+ vi.stubGlobal('Worker', TestWorker);+ await expect(serializePsd(document(), AbortSignal.abort())).rejects.toMatchObject({ name: 'AbortError' });+ expect(TestWorker.instances).toHaveLength(0);+ });+});++it('reports request deserialization failure through the private worker protocol', async () => {+ const scope = { postMessage: vi.fn(), onmessage: null, onmessageerror: null as null | (() => void) };+ vi.stubGlobal('self', scope);+ await import('./psdSerialization.worker');+ scope.onmessageerror!();+ expect(scope.postMessage).toHaveBeenCalledWith({ id: 1, error: 'PSD serialization request could not be read.' });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.worker.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.worker.tsnew file mode 100644index 0000000000..6c3555ad39--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdSerialization.worker.ts@@ -0,0 +1,17 @@+import { writePsd } from 'ag-psd';++import type { PsdSerializationRequest, PsdSerializationResponse } from './psdExport';++// Pixel-backed default writes do not call createCanvas/createImageData. No DOM/OffscreenCanvas adapter is needed.+self.onmessage = ({ data }: MessageEvent<PsdSerializationRequest>): void => {+ try {+ const bytes = writePsd(data.psd);+ self.postMessage({ id: data.id, bytes } satisfies PsdSerializationResponse, { transfer: [bytes] });+ } catch (error) {+ self.postMessage({ id: data.id, error: String(error) } satisfies PsdSerializationResponse);+ }+};++self.onmessageerror = (): void => {+ self.postMessage({ id: 1, error: 'PSD serialization request could not be read.' } satisfies PsdSerializationResponse);+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.tsindex 1e453e9971..4c694a8c85 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts@@ -281,3 +281,15 @@ export const useTextOptions = (engine: CanvasCoreStoreCapability): TextToolOptio/** The active text-editing session (create/edit mode + live source + transform), or `null`. */export const useTextEditSession = (engine: CanvasCoreStoreCapability): TextEditSession | null =>useCanvasInteractionState(engine, 'textEditSession');++/** PSD preparation/worker/download lifecycle belongs to the engine, across widget remounts. */+export const usePsdExportStatus = (+ engine: CanvasCoreStoreCapability | null+): CanvasInteractionState['psdExportStatus'] => {+ const subscribe = useCallback(+ (listener: () => void) => engine?.interaction.subscribe('psdExportStatus', listener) ?? (() => undefined),+ [engine]+ );+ const getSnapshot = useCallback(() => engine?.interaction.get('psdExportStatus') ?? 'idle', [engine]);+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsxindex 6e565f4dc6..225085cd17 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx@@ -63,6 +63,7 @@ const LayerStackHeaderComponent = ({}: LayerStackHeaderProps) => {const { t } = useTranslation();const actions = useLayerStackActions(stack, document, engine, editingLocked);+ const exportStatus = actions.find((action) => action.status)?.status;const handleToggle = useCallback((event: { stopPropagation: () => void }) => {event.stopPropagation();@@ -152,6 +153,11 @@ const LayerStackHeaderComponent = ({</Text><FeatureHintExclusion><HStack gap={LAYER_PANEL_CONTROL_GAP} onClick={stopPropagation} onMouseDown={keepFocus}>+ {exportStatus && (+ <Text role="status" color="fg.muted" fontSize="xs" maxW="7rem" truncate>+ {exportStatus}+ </Text>+ )}{actions.map((action) => (<Tooltip key={action.id} content={action.label}><IconButtondiff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsxindex d8fb654ecf..4baa910ab7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx@@ -45,7 +45,7 @@ export const LayerStackMenu = ({ anchor, document, editingLocked, engine, stack,<HStack gap="2" minW="0" w="full"><Icon as={action.icon} boxSize="3.5" color="fg.muted" flexShrink={0} /><Text flex="1" fontSize="md">- {action.label}+ {action.status ?? action.label}</Text></HStack></Menu.Item>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackPsdExport.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackPsdExport.browser.test.tsxnew file mode 100644index 0000000000..c4734bfa06--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackPsdExport.browser.test.tsx@@ -0,0 +1,197 @@+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */++import type * as PsdExportModule from '@workbench/canvas-engine/export/psdExport';+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';+import type { Project } from '@workbench/projectContracts';+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeAll, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import type { LayerRowCommands } from './layerRowCommands';++import { LayerStackHeader } from './LayerStackHeader';+import { LayerStackMenu } from './LayerStackMenu';++const harness = vi.hoisted(() => ({+ engine: null as CanvasEngine | null,+ store: null as ReturnType<typeof createWorkbenchStore> | null,+ execute: vi.fn<typeof PsdExportModule.executePsdExport>(),+}));+const activeProject = () => harness.store!.getState().projects[0]!;++// Reuse a real project and engine without starting account persistence or the canvas registry.+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useActiveProjectId: () => activeProject().id,+ useActiveProjectName: () => activeProject().name,+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(activeProject()),+}));+vi.mock('@workbench/canvas-operations/react', () => ({ useCanvasEngine: () => harness.engine }));+// Hold only the expensive export boundary; the controller, status stores, action hook and UI are real.+vi.mock('@workbench/canvas-engine/export/psdExport', async (importOriginal) => ({+ ...(await importOriginal<typeof PsdExportModule>()),+ executePsdExport: harness.execute,+}));++const i18n = createInstance();+let root: Root | null = null;+let host: HTMLDivElement | null = null;+let pixels: Blob;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++beforeAll(async () => {+ const translation = await fetch('/locales/en.json').then((response) => response.json());+ await i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation } } });+ const canvas = new OffscreenCanvas(16, 16);+ const context = canvas.getContext('2d')!;+ context.fillStyle = '#fff';+ context.fillRect(0, 0, 16, 16);+ pixels = await canvas.convertToBlob({ type: 'image/png' });+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ harness.engine?.lifecycle.dispose();+ harness.engine = null;+ harness.store = null;+ harness.execute.mockReset();+ root = null;+ host = null;+});++const noop = (): void => {};+const anchor = { x: 40, y: 80, width: 1, height: 1 };+const commands = { focus: noop, keyDown: noop, toggleCollapse: noop } as unknown as LayerRowCommands;++const renderActions = async () => {+ const initial = createInitialWorkbenchState();+ const base = initial.projects[0]!;+ const layer = layerContract('art', 'raster', {+ source: { image: { height: 16, imageName: 'art.png', width: 16 }, type: 'image' },+ });+ const store = createWorkbenchStore({+ ...initial,+ projects: [+ { ...base, canvas: { ...base.canvas, document: { ...base.canvas.document, stacks: stacksFrom([layer]) } } },+ ],+ });+ harness.store = store;+ const projectId = store.getState().activeProjectId;+ const engine = createCanvasEngine({+ ensureProjectOnServer: () => Promise.resolve(),+ imageResolver: () => Promise.resolve(pixels),+ mutationPort: createCanvasProjectMutationPort(store, projectId),+ projectId,+ reportError: noop,+ });+ harness.engine = engine;+ host = document.createElement('div');+ host.style.cssText = 'width: 360px; height: 40px';+ document.body.append(host);+ root = createRoot(host);+ const render = (menu = false) =>+ act(() =>+ root!.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <LayerStackHeader+ collapsed={false}+ commands={commands}+ document={activeProject().canvas.document}+ editingLocked={false}+ engine={engine}+ focused+ leafCount={1}+ posInSet={1}+ rowKey="stack:raster"+ setSize={1}+ stack="raster"+ />+ {menu && (+ <LayerStackMenu+ anchor={anchor}+ document={activeProject().canvas.document}+ editingLocked={false}+ engine={engine}+ stack="raster"+ onClose={() => void render()}+ />+ )}+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ await render();+ return { engine, openMenu: () => render(true) };+};++it.each(['header pointer', 'menu keyboard'] as const)(+ 'disables export, shows live progress and cancels through the real engine from the %s, then permits retry',+ async (surface) => {+ const jobs: { signal: AbortSignal; reject(error: Error): void }[] = [];+ harness.execute.mockImplementation((_plan, _fileName, deps) => {+ deps.onStage?.('serializing');+ return new Promise<void>((_resolve, reject) => {+ jobs.push({ signal: deps.signal!, reject });+ });+ });+ const { engine, openMenu } = await renderActions();+ const exportButton = page.getByRole('button', { exact: true, name: 'Export to PSD' });+ const cancelButton = page.getByRole('button', { exact: true, name: 'Cancel PSD export' });+ await expect.element(exportButton).toBeEnabled();+ await expect.element(cancelButton).not.toBeInTheDocument();++ await act(() => exportButton.click());++ await vi.waitFor(() => expect(jobs).toHaveLength(1));+ expect(engine.interaction.get('psdExportStatus')).toBe('serializing');+ await expect.element(exportButton).toBeDisabled();+ await expect.element(page.getByRole('status')).toHaveTextContent('Writing PSD…');+ await expect.element(cancelButton).toBeEnabled();+ if (surface === 'menu keyboard') {+ await openMenu();+ await expect+ .element(page.getByRole('menuitem', { name: 'Writing PSD…' }))+ .toHaveAttribute('aria-disabled', 'true');+ const cancelItem = document.querySelector<HTMLElement>('[role="menuitem"][data-value="cancelExportPsd"]')!;+ for (let step = 0; step < 4 && !cancelItem.hasAttribute('data-highlighted'); step++) {+ await act(() => userEvent.keyboard('{ArrowDown}'));+ }+ expect(cancelItem).toHaveAttribute('data-highlighted');+ await act(() => userEvent.keyboard('{Enter}'));+ } else {+ await act(() => cancelButton.click());+ }++ await vi.waitFor(() => expect(jobs[0]!.signal.aborted).toBe(true));+ expect(engine.interaction.get('psdExportStatus')).toBe('cancelling');+ await expect.element(page.getByRole('status')).toHaveTextContent('Cancelling PSD…');+ await expect.element(cancelButton).toBeDisabled();+ await expect.element(exportButton).toBeDisabled();+ await act(() => jobs[0]!.reject(new DOMException('Aborted', 'AbortError')));++ await expect.element(exportButton).toBeEnabled();+ await expect.element(cancelButton).not.toBeInTheDocument();+ await expect.element(page.getByRole('status')).not.toBeInTheDocument();+ expect(engine.interaction.get('psdExportStatus')).toBe('idle');+ await act(() => exportButton.click());+ await vi.waitFor(() => expect(jobs).toHaveLength(2));+ expect(jobs[1]!.signal.aborted).toBe(false);+ await act(() => engine.exports.cancelPsdExport());+ await act(() => jobs[1]!.reject(new DOMException('Aborted', 'AbortError')));+ await expect.element(exportButton).toBeEnabled();+ }+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsxindex a5ee7e375a..55dcb1e4d3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx@@ -53,19 +53,32 @@ import { buildLayerStackRows } from './layerTreeRows';vi.mock('./ControlLayerStatusIcon', () => ({ ControlLayerStatusIcon: () => null }));vi.mock('./LayerThumbnail', () => ({ LayerThumbnail: () => <span data-testid="thumbnail" /> }));/** Most cases use a stand-in header; geometry cases render the real one with the real action order. */-const realStackHeader = vi.hoisted(() => ({ on: false }));+const realStackHeader = vi.hoisted(() => ({ on: false, exporting: false }));vi.mock('./useLayerStackActions', async () => {const { getStackActions } = await import('./layerStackActions');const { PlusIcon } = await import('lucide-react');const labels = {exportPsd: 'Export to PSD',+ cancelExportPsd: 'Cancel PSD export',mergeVisible: 'Merge visible',new: 'New layer',toggleVisibility: 'Hide all on canvas',};return {- useLayerStackActions: (stack: Parameters<typeof getStackActions>[0]) =>- getStackActions(stack).map((id) => ({ disabled: false, icon: PlusIcon, id, label: labels[id], run: () => {} })),+ useLayerStackActions: (stack: Parameters<typeof getStackActions>[0]) => {+ const ids = getStackActions(stack);+ if (stack === 'raster' && realStackHeader.exporting) {+ ids.splice(2, 0, 'cancelExportPsd');+ }+ return ids.map((id) => ({+ disabled: realStackHeader.exporting && id === 'exportPsd',+ icon: PlusIcon,+ id,+ label: labels[id],+ status: realStackHeader.exporting && id === 'exportPsd' ? 'Writing PSD…' : undefined,+ run: () => {},+ }));+ },};});const StubStackHeader = ({@@ -415,6 +428,7 @@ beforeEach(() => {afterEach(async () => {await act(() => root?.unmount());realStackHeader.on = false;+ realStackHeader.exporting = false;host?.remove();host = null;root = null;@@ -860,6 +874,30 @@ describe('LayersTree selection, surfaces and structure', () => {expect(document.elementFromPoint(line!.left, centreY(line!))!.closest('[role="treeitem"]')).toBe(treeitem('Inner'));});+ it('keeps PSD progress and cancellation visible as the layers panel narrows', async () => {+ realStackHeader.on = true;+ realStackHeader.exporting = true;+ await renderTree([paint('layer')]);+ const panel = host!.querySelector<HTMLElement>('div[style*="width: 480px"]')!;+ for (const width of [280, 350, 440]) {+ panel.style.width = `${width}px`;+ await settle();+ const header = host!.querySelector<HTMLElement>('[role="treeitem"][aria-label="Raster Layers"]')!;+ const status = header.querySelector<HTMLElement>('[role="status"]')!;+ const cancel = header.querySelector<HTMLButtonElement>('button[aria-label="Cancel PSD export"]')!;+ const exportButton = header.querySelector<HTMLButtonElement>('button[aria-label="Export to PSD"]')!;+ const bounds = header.getBoundingClientRect();+ const progress = status.getBoundingClientRect();+ expect(status.textContent).toBe('Writing PSD…');+ expect(progress.width).toBeGreaterThanOrEqual(50);+ expect(progress.left).toBeGreaterThanOrEqual(bounds.left);+ expect(progress.right).toBeLessThanOrEqual(exportButton.getBoundingClientRect().left);+ expect(cancel.getBoundingClientRect().right).toBeLessThanOrEqual(bounds.right);+ expect(exportButton.disabled).toBe(true);+ expect(cancel.disabled).toBe(false);+ }+ });+it('puts the stack headers’ and child rows’ eyes in the layer rows’ eye column', async () => {realStackHeader.on = true;await renderTree([diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.tsindex 30ce64a037..e455f4a834 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.ts@@ -3,7 +3,7 @@ import type { CanvasLayerContract, LayerStackKind, SemanticNode } from '@workbenimport { isExportableRasterLayer, isNodeHidden } from '@workbench/canvas-engine/api';/** A stack-header action id. Extend this + `getStackActions` to add a new action. */-export type StackActionId = 'mergeVisible' | 'exportPsd' | 'toggleVisibility' | 'new';+export type StackActionId = 'mergeVisible' | 'cancelExportPsd' | 'exportPsd' | 'toggleVisibility' | 'new';/*** Offer merge/export only for raster stacks and hide/show only for overlays, where visibility must not disablediff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.tsindex 77855ef5c1..a5217fb678 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts@@ -21,6 +21,7 @@ export const getPsdExportNotice = (result: Exclude<PsdExportResult, AdjustmentRereturn { key: 'widgets.layers.groupActions.exportUnreadable', options: { name: result.layerName } };}switch (result) {+ case 'busy':case 'exported':return null;case 'not-ready':diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.tsindex 3382e6a098..c3b6245875 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts@@ -9,14 +9,14 @@ import {getDocumentLeaves,isAdjustmentRefusal,} from '@workbench/canvas-engine/api';-import { useCanvasEngineRead } from '@workbench/widgets/canvas/engineStoreHooks';+import { useCanvasEngineRead, usePsdExportStatus } from '@workbench/widgets/canvas/engineStoreHooks';import {describeAdjustmentRefusal,describeNamedRefusal,usePreparedCommit,} from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectName } from '@workbench/WorkbenchContext';-import { EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';+import { EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon, XIcon } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -40,6 +40,7 @@ export interface LayerStackAction {readonly label: string;readonly icon: LucideIcon;readonly disabled: boolean;+ readonly status?: string;run(): void;}@@ -74,16 +75,26 @@ export const useLayerStackActions = (canMergeVisibleRasters(engine.document.model()?.compileLeaves() ?? [], engine.exports.hasExportableLayerContent));const canExport = !!engine && exportable;+ const exportStatus = usePsdExportStatus(engine);+ const exporting = exportStatus !== 'idle';return useMemo(() => {const actions: Record<StackActionId, LayerStackAction> = {+ cancelExportPsd: {+ disabled: exportStatus === 'downloading' || exportStatus === 'cancelling',+ icon: XIcon,+ id: 'cancelExportPsd',+ label: t('widgets.layers.groupActions.cancelExportPsd'),+ run: () => engine?.exports.cancelPsdExport(),+ },exportPsd: {- disabled: editingLocked || !canExport,+ disabled: editingLocked || !canExport || exporting,icon: FileDownIcon,id: 'exportPsd',label: t('widgets.layers.groupActions.exportPsd'),+ status: exporting ? t(`widgets.layers.groupActions.psdExportStatus.${exportStatus}`) : undefined,run: () => {- if (!engine) {+ if (!engine || exporting) {return;}void engine.exports@@ -102,7 +113,9 @@ export const useLayerStackActions = (toaster.create({ title: t(notice.key, notice.options), type: 'warning' });}})- .catch(() => toaster.create({ title: t('widgets.layers.groupActions.exportFailed'), type: 'error' }));+ .catch(() => {+ toaster.create({ title: t('widgets.layers.groupActions.exportFailed'), type: 'error' });+ });},},mergeVisible: {@@ -175,7 +188,9 @@ export const useLayerStackActions = (},},};- return getStackActions(stack).map((id) => actions[id]);+ return getStackActions(stack).flatMap((id) =>+ id === 'exportPsd' && exporting ? [actions[id], actions.cancelExportPsd] : [actions[id]]+ );}, [addLayer,allVisible,@@ -185,6 +200,8 @@ export const useLayerStackActions = (commitPrepared,editingLocked,engine,+ exporting,+ exportStatus,nodes,projectName,stack,