Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(sync): preserve confirmed updates and recover stalled saves (#10161)
Josh Corbett86860b930b44
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex ad2f94077c..459ee21e16 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -52,6 +52,7 @@ Behavior specs live beside their owning code. Read the owner's document before c| ------------------------------------------------------------- | -------------------------------------------------------------------------------------- || Identity credential and session lifetimes | [features/identity/README.md](src/features/identity/README.md) || Application and project event logging | [platform/logging/README.md](src/platform/logging/README.md) |+| Models catalog and read fencing | [features/models/README.md](src/features/models/README.md) || Queue backend port and active sessions | [features/queue/README.md](src/features/queue/README.md) || Gallery listings and reveal | [features/gallery/README.md](src/features/gallery/README.md) || Intermediates manager and cleanup | [features/intermediates/README.md](src/features/intermediates/README.md) |diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 0cb757c1ce..544d234849 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -171,6 +171,7 @@}},"common": {+ "requestTimedOut": "The request timed out. Retry the operation.","donateToInvokeAI": "Donate to Invoke","actions": "Actions","active": "Active",diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex 94f91b2857..56d5529cf7 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -614,7 +614,11 @@ const runResponsiveTopbarJourney = async (browser) => {try {await waitForWorkbench(page);- await page.getByRole('button', { exact: true, name: '0 images remaining. Open queue' }).waitFor();+ // The representative queue is populated; measure the hydrated counter rather than its transient idle state.+ await page+ .locator('header')+ .getByRole('button', { name: /^[1-9]\d* (images? remaining|items? waiting for the connection)\. Open queue$/ })+ .waitFor();for (const width of [1_024, 900]) {await page.setViewportSize({ height: 900, width });diff --git a/invokeai/frontend/webv2/src/app/GalleryRealtimeRuntime.tsx b/invokeai/frontend/webv2/src/app/GalleryRealtimeRuntime.tsxindex 2892829b2c..e9a8ed3f44 100644--- a/invokeai/frontend/webv2/src/app/GalleryRealtimeRuntime.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryRealtimeRuntime.tsx@@ -9,8 +9,8 @@ import { attachExternalGenerationReveal } from '@workbench/image-actions/recallPimport { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';/**- * App-owned composition: uploads and other clients' completed generations the backend announces over the socket- * refresh the Gallery read model, and those whose batch asked for it are revealed in the Gallery.+ * App-owned composition: uploads and own-account socket completions refresh the Gallery in visible tabs.+ * Only external origins whose batch asked for reveal can change Gallery selection.*/export const GalleryRealtimeRuntime = () => {const queryClient = useQueryClient();@@ -38,6 +38,11 @@ export const GalleryRealtimeRuntime = () => {invalidate: () => invalidateGallery(queryClient),isClientQueueItemOrigin: isWebv2QueueItemOrigin,onRevealRequest: revealer.request,+ isVisible: () => document.visibilityState === 'visible',+ onVisibilityChange: (listener) => {+ document.addEventListener('visibilitychange', listener);+ return () => document.removeEventListener('visibilitychange', listener);+ },});runtime.start();diff --git a/invokeai/frontend/webv2/src/features/gallery/README.md b/invokeai/frontend/webv2/src/features/gallery/README.mdindex 4790fb2d84..ba8edaf82b 100644--- a/invokeai/frontend/webv2/src/features/gallery/README.md+++ b/invokeai/frontend/webv2/src/features/gallery/README.md@@ -14,7 +14,7 @@ Move, star and archive report an Undo (`notify.undoable`). Undo puts back each i## Realtime refresh and external reveal-Uploads, reconnects, and the signed-in user's completed queue items whose origin does not start with `webv2:` refresh the listings. This client's own items are refreshed by Queue, in the tab that tracks them only.+Uploads, reconnects, and all of the signed-in user's completed queue items refresh the listings, including completions from other frontend tabs and devices. Gallery owns socket-completion invalidation; Queue does not also refresh for those events. Bursts coalesce for 250 ms and passes stay at least 1 second apart, with a trailing pass for later events. Hidden tabs keep one pending refresh until shown. Query invalidations serialize and await active refetches, so a slow listing read lands before a later pass begins. Frontend origins (`webv2:`) refresh only: they never select an item, change filters, board or page, or request external reveal. Image and video results share this completion path.An external client asks for its results to be revealed by enqueueing with `POST /api/v1/queue/default/enqueue_batch` and `batch.destination` set to `gallery:reveal`. The request is honored only for the signed-in user's items (any user's on a single-user server) whose origin does not start with `webv2:`. Every other destination only refreshes, `gallery` included: legacy web sends it on every workflow and upscale run.diff --git a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.browser.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.browser.test.tsnew file mode 100644index 0000000000..78d99e4495--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.browser.test.ts@@ -0,0 +1,162 @@+import type { GalleryItem, GalleryItemsPage } from '@features/gallery/core/items';++import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryObserver } from '@tanstack/react-query';+import { afterEach, expect, it, vi } from 'vitest';++import { galleryItemsPageOptions } from './queries';+import { invalidateGallery } from './queryCache';+import { createGalleryRealtimeRuntime } from './realtimeRuntime';++const transport = vi.hoisted(() => ({ listItems: vi.fn() }));+vi.mock('./backend', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ listGalleryItems: transport.listItems,+}));++const cleanup: Array<() => void> = [];+afterEach(() => {+ for (const dispose of cleanup.splice(0).reverse()) {+ dispose();+ }+});++const item = (name: string, boardId: string): GalleryItem => ({+ boardId,+ category: 'general',+ createdAt: '2026-11-05T00:00:00Z',+ fullUrl: `/full/${name}`,+ height: 64,+ isIntermediate: false,+ kind: 'image',+ name,+ starred: false,+ thumbnailUrl: `/thumb/${name}`,+ width: 64,+});++it('refreshes two independent listings over browser completion events without starving slow reads or revealing', async () => {+ accountLifecycle.activate('realtime-browser');+ let savedName = 'before.png';+ let slow = false;+ const pendingReads: Array<() => void> = [];+ const releaseReads = () => {+ for (const resolve of pendingReads.splice(0)) {+ resolve();+ }+ };+ cleanup.push(releaseReads);+ const completed = new Map<string, number>();+ const canceled = vi.fn();+ transport.listItems.mockReset().mockImplementation(async ({ boardId, signal }) => {+ const name = savedName;+ signal.addEventListener('abort', canceled, { once: true });+ try {+ if (slow) {+ await new Promise<void>((resolve) => {+ pendingReads.push(resolve);+ });+ }+ signal.throwIfAborted();+ completed.set(boardId, (completed.get(boardId) ?? 0) + 1);+ return { items: [item(name, boardId)], total: 1 };+ } finally {+ signal.removeEventListener('abort', canceled);+ }+ });++ const channelName = `gallery-completions-${crypto.randomUUID()}`;+ const sender = new BroadcastChannel(channelName);+ cleanup.push(() => sender.close());+ const sessions = ['tab-one', 'tab-two'].map((boardId) => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ cleanup.push(() => client.clear());+ const observer = new QueryObserver(+ client,+ galleryItemsPageOptions({ boardId, galleryView: 'images', searchTerm: '' }, 0)+ );+ cleanup.push(observer.subscribe(() => undefined));+ const receiver = new BroadcastChannel(channelName);+ cleanup.push(() => receiver.close());+ const reveal = vi.fn();+ const invalidate = vi.fn(() => invalidateGallery(client));+ const runtime = createGalleryRealtimeRuntime({+ backend: {+ on: (event, handler) => {+ const listener = ({ data }: MessageEvent) => {+ if (data.event === event) {+ handler(data.payload as never);+ }+ };+ receiver.addEventListener('message', listener);+ return () => receiver.removeEventListener('message', listener);+ },+ onConnectionChange: () => () => undefined,+ },+ getSessionUserId: () => 'alice',+ invalidate,+ isClientQueueItemOrigin: (origin) => origin?.startsWith('webv2:') === true,+ onRevealRequest: reveal,+ });+ runtime.start();+ cleanup.push(runtime.dispose);+ return {+ boardId,+ observer,+ reveal,+ invalidate,+ };+ });+ await vi.waitFor(() => expect(sessions.every(({ observer }) => observer.getCurrentResult().isSuccess)).toBe(true));+ expect(transport.listItems).toHaveBeenCalledTimes(2);+ const completion = () =>+ sender.postMessage({+ event: 'queue_item_status_changed',+ payload: {+ destination: 'gallery:reveal',+ item_id: 1,+ origin: 'webv2:another-tab',+ status: 'completed',+ user_id: 'alice',+ },+ });+ slow = true;+ savedName = 'new-output.png';+ completion();+ await vi.waitFor(() => expect(pendingReads).toHaveLength(2));+ // Hold both reads past the runtime's coalescing interval, until another delivered event requests a trailing pass.+ completion();+ await vi.waitFor(+ () => {+ for (const { invalidate } of sessions) {+ expect(invalidate).toHaveBeenCalledTimes(2);+ }+ },+ { timeout: 4000 }+ );+ expect(transport.listItems).toHaveBeenCalledTimes(4);+ expect(canceled).not.toHaveBeenCalled();+ releaseReads();+ await vi.waitFor(() => {+ expect(transport.listItems).toHaveBeenCalledTimes(6);+ expect(pendingReads).toHaveLength(2);+ });+ releaseReads();+ await vi.waitFor(+ () => {+ for (const { boardId, observer } of sessions) {+ expect(completed.get(boardId)).toBeGreaterThanOrEqual(3);+ const data: GalleryItemsPage | undefined = observer.getCurrentResult().data;+ expect(data?.items[0]?.name).toBe('new-output.png');+ expect(observer.getCurrentResult().fetchStatus).toBe('idle');+ }+ },+ { timeout: 6000 }+ );+ expect(canceled).not.toHaveBeenCalled();+ expect(transport.listItems).toHaveBeenCalledTimes(6);+ for (const { reveal, invalidate } of sessions) {+ expect(reveal).not.toHaveBeenCalled();+ expect(invalidate).toHaveBeenCalledTimes(2);+ }+});diff --git a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.test.tsindex ec223f22f1..9017764813 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.test.ts@@ -29,6 +29,9 @@ describe('gallery realtime runtime', () => {};const invalidate = vi.fn();let sessionUserId: string | null = 'alice';+ let visible = true;+ let visibilityHandler: (() => void) | null = null;+ const detachVisibility = vi.fn();const getSessionUserId = () => sessionUserId;const onRevealRequest = vi.fn();const CLIENT_ORIGIN = 'this-client';@@ -39,6 +42,14 @@ describe('gallery realtime runtime', () => {invalidate,isClientQueueItemOrigin: (origin) => origin === CLIENT_ORIGIN,onRevealRequest,+ isVisible: () => visible,+ onVisibilityChange: (handler) => {+ visibilityHandler = handler;+ return () => {+ visibilityHandler = null;+ detachVisibility();+ };+ },});const emitStatusChanged = (event: {destination?: string | null;@@ -63,6 +74,9 @@ describe('gallery realtime runtime', () => {connectionHandler = null;initialStatus = 'connected';sessionUserId = 'alice';+ visible = true;+ visibilityHandler = null;+ detachVisibility.mockReset();backend.on.mockClear();backend.onConnectionChange.mockClear();invalidate.mockReset();@@ -120,6 +134,44 @@ describe('gallery realtime runtime', () => {runtime.dispose();});+ it('defers hidden-tab bursts until visible and cancels a queued pass when hidden', () => {+ const runtime = createRuntime();+ runtime.start();+ emitStatusChanged({ origin: CLIENT_ORIGIN });+ visible = false;+ visibilityHandler?.();+ expect(vi.getTimerCount()).toBe(0);+ for (let item_id = 0; item_id < 20; item_id += 1) {+ emitStatusChanged({ origin: CLIENT_ORIGIN, item_id, destination: 'gallery:reveal' });+ vi.advanceTimersByTime(1000);+ }+ expect(invalidate).not.toHaveBeenCalled();+ expect(onRevealRequest).not.toHaveBeenCalled();+ visible = true;+ visibilityHandler?.();+ vi.advanceTimersByTime(250);+ expect(invalidate).toHaveBeenCalledTimes(1);+ vi.advanceTimersByTime(1000);+ expect(invalidate).toHaveBeenCalledTimes(1);+ runtime.dispose();+ expect(detachVisibility).toHaveBeenCalledTimes(1);+ });++ it('drops hidden pending work on disposal or account expiration', () => {+ visible = false;+ const runtime = createRuntime();+ runtime.start();+ emitStatusChanged({ origin: CLIENT_ORIGIN });+ accountLifecycle.invalidate();+ visible = true;+ visibilityHandler?.();+ vi.advanceTimersByTime(1000);+ expect(invalidate).not.toHaveBeenCalled();+ runtime.dispose();+ expect(visibilityHandler).toBeNull();+ expect(vi.getTimerCount()).toBe(0);+ });+it('refetches after an outage but not on the boot-time connect', () => {initialStatus = 'connecting';const runtime = createRuntime();@@ -190,16 +242,15 @@ describe('gallery realtime runtime', () => {runtime.dispose();});- it('ignores completions that cannot add to this gallery or that Queue already refreshes for', () => {+ it('ignores other-account completions and non-completed items', () => {const runtime = createRuntime();const destination = 'gallery:reveal';runtime.start();// Another user's item, as an admin receives it, and as everyone else receives it.emitStatusChanged({ destination, user_id: 'bob' });+ emitStatusChanged({ destination, user_id: 'bob', origin: CLIENT_ORIGIN });emitStatusChanged({ destination: null, origin: null, user_id: 'redacted' });- // An item this client enqueued, which Queue refreshes for in the tab tracking it.- emitStatusChanged({ destination, origin: CLIENT_ORIGIN });for (const status of ['pending', 'in_progress', 'waiting', 'failed', 'canceled'] as const) {emitStatusChanged({ destination, status });@@ -212,6 +263,19 @@ describe('gallery realtime runtime', () => {runtime.dispose();});+ it('coalesces frontend completions from this and other tabs without revealing', () => {+ const runtime = createRuntime();+ runtime.start();+ for (let item_id = 1; item_id <= 20; item_id += 1) {+ emitStatusChanged({ destination: 'gallery:reveal', origin: CLIENT_ORIGIN, item_id });+ emitStatusChanged({ destination: 'gallery:reveal', origin: CLIENT_ORIGIN, item_id });+ }+ vi.advanceTimersByTime(250);+ expect(invalidate).toHaveBeenCalledTimes(1);+ expect(onRevealRequest).not.toHaveBeenCalled();+ runtime.dispose();+ });+it('hands on only the completions whose batch asked to be revealed', () => {const runtime = createRuntime();diff --git a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.tsindex b246965408..678c3547d1 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts@@ -32,9 +32,8 @@ export interface GalleryRealtimeRuntime {}/**- * Refresh external uploads, the session user's completions enqueued by other clients, and reconnects at least- * minIntervalMs apart. Coalesce pending events and guarantee a trailing pass without repeatedly cancelling page- * fetches.+ * Refresh uploads, all of the session user's completions, and reconnects at least minIntervalMs apart. Hidden+ * tabs retain one pending pass until visible. The Query invalidation owner serializes slow refetches.*/export const createGalleryRealtimeRuntime = ({backend,@@ -42,17 +41,21 @@ export const createGalleryRealtimeRuntime = ({getSessionUserId,invalidate,isClientQueueItemOrigin,+ isVisible = () => true,minIntervalMs = 1000,onRevealRequest,+ onVisibilityChange,}: {backend: GalleryRealtimeBackend;coalesceMs?: number;/** Null when events cannot be attributed to a user (single-user servers tag every event `system`). */getSessionUserId: () => string | null;invalidate: () => void | Promise<void>;- /** True for origins of items this client enqueues; Queue refreshes for those in the tab that tracks them. */+ /** Frontend origins refresh only; they never request external reveal. */isClientQueueItemOrigin: (origin: string | null) => boolean;+ isVisible?: () => boolean;minIntervalMs?: number;+ onVisibilityChange?: (listener: () => void) => () => void;/** Receives the backend item id of each of those completions whose batch asked to be revealed. */onRevealRequest?: (queueItemId: number) => void;}): GalleryRealtimeRuntime => {@@ -61,10 +64,11 @@ export const createGalleryRealtimeRuntime = ({let invalidationTimer: ReturnType<typeof setTimeout> | null = null;let lastInvalidatedAt = Number.NEGATIVE_INFINITY;let isStarted = false;+ let invalidationPending = false;const isActive = (): boolean => isStarted && isAccountScopeCurrent(owner);const scheduleInvalidation = (): void => {- if (!isActive() || invalidationTimer !== null) {+ if (!isActive() || !invalidationPending || !isVisible() || invalidationTimer !== null) {return;}@@ -75,32 +79,40 @@ export const createGalleryRealtimeRuntime = ({invalidationTimer = setTimeout(() => {invalidationTimer = null;- if (isActive()) {+ if (isActive() && isVisible()) {+ invalidationPending = false;lastInvalidatedAt = performance.now();void invalidate();}}, delay);};+ const requestInvalidation = (): void => {+ if (isActive()) {+ invalidationPending = true;+ scheduleInvalidation();+ }+ };++ const handleVisibilityChange = (): void => {+ if (!isVisible() && invalidationTimer !== null) {+ clearTimeout(invalidationTimer);+ invalidationTimer = null;+ }+ scheduleInvalidation();+ };+const handleQueueItemStatusChanged = (event: QueueItemStatusChangedPayload): void => {- // Admins also receive other users' full events and everyone else's arrive redacted, so only the session user's- // completions can add to this gallery. Items this client enqueued are left to Queue, which refreshes only in the- // tab tracking the item: another tab or device of the same user is not refreshed for them. Known limitation,- // left intentionally: refreshing here too would double-refresh the enqueuing tab.+ // Admins receive other users' events too. All own-account completions refresh here, including other tabs.const sessionUserId = getSessionUserId();- if (- !isActive() ||- event.status !== 'completed' ||- isClientQueueItemOrigin(event.origin) ||- (sessionUserId !== null && event.user_id !== sessionUserId)- ) {+ if (!isActive() || event.status !== 'completed' || (sessionUserId !== null && event.user_id !== sessionUserId)) {return;}- scheduleInvalidation();+ requestInvalidation();- if (event.destination === REVEAL_DESTINATION) {+ if (!isClientQueueItemOrigin(event.origin) && event.destination === REVEAL_DESTINATION) {onRevealRequest?.(event.item_id);}};@@ -117,8 +129,8 @@ export const createGalleryRealtimeRuntime = ({let previousStatus: BackendConnectionStatus | null = null;detachers.push(- backend.on('image_uploaded', scheduleInvalidation),- backend.on('video_uploaded', scheduleInvalidation),+ backend.on('image_uploaded', requestInvalidation),+ backend.on('video_uploaded', requestInvalidation),backend.on('queue_item_status_changed', handleQueueItemStatusChanged),backend.onConnectionChange((status) => {const isReconnect = previousStatus === 'disconnected' && status === 'connected';@@ -126,14 +138,18 @@ export const createGalleryRealtimeRuntime = ({previousStatus = status;if (isReconnect) {- scheduleInvalidation();+ requestInvalidation();}}));+ if (onVisibilityChange) {+ detachers.push(onVisibilityChange(handleVisibilityChange));+ }};const dispose = (): void => {isStarted = false;+ invalidationPending = false;for (const detach of detachers.splice(0)) {detach();diff --git a/invokeai/frontend/webv2/src/features/models/README.md b/invokeai/frontend/webv2/src/features/models/README.mdnew file mode 100644index 0000000000..1e74b14fbd--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/README.md@@ -0,0 +1,7 @@+# Models catalog++Paths are relative to the webv2 `src/` directory.++`features/models/data/modelsStore.ts` owns the shared catalog snapshot and by-key index. List refreshes are single-flight with at most one queued trailing read. Local model replacement, narrow patches (including optimistic rollback), deletion, and cover changes advance a mutation generation. A read started before that generation cannot replace the catalog or publish an obsolete error; it queues an authoritative trailing read so unrelated server changes remain visible. Cover URL versions remain local cache-busting state. Only successful mutation callers apply confirmed changes; a failed request alone does not supersede a valid read.++Account reset clears the catalog and flight state. Responses from an earlier account lifetime cannot update the current catalog or schedule reads for it.diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.browser.test.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.browser.test.tsnew file mode 100644index 0000000000..e433de8849--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.browser.test.ts@@ -0,0 +1,85 @@+import type { ModelConfig } from '@features/models/core/types';++import { accountLifecycle } from '@platform/state/accountLifecycle';+import { afterEach, expect, it, vi } from 'vitest';++import { deleteModel, updateModel } from './api';+import { getModelsSnapshot, refreshModels, removeModelsFromStore, replaceModelInStore } from './modelsStore';++afterEach(() => {+ vi.unstubAllGlobals();+ accountLifecycle.invalidate();+});++it.each(['rename', 'delete'] as const)(+ 'preserves a confirmed %s across deferred HTTP list responses',+ async (mutation) => {+ accountLifecycle.activate(`models-browser-${mutation}`);+ const original = { key: 'model-a', name: 'Before', base: 'sdxl', type: 'main' } as ModelConfig;+ let serverModels = [original];+ let finishOld!: () => void;+ let finishTrailing!: () => void;+ let listReads = 0;+ const mutationRequests: string[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn((input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(String(input), location.href);+ if (url.pathname.endsWith('/models/missing')) {+ return Promise.resolve(Response.json({ models: [] }));+ }+ if (url.pathname.endsWith('/models/models_dir')) {+ return Promise.resolve(Response.json('/models'));+ }+ if (url.pathname.endsWith('/models/')) {+ listReads += 1;+ const snapshot = [...serverModels];+ if (listReads === 2) {+ return new Promise<Response>((resolve) => {+ finishOld = () => resolve(Response.json({ models: snapshot }));+ });+ }+ if (listReads === 3) {+ return new Promise<Response>((resolve) => {+ finishTrailing = () => resolve(Response.json({ models: serverModels }));+ });+ }+ return Promise.resolve(Response.json({ models: snapshot }));+ }+ if (url.pathname.endsWith('/models/i/model-a')) {+ mutationRequests.push(init?.method ?? 'GET');+ if (init?.method === 'DELETE') {+ serverModels = [];+ return Promise.resolve(new Response(null, { status: 204 }));+ }+ const model = { ...original, name: 'Confirmed rename' };+ serverModels = [model];+ return Promise.resolve(Response.json(model));+ }+ throw new Error(`Unexpected model request: ${url.pathname}`);+ })+ );+ await refreshModels();+ const oldRead = refreshModels();+ if (mutation === 'rename') {+ replaceModelInStore(await updateModel(original.key, { name: 'Confirmed rename' }));+ } else {+ await deleteModel(original.key);+ removeModelsFromStore([original.key]);+ }+ const confirmed = getModelsSnapshot().models;+ finishOld();+ await oldRead;+ expect(getModelsSnapshot().models).toEqual(confirmed);+ expect(getModelsSnapshot().error).toBeNull();+ expect(listReads).toBe(3);+ expect(mutationRequests).toEqual([mutation === 'rename' ? 'PATCH' : 'DELETE']);+ serverModels = [...serverModels, { ...original, key: 'model-b', name: 'Unrelated server model' }];+ finishTrailing();+ await vi.waitFor(() => expect(getModelsSnapshot().modelsByKey.get('model-b')?.name).toBe('Unrelated server model'));+ expect(getModelsSnapshot().modelsByKey.get('model-a')?.name).toBe(+ mutation === 'rename' ? 'Confirmed rename' : undefined+ );+ expect(listReads).toBe(3);+ }+);diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.tsindex ffa25b2545..a78d56682f 100644--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts@@ -63,6 +63,99 @@ describe('models store loading', () => {expect(store.getModelsSnapshot().models.map((model) => model.key)).toEqual(['a']);});+ it.each(['replace', 'patch', 'delete', 'cover'] as const)(+ 'fences an older list after a confirmed %s and reads unrelated changes on the trailing pass',+ async (mutation) => {+ const original = { key: 'a', name: 'Before', cover_image: null } as ModelConfig;+ let finishOld!: (models: ModelConfig[]) => void;+ let finishFresh!: (models: ModelConfig[]) => void;+ api.listModels+ .mockReturnValueOnce(+ new Promise((resolve) => {+ finishOld = resolve;+ })+ )+ .mockReturnValueOnce(+ new Promise((resolve) => {+ finishFresh = resolve;+ })+ );+ const store = await import('./modelsStore');+ store.setModelsSnapshotForTests({ models: [original], status: 'loaded' });+ const refresh = store.refreshModels();+ if (mutation === 'replace') {+ store.replaceModelInStore({ ...original, name: 'After' });+ }+ if (mutation === 'patch') {+ store.patchModelInStore('a', { name: 'After' });+ }+ if (mutation === 'delete') {+ store.removeModelsFromStore(['a']);+ }+ if (mutation === 'cover') {+ store.markCoverImageChanged('a', true);+ }+ const confirmed = store.getModelsSnapshot().models;+ finishOld([original]);+ await refresh;+ expect(store.getModelsSnapshot().models).toEqual(confirmed);+ expect(api.listModels).toHaveBeenCalledTimes(2);+ finishFresh([...confirmed, { key: 'b', name: 'Unrelated' } as ModelConfig]);+ await store.ensureModelsLoaded();+ expect(store.getModelsSnapshot().modelsByKey.get('b')?.name).toBe('Unrelated');+ }+ );++ it('discards an obsolete list error after a mutation and still reads the authoritative trailing result', async () => {+ const original = { key: 'a', name: 'Before' } as ModelConfig;+ let rejectOld!: (error: Error) => void;+ let finishFresh!: (models: ModelConfig[]) => void;+ api.listModels+ .mockReturnValueOnce(+ new Promise((_resolve, reject) => {+ rejectOld = reject;+ })+ )+ .mockReturnValueOnce(+ new Promise((resolve) => {+ finishFresh = resolve;+ })+ );+ const store = await import('./modelsStore');+ store.setModelsSnapshotForTests({ models: [original], status: 'loaded' });+ const refresh = store.refreshModels();+ store.replaceModelInStore({ ...original, name: 'Confirmed' });+ rejectOld(new Error('Obsolete failure'));+ await refresh;+ expect(store.getModelsSnapshot()).toMatchObject({ error: null, status: 'loaded' });+ expect(store.getModelsSnapshot().modelsByKey.get('a')?.name).toBe('Confirmed');+ expect(api.listModels).toHaveBeenCalledTimes(2);+ finishFresh([{ ...original, name: 'Confirmed' }, { key: 'b', name: 'Unrelated' } as ModelConfig]);+ await store.ensureModelsLoaded();+ expect(store.getModelsSnapshot().modelsByKey.get('b')?.name).toBe('Unrelated');+ });++ it('accepts authoritative data after an optimistic change rolls back', async () => {+ const model = { key: 'a', name: 'Before', cpu_only: null } as ModelConfig;+ let finishOld!: (models: ModelConfig[]) => void;+ api.listModels+ .mockReturnValueOnce(+ new Promise((resolve) => {+ finishOld = resolve;+ })+ )+ .mockResolvedValueOnce([{ ...model, name: 'Server rename' }]);+ const store = await import('./modelsStore');+ store.setModelsSnapshotForTests({ models: [model], status: 'loaded' });+ const refresh = store.refreshModels();+ store.patchModelInStore('a', { cpu_only: true });+ store.patchModelInStore('a', { cpu_only: null });+ finishOld([model]);+ await refresh;+ await store.ensureModelsLoaded();+ expect(store.getModelsSnapshot().modelsByKey.get('a')).toMatchObject({ name: 'Server rename', cpu_only: null });+ });+it('unwraps FastAPI detail bodies into the snapshot error', async () => {const { ApiError } = await import('@platform/transport/http');api.listModels.mockRejectedValueOnce(new ApiError('{"detail":"Model records unavailable"}', 500));diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.tsindex 6c2279dc7c..2ff6911f4c 100644--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts@@ -52,9 +52,11 @@ const withModels = (models: ModelConfig[]): Pick<ModelsSnapshot, 'models' | 'modconst store = createExternalStore<ModelsSnapshot>(EMPTY_MODELS_SNAPSHOT);const refreshFlight = createTrailingSingleFlight();+let mutationGeneration = 0;registerAccountOwnedResource({clear: () => {+ mutationGeneration = 0;refreshFlight.reset();store.setSnapshot(EMPTY_MODELS_SNAPSHOT);},@@ -64,6 +66,7 @@ registerAccountOwnedResource({/** Re-fetch the library; concurrent calls share one request, and a call made mid-flight queues one trailing rerun. */export const refreshModels = (owner: AccountScope = captureAccountScope()): Promise<void> =>refreshFlight.run(() => {+ const generation = mutationGeneration;store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });return Promise.all([@@ -78,6 +81,11 @@ export const refreshModels = (owner: AccountScope = captureAccountScope()): Promreturn;}+ if (generation !== mutationGeneration) {+ void refreshModels(owner);+ return;+ }+store.patchSnapshot({...withModels(models),error: null,@@ -92,6 +100,11 @@ export const refreshModels = (owner: AccountScope = captureAccountScope()): Promreturn;}+ if (generation !== mutationGeneration) {+ void refreshModels(owner);+ return;+ }+store.patchSnapshot({error: getApiErrorMessage(error, 'Failed to load models.'),status: store.getSnapshot().models.length > 0 ? 'loaded' : 'error',@@ -117,6 +130,7 @@ export const subscribeModels = (listener: () => void): (() => void) => store.sub/** Patch one model in place after a successful update/convert. */export const replaceModelInStore = (model: ModelConfig): void => {+ mutationGeneration += 1;store.patchSnapshot(withModels(store.getSnapshot().models.map((existing) => (existing.key === model.key ? model : existing))));@@ -124,12 +138,14 @@ export const replaceModelInStore = (model: ModelConfig): void => {/** Apply a narrow optimistic model patch without replacing unrelated server fields. */export const patchModelInStore = (key: string, changes: Partial<ModelConfig>): void => {+ mutationGeneration += 1;store.patchSnapshot(withModels(store.getSnapshot().models.map((model) => (model.key === key ? { ...model, ...changes } : model))));};export const removeModelsFromStore = (keys: string[]): void => {+ mutationGeneration += 1;const removed = new Set(keys);store.patchSnapshot(withModels(store.getSnapshot().models.filter((model) => !removed.has(model.key))));@@ -137,6 +153,7 @@ export const removeModelsFromStore = (keys: string[]): void => {/** Update cover presence and URL version without refetching; backend cover URLs remain stable. */export const markCoverImageChanged = (key: string, hasImage: boolean): void => {+ mutationGeneration += 1;const { coverImageVersions, models } = store.getSnapshot();store.patchSnapshot({diff --git a/invokeai/frontend/webv2/src/features/queue/README.md b/invokeai/frontend/webv2/src/features/queue/README.mdindex 41067a730e..a3cd69f034 100644--- a/invokeai/frontend/webv2/src/features/queue/README.md+++ b/invokeai/frontend/webv2/src/features/queue/README.md@@ -10,6 +10,8 @@ Retry re-runs failed or canceled backend items under new ids; the run owning the`submitUtilityGraph` (`@features/queue/utility`) returns once the backend accepts the graph; its `settled` watch ends on the first of: a terminal status event for its origin; a re-read of its accepted items that finds a terminal status or answers 404 (`removed`), triggered by `queue_cleared`, a reconnect after a disconnect, `queue_items_canceled` naming an accepted id, or the periodic reconcile read, which re-arms while the item stays open; or an abort of its signal (`aborted`), which stops watching and leaves the backend item alone.+Gallery owns coalesced socket-completion invalidation for the account across tabs; Queue retains its connection reconciliation refresh. Completion invalidation does not depend on whether this tab tracks the run.+## Actions`ui/queueMenuActions.tsx` is the one queue action model: the top bar's button and menu, the widget header and its menu, and shortcuts (`requestQueueAction` in `@features/queue/reveal`, taken by the queue's always-mounted host once the read model has loaded) all call an action's `trigger`, never its runner. Its policy: cancelling the running item never asks, since Retry brings it back; cancelling all, cancelling all but the current item, and clearing failed, finished or all items always confirm, naming the scope and how many items they reach, with a way out that never reads "Cancel". Results report the same scope and counts. Pause and resume are one toggle that states what waits on the processor.diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.tsindex 775bd94fa4..f8bc6c8a36 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts@@ -581,51 +581,6 @@ describe('queueCoordinator', () => {});});- it('coalesces gallery refreshes across a burst of completions', async () => {- vi.useFakeTimers();- harness = createHarness({ galleryRefreshCoalesceMs: 400 });- harness.api.enqueueGenerate.mockResolvedValue({- batchId: 'batch-1',- enqueued: 10,- itemIds: Array.from({ length: 10 }, (_, index) => index + 1),- requested: 10,- });- harness.coordinator.connect();- await harness.coordinator.submitGenerate('local-1', generateRequest);- await vi.advanceTimersByTimeAsync(500); // flush the on-connect refresh- harness.callbacks.onGalleryRefresh.mockClear();-- for (let itemId = 1; itemId <= 10; itemId += 1) {- harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: itemId }));- }-- await vi.advanceTimersByTimeAsync(500);-- expect(harness.callbacks.onGalleryRefresh).toHaveBeenCalledTimes(1);- });-- it('does not refresh the gallery for failed or canceled items', async () => {- vi.useFakeTimers();- harness = createHarness({ galleryRefreshCoalesceMs: 400 });- harness.api.enqueueGenerate.mockResolvedValue({- batchId: 'batch-1',- enqueued: 2,- itemIds: [1, 2],- requested: 2,- });- harness.coordinator.connect();- await harness.coordinator.submitGenerate('local-1', generateRequest);- await vi.advanceTimersByTimeAsync(500); // flush the on-connect refresh- harness.callbacks.onGalleryRefresh.mockClear();-- harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1, status: 'failed' }));- harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 2, status: 'canceled' }));-- await vi.advanceTimersByTimeAsync(500);-- expect(harness.callbacks.onGalleryRefresh).not.toHaveBeenCalled();- });-it('routes progress events to the tracked item and clears them on completion', async () => {harness.coordinator.connect();diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.tsindex b0da14af22..3425edfa22 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts@@ -850,9 +850,7 @@ export const createQueueCoordinator = (settleWait(event.item_id, toTerminalOutcome(event.status, event.error_message, event.error_type));- if (event.status === 'completed') {- scheduleGalleryRefresh();- }+ // Gallery owns socket-completion invalidation across tabs.};const handleItemsCanceled = (event: QueueItemsCanceledEvent): void => {diff --git a/invokeai/frontend/webv2/src/platform/transport/http.test.ts b/invokeai/frontend/webv2/src/platform/transport/http.test.tsindex 304f4625f4..6da4ffceef 100644--- a/invokeai/frontend/webv2/src/platform/transport/http.test.ts+++ b/invokeai/frontend/webv2/src/platform/transport/http.test.ts@@ -1,7 +1,8 @@import { DEFAULT_LOGGING_CONFIG } from '@platform/logging/contracts';import { configureLogging, getLogSnapshot, resetLogging } from '@platform/logging/logger';import { accountLifecycle } from '@platform/state/accountLifecycle';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import i18next from 'i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';vi.mock('./deploymentBase', () => ({getDeploymentBasePath: () => '/invoke',@@ -10,6 +11,8 @@ vi.mock('./deploymentBase', () => ({import {ApiError,+ RequestDeadlineError,+ withRequestDeadline,absolutizeApiUrl,apiFetch,apiFetchJson,@@ -383,3 +386,108 @@ describe('structured error details', () => {expect(getApiErrorCode(new Error('offline'))).toBeNull();});});++describe('request deadline cancellation', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ configureTestAuth(() => ({ identity: null, token: null }));+ });+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ it.each(['headers', 'body', 'error-body'] as const)('aborts a hung %s and disposes the deadline', async (phase) => {+ let signal!: AbortSignal;+ vi.stubGlobal(+ 'fetch',+ vi.fn((_url, init) => {+ signal = init.signal;+ if (phase === 'headers') {+ return new Promise(() => {+ /* Simulate an unresponsive request. */+ });+ }+ return Promise.resolve(new Response(new ReadableStream(), { status: phase === 'body' ? 200 : 500 }));+ })+ );+ const result = expect(+ withRequestDeadline((signal) => apiFetchJson('/hung', { signal }), 100)+ ).rejects.toBeInstanceOf(RequestDeadlineError);+ await vi.advanceTimersByTimeAsync(100);+ await result;+ expect(signal.aborted).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(['caller', 'account'] as const)('cancels underlying work immediately on %s abort', async (source) => {+ const caller = new AbortController();+ let requestSignal!: AbortSignal;+ const result = withRequestDeadline(+ (signal) => {+ requestSignal = signal;+ return new Promise(() => {+ /* Simulate an unresponsive request. */+ });+ },+ 100,+ caller.signal+ );+ const rejected = expect(result).rejects.toMatchObject({ name: 'AbortError' });+ if (source === 'caller') {+ caller.abort();+ } else {+ accountLifecycle.invalidate();+ }+ await rejected;+ expect(requestSignal.aborted).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('uses the active language when a deadline surfaces an error', async () => {+ await i18next.init({+ lng: 'es',+ fallbackLng: false,+ resources: {+ es: { translation: { common: { requestTimedOut: 'Tiempo agotado. Vuelva a intentarlo.' } } },+ },+ });+ try {+ const result = expect(withRequestDeadline(() => new Promise(() => {}), 100)).rejects.toThrow(+ 'Tiempo agotado. Vuelva a intentarlo.'+ );+ await vi.advanceTimersByTimeAsync(100);+ await result;+ } finally {+ i18next.removeResourceBundle('es', 'translation');+ await i18next.changeLanguage('en');+ }+ });++ it('consumes a late rejection after the deadline has already ended the wait', async () => {+ let rejectLate!: (error: Error) => void;+ const result = expect(+ withRequestDeadline(+ () =>+ new Promise((_resolve, reject) => {+ rejectLate = reject;+ }),+ 100+ )+ ).rejects.toBeInstanceOf(RequestDeadlineError);+ await vi.advanceTimersByTimeAsync(100);+ await result;+ rejectLate(new Error('late response failure'));+ await vi.advanceTimersByTimeAsync(0);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('cleans up after success, rejection and an already aborted caller', async () => {+ await expect(withRequestDeadline(() => Promise.resolve(1), 100)).resolves.toBe(1);+ await expect(withRequestDeadline(() => Promise.reject(new Error('failed')), 100)).rejects.toThrow('failed');+ const request = vi.fn();+ await expect(withRequestDeadline(request, 100, AbortSignal.abort())).rejects.toMatchObject({ name: 'AbortError' });+ expect(request).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/transport/http.ts b/invokeai/frontend/webv2/src/platform/transport/http.tsindex b5b2209431..f251923a82 100644--- a/invokeai/frontend/webv2/src/platform/transport/http.ts+++ b/invokeai/frontend/webv2/src/platform/transport/http.ts@@ -5,6 +5,7 @@import { recordLogEvent } from '@platform/logging/logger';import { captureAccountScope } from '@platform/state/accountLifecycle';+import i18next from 'i18next';import { getDeploymentBasePath, getDeploymentBaseUrl } from './deploymentBase';@@ -350,3 +351,36 @@ export const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>signal?.addEventListener('abort', onAbort, { once: true });});++/** Bound an entire operation, including body consumption, while cancelling its underlying requests. */+export const withRequestDeadline = async <T>(+ request: (signal: AbortSignal) => Promise<T>,+ timeoutMs: number,+ signal?: AbortSignal+): Promise<T> => {+ const controller = new AbortController();+ const requestSignal = AbortSignal.any([controller.signal, captureAccountScope().signal, ...(signal ? [signal] : [])]);+ const timer = setTimeout(() => controller.abort(new RequestDeadlineError()), Math.max(0, timeoutMs));+ let rejectAborted: (() => void) | undefined;+ try {+ requestSignal.throwIfAborted();+ return await new Promise<T>((resolve, reject) => {+ rejectAborted = () => reject(requestSignal.reason);+ requestSignal.addEventListener('abort', rejectAborted, { once: true });+ // Attach both handlers even if cancellation wins, so a late rejection is always consumed.+ request(requestSignal).then(resolve, reject);+ });+ } finally {+ clearTimeout(timer);+ if (rejectAborted) {+ requestSignal.removeEventListener('abort', rejectAborted);+ }+ }+};++export class RequestDeadlineError extends Error {+ constructor() {+ super(i18next.t('common.requestTimedOut', { defaultValue: 'The request timed out. Retry the operation.' }));+ this.name = 'RequestDeadlineError';+ }+}diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.mdindex 9677ca96ed..f512b69375 100644--- a/invokeai/frontend/webv2/src/workbench/projects/README.md+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md@@ -34,6 +34,14 @@ Workflow reads the active workflow through the App-composed port and edits, publWorkbench persistence is scoped to one mounted Workbench and its account lifetime. `createWorkbenchPersistenceRuntime` owns hydration ordering, debounced autosave, hidden-page saves, revision/generation checks, conflict application, reconnect replay, status publication, exit checkpoint, without importing React. `createSyncedWorkbenchPersistence` builds local/remote project sync state for one mounted Workbench; no process-wide maps, sets, flags, or caches hold that state. It also owns the unload journal: runtime asks it, via its persistence port, to journal unsaved state synchronously when page is hidden or unloads, and its load reconciles the journal into the draft store under the draft store's fencing rules. `WorkbenchProvider` constructs these lifetimes, starts the runtime and ends it with its exit checkpoint through the mount lifecycle adapter, and selects aggregate hydration state. Checkpoint and persistence lease outlive the unmount until it settles. Provider also hands the checkpoint to the account lifetime's next editor through a module-level map keyed by account scope; that editor loads after it, waiting at most 10 seconds; the tab's editor session is reference-counted across the two. Project transition commands commit pending editor drafts themselves, so callers do not flush before creating, opening, switching, or closing a project.+Project record reads, content/workspace writes, and project deletion have a 150-second request deadline, including response-body consumption. This allows the server's 120-second maximum request upload duration plus 30 seconds for processing and the response, so supported large documents can save over slower connections. Client-state reads have a 30-second deadline. Cancellation aborts the request and ends the wait, with timer/listener cleanup on every settlement. Uploads and model operations have no universal deadline; an import’s project creation uses these project budgets. Busy project writes admit at most nine attempts within 125 seconds; every started attempt gets its full 150 seconds, so a late admitted attempt may finish about 275 seconds after the operation began. A project request that stalls releases the serialized save queue, so later edits and project switches in the same mounted editor can save once any following session write settles. Dirty drafts remain pending on unavailable reconciliation; normal autosave retry/status policy applies, without parallel writes.++A deadline does not prove a write failed. Creates repeat their reserved identity only within the write admission budget and reconcile matching content; absence after unanswered attempts never authorizes cleanup. Content/workspace timeouts use revision/content reconciliation: acknowledge held bytes, retry unchanged or previously sent server state once at its revision, or report divergence. Unanswered state survives that retry, so a late commit followed by a revision conflict does not invent a competing writer. An inconclusive read or exhausted unanswered retry leaves the draft pending. Undo to previously acknowledged bytes still sends revision-fenced writes for any half with an unanswered different body. A read holding the desired bytes at a strictly newer revision also proves the fence; an unchanged revision cannot prove that older body will not commit later. Whole documents retain the same sent-body evidence. A reconciled create applies its server board assignment and refreshes board lists.++A timed-out delete repeats the same identity and board policy once; settled idempotent deletion confirms the outcome even if the first attempt committed. Reconciliation reads have their own 150-second deadline. An immediately unanswered create exhausts its 125-second write admission window in the first 150-second attempt, then reads once inside the API and once more in durable persistence: an unanswered result can take 450 seconds. Busy backoff before a final admitted request and both reads can extend that to about 575 seconds. Each project half and reconciliation read has its own budget; an entire multi-project save has no single wall-clock deadline. Browser suspension can delay timers. Server work may commit after cancellation; identity/revision fencing, rather than cancellation alone, prevents duplicate creation and stale acknowledgement.++Client-state writes (session, account settings, and cover index) are unconditional and have no application deadline. Their callers keep writes ordered until the request settles; a timed-out request could otherwise commit after a newer write and overwrite it. A hung session write can still hold the autosave queue, and a hung settings or cover-index write holds its own queue. Account cancellation, unload journaling, and bounded editor re-entry retain their existing limits; bounding these writes safely requires server-side write ordering or revision fencing.+## Browser recovery- Account-owned IndexedDB stores only unacknowledged project drafts, unload journal entries, active queue runs, receipt acknowledgements, bounded recall values. Clean server documents not mirrored. Journal has its own database, deleted with the workbench database by account cleanup and by clearing workspace data.@@ -58,7 +66,7 @@ Navigation never blocked in the app; local capture of committed state is the con- **Closing the last tab.** Empty session is marked closed when requested. From then until editor leaves, nothing saves, so project cannot be written back into the session. If close does not complete (queue work started, project changed, or session write failed), session is reopened and written again, and a save that came due while closed (an edit committed meanwhile) runs at once, so its outcome reaches autosave status and retries as usual.- **Account changes.** Ended account lifetime abandons its checkpoint: nothing of the old account is written afterwards.- **Re-entry.** Remounted editor of same account loads only after previous checkpoint settled and its persistence closed, so it never hydrates an older snapshot and two editors never write at once. Provider keeps that handoff per account lifetime, keyed by its scope, so another account never waits on it.-- **Re-entry after 10 seconds.** New editor loads anyway. Previous checkpoint is superseded: starts no further write and gives up its project mutation locks. If it still had an unsaved revision, it logs that the revision was not written. Staging happens inside the persistence queue, so while a request stalls nothing newer than the save before it reaches local recovery; edits committed after that are lost in this case, before any unload, so no unload prompt can keep them. A tab closed during the wait instead journals them through the exit checkpoint (above), and is prompted as an editor is. Stalled request is not cancelled. Until it returns, or tab closes, superseded persistence keeps its draft-store connection and its hold on the tab's editor session. New editor holds the same session, which stays locked to this tab until its last holder releases it. Late write is fenced like another tab's, by draft-writer claims and revision conflicts.+- **Re-entry after 10 seconds.** New editor loads anyway. Previous checkpoint is superseded: starts no further write and gives up its project mutation locks. If it still had an unsaved revision, it logs that the revision was not written. Staging happens inside the persistence queue, so while a request stalls nothing newer than the save before it reaches local recovery; edits committed after that are lost in this case, before any unload, so no unload prompt can keep them. A tab closed during the wait instead journals them through the exit checkpoint (above), and is prompted as an editor is. A project request still pending at the handoff keeps its own 150-second deadline and is cancelled when that expires; an unconditional client-state write has no deadline (above). Until it settles, or tab closes, superseded persistence keeps its draft-store connection and its hold on the tab's editor session. New editor holds the same session, which stays locked to this tab until its last holder releases it. Late write is fenced like another tab's, by draft-writer claims and revision conflicts.- **Hidden pages.** On `pagehide` and when page becomes hidden, runtime commits drafts editors still hold (the draft registry), writes the unload journal for an unsaved revision (including one whose save is in flight), then saves it at once instead of after autosave debounce. Committing a draft leaves control's value, caret and focus as they were. Revision whose save failed, or one already being saved, is not sent again; while session is closed nothing is committed, journaled, or saved. Save is asynchronous, so it completes when the hidden page keeps running (switching tabs or apps, minimising, or entering back/forward cache), and its acknowledgement retires the journal. It cannot complete while page unloads (reload, closing tab, navigating away), so across an unload the journal is what survives: next load of the account recovers the edit as a pending draft and saves it. Tab restored from back/forward cache writes through the same account-scope, draft-writer, and revision checks as every other write.- **Unload prompt.** A `beforeunload` listener is registered only while an unload could lose an edit (`isUnloadAtRisk`), since a listener alone can cost the page its back/forward cache in some browsers: open documents that together exceed the journal budget (sized as a save or the journal last serialized them, or as loaded until then), local recovery failing for an open project (storage full or unavailable), the journal unavailable at load or for its last write, or a last journal that failed outright. The runtime rechecks on each persisted revision, settled save or journal, session reopen, and exit; healthy storage with projects inside the budget registers nothing. A document that grows past the budget after its last serialization is caught by its next save, not before. While registered, `beforeunload` (which comes before `pagehide`) commits held drafts and writes the unload journal (the later events find it written), and asks the browser to confirm leaving (its own generic wording) only when an unsaved revision would not survive the unload: a project the journal skipped for its budget, an edit it could not write, or one journaled for a project whose local recovery is failing, in each case until a stage succeeds or the server acknowledges the revision. `hasChangesUnloadWouldLose` answers from what that journal recorded, without serializing again. An ordinary edit the journal holds never prompts, nor does anything while the session is closed, before load, after the account lifetime ended, or for an exit checkpoint a newer editor superseded; an exit checkpoint still saving keeps the editor's listener rules. A journal write that aborts after starting (storage filling during the unload) cannot be known in time and does not prompt.- **What is and is not guaranteed.** In Chromium, an ordinary reload, tab close, or navigation away right after an edit keeps the edit, including one still held in a debounced field: journal write is committed before the handler returns and the browser finishes it. Nothing guaranteed when browser or OS is killed, crashes, or loses power before the write reaches disk (transaction uses default, relaxed durability), when a page is discarded without a `pagehide` or hidden event (edit made after last hidden event is lost), for projects over the journal budget, or when browser storage is unavailable or full; those last two bring up the unload prompt while they hold an unsaved revision, so leaving anyway is the user's choice. Undo made just before page goes away is retired by the same kind of blind write and can be lost the same way: then the undone edit comes back on next load, silently when server revision has not moved. Other browsers follow same IndexedDB rules but are not verified to finish a committed write during unload.diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.tsindex c921eacf3e..c178b0bc8f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts@@ -3,7 +3,7 @@ import type * as transportModule from '@platform/transport/http';import { galleryKeys } from '@features/gallery/queries';import { queryClient } from '@platform/query/client';import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';-import { ApiError } from '@platform/transport/http';+import { ApiError, RequestDeadlineError } from '@platform/transport/http';import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';const transport = vi.hoisted(() => ({@@ -19,6 +19,7 @@ vi.mock('@platform/transport/http', async (importOriginal) => ({import {deleteProject,+ deleteClientStateValue,createProject,createProjectSettled,getProjectDocumentSchemaRefusal,@@ -27,6 +28,7 @@ import {isProjectCanvasSchemaUnsupportedError,ProjectCreateAbsentError,saveProjectWorkspace,+ setClientStateValue,updateProject,} from './api';@@ -266,7 +268,7 @@ describe('canvas schema compatibility declarations', () => {expect(transport.apiFetchJson).toHaveBeenCalledWith('/api/v1/projects/project%2Fone?max_canvas_schema_version=6&max_document_schema_version=4',- { signal: undefined }+ { signal: expect.any(AbortSignal) });});@@ -285,7 +287,7 @@ describe('canvas schema compatibility declarations', () => {minimum_canvas_schema_version: 3,}),method: 'POST',- signal: undefined,+ signal: expect.any(AbortSignal),});});@@ -309,7 +311,7 @@ describe('canvas schema compatibility declarations', () => {max_document_schema_version: 4,}),method: 'PUT',- signal: undefined,+ signal: expect.any(AbortSignal),});});@@ -350,26 +352,35 @@ describe('canvas schema compatibility declarations', () => {const random = vi.spyOn(Math, 'random').mockReturnValue(0);transport.apiFetchJson.mockRejectedValueOnce(busy).mockRejectedValueOnce(busy).mockRejectedValueOnce(busy);transport.apiFetchJson.mockRejectedValueOnce(busy).mockRejectedValueOnce(busy).mockRejectedValueOnce(busy);- transport.apiFetchJson.mockRejectedValueOnce(busy).mockRejectedValueOnce(busy).mockResolvedValueOnce({- project_id: 'project-1',- });-- const write = updateProject('project-1', { data: {}, expected_revision: 1, name: 'Project' });+ transport.apiFetchJson+ .mockRejectedValueOnce(busy)+ .mockRejectedValueOnce(busy)+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ setTimeout(() => resolve({ project_id: 'project-1' }), 2_000);+ })+ );++ const write = expect(+ updateProject('project-1', { data: {}, expected_revision: 1, name: 'Project' })+ ).resolves.toMatchObject({ project_id: 'project-1' });await vi.advanceTimersByTimeAsync(123_999);expect(transport.apiFetchJson).toHaveBeenCalledTimes(8);await vi.advanceTimersByTimeAsync(1);- await expect(write).resolves.toMatchObject({ project_id: 'project-1' });+ await vi.advanceTimersByTimeAsync(2_000);+ await write;expect(transport.apiFetchJson).toHaveBeenCalledTimes(9);vi.useRealTimers();random.mockRestore();});- it('stops retrying when the owning account scope expires during backoff', async () => {+ it('stops retrying when the account expires during backoff even without a caller signal', async () => {const owner = captureAccountScope();const busy = new ApiError('{"detail":{"code":"project_write_busy"}}', 429, new Headers({ 'Retry-After': '60' }));transport.apiFetchJson.mockRejectedValue(busy);- const write = updateProject('project-1', { data: {}, expected_revision: 1, name: 'Project' }, owner.signal);+ const write = updateProject('project-1', { data: {}, expected_revision: 1, name: 'Project' });await vi.waitFor(() => expect(transport.apiFetchJson).toHaveBeenCalledTimes(1));accountLifecycle.invalidate();@@ -511,7 +522,7 @@ describe('project workspaces', () => {max_document_schema_version: 4,}),method: 'PUT',- signal: undefined,+ signal: expect.any(AbortSignal),});});@@ -539,7 +550,7 @@ describe('project workspaces', () => {max_document_schema_version: 4,}),method: 'PUT',- signal: undefined,+ signal: expect.any(AbortSignal),});});@@ -586,7 +597,7 @@ describe('project workspaces', () => {minimum_canvas_schema_version: 3,}),method: 'POST',- signal: undefined,+ signal: expect.any(AbortSignal),});});@@ -643,3 +654,146 @@ describe('project workspaces', () => {).rejects.toBe(conflict);});});++describe('project request deadlines', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ onTestFinished(() => {+ vi.useRealTimers();+ });+ });++ it.each(['set', 'delete'] as const)(+ 'waits for an unconditional client-state %s to settle beyond the project deadline',+ async (kind) => {+ let finish!: () => void;+ const pending = new Promise<void>((resolve) => {+ finish = resolve;+ });+ (kind === 'set' ? transport.apiFetchJson : transport.apiFetch).mockReturnValueOnce(pending);+ let status = 'pending';+ const result = (+ kind === 'set' ? setClientStateValue('session', 'value') : deleteClientStateValue('session')+ ).then(+ () => {+ status = 'resolved';+ },+ () => {+ status = 'rejected';+ }+ );++ await vi.advanceTimersByTimeAsync(151_000);+ const statusAtDeadline = status;+ finish();+ await result;++ expect(statusAtDeadline).toBe('pending');+ expect(status).toBe('resolved');+ }+ );++ it.each(['content', 'workspace', 'read'] as const)(+ 'allows a slow %s transfer within the server upload contract',+ async (kind) => {+ let requestSignal!: AbortSignal;+ transport.apiFetchJson.mockImplementationOnce((_path, init) => {+ requestSignal = init.signal;+ return new Promise((resolve) => {+ setTimeout(() => resolve({ revision: 2 }), 120_000);+ });+ });+ const result = expect(+ kind === 'read'+ ? getProject('p')+ : kind === 'workspace'+ ? saveProjectWorkspace('p', { data: {}, expected_revision: 1 })+ : updateProject('p', { data: {}, expected_revision: 1, name: 'P' })+ ).resolves.toMatchObject({ revision: 2 });+ await vi.advanceTimersByTimeAsync(120_000);+ await result;+ expect(requestSignal.aborted).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ }+ );++ it.each(['content', 'workspace', 'read'] as const)(+ 'cancels a stalled %s request and permits the next operation',+ async (kind) => {+ let stalledSignal!: AbortSignal;+ transport.apiFetchJson+ .mockImplementationOnce((_path, init) => {+ stalledSignal = init.signal;+ return new Promise(() => {+ /* Simulate an unresponsive request. */+ });+ })+ .mockResolvedValueOnce({ revision: 2 });+ const run = () =>+ kind === 'read'+ ? getProject('p')+ : kind === 'workspace'+ ? saveProjectWorkspace('p', { data: {}, expected_revision: 1 })+ : updateProject('p', { data: {}, expected_revision: 1, name: 'P' });+ const first = expect(run()).rejects.toBeInstanceOf(RequestDeadlineError);+ await vi.advanceTimersByTimeAsync(150_000);+ await first;+ expect(stalledSignal.aborted).toBe(true);+ await expect(run()).resolves.toMatchObject({ revision: 2 });+ expect(vi.getTimerCount()).toBe(0);+ }+ );++ it('settles a timed-out create by the same identity without creating another project', async () => {+ const request = { data: {}, name: 'P', project_id: 'reserved' };+ transport.apiFetchJson+ .mockImplementationOnce(+ () =>+ new Promise(() => {+ /* Simulate an unresponsive request. */+ })+ )+ .mockResolvedValueOnce({ ...request, minimum_canvas_schema_version: 3, minimum_document_schema_version: 4 });+ const result = createProjectSettled(request, captureAccountScope());+ await vi.advanceTimersByTimeAsync(150_000);+ await expect(result).resolves.toMatchObject({ project_id: 'reserved' });+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(2);+ expect(transport.apiFetchJson.mock.calls[1]![0]).toContain('/projects/reserved?');+ expect(vi.getTimerCount()).toBe(0);+ });++ it('bounds an unanswered create and its reconciliation without proving absence', async () => {+ transport.apiFetchJson.mockImplementation(+ () =>+ new Promise(() => {+ /* Simulate an unresponsive request. */+ })+ );+ const result = expect(+ createProjectSettled({ data: {}, name: 'P', project_id: 'reserved' }, captureAccountScope())+ ).rejects.toBeInstanceOf(RequestDeadlineError);+ await vi.advanceTimersByTimeAsync(300_000);+ await result;+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(2);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('settles an ambiguous delete by repeating its identity and board policy', async () => {+ transport.apiFetch+ .mockImplementationOnce(+ () =>+ new Promise(() => {+ /* Simulate an unresponsive request. */+ })+ )+ .mockResolvedValueOnce(new Response(null, { status: 204 }));+ const result = deleteProject('reserved', undefined, 'delete');+ await vi.advanceTimersByTimeAsync(150_000);+ await expect(result).resolves.toBeUndefined();+ expect(transport.apiFetch.mock.calls.map(([url]) => url)).toEqual([+ '/api/v1/projects/reserved?boards=delete',+ '/api/v1/projects/reserved?boards=delete',+ ]);+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.tsindex 7d955386db..f23d94e052 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts@@ -1,8 +1,15 @@import type { AccountScope } from '@platform/state/accountLifecycle';import { queryClient } from '@platform/query/client';-import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';-import { ApiError, apiFetch, apiFetchJson, sleep } from '@platform/transport/http';+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';+import {+ ApiError,+ apiFetch,+ apiFetchJson,+ RequestDeadlineError,+ sleep,+ withRequestDeadline,+} from '@platform/transport/http';import {DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,@@ -15,6 +22,9 @@ import { PROJECT_SPLIT_DOCUMENT_SCHEMA_VERSION } from './documentSchemaVersion';const PROJECTS_BASE = '/api/v1/projects';const PROJECT_WRITE_MAX_ATTEMPTS = 9;const PROJECT_WRITE_RETRY_WINDOW_MS = 125_000;+// The server permits 120 seconds to receive a project body; allow another 30 for processing and the response.+const PROJECT_REQUEST_TIMEOUT_MS = 150_000;+const CLIENT_STATE_READ_TIMEOUT_MS = 30_000;// The path's queue segment is ignored by the backend (kept for compatibility).const CLIENT_STATE_BASE = '/api/v1/client_state/default';@@ -116,13 +126,22 @@ export interface ProjectWorkspaceSaveRequest {}export const listProjects = (signal?: AbortSignal): Promise<ProjectSummaryDTO[]> =>- apiFetchJson<ProjectSummaryDTO[]>(`${PROJECTS_BASE}/`, { signal });+ withRequestDeadline(+ (signal) => apiFetchJson<ProjectSummaryDTO[]>(`${PROJECTS_BASE}/`, { signal }),+ PROJECT_REQUEST_TIMEOUT_MS,+ signal+ );export const getProject = (projectId: string, signal?: AbortSignal): Promise<ProjectWithWorkspaceDTO> =>- apiFetchJson<ProjectWithWorkspaceDTO>(- `${PROJECTS_BASE}/${encodeURIComponent(projectId)}?max_canvas_schema_version=${MAX_SUPPORTED_CANVAS_SCHEMA_VERSION}` +- `&max_document_schema_version=${PROJECT_SPLIT_DOCUMENT_SCHEMA_VERSION}`,- { signal }+ withRequestDeadline(+ (signal) =>+ apiFetchJson<ProjectWithWorkspaceDTO>(+ `${PROJECTS_BASE}/${encodeURIComponent(projectId)}?max_canvas_schema_version=${MAX_SUPPORTED_CANVAS_SCHEMA_VERSION}` ++ `&max_document_schema_version=${PROJECT_SPLIT_DOCUMENT_SCHEMA_VERSION}`,+ { signal }+ ),+ PROJECT_REQUEST_TIMEOUT_MS,+ signal);const isProjectWriteBusyError = (error: unknown): error is ApiError => {@@ -160,14 +179,19 @@ const createProjectWriteRetryBudget = (): ProjectWriteRetryBudget => ({});const requestProjectWrite = async <T>(- request: () => Promise<T>,+ request: (signal: AbortSignal) => Promise<T>,signal: AbortSignal | undefined,budget: ProjectWriteRetryBudget = createProjectWriteRetryBudget()): Promise<T> => {+ const requestSignal = AbortSignal.any([captureAccountScope().signal, ...(signal ? [signal] : [])]);while (budget.attempts < PROJECT_WRITE_MAX_ATTEMPTS) {budget.attempts += 1;try {- return await request();+ requestSignal.throwIfAborted();+ if (Date.now() >= budget.deadline) {+ throw new RequestDeadlineError();+ }+ return await withRequestDeadline(request, PROJECT_REQUEST_TIMEOUT_MS, requestSignal);} catch (error) {if (!isProjectWriteBusyError(error) || budget.attempts >= PROJECT_WRITE_MAX_ATTEMPTS) {throw error;@@ -183,7 +207,7 @@ const requestProjectWrite = async <T>(if (delayMs > remainingMs) {throw error;}- await sleep(delayMs, signal);+ await sleep(delayMs, requestSignal);}}@@ -219,7 +243,7 @@ const createProjectFromBody = (budget: ProjectWriteRetryBudget): Promise<ProjectWithWorkspaceDTO> =>requestProjectWrite(- () =>+ (signal) =>apiFetchJson<ProjectWithWorkspaceDTO>(`${PROJECTS_BASE}/`, {body,method: 'POST',@@ -244,7 +268,7 @@ export const updateProject = (});return requestProjectWrite(- () =>+ (signal) =>apiFetchJson<ProjectWithWorkspaceDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, {body,method: 'PUT',@@ -272,7 +296,7 @@ export const saveProjectWorkspace = (});return requestProjectWrite(- () =>+ (signal) =>apiFetchJson<ProjectWorkspaceDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}/workspace`, {body,method: 'PUT',@@ -292,9 +316,26 @@ export const deleteProject = async (signal?: AbortSignal,boards: DeleteProjectBoards = 'release'): Promise<void> => {+ signal ??= captureAccountScope().signal;const query = boards === 'release' ? '' : '?boards=delete';- await apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}${query}`, { method: 'DELETE', signal });+ try {+ await withRequestDeadline(+ (signal) => apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}${query}`, { method: 'DELETE', signal }),+ PROJECT_REQUEST_TIMEOUT_MS,+ signal+ );+ } catch (error) {+ if (!(error instanceof RequestDeadlineError)) {+ throw error;+ }+ // Deletion is idempotent: a settled repeat returns 204 even when the first request already removed the project.+ await withRequestDeadline(+ (signal) => apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}${query}`, { method: 'DELETE', signal }),+ PROJECT_REQUEST_TIMEOUT_MS,+ signal+ );+ }};/** Every board of the project with its visible media; excludes intermediate/other categories. */@@ -546,10 +587,16 @@ const isRefusal = (error: unknown): boolean => error instanceof ApiError && erroconst isIndeterminate = (error: unknown): boolean => !(error instanceof ApiError) || error.status >= 500;export const getClientStateValue = (key: string, signal?: AbortSignal): Promise<string | null> =>- apiFetchJson<string | null>(`${CLIENT_STATE_BASE}/get_by_key?key=${encodeURIComponent(key)}`, { signal });+ withRequestDeadline(+ (signal) =>+ apiFetchJson<string | null>(`${CLIENT_STATE_BASE}/get_by_key?key=${encodeURIComponent(key)}`, { signal }),+ CLIENT_STATE_READ_TIMEOUT_MS,+ signal+ );/** The endpoint takes a JSON-encoded string body, hence the stringify of a string. */export const setClientStateValue = async (key: string, value: string, signal?: AbortSignal): Promise<void> => {+ // Unconditional writes must settle before callers release their ordering queues; a timeout cannot fence a late commit.await apiFetchJson<string>(`${CLIENT_STATE_BASE}/set_by_key?key=${encodeURIComponent(key)}`, {body: JSON.stringify(value),method: 'POST',diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.tsindex 25195e9acc..47c8f57aef 100644--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts@@ -2,10 +2,15 @@ import type { AccountScope } from '@platform/state/accountLifecycle';import type { Project, WorkbenchState } from '@workbench/projectContracts';import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';-import { ApiError } from '@platform/transport/http';+import { ApiError, RequestDeadlineError, withRequestDeadline } from '@platform/transport/http';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';import { MAX_SUPPORTED_CANVAS_SCHEMA_VERSION } from '@workbench/canvasSchemaVersion';+import {+ createWorkbenchPersistenceRuntime,+ type PersistenceAggregatePort,+ type PersistenceClock,+} from '@workbench/persistenceRuntime';import { createAccountOwnedQueueRunJournal } from '@workbench/queue-integration/queueRunJournal';import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';import {@@ -13,7 +18,7 @@ import {createInitialWorkbenchState,withAuthoritativeProjectBoard,} from '@workbench/workbenchState';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';import type { ProjectSummaryDTO, ProjectWithWorkspaceDTO } from './api';import type { ProjectDraftStore } from './draftStore';@@ -1689,6 +1694,780 @@ describe('durable project persistence', () => {expect(service.hasPendingChanges()).toBe(true);});+ it.each([false, true])(+ 'recovers a real mounted runtime and durable service after a hung save (queued edits: %s)',+ async (queuedEdits) => {+ vi.useFakeTimers();+ const owner = captureAccountScope();+ const api = createApi();+ const original = createDraftProject([]);+ const other = createDraftProject([original]);+ api.records.set(original.id, toSplitRecord(original));+ api.records.set(other.id, toSplitRecord(other));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(owner, api);+ let state = stateWith([original]);+ let revision = 0;+ let hydrated = false;+ const events: string[] = [];+ const listeners = new Set<() => void>();+ const emit = () => {+ for (const listener of listeners) {+ listener();+ }+ };+ const aggregate: PersistenceAggregatePort = {+ assignProjectBoard: () => {},+ getPersistedRevision: () => revision,+ getState: () => state,+ hydrate: (next) => {+ state = next;+ revision += 1;+ emit();+ },+ notifyProjectNotFound: () => {},+ reportLoadAvailable: () => {},+ reportRefusedProjects: () => {},+ reportLoadError: () => {},+ reportLoadUnavailable: () => {},+ saveFailed: () => events.push('failed'),+ saveNeedsAttention: () => events.push('attention'),+ savePending: () => events.push('pending'),+ saveScheduled: () => {},+ saveStarted: () => events.push('started'),+ saveSucceeded: () => events.push('saved'),+ setHasHydrated: (next) => {+ hydrated = next;+ emit();+ },+ subscribe: (listener) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+ const callbacks = new Map<number, () => void>();+ let clockId = 0;+ const clock: PersistenceClock = {+ clearTimeout: (id) => {+ callbacks.delete(id as number);+ },+ setTimeout: (callback) => {+ callbacks.set(++clockId, callback);+ return clockId;+ },+ };+ const runScheduled = () => {+ const pending = [...callbacks.values()];+ callbacks.clear();+ for (const callback of pending) {+ callback();+ }+ };+ const runtime = createWorkbenchPersistenceRuntime({+ aggregate,+ clock,+ persistence: service,+ signal: owner.signal,+ });+ try {+ runtime.start();+ await vi.waitFor(() => expect(hydrated).toBe(true));+ let stalledSignal!: AbortSignal;+ vi.mocked(api.updateProject).mockImplementationOnce((_id, _request, signal) =>+ withRequestDeadline(+ (requestSignal) => {+ stalledSignal = requestSignal;+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ return new Promise(() => {});+ },+ 150_000,+ signal+ )+ );+ state = { ...state, projects: [{ ...state.projects[0]!, name: 'First edit' }] };+ revision += 1;+ emit();+ runScheduled();+ await vi.waitFor(() => expect(api.updateProject).toHaveBeenCalledTimes(1));+ const switchAndEdit = () => {+ state = {+ ...state,+ activeProjectId: other.id,+ projects: [+ { ...state.projects[0]!, name: 'After timeout' },+ withAuthoritativeProjectBoard(other, `board-${other.id}`),+ ],+ };+ revision += 1;+ emit();+ runScheduled();+ };+ if (queuedEdits) {+ switchAndEdit();+ }+ await vi.advanceTimersByTimeAsync(150_000);+ expect(stalledSignal.aborted).toBe(true);+ if (!queuedEdits) {+ await vi.waitFor(() => expect(events).toContain('pending'));+ switchAndEdit();+ }+ await vi.waitFor(() => expect(api.records.get(original.id)?.name).toBe('After timeout'));+ await vi.waitFor(() => expect(events).toContain('saved'));+ expect(events).not.toContain('failed');+ expect(events).not.toContain('attention');+ expect(api.saveSession).toHaveBeenLastCalledWith(+ expect.objectContaining({ activeProjectId: other.id }),+ 'editor-1',+ expect.anything(),+ owner.signal+ );+ expect(service.hasPendingChanges()).toBe(false);+ } finally {+ await runtime.exit().settled;+ await service.close();+ vi.useRealTimers();+ }+ }+ );++ it.each(['content', 'workspace'] as const)(+ 'does not rewrite server state after resolving an answered %s write conflict',+ async (half) => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const edit = (project: Project, value: string): Project =>+ half === 'content'+ ? { ...project, name: value }+ : { ...project, promptHistory: [{ negativePrompt: null, positivePrompt: value }] };+ api.records.set(+ original.id,+ toSplitRecord(edit(loaded, 'Server version'), half === 'content' ? 2 : 1, half === 'workspace' ? 2 : 1)+ );+ expect((await service.saveWorkbench(stateWith([edit(loaded, 'Local version')]))).conflicts).toHaveLength(1);+ const resolved = await service.resolveConflictUseServer(original.id);+ service.acknowledgeProjectResolution(original.id);+ if (resolved.status !== 'loaded') {+ throw new Error('Expected the server resolution to load.');+ }+ const contentWrites = vi.mocked(api.updateProject).mock.calls.length;+ const workspaceWrites = vi.mocked(api.saveProjectWorkspace).mock.calls.length;+ api.records.set(+ original.id,+ toSplitRecord(+ edit(resolved.project, 'New remote version'),+ half === 'content' ? 3 : 1,+ half === 'workspace' ? 3 : 1+ )+ );+ expect(await service.saveWorkbench(stateWith([resolved.project]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ });+ expect(api.updateProject).toHaveBeenCalledTimes(contentWrites);+ expect(api.saveProjectWorkspace).toHaveBeenCalledTimes(workspaceWrites);+ }+ );++ it('retires answered content sends before resolving a later workspace conflict', async () => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const workspace = [{ negativePrompt: null, positivePrompt: 'Workspace X' }];+ vi.mocked(api.saveProjectWorkspace).mockRejectedValueOnce(new TypeError('Failed to fetch'));+ expect(+ await service.saveWorkbench(stateWith([{ ...loaded, name: 'Content B', promptHistory: workspace }]))+ ).toMatchObject({+ conflicts: [],+ shouldRetry: true,+ });+ api.records.set(+ original.id,+ toSplitRecord(+ {+ ...loaded,+ name: 'Content B',+ promptHistory: [{ negativePrompt: null, positivePrompt: 'Remote workspace Y' }],+ },+ 2,+ 2+ )+ );+ expect(+ (await service.saveWorkbench(stateWith([{ ...loaded, name: 'Content C', promptHistory: workspace }]))).conflicts+ ).toEqual([expect.objectContaining({ half: 'workspace' })]);+ const resolved = await service.resolveConflictUseServer(original.id);+ service.acknowledgeProjectResolution(original.id);+ if (resolved.status !== 'loaded') {+ throw new Error('Expected the workspace resolution to load.');+ }+ expect(resolved.project).toMatchObject({+ name: 'Content C',+ promptHistory: [{ positivePrompt: 'Remote workspace Y' }],+ });+ const contentWrites = vi.mocked(api.updateProject).mock.calls.length;+ const workspaceWrites = vi.mocked(api.saveProjectWorkspace).mock.calls.length;+ api.records.set(original.id, toSplitRecord({ ...resolved.project, name: 'Remote content D' }, 4, 2));+ expect(await service.saveWorkbench(stateWith([resolved.project]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ });+ expect(api.updateProject).toHaveBeenCalledTimes(contentWrites);+ expect(api.saveProjectWorkspace).toHaveBeenCalledTimes(workspaceWrites);+ expect(api.records.get(original.id)?.name).toBe('Remote content D');+ });++ it('retires content sends proven by a read even when the workspace needs resolution', async () => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ vi.mocked(api.updateProject).mockImplementationOnce(async (...args) => {+ await write(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ throw new RequestDeadlineError();+ });+ expect(await service.saveWorkbench(stateWith([{ ...loaded, name: 'Content B' }]))).toMatchObject({+ shouldRetry: true,+ });+ vi.mocked(api.updateProject)+ .mockImplementationOnce(write)+ .mockImplementationOnce(async (...args) => {+ await write(...args);+ api.records.set(+ original.id,+ toSplitRecord(+ { ...loaded, name: 'Content C', promptHistory: [{ negativePrompt: null, positivePrompt: 'Remote Y' }] },+ 3,+ 2+ )+ );+ throw new RequestDeadlineError();+ });+ expect(+ (+ await service.saveWorkbench(+ stateWith([+ { ...loaded, name: 'Content C', promptHistory: [{ negativePrompt: null, positivePrompt: 'Local X' }] },+ ])+ )+ ).conflicts+ ).toEqual([expect.objectContaining({ half: 'workspace' })]);+ const resolved = await service.resolveConflictUseServer(original.id);+ service.acknowledgeProjectResolution(original.id);+ if (resolved.status !== 'loaded') {+ throw new Error('Expected the workspace resolution to load.');+ }+ const writes = vi.mocked(api.updateProject).mock.calls.length;+ api.records.set(original.id, toSplitRecord({ ...resolved.project, name: 'Remote D' }, 4, 2));+ expect(await service.saveWorkbench(stateWith([resolved.project]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ });+ expect(api.updateProject).toHaveBeenCalledTimes(writes);+ });++ it('retains unanswered content when using the server workspace before a late content commit', async () => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ let commitLate!: () => Promise<unknown>;+ vi.mocked(api.updateProject).mockImplementationOnce((...args) => {+ commitLate = () => write(...args);+ api.records.set(+ original.id,+ toSplitRecord(+ { ...loaded, promptHistory: [{ negativePrompt: null, positivePrompt: 'Server workspace' }] },+ 1,+ 2+ )+ );+ return Promise.reject(new RequestDeadlineError());+ });+ const pending = {+ ...loaded,+ name: 'Unanswered content',+ promptHistory: [{ negativePrompt: null, positivePrompt: 'Local workspace' }],+ };+ expect((await service.saveWorkbench(stateWith([pending]))).conflicts).toEqual([+ expect.objectContaining({ half: 'workspace' }),+ ]);+ await service.saveWorkbench(stateWith([{ ...pending, name: 'Newer content' }]));+ const resolved = await service.resolveConflictUseServer(original.id);+ service.acknowledgeProjectResolution(original.id);+ if (resolved.status !== 'loaded') {+ throw new Error('Expected the workspace resolution to load.');+ }+ expect(resolved.project).toMatchObject({+ name: 'Newer content',+ promptHistory: [{ positivePrompt: 'Server workspace' }],+ });+ await commitLate();+ expect(await service.saveWorkbench(stateWith([resolved.project]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ });+ expect(api.records.get(original.id)?.name).toBe('Newer content');+ expect(api.records.get(original.id)?.workspace?.data).toMatchObject({+ promptHistory: [{ positivePrompt: 'Server workspace' }],+ });+ });++ it('assigns the board after a late create when a newer edit must still be saved', async () => {+ const owner = captureAccountScope();+ const { queryClient } = await import('@platform/query/client');+ const { galleryKeys } = await import('@features/gallery/queries');+ const invalidate = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue();+ onTestFinished(() => invalidate.mockRestore());+ const api = createApi();+ const project = createDraftProject([]);+ const create = vi.mocked(api.createProject).getMockImplementation()!;+ let lateCreate!: () => Promise<unknown>;+ vi.mocked(api.createProject).mockImplementationOnce((...args) => {+ lateCreate = () => create(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ return Promise.reject(new RequestDeadlineError());+ });+ const service = createService(owner, api);+ expect(await service.saveWorkbench(stateWith([project]))).toMatchObject({ shouldRetry: true });+ await lateCreate();+ vi.mocked(api.createProject).mockRejectedValueOnce(new ApiError('Already exists', 409));+ const result = await service.saveWorkbench(stateWith([{ ...project, name: 'Newer edit' }]));+ expect(result).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ projectBoardAssignments: [{ projectId: project.id, boardId: `board-${project.id}` }],+ });+ await vi.waitFor(() => expect(invalidate).toHaveBeenCalledWith({ queryKey: galleryKeys.boardsForAccount(owner) }));+ expect(api.records.get(project.id)?.name).toBe('Newer edit');+ });++ it.each([false, true])(+ 'refuses a late create whose authoritative name changed elsewhere (newer edit: %s)',+ async (newerEdit) => {+ const api = createApi();+ const project = createDraftProject([]);+ const create = vi.mocked(api.createProject).getMockImplementation()!;+ let lateCreate!: () => Promise<unknown>;+ vi.mocked(api.createProject).mockImplementationOnce((...args) => {+ lateCreate = () => create(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ return Promise.reject(new RequestDeadlineError());+ });+ const service = createService(captureAccountScope(), api);+ expect(await service.saveWorkbench(stateWith([project]))).toMatchObject({ shouldRetry: true });+ await lateCreate();+ const created = api.records.get(project.id)!;+ // The backend accepts the authoritative name independently from its opaque document.+ api.records.set(project.id, { ...created, name: 'Remote rename', revision: 2 });+ vi.mocked(api.createProject).mockRejectedValueOnce(new ApiError('Already exists', 409));+ const result = await service.saveWorkbench(+ stateWith([{ ...project, name: newerEdit ? 'Newer local edit' : project.name }])+ );+ expect(result.conflicts).toEqual([expect.objectContaining({ kind: 'revision', serverRevision: 2 })]);+ expect(api.updateProject).not.toHaveBeenCalled();+ expect(api.saveProjectWorkspace).not.toHaveBeenCalled();+ expect(api.records.get(project.id)?.name).toBe('Remote rename');+ }+ );++ it.each(['content', 'workspace'] as const)(+ 'acknowledges a committed %s undo fence from a higher revision despite a lost answer',+ async (half) => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const changed =+ half === 'content'+ ? { ...loaded, name: 'Undone edit' }+ : { ...loaded, promptHistory: [{ negativePrompt: null, positivePrompt: 'Undone edit' }] };+ const method = half === 'content' ? 'updateProject' : 'saveProjectWorkspace';+ const write = vi.mocked(api[method]).getMockImplementation()! as (...args: unknown[]) => Promise<unknown>;+ vi.mocked(api[method]).mockImplementationOnce(async (...args: unknown[]) => {+ await write(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ throw new RequestDeadlineError();+ });+ expect(await service.saveWorkbench(stateWith([changed]))).toMatchObject({ shouldRetry: true });+ vi.mocked(api[method]).mockImplementation(async (...args: unknown[]) => {+ await write(...args);+ throw new RequestDeadlineError();+ });+ expect(await service.saveWorkbench(stateWith([loaded]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ });+ const calls = vi.mocked(api[method]).mock.calls.length;+ expect(await service.saveWorkbench(stateWith([loaded]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ });+ expect(api[method]).toHaveBeenCalledTimes(calls);+ }+ );++ it.each(['content', 'workspace'] as const)(+ 'does not acknowledge an unanswered %s undo fence from an unchanged revision',+ async (half) => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const changed =+ half === 'content'+ ? { ...loaded, name: 'Still pending' }+ : { ...loaded, promptHistory: [{ negativePrompt: null, positivePrompt: 'Still pending' }] };+ const method = half === 'content' ? 'updateProject' : 'saveProjectWorkspace';+ vi.mocked(api[method]).mockRejectedValue(new RequestDeadlineError());+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ expect(await service.saveWorkbench(stateWith([changed]))).toMatchObject({ shouldRetry: true });+ expect(await service.saveWorkbench(stateWith([loaded]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: true,+ shouldRetry: true,+ });+ expect(api[method]).toHaveBeenCalledTimes(3);+ }+ );++ it.each([false, true])(+ 'bounds an unanswered create through API and persistence reconciliation (busy: %s)',+ async (busy) => {+ vi.useFakeTimers();+ const { createProjectSettled, getProject } = await import('./api');+ const api = createApi();+ api.createProject = createProjectSettled;+ api.getProject = getProject;+ const fetch = vi.fn(+ (): Promise<Response> =>+ new Promise(() => {+ /* Simulate an unresponsive request. */+ })+ );+ if (busy) {+ for (let attempt = 0; attempt < 8; attempt += 1) {+ fetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ detail: { code: 'project_write_busy' } }), {+ status: 429,+ headers: { 'Retry-After': '0' },+ })+ );+ }+ }+ vi.stubGlobal('fetch', fetch);+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);+ try {+ const service = createService(captureAccountScope(), api);+ const save = service.saveWorkbench(stateWith([createDraftProject([])]));+ let settled = false;+ void save.then(() => {+ settled = true;+ });+ // Each layer performs one bounded read after the final unanswered POST.+ const duration = busy ? 574_000 : 450_000;+ await vi.advanceTimersByTimeAsync(duration - 1);+ expect(settled).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ expect(await save).toMatchObject({ conflicts: [], hasPendingChanges: true, shouldRetry: true });+ expect(fetch).toHaveBeenCalledTimes(busy ? 11 : 3);+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ random.mockRestore();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ }+ }+ );++ it('keeps a late content commit followed by a retry conflict recoverable while workspace is still owed', async () => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const changed = {+ ...loaded,+ name: 'Late content',+ promptHistory: [{ negativePrompt: null, positivePrompt: 'Workspace owed' }],+ };+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ let lateCommit!: () => Promise<unknown>;+ vi.mocked(api.updateProject)+ .mockImplementationOnce((...args) => {+ lateCommit = () => write(...args);+ return Promise.reject(new RequestDeadlineError());+ })+ .mockImplementationOnce(async (...args) => {+ await lateCommit();+ return write(...args);+ });+ const result = await service.saveWorkbench(stateWith([changed]));+ expect(result).toMatchObject({ conflicts: [], hasPendingChanges: true, shouldRetry: true });+ const next = await service.saveWorkbench(stateWith([changed]));+ expect(next).toMatchObject({ conflicts: [], hasPendingChanges: false });+ expect(api.records.get(original.id)?.workspace?.data).toMatchObject({ promptHistory: changed.promptHistory });+ });++ it('retains unanswered state across saves when late own bytes cause repeated conflicts', async () => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ let lateCommit!: () => Promise<unknown>;+ vi.mocked(api.updateProject).mockImplementationOnce((...args) => {+ lateCommit = () => write(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ return Promise.reject(new RequestDeadlineError());+ });+ expect(await service.saveWorkbench(stateWith([{ ...loaded, name: 'Unanswered' }]))).toMatchObject({+ shouldRetry: true,+ });+ await lateCommit();+ vi.mocked(api.updateProject)+ .mockRejectedValueOnce(new ApiError('conflict', 409))+ .mockRejectedValueOnce(new ApiError('conflict', 409));+ expect(await service.saveWorkbench(stateWith([loaded]))).toMatchObject({ shouldRetry: true, conflicts: [] });+ expect(await service.saveWorkbench(stateWith([loaded]))).toMatchObject({ hasPendingChanges: false, conflicts: [] });+ expect(api.records.get(original.id)?.name).toBe(loaded.name);+ });++ it.each(['content', 'workspace'] as const)(+ 'fences an undo against an unanswered %s write that commits after the undo',+ async (half) => {+ const api = createApi();+ const original = createDraftProject([]);+ api.records.set(original.id, toSplitRecord(original));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: original.id,+ openProjectIds: [original.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const changed =+ half === 'content'+ ? { ...loaded, name: 'Undone content' }+ : { ...loaded, promptHistory: [{ negativePrompt: null, positivePrompt: 'Undone workspace' }] };+ let lateCommit!: () => Promise<unknown>;+ if (half === 'content') {+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ vi.mocked(api.updateProject)+ .mockImplementationOnce((...args) => {+ lateCommit = () => write(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ return Promise.reject(new RequestDeadlineError());+ })+ .mockImplementationOnce(async (...args) => {+ await lateCommit();+ return write(...args);+ });+ } else {+ const write = vi.mocked(api.saveProjectWorkspace).getMockImplementation()!;+ vi.mocked(api.saveProjectWorkspace)+ .mockImplementationOnce((...args) => {+ lateCommit = () => write(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ return Promise.reject(new RequestDeadlineError());+ })+ .mockImplementationOnce(async (...args) => {+ await lateCommit();+ return write(...args);+ });+ }+ expect(await service.saveWorkbench(stateWith([changed]))).toMatchObject({ shouldRetry: true, conflicts: [] });+ expect(await service.saveWorkbench(stateWith([loaded]))).toMatchObject({+ hasPendingChanges: false,+ conflicts: [],+ });+ const server = deserializeProjectRecord(api.records.get(original.id)!);+ expect(server.status).toBe('loaded');+ if (server.status === 'loaded') {+ expect(server.project.name).toBe(loaded.name);+ expect(server.project.promptHistory).toEqual(loaded.promptHistory);+ }+ expect(await service.saveWorkbench(stateWith([{ ...loaded, name: 'After undo' }]))).toMatchObject({+ hasPendingChanges: false,+ conflicts: [],+ });+ }+ );++ it('returns a project board assignment when a create is acknowledged through reconciliation', async () => {+ const { queryClient } = await import('@platform/query/client');+ const { galleryKeys } = await import('@features/gallery/queries');+ const invalidate = vi.spyOn(queryClient, 'invalidateQueries');+ onTestFinished(() => invalidate.mockRestore());+ const owner = captureAccountScope();+ const api = createApi();+ const project = createDraftProject([]);+ const create = vi.mocked(api.createProject).getMockImplementation()!;+ vi.mocked(api.createProject).mockImplementationOnce(async (...args) => {+ await create(...args);+ throw new RequestDeadlineError();+ });+ const result = await createService(owner, api).saveWorkbench(stateWith([project]));+ await vi.waitFor(() => expect(invalidate).toHaveBeenCalledWith({ queryKey: galleryKeys.boardsForAccount(owner) }));+ expect(result).toMatchObject({+ hasPendingChanges: false,+ conflicts: [],+ projectBoardAssignments: [{ projectId: project.id, boardId: `board-${project.id}` }],+ });+ });++ it.each(['committed', 'uncommitted', 'diverged', 'unavailable', 'repeated-timeout', 'missing'] as const)(+ 'reconciles a timed-out update with %s server state and preserves newer edits',+ async (outcome) => {+ const owner = captureAccountScope();+ const api = createApi();+ const draftStore = createMemoryProjectDraftStore();+ const project = createDraftProject([]);+ api.records.set(project.id, toSplitRecord(project));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: project.id,+ openProjectIds: [project.id],+ });+ const service = createService(owner, api, draftStore);+ const loaded = await service.loadWorkbench();+ const local = { ...loaded.state.projects[0]!, name: 'First edit' };+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ vi.mocked(api.updateProject).mockImplementationOnce(async (...args) => {+ if (outcome === 'committed') {+ await write(...args);+ }+ if (outcome === 'diverged') {+ api.records.set(project.id, toSplitRecord({ ...project, name: 'Other writer' }, 2));+ }+ if (outcome === 'unavailable') {+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ }+ if (outcome === 'missing') {+ vi.mocked(api.getProject).mockRejectedValueOnce(new ApiError('not yet visible', 404));+ }+ if (outcome === 'repeated-timeout') {+ vi.mocked(api.updateProject).mockRejectedValueOnce(new RequestDeadlineError());+ }+ throw new RequestDeadlineError();+ });+ const result = await service.saveWorkbench(stateWith([local]));+ if (outcome === 'diverged') {+ expect(result.conflicts).toEqual([expect.objectContaining({ kind: 'revision' })]);+ } else if (['unavailable', 'repeated-timeout', 'missing'].includes(outcome)) {+ expect(result).toMatchObject({ hasPendingChanges: true, shouldRetry: true });+ await expect(draftStore.get(project.id, 'editor-1')).resolves.toMatchObject({+ kind: 'found',+ draft: { state: 'dirty' },+ });+ } else {+ expect(result).toMatchObject({ hasPendingChanges: false, conflicts: [] });+ expect(api.updateProject).toHaveBeenCalledTimes(outcome === 'committed' ? 1 : 2);+ }+ if (outcome !== 'diverged') {+ const next = await service.saveWorkbench(stateWith([{ ...local, name: 'Newer edit' }]));+ expect(next).toMatchObject({ hasPendingChanges: false, conflicts: [] });+ expect(api.records.get(project.id)?.name).toBe('Newer edit');+ }+ }+ );++ it.each([true, false])(+ 'reconciles a workspace timeout after content is acknowledged (committed: %s)',+ async (committed) => {+ const api = createApi();+ const project = createDraftProject([]);+ api.records.set(project.id, toSplitRecord(project));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: project.id,+ openProjectIds: [project.id],+ });+ const service = createService(captureAccountScope(), api);+ const loaded = (await service.loadWorkbench()).state.projects[0]!;+ const write = vi.mocked(api.saveProjectWorkspace).getMockImplementation()!;+ vi.mocked(api.saveProjectWorkspace).mockImplementationOnce(async (...args) => {+ if (committed) {+ await write(...args);+ }+ throw new RequestDeadlineError();+ });+ const result = await service.saveWorkbench(+ stateWith([+ {+ ...loaded,+ name: 'Content changed',+ promptHistory: [{ negativePrompt: null, positivePrompt: 'Workspace changed' }],+ },+ ])+ );+ expect(result).toMatchObject({ hasPendingChanges: false, conflicts: [] });+ expect(api.updateProject).toHaveBeenCalledTimes(1);+ expect(api.saveProjectWorkspace).toHaveBeenCalledTimes(committed ? 1 : 2);+ expect(api.records.get(project.id)?.workspace?.data).toMatchObject({+ promptHistory: [{ negativePrompt: null, positivePrompt: 'Workspace changed' }],+ });+ }+ );+it('persists a divergent revision conflict and does not auto-fork', async () => {const owner = captureAccountScope();const api = createApi();@@ -4940,6 +5719,92 @@ describe('a project from before the split whose workflow repeats an item id', ()});});+ it('acknowledges an unanswered committed whole-document save without inventing a conflict', async () => {+ const { api, project, service } = await open(toRecord(withRepeatedNode(createDraftProject([]))));+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ vi.mocked(api.updateProject).mockImplementationOnce(async (...args) => {+ await write(...args);+ throw new RequestDeadlineError();+ });+ const result = await service.saveWorkbench(stateWith([{ ...project, name: 'Committed whole' }]));+ expect(result).toMatchObject({ hasPendingChanges: false, conflicts: [] });+ expect(api.updateProject).toHaveBeenCalledTimes(1);+ expect(api.saveProjectWorkspace).not.toHaveBeenCalled();+ });++ it('acknowledges a whole-document undo fence whose commit is proven by a higher revision', async () => {+ const { api, project, service } = await open(toRecord(withRepeatedNode(createDraftProject([]))));+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ vi.mocked(api.updateProject).mockImplementationOnce(async (...args) => {+ await write(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ throw new RequestDeadlineError();+ });+ expect(await service.saveWorkbench(stateWith([{ ...project, name: 'Undone whole' }]))).toMatchObject({+ shouldRetry: true,+ });+ vi.mocked(api.updateProject).mockImplementation(async (...args) => {+ await write(...args);+ throw new RequestDeadlineError();+ });+ expect(await service.saveWorkbench(stateWith([project]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ });+ const writes = vi.mocked(api.updateProject).mock.calls.length;+ expect(await service.saveWorkbench(stateWith([project]))).toMatchObject({+ conflicts: [],+ hasPendingChanges: false,+ });+ expect(api.updateProject).toHaveBeenCalledTimes(writes);+ expect(api.records.get(project.id)).toMatchObject({ name: project.name, revision: 3 });+ });++ it('fences a whole-document undo against an unanswered save that commits later', async () => {+ const { api, project, service } = await open(toRecord(withRepeatedNode(createDraftProject([]))));+ const write = vi.mocked(api.updateProject).getMockImplementation()!;+ let lateCommit!: () => Promise<unknown>;+ vi.mocked(api.updateProject)+ .mockImplementationOnce((...args) => {+ lateCommit = () => write(...args);+ vi.mocked(api.getProject).mockRejectedValueOnce(new RequestDeadlineError());+ return Promise.reject(new RequestDeadlineError());+ })+ .mockImplementationOnce(async (...args) => {+ await lateCommit();+ return write(...args);+ });+ expect(await service.saveWorkbench(stateWith([{ ...project, name: 'Undone whole' }]))).toMatchObject({+ shouldRetry: true,+ conflicts: [],+ });+ expect(await service.saveWorkbench(stateWith([project]))).toMatchObject({+ hasPendingChanges: false,+ conflicts: [],+ });+ expect(api.records.get(project.id)?.name).toBe(project.name);+ expect(api.saveProjectWorkspace).not.toHaveBeenCalled();+ });++ it('keeps repeated unanswered whole-document saves pending and saves a later edit', async () => {+ const { api, project, service } = await open(toRecord(withRepeatedNode(createDraftProject([]))));+ vi.mocked(api.updateProject)+ .mockRejectedValueOnce(new RequestDeadlineError())+ .mockRejectedValueOnce(new RequestDeadlineError());++ const result = await service.saveWorkbench(stateWith([{ ...project, name: 'Unanswered whole' }]));++ expect(result).toMatchObject({ hasPendingChanges: true, shouldRetry: true, conflicts: [] });+ expect(api.updateProject).toHaveBeenCalledTimes(2);+ expect(api.records.get(project.id)?.name).toBe(project.name);++ const next = await service.saveWorkbench(stateWith([{ ...project, name: 'Later whole edit' }]));++ expect(next).toMatchObject({ hasPendingChanges: false, conflicts: [] });+ expect(api.records.get(project.id)?.name).toBe('Later whole edit');+ expect(api.saveProjectWorkspace).not.toHaveBeenCalled();+ });+it('raises the canvas floor to 5 when a whole save adds a noise adjustment, so a v4 reader is refused', async () => {const project = withRepeatedNode(createDraftProject([]));const { api, project: loaded, service } = await open(toRecord(project));diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.tsindex 7e2e784d9d..f1bcad18ff 100644--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts@@ -4,6 +4,7 @@ import type { Project, ProjectLoadResult, RefusedWorkbenchProject, WorkbenchStatimport { createUuid } from '@platform/browser/randomUuid';import { createLogger } from '@platform/logging/logger';import { assertAccountScopeCurrent, isAccountScopeCurrent, type AccountScope } from '@platform/state/accountLifecycle';+import { RequestDeadlineError } from '@platform/transport/http';import {getProjectCanvasSchemaRequirement,isCanvasSchemaVersionSupported,@@ -54,6 +55,7 @@ import {getProjectCanvasSchemaCompatibilityRefusal,getProjectDocumentSchemaRefusal,getProjectWriteSizeRefusal,+ invalidateBoardLists,isProjectConflictError,isProjectNotFoundError,listProjects,@@ -1092,12 +1094,17 @@ export const createDurableSyncedWorkbenchPersistence = (projectsRequiringDocumentUpgrade.has(project.id) && !conflicts.has(project.id) && !schemaRefusals.has(project.id);const needsStage =needsDocumentUpgrade ||+ (sentHalves.has(project.id) && existingDraft?.documentJson !== serialized.documentJson) ||(!entry && existingDraft?.documentJson !== serialized.documentJson) ||(entry !== undefined &&entry.pushedDoc !== serialized.documentJson &&existingDraft?.documentJson !== serialized.documentJson);const needsPush =- needsStage || pendingProjectIds.has(project.id) || conflicts.has(project.id) || schemaRefusals.has(project.id);+ needsStage ||+ sentHalves.has(project.id) ||+ pendingProjectIds.has(project.id) ||+ conflicts.has(project.id) ||+ schemaRefusals.has(project.id);return { existingDraft, needsPush, needsStage, project, serialized };};type ProjectSavePlan = ReturnType<typeof createProjectSavePlan>;@@ -1392,12 +1399,21 @@ export const createDurableSyncedWorkbenchPersistence = (hasPending = true;return { documentJson, kind: 'conflicted' };}- if (entry?.pushedDoc === documentJson && !projectsRequiringDocumentUpgrade.has(project.id)) {+ if (+ entry?.pushedDoc === documentJson &&+ !sentHalves.has(project.id) &&+ !projectsRequiringDocumentUpgrade.has(project.id)+ ) {await settleAck(project, generation, entry, document, documentJson, store, editorSessionId);return { documentJson, kind: 'acknowledged' };}const halves = splitProjectDocument(document);+ const previousSent = sentHalves.get(project.id);+ // Undo must write a revision fence: an unanswered older body can still commit after an unchanged read.+ let fenceContent =+ previousSent?.content.some((body) => body !== halves.contentJson && body !== documentJson) === true;+ let fenceWorkspace = previousSent?.workspace.some((body) => body !== halves.workspaceJson) === true;// Split content that repeats an item id would be refused by every later load, so such a project, which only a// build before the split could have written, is created whole and keeps saving whole (see `toProjectCreation`).const keepsWhole = findRepeatedWorkflowItem(halves.content.workflows.entries) !== null;@@ -1442,6 +1458,24 @@ export const createDurableSyncedWorkbenchPersistence = ([half]: [...sent[half].filter((body) => body !== json), json].slice(-SENT_HALVES_KEPT),});};+ /** A newer authoritative revision fences every older send of this half, even while its sibling is pending. */+ const acknowledgeHalf = (half: 'content' | 'workspace'): void => {+ if (half === 'content') {+ fenceContent = false;+ } else {+ fenceWorkspace = false;+ }+ const sent = sentHalves.get(project.id);+ if (!sent) {+ return;+ }+ const remaining = { ...sent, [half]: [] };+ if (remaining.content.length === 0 && remaining.workspace.length === 0) {+ sentHalves.delete(project.id);+ } else {+ sentHalves.set(project.id, remaining);+ }+ };/*** The lineage rebased onto the content just acknowledged, before the workspace is sent: should that save fail or* the page go, recovery builds on the content the server now holds rather than conflicting with its own save.@@ -1472,6 +1506,7 @@ export const createDurableSyncedWorkbenchPersistence = (*/const pushHalves = async (base: SyncEntry | undefined): Promise<Omit<SyncEntry, 'pushedDoc'> | 'conflicted'> => {if (keepsWhole && !base) {+ noteSent('content', documentJson);const created = await api.createProject({data: document as unknown as Record<string, unknown>,@@ -1493,6 +1528,7 @@ export const createDurableSyncedWorkbenchPersistence = ();return 'conflicted';}+ acknowledgeHalf('content');pendingBoardAssignments.set(project.id, { boardId: created.board_id, projectId: project.id });return record({minimumCanvasSchemaVersion: created.minimum_canvas_schema_version,@@ -1503,6 +1539,7 @@ export const createDurableSyncedWorkbenchPersistence = (});}if (keepsWhole && base) {+ noteSent('content', documentJson);const raisedFloor = getRaisedCanvasSchemaFloor(document, base.minimumCanvasSchemaVersion);const updated = await api.updateProject(project.id,@@ -1515,6 +1552,7 @@ export const createDurableSyncedWorkbenchPersistence = (owner.signal);assertOwner();+ acknowledgeHalf('content');// Never splitting, it needs no upgrade: the shortcut for an unchanged document applies again.projectsRequiringDocumentUpgrade.delete(project.id);return record({@@ -1552,6 +1590,7 @@ export const createDurableSyncedWorkbenchPersistence = ();return 'conflicted';}+ acknowledgeHalf('content');pendingBoardAssignments.set(project.id, { boardId: created.board_id, projectId: project.id });// The answer names the workspace it stored, which is this save's only when it is what this save sent: a// create settled by a read of an earlier attempt that committed unanswered carries that attempt's workspace,@@ -1559,6 +1598,9 @@ export const createDurableSyncedWorkbenchPersistence = (// next against the revision the answer named; a server that stored none leaves it owed the same way.const workspaceStored =created.workspace !== null && JSON.stringify(created.workspace.data) === halves.workspaceJson;+ if (workspaceStored) {+ acknowledgeHalf('workspace');+ }acknowledged = record({minimumCanvasSchemaVersion: created.minimum_canvas_schema_version,pushedContent: halves.contentJson,@@ -1593,7 +1635,11 @@ export const createDurableSyncedWorkbenchPersistence = (owner.signal);assertOwner();+ acknowledgeHalf('content');projectsRequiringDocumentUpgrade.delete(project.id);+ if (updated.workspace) {+ acknowledgeHalf('workspace');+ }// The answer names the workspace it stored; a server that stored none leaves it owed, and it is sent next.acknowledged = record({minimumCanvasSchemaVersion: updated.minimum_canvas_schema_version,@@ -1608,7 +1654,11 @@ export const createDurableSyncedWorkbenchPersistence = (baseRevision: updated.revision,});}- } else if (projectsRequiringDocumentUpgrade.has(project.id) || base.pushedContent !== halves.contentJson) {+ } else if (+ projectsRequiringDocumentUpgrade.has(project.id) ||+ fenceContent ||+ base.pushedContent !== halves.contentJson+ ) {const raisedFloor = getRaisedCanvasSchemaFloor(document, base.minimumCanvasSchemaVersion);noteSent('content', halves.contentJson);const updated = await api.updateProject(@@ -1624,6 +1674,7 @@ export const createDurableSyncedWorkbenchPersistence = (owner.signal);assertOwner();+ acknowledgeHalf('content');projectsRequiringDocumentUpgrade.delete(project.id);acknowledged = record({...base,@@ -1640,7 +1691,7 @@ export const createDurableSyncedWorkbenchPersistence = (} else {acknowledged = base;}- if (acknowledged.pushedWorkspace !== halves.workspaceJson) {+ if (fenceWorkspace || acknowledged.pushedWorkspace !== halves.workspaceJson) {noteSent('workspace', halves.workspaceJson);const saved = await api.saveProjectWorkspace(project.id,@@ -1651,6 +1702,7 @@ export const createDurableSyncedWorkbenchPersistence = (owner.signal);assertOwner();+ acknowledgeHalf('workspace');acknowledged = record({...acknowledged,pushedWorkspace: halves.workspaceJson,@@ -1666,11 +1718,15 @@ export const createDurableSyncedWorkbenchPersistence = (* any other half diverged.*/const reconcile = async (): Promise<- | { kind: 'acknowledged' | 'retry'; entry: Omit<SyncEntry, 'pushedDoc'> }+ | { kind: 'acknowledged' | 'retry'; entry: SyncEntry }| { kind: 'diverged'; half?: 'workspace'; serverRevision: number }> => {const latest = await api.getProject(project.id, owner.signal);assertOwner();+ // A first create must match both name channels, as the API's create reconciliation requires.+ if (!entry && latest.name !== latest.data.name) {+ return { kind: 'diverged', serverRevision: latest.revision };+ }const loaded = deserializeProjectRecord(latest);if (loaded.status !== 'loaded') {return { kind: 'diverged', serverRevision: latest.revision };@@ -1679,34 +1735,63 @@ export const createDurableSyncedWorkbenchPersistence = (const serverHalves = splitProjectDocument(server.document);const split = isSplitProjectRecord(latest);const base = syncEntries.get(project.id);- const contentHeld = split && serverHalves.contentJson === halves.contentJson;+ // Hydration assigns the new inbox locally; compare first-create sends against the original wire bodies too.+ const createdContentJson = entry ? null : JSON.stringify(latest.data);+ const createdWorkspaceJson = !entry && latest.workspace ? JSON.stringify(latest.workspace.data) : null;+ const createdContentHeld = createdContentJson === (split ? halves.contentJson : documentJson);+ const contentHeld =+ createdContentHeld ||+ (split ? serverHalves.contentJson === halves.contentJson : keepsWhole && server.documentJson === documentJson);const sent = sentHalves.get(project.id);// Unmoved: still what this page last had acknowledged, or what it sent and never heard back about.- const contentUnmoved = split- ? base?.pushedContent === serverHalves.contentJson || sent?.content.includes(serverHalves.contentJson) === true- : base !== undefined && base.pushedContent === null && base.pushedDoc === server.documentJson;- const workspaceHeld = Boolean(latest.workspace) && serverHalves.workspaceJson === halves.workspaceJson;+ const contentUnmoved =+ (createdContentJson !== null && sent?.content.includes(createdContentJson) === true) ||+ (split+ ? base?.pushedContent === serverHalves.contentJson ||+ sent?.content.includes(serverHalves.contentJson) === true+ : (base !== undefined && base.pushedContent === null && base.pushedDoc === server.documentJson) ||+ sent?.content.includes(server.documentJson) === true);+ const workspaceHeld =+ createdWorkspaceJson === halves.workspaceJson ||+ (!split && keepsWhole) ||+ (Boolean(latest.workspace) && serverHalves.workspaceJson === halves.workspaceJson);const workspaceUnmoved = latest.workspace? base?.pushedWorkspace === serverHalves.workspaceJson ||- sent?.workspace.includes(serverHalves.workspaceJson) === true+ sent?.workspace.includes(serverHalves.workspaceJson) === true ||+ (createdWorkspaceJson !== null && sent?.workspace.includes(createdWorkspaceJson) === true): (base?.workspaceRevision ?? null) === null;+ // Retire a proven half even when its sibling needs conflict resolution.+ if (contentHeld && latest.revision > (base?.revision ?? 0)) {+ acknowledgeHalf('content');+ }+ if (workspaceHeld && (latest.workspace?.revision ?? 0) > (base?.workspaceRevision ?? 0)) {+ acknowledgeHalf('workspace');+ }if (!(contentHeld || contentUnmoved)) {return { kind: 'diverged', serverRevision: latest.revision };}if (!(workspaceHeld || workspaceUnmoved)) {return { half: 'workspace', kind: 'diverged', serverRevision: latest.revision };}- const entry = {+ const reconciledEntry = {minimumCanvasSchemaVersion: latest.minimum_canvas_schema_version,- pushedContent: split ? serverHalves.contentJson : null,- pushedWorkspace: latest.workspace ? serverHalves.workspaceJson : null,+ pushedContent: split ? (contentHeld ? halves.contentJson : serverHalves.contentJson) : null,+ pushedWorkspace: latest.workspace ? (workspaceHeld ? halves.workspaceJson : serverHalves.workspaceJson) : null,revision: latest.revision,workspaceRevision: latest.workspace?.revision ?? null,};- return { entry, kind: contentHeld && workspaceHeld ? 'acknowledged' : 'retry' };+ if (!entry && (contentHeld || contentUnmoved)) {+ pendingBoardAssignments.set(project.id, { boardId: latest.board_id, projectId: project.id });+ invalidateBoardLists(owner);+ }+ return {+ entry: { ...reconciledEntry, pushedDoc: split ? acknowledgedDocument(reconciledEntry) : server.documentJson },+ kind: contentHeld && workspaceHeld && !fenceContent && !fenceWorkspace ? 'acknowledged' : 'retry',+ };};let base = entry;+ let unanswered = previousSent !== undefined;// One retry: a second conflict means someone is saving this project now, which is a divergence to resolve.for (let attempt = 0; ; attempt += 1) {try {@@ -1737,7 +1822,9 @@ export const createDurableSyncedWorkbenchPersistence = (}return conflicted({ kind: 'deleted' });}- if (!isStatus(error, 409)) {+ const timedOut = error instanceof RequestDeadlineError;+ unanswered ||= timedOut;+ if (!isStatus(error, 409) && !timedOut) {if (isDeterministicClientError(error)) {throw error;}@@ -1757,10 +1844,10 @@ export const createDurableSyncedWorkbenchPersistence = (if (readRefusal) {return settleRefusal(readRefusal);}- if (isStatus(readError, 404)) {+ if (isStatus(readError, 404) && !unanswered) {return conflicted({ kind: 'deleted' });}- if (isDeterministicClientError(readError)) {+ if (isDeterministicClientError(readError) && !(unanswered && isStatus(readError, 404))) {throw readError;}hasPending = true;@@ -1770,6 +1857,10 @@ export const createDurableSyncedWorkbenchPersistence = (await settleAck(project, generation, settled.entry, document, documentJson, store, editorSessionId);return { documentJson, kind: 'acknowledged' };}+ if (settled.kind === 'retry' && attempt > 0 && unanswered) {+ hasPending = true;+ return { documentJson, kind: 'unsynced' };+ }if (settled.kind === 'diverged' || attempt > 0) {return conflicted({...(settled.kind === 'diverged' && settled.half ? { half: settled.half } : {}),@@ -1777,7 +1868,7 @@ export const createDurableSyncedWorkbenchPersistence = (serverRevision: settled.kind === 'diverged' ? settled.serverRevision : settled.entry.revision,});}- base = { ...settled.entry, pushedDoc: acknowledgedDocument(settled.entry) };+ base = settled.entry;syncEntries.set(project.id, base);}}@@ -2118,6 +2209,15 @@ export const createDurableSyncedWorkbenchPersistence = (throw error;}pendingProjectIds.add(projectId);+ const sent = sentHalves.get(projectId);+ if (sent) {+ // The server workspace replaces this tab's workspace sends; pending authored content remains local.+ if (sent.content.length > 0) {+ sentHalves.set(projectId, { ...sent, workspace: [] });+ } else {+ sentHalves.delete(projectId);+ }+ }hasPending = true;resolveProjectSyncConflict(projectId, { projectId, revision: record.revision }, hasPending);projectResolutionFences.set(projectId, { kind: 'replace', project: merged.project });@@ -3685,6 +3785,7 @@ export const createDurableSyncedWorkbenchPersistence = (}await deleteDraft(projectId);syncEntries.set(projectId, toSyncEntry(record, result.project));+ sentHalves.delete(projectId);if (recordRequiresDocumentUpgrade(record, result.project)) {projectsRequiringDocumentUpgrade.add(projectId);} else {