Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(webv2): bitmap persistence circuit breaker

joshistoastc896e8cf38ce
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
index d5bcc2b225..c0f20fd24f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
@@ -6,10 +6,55 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { createBitmapStore } from './bitmapStore';
+import type { BitmapStoreTimers } from './bitmapStore';
+
+import { createBitmapStore, DEFAULT_FAILURE_BACKOFF_MS } from './bitmapStore';
const LAYER = 'layer-1';
+/**
+ * A manual, fully-controlled timer stub for the ambient-failure tests: jobs
+ * queue up (recording their requested delay) and only run when explicitly
+ * fired via `fireNext`, so a test can assert the exact reschedule delay at
+ * each step without depending on fake-timer advancement matching it.
+ */
+interface ManualTimers extends BitmapStoreTimers {
+ /** Every delay ever passed to `setTimeout`, in call order. */
+ readonly scheduledDelays: number[];
+ /** Runs the oldest still-pending job's handler synchronously, if any. */
+ fireNext(): void;
+ /** Count of jobs queued but not yet fired or cleared. */
+ pendingCount(): number;
+}
+
+const createManualTimers = (): ManualTimers => {
+ let nextHandle = 1;
+ const jobs = new Map<number, () => void>();
+ const scheduledDelays: number[] = [];
+ return {
+ clearTimeout: (handle) => {
+ jobs.delete(handle);
+ },
+ fireNext: () => {
+ const next = jobs.entries().next();
+ if (next.done) {
+ return;
+ }
+ const [handle, handler] = next.value;
+ jobs.delete(handle);
+ handler();
+ },
+ pendingCount: () => jobs.size,
+ scheduledDelays,
+ setTimeout: (handler, ms) => {
+ const handle = nextHandle++;
+ jobs.set(handle, handler);
+ scheduledDelays.push(ms);
+ return handle;
+ },
+ };
+};
+
/** A resolvable deferred, so a test can hold an upload pending on demand. */
const createDeferred = <T>(): {
promise: Promise<T>;
@@ -37,10 +82,14 @@ interface HarnessOptions {
hashBlob?: (blob: Blob) => Promise<string>;
uploadImage?: (blob: Blob) => Promise<CanvasImageUploadResult>;
maxUploadAttempts?: number;
- onError?: (error: unknown, layerId: string) => void;
+ failureBackoffMs?: readonly number[];
+ maxConsecutiveFailures?: number;
+ onError?: (error: unknown, layerId: string, info: { consecutiveFailures: number; willRetry: boolean }) => void;
/** The layer-local content-rect origin the surface sits at (default 0,0). */
offset?: { x: number; y: number };
sleep?: (ms: number) => Promise<void>;
+ /** 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. */
@@ -68,15 +117,18 @@ const createHarness = (options: HarnessOptions = {}) => {
debounceMs: 1500,
dispatch,
encodeSurface,
+ failureBackoffMs: options.failureBackoffMs,
getLayerSource: () => source,
getLayerSurface: () => ({ 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],
// Immediate backoff so retries don't depend on timer advancement.
sleep: options.sleep ?? (() => Promise.resolve()),
+ timers: options.timers,
uploadImage,
});
@@ -705,6 +757,10 @@ describe('createBitmapStore', () => {
debounceMs: 1500,
dispatch,
encodeSurface: () => Promise.resolve(new Blob(['pixels'], { type: 'image/png' })),
+ // A fixed 1500ms ambient retry delay, unrelated to this test's subject
+ // (the barrier's own anti-spin): the growing-backoff schedule is covered
+ // by the dedicated 'ambient failure handling' tests below.
+ failureBackoffMs: [1500],
getLayerSource: () => PAINT_SOURCE,
getLayerSurface: () => ({ offset: { x: 0, y: 0 }, surface }),
hashBlob: (blob) => blob.text(),
@@ -726,7 +782,8 @@ describe('createBitmapStore', () => {
expect(dispatch).not.toHaveBeenCalled();
expect(onError).toHaveBeenCalledTimes(1);
- // The layer is still dirty (deferred, not dropped): a later debounce retries it.
+ // The layer is still dirty (deferred, not dropped): a later ambient retry
+ // (at the fixed backoff configured above) fires it again.
await vi.advanceTimersByTimeAsync(1500);
expect(uploadImage.mock.calls.length).toBeGreaterThan(2);
@@ -1132,4 +1189,160 @@ 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('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();
+ });
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
index 20a8e510c2..2b709ed179 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
@@ -59,6 +59,10 @@ export const DEFAULT_MAX_UPLOAD_ATTEMPTS = 3;
export const DEFAULT_RETRY_DELAYS_MS = [250, 1000] as const;
/** Default cap on the hash→image dedupe map. */
export const DEFAULT_DEDUPE_CAP = 64;
+/** Growing re-flush delays after consecutive ambient failures. */
+export const DEFAULT_FAILURE_BACKOFF_MS = [2000, 5000, 15000, 30000] as const;
+/** Consecutive ambient failures before the circuit opens (no more auto-retries). */
+export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
export class BitmapPersistenceError extends Error {
readonly layerIds: readonly string[];
@@ -127,12 +131,21 @@ export interface BitmapStoreDeps {
retryDelaysMs?: readonly number[];
/** Cap on the dedupe map (default {@link DEFAULT_DEDUPE_CAP}). */
dedupeCap?: number;
+ /** Growing re-flush delays after consecutive ambient failures (default {@link DEFAULT_FAILURE_BACKOFF_MS}). */
+ failureBackoffMs?: readonly number[];
+ /** Consecutive ambient failures before the circuit opens (default {@link DEFAULT_MAX_CONSECUTIVE_FAILURES}). */
+ maxConsecutiveFailures?: number;
/** Injectable timers (default: global). */
timers?: BitmapStoreTimers;
/** Injectable delay used for retry backoff (default: `timers.setTimeout`). */
sleep?(ms: number): Promise<void>;
- /** Reports a persistent flush/upload failure. Omitted callbacks leave the failure unreported. */
- onError?(error: unknown, layerId: string): void;
+ /**
+ * Reports a persistent flush/upload failure. Called on the FIRST failure of a
+ * streak and again when the circuit opens; intermediate retries are silent, so
+ * a persistently failing layer surfaces one report, not one every retry cycle.
+ * Omitted callbacks leave the failure unreported.
+ */
+ onError?(error: unknown, layerId: string, info: { consecutiveFailures: number; willRetry: boolean }): void;
}
/** The imperative bitmap-store handle. */
@@ -192,6 +205,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
const maxAttempts = Math.max(1, deps.maxUploadAttempts ?? DEFAULT_MAX_UPLOAD_ATTEMPTS);
const retryDelays = deps.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
const dedupeCap = Math.max(1, deps.dedupeCap ?? DEFAULT_DEDUPE_CAP);
+ const failureBackoffMs = deps.failureBackoffMs ?? DEFAULT_FAILURE_BACKOFF_MS;
+ const maxConsecutiveFailures = Math.max(1, deps.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES);
const timers = deps.timers ?? defaultTimers;
const hashBlob = deps.hashBlob ?? defaultHashBlob;
const sleep =
@@ -200,7 +215,11 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
new Promise((resolve) => {
timers.setTimeout(resolve, ms);
}));
- const reportError = (error: unknown, layerId: string): void => deps.onError?.(error, layerId);
+ const reportError = (
+ error: unknown,
+ layerId: string,
+ info: { consecutiveFailures: number; willRetry: boolean }
+ ): void => deps.onError?.(error, layerId, info);
/** Layers awaiting a flush (either debounced or re-dirtied during a flush). */
const dirty = new Set<string>();
@@ -216,6 +235,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
const debounceTimers = new Map<string, number>();
/** The in-flight flush op per layer (at most one), used by the barrier and to serialize. */
const inFlight = new Map<string, Promise<void>>();
+ /** Consecutive ambient flush failures per layer; cleared on success or a fresh stroke. */
+ const failureCounts = new Map<string, number>();
/** Content-hash → uploaded image, an LRU-ish dedupe cache (bounded). */
const hashToImage = new Map<string, CanvasImageUploadResult>();
/** Layer id → the image name most recently dispatched by this store (self-echo guard). */
@@ -253,12 +274,12 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
}
};
- const scheduleFlush = (layerId: string): void => {
+ const scheduleFlush = (layerId: string, delayMs: number = debounceMs): void => {
clearTimer(layerId);
const handle = timers.setTimeout(() => {
debounceTimers.delete(layerId);
void runFlush(layerId);
- }, debounceMs);
+ }, delayMs);
debounceTimers.set(layerId, handle);
};
@@ -328,12 +349,21 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// 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.
+ const failures = (failureCounts.get(layerId) ?? 0) + 1;
+ failureCounts.set(layerId, failures);
+ const willRetry = failures < maxConsecutiveFailures;
dirty.add(layerId);
dirtyReason.set(layerId, 'failure');
- try {
- reportError(error, layerId);
- } catch {
- // Keep the bounded retry state intact when an observer itself fails.
+ // Report only the first failure of a streak and the one that opens the
+ // circuit — an unreachable server would otherwise toast once per retry,
+ // forever. Intermediate retries stay silent; `runFlush`'s `finally` still
+ // bounds them via the same `failureCounts` and growing backoff below.
+ if (failures === 1 || !willRetry) {
+ try {
+ reportError(error, layerId, { consecutiveFailures: failures, willRetry });
+ } catch {
+ // Keep the bounded retry state intact when an observer itself fails.
+ }
}
};
const placed = deps.getLayerSurface(layerId);
@@ -460,6 +490,10 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// Record BEFORE dispatching: `dispatch` may notify the mirror synchronously,
// so `isSelfEcho` must already see the applied name when the engine reacts.
lastApplied.set(layerId, result.imageName);
+ // The upload that may have been failing repeatedly just succeeded: close the
+ // ambient breaker so a later failure is reported (and backed off) as a fresh
+ // streak, not a silent continuation of one already surfaced.
+ failureCounts.delete(layerId);
let accepted: boolean;
try {
accepted = deps.dispatchBitmap
@@ -495,6 +529,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
if (accepted !== true) {
lastApplied.delete(layerId);
if (deps.getLayerSource(layerId) !== null) {
+ // Bounded by the same breaker as an upload failure, but silent: a
+ // declined acceptance isn't a network/server error worth surfacing.
+ failureCounts.set(layerId, (failureCounts.get(layerId) ?? 0) + 1);
dirty.add(layerId);
dirtyReason.set(layerId, 'failure');
}
@@ -514,7 +551,17 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
inFlight.delete(layerId);
// Re-dirtied during the flush (new stroke) or a failure re-queued it.
if (dirty.has(layerId) && !disposed && !isSuspended(layerId)) {
- scheduleFlush(layerId);
+ if (dirtyReason.get(layerId) !== 'failure') {
+ 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.
@@ -529,6 +576,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
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);
dirty.add(layerId);
dirtyReason.set(layerId, 'stroke');
if (!isSuspended(layerId)) {
@@ -590,6 +640,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
dirty.delete(layerId);
dirtyReason.delete(layerId);
lastApplied.delete(layerId);
+ failureCounts.delete(layerId);
clearTimer(layerId);
};
@@ -665,6 +716,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// The self-echo map is per-(old)document; a reused layer id in the new
// document must not inherit it. `hashToImage` is content-addressed and kept.
lastApplied.clear();
+ // Same reasoning as `lastApplied`: a reused layer id in the new document
+ // must start with a closed circuit, not inherit the old document's streak.
+ failureCounts.clear();
};
const dispose = (): void => {
@@ -681,6 +735,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
hashToImage.clear();
lastApplied.clear();
layerGenerations.clear();
+ failureCounts.clear();
};
return { discardLayer, dispose, flushPendingUploads, isSelfEcho, markLayerDirty, reset, suspendLayer };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 04e2a38361..7f5adce9bc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -546,7 +546,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
return { offset: { x: entry.rect.x, y: entry.rect.y }, surface: entry.surface };
},
- onError: (error, layerId) => reportError('Bitmap persistence failed', layerId, error),
+ onError: (error, layerId, _info) => reportError('Bitmap persistence failed', layerId, error),
uploadImage: (blob) => opts.uploadImage(blob),
});
const persistenceController = new PersistenceController(bitmapStore);
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index d0d6734bfa..8429e4db25 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -2102,6 +2102,39 @@ describe('workbenchReducer Phase 5 generation flow', () => {
expect(state.notifications).toEqual([]);
});
+ it('coalesces back-to-back identical notifications instead of stacking them', () => {
+ const state = createInitialWorkbenchState();
+
+ const once = reduceWorkbench(state, { message: 'Bitmap persistence failed', type: 'recordError' });
+ const twice = reduceWorkbench(once, { message: 'Bitmap persistence failed', type: 'recordError' });
+
+ expect(twice.notifications).toHaveLength(once.notifications.length);
+ expect(twice.notifications[0]?.occurrenceCount).toBe(2);
+ expect(twice.notifications[0]?.id).toBe(once.notifications[0]?.id);
+ });
+
+ it('includes the error context detail in the recordError notification message', () => {
+ const state = createInitialWorkbenchState();
+
+ const next = reduceWorkbench(state, {
+ context: { error: 'network unreachable', layerId: 'layer-1' },
+ message: 'Bitmap persistence failed',
+ type: 'recordError',
+ });
+
+ expect(next.notifications[0]?.message).toBe('Bitmap persistence failed: network unreachable');
+ });
+
+ it('does not coalesce notifications with a different message', () => {
+ const state = createInitialWorkbenchState();
+
+ const once = reduceWorkbench(state, { message: 'Bitmap persistence failed', type: 'recordError' });
+ const twice = reduceWorkbench(once, { message: 'Something else failed', type: 'recordError' });
+
+ expect(twice.notifications).toHaveLength(once.notifications.length + 1);
+ expect(twice.notifications[0]?.id).not.toBe(once.notifications[0]?.id);
+ });
+
describe('enqueue notifications', () => {
it('records an enqueue notification when submitResolvedInvocationSnapshot adds a queue item', () => {
const state = primeGenerate();
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index a58f70480c..f8362e495a 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -368,7 +368,7 @@ type WorkbenchReducerAction =
type: 'recordError';
message: string;
area?: string;
- context?: Record<string, unknown>;
+ context?: { error?: string; layerId?: string };
namespace?: DeveloperLogNamespace;
projectId?: string;
}
@@ -424,10 +424,30 @@ const createNotification = ({
title,
});
-const addNotification = (state: WorkbenchState, notification: WorkbenchNotification): WorkbenchState => ({
- ...state,
- notifications: [notification, ...state.notifications].slice(0, NOTIFICATION_LIMIT),
-});
+const addNotification = (state: WorkbenchState, notification: WorkbenchNotification): WorkbenchState => {
+ const [newest, ...rest] = state.notifications;
+
+ // Coalesce an exact repeat of the newest notification into an occurrence
+ // bump on the SAME id, instead of stacking a new one — the toaster dedupes
+ // toasts by id, so a repeat then stops re-toasting for free (e.g. an
+ // ambient retry failing the same way every cycle).
+ if (
+ newest &&
+ newest.kind === notification.kind &&
+ newest.title === notification.title &&
+ newest.message === notification.message
+ ) {
+ return {
+ ...state,
+ notifications: [
+ { ...newest, createdAt: notification.createdAt, occurrenceCount: (newest.occurrenceCount ?? 1) + 1 },
+ ...rest,
+ ],
+ };
+ }
+
+ return { ...state, notifications: [notification, ...state.notifications].slice(0, NOTIFICATION_LIMIT) };
+};
/** Adds the "Invocation queued" notice iff the reduction actually grew the active queue. */
const withEnqueueNotification = (state: WorkbenchState, nextState: WorkbenchState): WorkbenchState => {
@@ -4112,7 +4132,15 @@ export const __workbenchReducerInternal = (
);
}
case 'recordError': {
- return addNotification(state, createNotification({ kind: 'error', message: action.message, title: 'Error' }));
+ const detail = action.context?.error;
+ return addNotification(
+ state,
+ createNotification({
+ kind: 'error',
+ message: detail ? `${action.message}: ${detail}` : action.message,
+ title: 'Error',
+ })
+ );
}
case 'setBackendConnectionStatus': {
const timestamp = now();