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
Merge branch 'main' into fix/canvas-layer-guarding
Lincoln Steina1c7f2126418
diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.tsindex efc8dbd37d,7027613951..14078dfbbc--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts@@@ -46,10 -88,8 +93,12 @@@ interface HarnessOptions/** The layer-local content-rect origin the surface sits at (default 0,0). */offset?: { x: number; y: number };sleep?: (ms: number) => Promise<void>;+ /** Absent ⇒ the seam is not wired at all, i.e. no trimming (the default). */+ trimLayerPixels?: (layerId: string) => PaintCacheTrim;+ clearBitmap?: (layerId: string) => boolean;+ getAuthoritativeLayerSource?: (layerId: string) => CanvasLayerSourceContract | null;+ /** Overrides the debounce/backoff timer seam (default: real fake timers via `vi`). */+ timers?: BitmapStoreTimers;}/** The default source: a plain paint layer, matching every pre-existing test's assumption. */@@@ -79,15 -117,12 +128,17 @@@ const createHarness = (options: HarnessdebounceMs: 1500,dispatch,encodeSurface,+ ...(clearBitmap ? { clearBitmap } : {}),+ ...(trimLayerPixels ? { trimLayerPixels } : {}),+ ...(options.getAuthoritativeLayerSource+ ? { getAuthoritativeLayerSource: options.getAuthoritativeLayerSource }+ : {}),+ failureBackoffMs: options.failureBackoffMs,getLayerSource: () => source,- getLayerSurface: () => ({ offset, surface }),+ getLayerSurface: () => (options.getLayerSurface ? options.getLayerSurface(surface, offset) : { offset, surface }),// Deterministic content hash: the encoded blob's own text.hashBlob: options.hashBlob ?? ((blob) => blob.text()),+ maxConsecutiveFailures: options.maxConsecutiveFailures,maxUploadAttempts: options.maxUploadAttempts ?? 3,onError: options.onError,retryDelaysMs: [1],@@@ -1150,265 -1189,296 +1207,559 @@@ describe('createBitmapStore', () =>h.store.dispose();});});++ describe('ambient failure handling', () => {+ it('reschedules a failed layer with growing backoff instead of the base debounce', async () => {+ const timers = createManualTimers();+ const uploadImage = vi.fn(() => Promise.reject(new Error('upload failed')));+ const h = createHarness({ maxUploadAttempts: 1, timers, uploadImage });++ h.store.markLayerDirty(LAYER);+ // The very first schedule is a fresh stroke: the base debounce, not backoff.+ expect(timers.scheduledDelays).toEqual([1500]);++ timers.fireNext(); // 1st ambient flush → fails.+ await drainUntil(() => timers.scheduledDelays.length === 2);+ expect(timers.scheduledDelays[1]).toBe(DEFAULT_FAILURE_BACKOFF_MS[0]);++ timers.fireNext(); // 2nd ambient flush → fails again.+ await drainUntil(() => timers.scheduledDelays.length === 3);+ expect(timers.scheduledDelays[2]).toBe(DEFAULT_FAILURE_BACKOFF_MS[1]);++ timers.fireNext(); // 3rd ambient flush → fails again.+ await drainUntil(() => timers.scheduledDelays.length === 4);+ expect(timers.scheduledDelays[3]).toBe(DEFAULT_FAILURE_BACKOFF_MS[2]);++ h.store.dispose();+ });++ it('opens the circuit after maxConsecutiveFailures and stops rescheduling', async () => {+ const timers = createManualTimers();+ const uploadImage = vi.fn(() => Promise.reject(new Error('upload failed')));+ const onError = vi.fn();+ const h = createHarness({ maxConsecutiveFailures: 3, maxUploadAttempts: 1, onError, timers, uploadImage });++ h.store.markLayerDirty(LAYER);+ timers.fireNext(); // failure 1 of 3 → still retrying.+ await drainUntil(() => timers.scheduledDelays.length === 2);+ timers.fireNext(); // failure 2 of 3 → still retrying.+ await drainUntil(() => timers.scheduledDelays.length === 3);+ timers.fireNext(); // failure 3 of 3 → circuit opens.+ await drainUntil(() => onError.mock.calls.length === 2);+ // Let the settling flush's `finally` run to completion (it schedules+ // nothing on this branch, so there is no state change to await directly).+ await drainUntil(() => false, 10);++ expect(timers.pendingCount()).toBe(0);+ expect(timers.scheduledDelays).toHaveLength(3);++ // The layer remains dirty, not dropped: a fresh barrier call still+ // attempts it (the breaker only gates the AMBIENT reschedule).+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ expect(uploadImage).toHaveBeenCalledTimes(4);++ h.store.dispose();+ });++ it('reports the first failure and the final failure only', async () => {+ const timers = createManualTimers();+ const uploadImage = vi.fn(() => Promise.reject(new Error('upload failed')));+ const onError = vi.fn();+ const h = createHarness({ maxConsecutiveFailures: 3, maxUploadAttempts: 1, onError, timers, uploadImage });++ h.store.markLayerDirty(LAYER);+ timers.fireNext();+ await drainUntil(() => timers.scheduledDelays.length === 2);+ timers.fireNext();+ await drainUntil(() => timers.scheduledDelays.length === 3);+ timers.fireNext();+ await drainUntil(() => onError.mock.calls.length === 2);++ expect(onError).toHaveBeenCalledTimes(2);+ expect(onError).toHaveBeenNthCalledWith(1, expect.any(Error), LAYER, {+ consecutiveFailures: 1,+ willRetry: true,+ });+ expect(onError).toHaveBeenNthCalledWith(2, expect.any(Error), LAYER, {+ consecutiveFailures: 3,+ willRetry: false,+ });++ h.store.dispose();+ });++ it('does not re-report when a barrier retries an already-open circuit', async () => {+ const timers = createManualTimers();+ const uploadImage = vi.fn(() => Promise.reject(new Error('upload failed')));+ const onError = vi.fn();+ const h = createHarness({ maxConsecutiveFailures: 3, maxUploadAttempts: 1, onError, timers, uploadImage });++ h.store.markLayerDirty(LAYER);+ timers.fireNext(); // failure 1 of 3.+ await drainUntil(() => timers.scheduledDelays.length === 2);+ timers.fireNext(); // failure 2 of 3.+ await drainUntil(() => timers.scheduledDelays.length === 3);+ timers.fireNext(); // failure 3 of 3 → circuit opens.+ await drainUntil(() => onError.mock.calls.length === 2);+ await drainUntil(() => false, 10);++ expect(uploadImage).toHaveBeenCalledTimes(3);+ expect(onError).toHaveBeenCalledTimes(2);++ // flushPendingUploads() runs before every Generate/export and on+ // blur/pagehide/visibilitychange; it still attempts a circuit-open layer+ // (the breaker only gates the AMBIENT reschedule), so a persistently+ // failing layer must not re-report on every one of those barrier retries.+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');++ expect(uploadImage).toHaveBeenCalledTimes(5);+ expect(onError).toHaveBeenCalledTimes(2);++ h.store.dispose();+ });++ it('reports exactly once when maxConsecutiveFailures is 1 (opens on the very first failure)', async () => {+ const timers = createManualTimers();+ const uploadImage = vi.fn(() => Promise.reject(new Error('upload failed')));+ const onError = vi.fn();+ const h = createHarness({ maxConsecutiveFailures: 1, maxUploadAttempts: 1, onError, timers, uploadImage });++ h.store.markLayerDirty(LAYER);+ timers.fireNext(); // the only ambient attempt: the circuit opens immediately.+ await drainUntil(() => onError.mock.calls.length === 1);+ await drainUntil(() => false, 10);++ expect(timers.pendingCount()).toBe(0);+ expect(onError).toHaveBeenCalledTimes(1);+ expect(onError).toHaveBeenNthCalledWith(1, expect.any(Error), LAYER, {+ consecutiveFailures: 1,+ willRetry: false,+ });++ // Further barrier retries against the already-open circuit stay silent.+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');++ expect(onError).toHaveBeenCalledTimes(1);++ h.store.dispose();+ });++ it('reports a real failure even when silent declines already advanced the streak', async () => {+ const surface = createTestStubRasterBackend().createSurface(10, 10);+ let content = 'pixels-A';+ let uploadShouldFail = false;+ const encodeSurface = vi.fn(() => Promise.resolve(new Blob([content], { type: 'image/png' })));+ const uploadImage = vi.fn(() => {+ if (uploadShouldFail) {+ return Promise.reject(new Error('network unreachable'));+ }+ return Promise.resolve<CanvasImageUploadResult>({ height: 10, imageName: 'img-decline', width: 10 });+ });+ const dispatchBitmap = vi.fn(() => false);+ const onError = vi.fn();+ const store = createBitmapStore({+ debounceMs: 1500,+ dispatch: vi.fn(() => true),+ dispatchBitmap,+ encodeSurface,+ getLayerSource: () => PAINT_SOURCE,+ getLayerSurface: () => ({ offset: { x: 0, y: 0 }, surface }),+ hashBlob: (blob) => blob.text(),+ maxUploadAttempts: 2,+ onError,+ retryDelaysMs: [1],+ sleep: () => Promise.resolve(),+ uploadImage,+ });++ store.markLayerDirty(LAYER);+ // Two silent declines advance the streak without reporting anything.+ await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ expect(onError).not.toHaveBeenCalled();++ // A real upload failure lands mid-streak (position 3 of a 5-max streak):+ // under the old `failures === 1 || failures === max` check this matched+ // neither condition and would have gone unreported.+ content = 'pixels-B';+ uploadShouldFail = true;+ await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');++ expect(onError).toHaveBeenCalledOnce();+ expect(onError).toHaveBeenCalledWith(expect.any(Error), LAYER, { consecutiveFailures: 3, willRetry: true });++ store.dispose();+ });++ it('reports when silent declines alone open the circuit', async () => {+ const surface = createTestStubRasterBackend().createSurface(10, 10);+ const dispatchBitmap = vi.fn(() => false);+ const onError = vi.fn();+ const store = createBitmapStore({+ debounceMs: 1500,+ dispatch: vi.fn(() => true),+ dispatchBitmap,+ encodeSurface: () => Promise.resolve(new Blob(['pixels'], { type: 'image/png' })),+ getLayerSource: () => PAINT_SOURCE,+ getLayerSurface: () => ({ offset: { x: 0, y: 0 }, surface }),+ hashBlob: (blob) => blob.text(),+ maxConsecutiveFailures: 3,+ onError,+ uploadImage: () => Promise.resolve({ height: 10, imageName: 'img-decline', width: 10 }),+ });++ store.markLayerDirty(LAYER);+ await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed'); // decline 1 of 3.+ await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed'); // decline 2 of 3.+ expect(onError).not.toHaveBeenCalled();++ // decline 3 of 3 opens the circuit — silently opened, but must still be heard.+ await expect(store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');++ expect(onError).toHaveBeenCalledOnce();+ expect(onError).toHaveBeenCalledWith(expect.any(Error), LAYER, { consecutiveFailures: 3, willRetry: false });++ store.dispose();+ });++ it('a new stroke closes the circuit and resets the failure count', async () => {+ const timers = createManualTimers();+ let shouldFail = true;+ const uploadImage = vi.fn(() =>+ shouldFail+ ? Promise.reject(new Error('upload failed'))+ : Promise.resolve<CanvasImageUploadResult>({ height: 10, imageName: 'img-recovered', width: 10 })+ );+ const onError = vi.fn();+ const h = createHarness({ maxConsecutiveFailures: 2, maxUploadAttempts: 1, onError, timers, uploadImage });++ h.store.markLayerDirty(LAYER);+ timers.fireNext(); // failure 1 of 2.+ await drainUntil(() => timers.scheduledDelays.length === 2);+ timers.fireNext(); // failure 2 of 2 → circuit opens.+ await drainUntil(() => onError.mock.calls.length === 2);+ await drainUntil(() => false, 10);++ expect(timers.pendingCount()).toBe(0);++ // A fresh stroke closes the circuit: it schedules again at the base+ // debounce (not a backoff delay), and the now-succeeding upload clears+ // everything.+ shouldFail = false;+ h.store.markLayerDirty(LAYER);+ expect(timers.scheduledDelays.at(-1)).toBe(1500);++ timers.fireNext();+ await drainUntil(() => h.dispatch.mock.calls.length === 1);++ expect(h.dispatch).toHaveBeenCalledTimes(1);+ // The recovered flush does not report anything new.+ expect(onError).toHaveBeenCalledTimes(2);++ h.store.dispose();+ });++ it('a successful flush resets the failure count', async () => {+ const timers = createManualTimers();+ let shouldFail = true;+ const uploadImage = vi.fn(() =>+ shouldFail+ ? Promise.reject(new Error('upload failed'))+ : Promise.resolve<CanvasImageUploadResult>({ height: 10, imageName: 'img-ok', width: 10 })+ );+ const onError = vi.fn();+ const h = createHarness({ maxUploadAttempts: 1, onError, timers, uploadImage });++ h.store.markLayerDirty(LAYER);+ timers.fireNext(); // fails once → reported, backoff[0] scheduled.+ await drainUntil(() => timers.scheduledDelays.length === 2);+ expect(timers.scheduledDelays[1]).toBe(DEFAULT_FAILURE_BACKOFF_MS[0]);+ expect(onError).toHaveBeenCalledTimes(1);++ shouldFail = false;+ timers.fireNext(); // succeeds → clears the failure count.+ await drainUntil(() => h.dispatch.mock.calls.length === 1);++ // A later failure, on fresh pixels, is a new streak (consecutiveFailures:+ // 1), not a continuation of the earlier one.+ shouldFail = true;+ h.setEncoded('pixels-B');+ h.store.markLayerDirty(LAYER);+ timers.fireNext();+ await drainUntil(() => onError.mock.calls.length === 2);++ expect(onError).toHaveBeenNthCalledWith(2, expect.any(Error), LAYER, {+ consecutiveFailures: 1,+ willRetry: true,+ });+ expect(timers.scheduledDelays.at(-1)).toBe(DEFAULT_FAILURE_BACKOFF_MS[0]);++ h.store.dispose();+ });+ });});++describe('truthful extent: trimming and clearing', () => {+ /** A paint source already pointing at an uploaded bitmap. */+ const withBitmap: CanvasLayerSourceContract = {+ bitmap: { contentHash: 'h', height: 10, imageName: 'img-old', width: 10 },+ offset: { x: 0, y: 0 },+ type: 'paint',+ };++ it('clears the ref instead of uploading when the trim finds no visible pixels', async () => {+ const h = createHarness({ trimLayerPixels: () => 'emptied' });+ h.setSource(withBitmap);++ h.store.markLayerDirty(LAYER);+ await vi.advanceTimersByTimeAsync(1500);+ await h.store.flushPendingUploads();++ // A transparent PNG must never be encoded or uploaded.+ expect(h.encodeSurface).not.toHaveBeenCalled();+ expect(h.uploadImage).not.toHaveBeenCalled();+ expect(h.dispatch).toHaveBeenCalledTimes(1);+ expect(h.dispatch.mock.calls[0][0]).toEqual({+ id: LAYER,+ source: { bitmap: null, type: 'paint' },+ type: 'updateCanvasLayerSource',+ });+ h.store.dispose();+ });++ it('prefers the injected clearBitmap seam over the default dispatch', async () => {+ const h = createHarness({ clearBitmap: () => true, trimLayerPixels: () => 'emptied' });+ h.setSource(withBitmap);++ h.store.markLayerDirty(LAYER);+ await vi.advanceTimersByTimeAsync(1500);+ await h.store.flushPendingUploads();++ expect(h.clearBitmap).toHaveBeenCalledWith(LAYER);+ expect(h.dispatch).not.toHaveBeenCalled();+ h.store.dispose();+ });++ it('does not dispatch when the document already holds no bitmap', async () => {+ const h = createHarness({ trimLayerPixels: () => 'emptied' });+ // Default source is `{ bitmap: null }` — the clear would be a no-op.++ h.store.markLayerDirty(LAYER);+ await vi.advanceTimersByTimeAsync(1500);+ await h.store.flushPendingUploads();++ expect(h.dispatch).not.toHaveBeenCalled();+ h.store.dispose();+ });++ it('drops a stale self-echo entry when the document already holds no bitmap', async () => {+ let erased = false;+ const h = createHarness({ trimLayerPixels: () => (erased ? 'emptied' : 'kept') });++ h.store.markLayerDirty(LAYER);+ await h.store.flushPendingUploads();+ const applied = (h.dispatch.mock.calls[0][0] as { source: { bitmap: CanvasImageRef } }).source.bitmap;+ expect(h.store.isSelfEcho(LAYER, { bitmap: applied, type: 'paint' })).toBe(true);++ erased = true;+ h.setSource({ bitmap: null, type: 'paint' });+ h.store.markLayerDirty(LAYER);+ await h.store.flushPendingUploads();++ expect(h.store.isSelfEcho(LAYER, { bitmap: applied, type: 'paint' })).toBe(false);+ expect(h.dispatch).toHaveBeenCalledTimes(1);+ h.store.dispose();+ });++ it('drops the self-echo entry, so a later undo re-dispatching the old name is not mistaken for an echo', async () => {+ let erased = false;+ const h = createHarness({ trimLayerPixels: () => (erased ? 'emptied' : 'kept') });++ // First flush establishes `lastApplied` for the uploaded image.+ h.store.markLayerDirty(LAYER);+ await vi.advanceTimersByTimeAsync(1500);+ await h.store.flushPendingUploads();+ const applied = (h.dispatch.mock.calls[0][0] as { source: { bitmap: CanvasImageRef } }).source.bitmap;+ expect(h.store.isSelfEcho(LAYER, { bitmap: applied, type: 'paint' })).toBe(true);++ // Now the layer is erased and the trim empties it.+ erased = true;+ h.setSource({ bitmap: applied, offset: { x: 0, y: 0 }, type: 'paint' });+ h.store.markLayerDirty(LAYER);+ await vi.advanceTimersByTimeAsync(1500);+ await h.store.flushPendingUploads();++ expect(h.store.isSelfEcho(LAYER, { bitmap: applied, type: 'paint' })).toBe(false);+ h.store.dispose();+ });++ it('requeues as a failure when the clear is rejected', async () => {+ const onError = vi.fn();+ const h = createHarness({ clearBitmap: () => false, onError, trimLayerPixels: () => 'emptied' });+ h.setSource(withBitmap);++ h.store.markLayerDirty(LAYER);+ await vi.advanceTimersByTimeAsync(1500);+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ h.store.dispose();+ });++ it('retries a rejected clear after the trim has already collapsed the cache', async () => {+ let cacheEmpty = false;+ let clearAttempts = 0;+ const h = createHarness({+ clearBitmap: () => {+ clearAttempts += 1;+ return clearAttempts === 2;+ },+ getLayerSurface: (surface, offset) => (cacheEmpty ? null : { offset, surface }),+ trimLayerPixels: () => {+ if (cacheEmpty) {+ return 'kept';+ }+ cacheEmpty = true;+ return 'emptied';+ },+ });+ h.setSource(withBitmap);++ h.store.markLayerDirty(LAYER);+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ await expect(h.store.flushPendingUploads()).resolves.toBeUndefined();++ expect(h.clearBitmap).toHaveBeenCalledTimes(2);+ expect(h.encodeSurface).not.toHaveBeenCalled();+ expect(h.uploadImage).not.toHaveBeenCalled();+ h.store.dispose();+ });++ it('cancels a pending clear when a new stroke restores visible pixels', async () => {+ let cacheEmpty = false;+ let trimmedOnce = false;+ const h = createHarness({+ clearBitmap: () => false,+ getLayerSurface: (surface, offset) => (cacheEmpty ? null : { offset, surface }),+ trimLayerPixels: () => {+ if (!trimmedOnce) {+ trimmedOnce = true;+ cacheEmpty = true;+ return 'emptied';+ }+ return 'kept';+ },+ });+ h.setSource(withBitmap);++ h.store.markLayerDirty(LAYER);+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');++ cacheEmpty = false;+ h.store.markLayerDirty(LAYER);+ await expect(h.store.flushPendingUploads()).resolves.toBeUndefined();++ expect(h.clearBitmap).toHaveBeenCalledOnce();+ expect(h.uploadImage).toHaveBeenCalledOnce();+ h.store.dispose();+ });++ it('reports a throwing trim as a typed persistence failure and keeps it retryable', async () => {+ const error = new Error('alpha readback failed');+ const onError = vi.fn();+ const h = createHarness({+ onError,+ trimLayerPixels: () => {+ throw error;+ },+ });+ h.setSource(withBitmap);++ h.store.markLayerDirty(LAYER);+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');++ expect(h.trimLayerPixels).toHaveBeenCalledTimes(2);- expect(onError).toHaveBeenCalledTimes(2);- expect(onError).toHaveBeenNthCalledWith(1, error, LAYER);++ // Both attempts advance the shared breaker; only the streak's first failure++ // is reported (the second is a silent continuation, not a fresh problem).++ expect(onError).toHaveBeenCalledTimes(1);++ expect(onError).toHaveBeenNthCalledWith(1, error, LAYER, { consecutiveFailures: 1, willRetry: true });+ expect(h.encodeSurface).not.toHaveBeenCalled();+ h.store.dispose();+ });++ it('treats a throwing clear that nevertheless landed as success', async () => {+ let cleared = false;+ const onError = vi.fn();+ const h = createHarness({+ clearBitmap: () => {+ cleared = true;+ throw new Error('mirror notified synchronously and threw');+ },+ getAuthoritativeLayerSource: () => (cleared ? { bitmap: null, type: 'paint' } : withBitmap),+ onError,+ trimLayerPixels: () => 'emptied',+ });+ h.setSource(withBitmap);++ h.store.markLayerDirty(LAYER);+ await vi.advanceTimersByTimeAsync(1500);+ await h.store.flushPendingUploads();++ expect(onError).not.toHaveBeenCalled();+ h.store.dispose();+ });++ it('defers persistence without uploading an untrimmed surface, then retries when ready', async () => {+ let busy = true;+ const h = createHarness({ trimLayerPixels: () => (busy ? 'deferred' : 'kept') });++ h.store.markLayerDirty(LAYER);+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');++ expect(h.encodeSurface).not.toHaveBeenCalled();+ expect(h.uploadImage).not.toHaveBeenCalled();+ expect(h.dispatch).not.toHaveBeenCalled();++ busy = false;+ await expect(h.store.flushPendingUploads()).resolves.toBeUndefined();++ expect(h.uploadImage).toHaveBeenCalledTimes(1);+ expect(h.dispatch).toHaveBeenCalledTimes(1);+ h.store.dispose();+ });++ it('persists the POST-trim offset, proving the surface is re-read after trimming', async () => {+ // The trim moves the cache origin; the flush must carry the new one.+ const h = createHarness({+ offset: { x: 10, y: 10 },+ trimLayerPixels: () => {+ h.setOffset({ x: 34, y: 41 });+ return 'trimmed';+ },+ });++ h.store.markLayerDirty(LAYER);+ await vi.advanceTimersByTimeAsync(1500);+ await h.store.flushPendingUploads();++ expect(h.dispatch.mock.calls[0][0]).toMatchObject({+ source: { offset: { x: 34, y: 41 }, type: 'paint' },+ });+ h.store.dispose();+ });++ it('never trims a layer whose source has converted away from paint', async () => {+ const h = createHarness({ trimLayerPixels: () => 'emptied' });+ h.store.markLayerDirty(LAYER);+ h.setSource({ height: 10, kind: 'rect', fill: '#fff', stroke: null, strokeWidth: 0, type: 'shape', width: 10 });++ await vi.advanceTimersByTimeAsync(1500);+ await h.store.flushPendingUploads();++ // Trimming a parametric-backed cache would break the compositor's rect invariant.+ expect(h.trimLayerPixels).not.toHaveBeenCalled();+ expect(h.dispatch).not.toHaveBeenCalled();+ h.store.dispose();+ });+});diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.tsindex 8c92e75bf7,6390ba8207..515a419bff--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts@@@ -1,55 -1,30 +1,36 @@@/**- * The bitmap store: paint persistence via content-hashed server images.+ * Paint persistence via content-hashed server images.*- * Painting bakes strokes straight into a layer's raster cache surface (see- * `strokeSession`/`paintTool`), but nothing persists — a reload would lose the- * strokes. This store closes that loop: on each committed stroke it marks the- * layer dirty, and after a short idle window it encodes the layer's full cache- * surface to a PNG, content-hashes it (SHA-256), dedupes against already- * uploaded bitmaps, uploads new ones, and — only once the upload succeeds —- * dispatches `updateCanvasLayerSource` so the reducer-owned document points its- * paint layer at the persisted image name. The reducer stays pixel-free: only a- * `CanvasImageRef` (name + dims + hash) ever crosses the boundary.+ * Strokes bake into a layer's raster cache surface but nothing persists. On each+ * committed stroke this marks the layer dirty; after an idle window it encodes+ * the cache surface to PNG, SHA-256s it, dedupes, uploads, and only on success+ * dispatches `updateCanvasLayerSource`. The reducer stays pixel-free — only a+ * `CanvasImageRef` crosses the boundary.*- * Key invariants:- * - **Swap-on-success**: the contract keeps its previous ref until the upload- * resolves. A failed upload never dispatches; the layer stays dirty and the- * old ref stays valid, so a reload still shows the last persisted pixels.- * - **Debounce per layer** (~1.5 s idle): a new stroke resets the timer, so a- * burst of strokes uploads once.- * - **Content-hash dedupe**: identical pixels reuse the previously uploaded- * image name and skip the upload entirely. This is what makes undo cheap- * (restoring old pixels re-hashes to the already-uploaded image).- * - **Self-echo guard**: the dispatch round-trips back through the document- * mirror as a source change for the layer. {@link BitmapStore.isSelfEcho}- * lets the engine skip re-rasterizing/invalidating the cache for the exact- * bitmap ref this store just applied (the pixels already match).- * - **Source-type guard**: a layer's cache surface survives a source-type- * change (e.g. rasterize's paint bake, then an undo back to shape/gradient)- * — only the document's source pointer changes, not the cache. So every- * flush re-checks `getLayerSource` (at entry AND again right before the- * dispatch, since encode/hash/upload all await) and drops the pending work- * without dispatching if the layer is no longer `paint` (or no longer- * exists). Otherwise a stale debounced flush would silently convert a- * parametric layer back to `paint` with wrong-extent pixels.- * - **Redundant-dispatch skip is ground-truth, not memory**: right before- * dispatching, a flush skips if the DOCUMENT's current bitmap ref (via- * `getLayerSource`) already equals the resolved image name — not if- * `lastApplied` (this store's memory of what it last dispatched) does. A- * round trip through a non-`paint` source and back (rasterize → undo →- * redo) leaves `lastApplied` pointing at a name the document no longer- * references (the redo lands on `{ bitmap: null }`); comparing against that- * stale memory would suppress the re-dispatch forever. Comparing against- * the document itself self-heals regardless of how it drifted.- * - **Truthful extent**: the persisted bitmap's DIMENSIONS become the layer's+ * Invariants:+ * - **Swap-on-success**: a failed upload never dispatches, so the layer stays+ * dirty and a reload still shows the last persisted pixels.+ * - **Debounce per layer** (~1.5 s): a stroke burst uploads once.+ * - **Content-hash dedupe**: identical pixels skip the upload, which is what+ * makes undo cheap.+ * - **Self-echo guard**: the dispatch round-trips back as a source change;+ * {@link BitmapStore.isSelfEcho} lets the engine skip re-rasterizing it.+ * - **Source-type guard**: a cache surface survives a source-type change, so+ * every flush re-checks `getLayerSource` both at entry and again before+ * dispatching (encode/hash/upload all await). Otherwise a stale flush would+ * convert a parametric layer back to `paint` with wrong-extent pixels.+ * - **Redundant-dispatch skip reads the document, not `lastApplied`**: a round+ * trip through a non-`paint` source (rasterize → undo → redo) leaves+ * `lastApplied` naming an image the document no longer references, and+ * comparing against it would suppress the re-dispatch forever.++ * - **Truthful extent**: the persisted bitmap's dimensions become the layer's+ * content rect, which draws the move outline, frames the transform tool and- * drives fit-to-content. The cache only ever grows, so each flush first trims it- * to its visible pixels ({@link BitmapStoreDeps.trimLayerPixels}); a layer left- * with none is cleared to `{ bitmap: null }` rather than uploading a transparent- * PNG whose dimensions would keep reporting a phantom rect.++ * drives fit-to-content. The cache only ever grows, so each flush first trims++ * it to its visible pixels ({@link BitmapStoreDeps.trimLayerPixels}); a layer++ * left with none is cleared to `{ bitmap: null }` rather than uploading a++ * transparent PNG whose dimensions would keep reporting a phantom rect.*- * Every side-effecting dependency (encode, upload, hash, dispatch, timers) is- * injectable, so this runs in node tests with fakes. Zero React.+ * Every side effect is injectable, so this runs in node tests. Zero React.*/import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';@@@ -346,115 -326,52 +355,149 @@@ export const createBitmapStore = (depsthrow lastError ?? new Error('Canvas image upload failed');};+ /**+ * Shared bookkeeping for both ways a flush fails: a throw, and a decline+ * (`accepted !== true` — not an error, but bounded by the same breaker).+ * Advances `failureCounts` and re-dirties the layer, so `runFlush` reschedules+ * with backoff until `maxConsecutiveFailures`, after which only a fresh stroke+ * gets back in.+ *+ * Reports the first non-silent failure of a streak, plus — unconditionally —+ * the failure that opens the circuit, even a silent decline: once open,+ * strokes stop persisting entirely and that has to be heard. Everything else+ * stays quiet, or an unreachable server would toast once per retry forever,+ * including the barrier retries every Generate/export/blur attempts.+ *+ * Bookkeeping commits BEFORE `reportError`, because an observer may call back+ * into this store and its outcome must be the final word.+ */+ const recordFlushFailure = (layerId: string, error: unknown, options: { silent: boolean }): void => {+ const failures = (failureCounts.get(layerId) ?? 0) + 1;+ failureCounts.set(layerId, failures);+ const willRetry = failures < maxConsecutiveFailures;+ dirty.add(layerId);+ dirtyReason.set(layerId, 'failure');+ const opensCircuit = failures === maxConsecutiveFailures;+ if (!opensCircuit && (options.silent || reportedStreaks.has(layerId))) {+ return;+ }+ reportedStreaks.add(layerId);+ try {+ reportError(error, layerId, { consecutiveFailures: failures, willRetry });+ } catch {+ // Keep the bounded retry state intact when an observer itself fails.+ }+ };++ /**+ * Clears a layer's bitmap ref, for a layer the trim found empty. Synchronous+ * throughout, so no generation re-check is needed before the dispatch.+ */+ const clearLayerBitmap = (layerId: string, requeueFailure: (error: unknown) => void): void => {+ // Drop the self-echo entry on every path: the trim established that the live+ // cache no longer matches the last bitmap this store dispatched, including+ // when the document has already independently reached `bitmap: null`.+ lastApplied.delete(layerId);+ // Redundant-dispatch skip against GROUND TRUTH, not `lastApplied` — see the header.+ const sourceNow = deps.getLayerSource(layerId);+ if (!sourceNow || sourceNow.type !== 'paint') {+ pendingClears.delete(layerId);+ return;+ }+ if (!sourceNow.bitmap) {+ pendingClears.delete(layerId);+ return;+ }+ let accepted: boolean;+ try {+ accepted = deps.clearBitmap+ ? deps.clearBitmap(layerId)+ : deps.dispatch({+ id: layerId,+ source: { bitmap: null, type: 'paint' },+ type: 'updateCanvasLayerSource',+ });+ } catch (error) {+ const authoritativeSource = (deps.getAuthoritativeLayerSource ?? deps.getLayerSource)(layerId);+ // As on the upload path: a dispatch that threw after the reducer committed- // still landed, so it must not be requeued.++ // still landed, so it must not be requeued — and it closes the breaker.+ if (authoritativeSource?.type === 'paint' && !authoritativeSource.bitmap) {+ pendingClears.delete(layerId);++ failureCounts.delete(layerId);++ reportedStreaks.delete(layerId);+ return;+ }+ if (authoritativeSource !== null) {+ requeueFailure(error);+ }+ return;+ }+ if (accepted !== true && deps.getLayerSource(layerId) !== null) {- dirty.add(layerId);- dirtyReason.set(layerId, 'failure');- } else {- pendingClears.delete(layerId);++ // As with a declined bitmap dispatch: not a network error worth a toast of++ // its own, but it still advances (and can open) the shared breaker. The++ // clear stays pending, so the next flush re-attempts it even though the++ // trim has already collapsed the cache.++ recordFlushFailure(layerId, new Error('Bitmap clear was not accepted.'), { silent: true });++ return;+ }++ pendingClears.delete(layerId);++ failureCounts.delete(layerId);++ reportedStreaks.delete(layerId);+ };+/** Encodes → hashes → dedupes/uploads → swaps the layer's ref, once. */const flushLayer = async (layerId: string): Promise<void> => {const generationAtEntry = layerGenerations.get(layerId) ?? 0;const isCurrentGeneration = (): boolean => !disposed && (layerGenerations.get(layerId) ?? 0) === generationAtEntry;const requeueFailure = (error: unknown): void => {if (!isCurrentGeneration()) {+ // A discard/reset already invalidated this flush; its own bookkeeping+ // stands, and this stale failure has nothing left to report.return;}- // Requeue before notifying. An injected error observer may deliberately- // discard/reset this generation; its cancellation must be the final word,- // not followed by a stale dirty.add(). Observer exceptions are ancillary.- dirty.add(layerId);- dirtyReason.set(layerId, 'failure');- try {- reportError(error, layerId);- } catch {- // Keep the bounded retry state intact when an observer itself fails.- }+ recordFlushFailure(layerId, error, { silent: false });};+ // Source-type guard (see `getLayerSource` doc): the dirty mark may predate+ // a conversion away from `paint` (rasterize → undo is the motivating case,+ // but any convert-back qualifies). The cache surface survives a source swap,+ // so without this check we'd encode and dispatch a `paint` source over a layer+ // that is no longer paint at all. Drop the pending flush entirely: nothing+ // about this dirty mark is still valid, and a future genuine paint stroke will+ // re-mark it if the layer ever becomes a paint layer again.+ //+ // Also before the TRIM: shrinking a cache that now backs a parametric render+ // would break the compositor's cache-rect-equals-content-rect invariant.+ const sourceAtEntry = deps.getLayerSource(layerId);+ if (!sourceAtEntry || sourceAtEntry.type !== 'paint') {+ pendingClears.delete(layerId);+ dirty.delete(layerId);+ clearTimer(layerId);+ return;+ }+ // Truthful extent (see the header). `getLayerSurface` below re-reads the cache,+ // so it picks up the trimmed surface and origin with no further work.+ let trimResult: PaintCacheTrim = 'kept';+ try {+ trimResult = deps.trimLayerPixels?.(layerId) ?? 'kept';+ } catch (error) {+ requeueFailure(error);+ return;+ }+ if (trimResult === 'emptied') {+ pendingClears.add(layerId);+ }+ if (trimResult === 'deferred') {+ dirty.add(layerId);+ dirtyReason.set(layerId, 'deferred');+ clearTimer(layerId);+ return;+ }+ if (pendingClears.has(layerId)) {+ dirty.delete(layerId);+ clearTimer(layerId);+ clearLayerBitmap(layerId, requeueFailure);+ return;+ }const placed = deps.getLayerSurface(layerId);if (!placed) {// Layer or its cache is gone (or empty); nothing to persist.@@@ -617,9 -546,19 +658,22 @@@}const op = flushLayer(layerId).finally(() => {inFlight.delete(layerId);-- // Re-dirtied during the flush (new stroke) or a failure re-queued it.++ // Re-dirtied during the flush (new stroke), deferred by an operation that++ // still owns the pixels, or a failure re-queued it.if (dirty.has(layerId) && !disposed && !isSuspended(layerId)) {- scheduleFlush(layerId);+ if (dirtyReason.get(layerId) !== 'failure') {++ // `'stroke'` and `'deferred'` both re-poll on the ordinary debounce;++ // a deferral is transient and costs only the trim's busy check.+ scheduleFlush(layerId);+ } else {+ const failures = failureCounts.get(layerId) ?? 0;+ if (failures < maxConsecutiveFailures) {+ scheduleFlush(layerId, failureBackoffMs[Math.min(failures - 1, failureBackoffMs.length - 1)] ?? debounceMs);+ }+ // failures >= max: the circuit is open — stay dirty, no timer. A new+ // stroke (markLayerDirty) or a flushPendingUploads barrier call is+ // the only way back in.+ }} else {// Any invalidated operation for this id has now settled and there is no// successor waiting to inherit its generation. Retire the tombstone.@@@ -634,7 -573,10 +688,11 @@@if (disposed) {return;}+ // A fresh stroke closes the circuit: whatever was failing about the old+ // pixels no longer applies to the ones about to be persisted.+ failureCounts.delete(layerId);+ reportedStreaks.delete(layerId);+ pendingClears.delete(layerId);dirty.add(layerId);dirtyReason.set(layerId, 'stroke');if (!isSuspended(layerId)) {@@@ -696,7 -638,8 +754,9 @@@dirty.delete(layerId);dirtyReason.delete(layerId);lastApplied.delete(layerId);+ failureCounts.delete(layerId);+ reportedStreaks.delete(layerId);+ pendingClears.delete(layerId);clearTimer(layerId);};