Skip to content

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

fix(webv2): report the real outcome of a push and a create

Josh Corbett934cc0912f35
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index bc2f72b3dd..5f0d6f9bb5 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -427,6 +427,8 @@
"missingReferences_one": "1 project reference could not be included.",
"missingReferences_other": "{{count}} project references could not be included.",
"notAProject": "This file is not an Invoke project.",
+ "notSynced": "This project has changes that have not reached the server yet. Try again once it reconnects.",
+ "supersededElsewhere": "This project was changed on another device. Your local edits continue in the recovered copy — use that one instead.",
"packing": "Packing the archive…",
"restoringProgress": "Restoring {{completed}} of {{total}} assets…",
"tooLarge": "This project file is too large to open.",
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
index 3ed47bec3f..57cb8271cd 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
@@ -8,6 +8,8 @@ import { captureAccountScope } from '@platform/state/accountLifecycle';
import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from '@platform/state/selectors';
import { createContext, use, useEffect, useSyncExternalStore, useState, type ReactNode } from 'react';
+import type { ProjectPushOutcome } from './projects/projectFlush';
+
import { WorkbenchSplashScreen } from './components/WorkbenchSplashScreen';
import { createExtensionRegistry, type ExtensionRegistry } from './extensions/extensionRegistry';
import { createWorkbenchPersistenceRuntime } from './persistenceRuntime';
@@ -89,12 +91,15 @@ export const WorkbenchProvider = ({
store.commands.projects.close(projectId);
}
},
- flushProject: async (projectId) => {
+ deleteProject: (projectId) => persistence.deleteProjectOnServer(projectId),
+ flushProject: (projectId) => {
const project = store.getSnapshot().projects.find((candidate) => candidate.id === projectId);
- if (project) {
- await persistence.flushProjectToServer(project);
- }
+ // A project the editor no longer holds has nothing to push, and the id is by definition
+ // whatever the server last acknowledged for it.
+ return project
+ ? persistence.flushProjectToServer(project)
+ : Promise.resolve<ProjectPushOutcome>({ documentJson: '', kind: 'acknowledged' });
},
getOpenProjectIds: () => store.getSnapshot().projects.map((project) => project.id),
markProjectDeleted: (projectId) => {
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
index d6b831f925..197e338a54 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
@@ -1,8 +1,9 @@
import type { HydratedWorkbenchSnapshot } from '@workbench/persistenceContracts';
-import type { WorkbenchState } from '@workbench/projectContracts';
+import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { describe, expect, it, vi } from 'vitest';
+import type { ProjectRecoveredIdentity } from './projects/projectFlush';
import type { WorkbenchSaveResult } from './projects/syncedPersistence';
import {
@@ -65,6 +66,37 @@ class FakeClock implements PersistenceClock {
}
}
+const recoveredIdentity = (projectId: string, name = 'Recovered'): ProjectRecoveredIdentity => ({
+ id: 'recovered',
+ name,
+ recoveredAt: '2026-08-07T00:00:00.000Z',
+ recoveryOf: projectId,
+});
+
+/**
+ * What the real reducers do with a fork: keep the live project's content and re-label it with the
+ * server's identity. Mirrored here rather than simplified to `recoveredProject`, because the runtime
+ * applies these results even when the save that produced them is stale — and a fake that swapped in
+ * the snapshot would agree with a runtime that silently discarded the newest edits.
+ */
+const forkFromLive = (
+ state: WorkbenchState,
+ projectId: string,
+ resolution: { recoveredIdentity: ProjectRecoveredIdentity; recoveredProject: Project }
+): Project => {
+ const live = state.projects.find((project) => project.id === projectId);
+
+ return live
+ ? {
+ ...live,
+ id: resolution.recoveredIdentity.id,
+ name: resolution.recoveredIdentity.name,
+ recoveredAt: resolution.recoveredIdentity.recoveredAt,
+ recoveryOf: resolution.recoveredIdentity.recoveryOf,
+ }
+ : resolution.recoveredProject;
+};
+
const createAggregate = (initialState = createInitialWorkbenchState()) => {
let state = structuredClone(initialState);
let revision = 0;
@@ -97,7 +129,7 @@ const createAggregate = (initialState = createInitialWorkbenchState()) => {
projects: [
...state.projects.filter((project) => project.id !== conflict.projectId),
conflict.serverProject,
- conflict.recoveredProject,
+ forkFromLive(state, conflict.projectId, conflict),
],
};
revision += 1;
@@ -107,7 +139,9 @@ const createAggregate = (initialState = createInitialWorkbenchState()) => {
reconcileDeletedProject: (fork) => {
state = {
...state,
- projects: state.projects.map((project) => (project.id === fork.projectId ? fork.recoveredProject : project)),
+ projects: state.projects.map((project) =>
+ project.id === fork.projectId ? forkFromLive(state, fork.projectId, fork) : project
+ ),
};
revision += 1;
events.push('deleted-fork');
@@ -134,10 +168,11 @@ const createAggregate = (initialState = createInitialWorkbenchState()) => {
state = { ...state, backendConnection: { status: 'connected' } };
emit();
},
- edit(name = 'Edited') {
+ /** `patch` is for content a fork's identity does not overwrite, so a test can tell them apart. */
+ edit(name = 'Edited', patch: Partial<Project> = {}) {
state = {
...state,
- projects: state.projects.map((project, index) => (index === 0 ? { ...project, name } : project)),
+ projects: state.projects.map((project, index) => (index === 0 ? { ...project, ...patch, name } : project)),
};
revision += 1;
emit();
@@ -304,6 +339,53 @@ describe('Workbench persistence runtime', () => {
expect(aggregate.events).toContain('save-succeeded:current');
});
+ it('applies a stale save’s deletion fork without discarding what landed mid-flight', async () => {
+ // The two halves of this have to hold together. Dropping the fork because the save went stale
+ // re-creates the deleted project under its old id on the next push; applying a fork built from
+ // the pushed snapshot throws away the edit that made the save stale in the first place. The
+ // answer is that a fork carries an identity, not a document.
+ const aggregate = createAggregate();
+ const { persistence } = createPersistence(() => Promise.resolve(null));
+ const pending = deferred<WorkbenchSaveResult>();
+ vi.mocked(persistence.saveWorkbench).mockImplementationOnce(() => pending.promise);
+ const clock = new FakeClock();
+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });
+
+ runtime.start();
+ await flushPromises();
+ aggregate.edit('Before the push', { settings: { ...aggregate.state.projects[0]!.settings, useCpuNoise: false } });
+
+ const original = aggregate.state.projects[0]!;
+
+ clock.runAll();
+
+ // Lands while the save is in flight, which is what makes the result stale.
+ aggregate.edit('After the push started', { settings: { ...original.settings, useCpuNoise: true } });
+
+ pending.resolve({
+ ...saveResult(aggregate.state, 'stale'),
+ deletedProjectForks: [
+ {
+ projectId: original.id,
+ recoveredIdentity: recoveredIdentity(original.id, 'Recovered'),
+ // What the push was carrying, one edit behind.
+ recoveredProject: { ...original, id: 'recovered', name: 'Before the push' },
+ },
+ ],
+ });
+ await flushPromises();
+
+ // Applied despite the staleness: dropping it would let the next push re-create the deleted id.
+ expect(aggregate.events).toContain('deleted-fork');
+ expect(aggregate.state.projects.map((project) => project.id)).not.toContain(original.id);
+
+ const fork = aggregate.state.projects.find((project) => project.id === 'recovered');
+
+ expect(fork?.recoveryOf).toBe(original.id);
+ // ...and the edit that made it stale is in the fork rather than lost between the two copies.
+ expect(fork?.settings.useCpuNoise).toBe(true);
+ });
+
it('ignores server outcomes once disposed', async () => {
const aggregate = createAggregate();
const { persistence } = createPersistence(() => Promise.resolve(null));
@@ -421,6 +503,7 @@ describe('Workbench persistence runtime', () => {
conflicts: [
{
projectId: original.id,
+ recoveredIdentity: recoveredIdentity(original.id),
recoveredProject: { ...original, id: 'recovered', name: 'Recovered' },
serverProject: { ...original, name: 'Server' },
},
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
index aa453c654f..6d9c46bcac 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
@@ -132,11 +132,16 @@ export const createWorkbenchPersistenceRuntime = ({
// a board dispatches through the reducer and bumps the generation this check compares against.
const isStale = isStaleSave(revision, saveGeneration, requireCurrentRevision);
- // Applied either way. These are facts about the *server* — the board it minted, the fork it
- // already holds — not statements about the snapshot that was sent. A save is stale whenever a
- // keystroke lands while it is in flight, which for a project's very first save is the common
- // case; dropping the answer there leaves a new project pointing at no board, and a deleted one
- // recreated under its old id by the next push.
+ // Applied either way. Every one of these is a fact about the *server* — the board it minted,
+ // the id the fork already occupies — rather than a statement about the snapshot that was sent.
+ // A save is stale whenever a keystroke lands while it is in flight, which for a project's very
+ // first save is the common case; dropping the answer there leaves a new project pointing at no
+ // board, and a deleted one recreated under its old id by the next push.
+ //
+ // What makes that safe for the two that replace a project, and not only for the idempotent
+ // board write, is that they no longer carry a document. A fork hands over an *identity*, and
+ // the reducer re-labels the live project with it; the content the person can see is never
+ // swapped for the snapshot this save started from. See `ProjectRecoveredIdentity`.
applySaveResult(result);
if (isStale) {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
index 736b16f5eb..16f27781d4 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
@@ -15,7 +15,7 @@ vi.mock('@platform/transport/http', async (importOriginal) => ({
apiFetchJson: transport.apiFetchJson,
}));
-import { isProjectConfirmedAbsent } from './api';
+import { createProjectSettled, ProjectCreateAbsentError } from './api';
beforeEach(() => {
transport.apiFetch.mockReset();
@@ -23,36 +23,100 @@ beforeEach(() => {
accountLifecycle.activate('project-api-test-user');
});
-describe('isProjectConfirmedAbsent', () => {
- it('confirms absence only from an authoritative not-found response in the current account scope', async () => {
- const owner = captureAccountScope();
+/**
+ * The caller has already uploaded a board's worth of media by the time this runs, and it deletes
+ * that media if — and only if — this proves the project does not exist. Getting it wrong one way
+ * leaves clutter; the other way guts a project that does exist. So absence has to be *proved*, never
+ * assumed from silence.
+ */
+describe('createProjectSettled', () => {
+ const request = { data: {}, name: 'Imported', project_id: 'project-1' };
+ const post = () => ({ body: JSON.stringify(request), method: 'POST', signal: expect.anything() });
- transport.apiFetchJson.mockRejectedValueOnce(new ApiError('not found', 404));
+ it('returns the record a create succeeded with', async () => {
+ transport.apiFetchJson.mockResolvedValueOnce({ project_id: 'project-1' });
- await expect(isProjectConfirmedAbsent('project/1', owner)).resolves.toBe(true);
- expect(transport.apiFetchJson).toHaveBeenCalledWith('/api/v1/projects/project%2F1', { signal: owner.signal });
+ await expect(createProjectSettled(request, captureAccountScope())).resolves.toMatchObject({
+ project_id: 'project-1',
+ });
+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(1);
});
- it('does not confirm absence when the project exists', async () => {
- transport.apiFetchJson.mockResolvedValueOnce({ project_id: 'project-1' });
+ /**
+ * The case a `GET` cannot answer. The create may be mid-transaction, so a read of the id returns
+ * 404 about a project that is moments from existing — and the caller deletes its media. A second
+ * `POST` cannot commit before the first, so its answer is about a settled database.
+ */
+ it('adopts the project when a retried create finds the first one committed', async () => {
+ transport.apiFetchJson
+ .mockRejectedValueOnce(new TypeError('network error'))
+ .mockRejectedValueOnce(new ApiError('conflict', 409))
+ .mockResolvedValueOnce({ project_id: 'project-1', name: 'Imported' });
+
+ await expect(createProjectSettled(request, captureAccountScope())).resolves.toMatchObject({
+ project_id: 'project-1',
+ });
+ expect(transport.apiFetchJson).toHaveBeenNthCalledWith(1, '/api/v1/projects/', post());
+ expect(transport.apiFetchJson).toHaveBeenNthCalledWith(2, '/api/v1/projects/', post());
+ expect(transport.apiFetchJson).toHaveBeenNthCalledWith(3, '/api/v1/projects/project-1', expect.anything());
+ });
- await expect(isProjectConfirmedAbsent('project-1', captureAccountScope())).resolves.toBe(false);
+ it('creates the project when the first attempt never landed', async () => {
+ transport.apiFetchJson
+ .mockRejectedValueOnce(new ApiError('bad gateway', 502))
+ .mockResolvedValueOnce({ project_id: 'project-1' });
+
+ await expect(createProjectSettled(request, captureAccountScope())).resolves.toMatchObject({
+ project_id: 'project-1',
+ });
});
- it('does not authorize cleanup after the owning account scope expires', async () => {
+ it('proves absence when the retry conflicts and the id is genuinely free', async () => {
+ // Somebody else holds the staging board; our id was never written.
+ transport.apiFetchJson
+ .mockRejectedValueOnce(new TypeError('network error'))
+ .mockRejectedValueOnce(new ApiError('conflict', 409))
+ .mockRejectedValueOnce(new ApiError('not found', 404));
+
+ await expect(createProjectSettled(request, captureAccountScope())).rejects.toBeInstanceOf(ProjectCreateAbsentError);
+ });
+
+ it('proves absence when the server answers with an outright refusal', async () => {
+ transport.apiFetchJson.mockRejectedValueOnce(new ApiError('no such board', 404));
+
+ await expect(createProjectSettled(request, captureAccountScope())).rejects.toBeInstanceOf(ProjectCreateAbsentError);
+ // Deterministic: no retry, because the server already answered.
+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves an unresolved outcome unresolved rather than authorizing a rollback', async () => {
+ const failure = new TypeError('network error');
+
+ transport.apiFetchJson.mockRejectedValueOnce(failure).mockRejectedValueOnce(new TypeError('still offline'));
+
+ // The original failure, not a proof of absence: unknown must never authorize deletion.
+ await expect(createProjectSettled(request, captureAccountScope())).rejects.toBe(failure);
+ });
+
+ it('does not retry a create whose id the server would choose', async () => {
+ const failure = new TypeError('network error');
+
+ transport.apiFetchJson.mockRejectedValueOnce(failure);
+
+ // A second POST would mint a second project rather than collide with the first.
+ await expect(createProjectSettled({ data: {}, name: 'Imported' }, captureAccountScope())).rejects.toBe(failure);
+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops rather than acting once the owning account scope expires', async () => {
const owner = captureAccountScope();
transport.apiFetchJson.mockImplementationOnce(() => {
accountLifecycle.invalidate();
+
return Promise.reject(new ApiError('not found', 404));
});
- await expect(isProjectConfirmedAbsent('project-1', owner)).resolves.toBe(false);
- });
-
- it('does not treat transport or server failures as proof of absence', async () => {
- transport.apiFetchJson.mockRejectedValueOnce(new ApiError('unavailable', 503));
-
- await expect(isProjectConfirmedAbsent('project-1', captureAccountScope())).resolves.toBe(false);
+ await expect(createProjectSettled(request, owner)).rejects.not.toBeInstanceOf(ProjectCreateAbsentError);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.ts
index 5adb9d3a35..d7bf368369 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts
@@ -1,6 +1,6 @@
import type { AccountScope } from '@platform/state/accountLifecycle';
-import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { ApiError, apiFetch, apiFetchJson } from '@platform/transport/http';
/**
@@ -106,17 +106,109 @@ export const isProjectConflictError = (error: unknown): boolean => error instanc
export const isProjectNotFoundError = (error: unknown): boolean => error instanceof ApiError && error.status === 404;
-/** A rejected create is safe to compensate only when its chosen id is authoritatively absent. */
-export const isProjectConfirmedAbsent = async (projectId: string, owner: AccountScope): Promise<boolean> => {
- try {
- await getProject(projectId, owner.signal);
+/**
+ * A create that never reached the server, and is therefore safe to compensate for.
+ *
+ * Raised by {@link createProjectSettled} in place of the original rejection when it can prove the
+ * project does not exist. Callers roll back on this and on nothing else.
+ */
+export class ProjectCreateAbsentError extends Error {
+ readonly cause: unknown;
+
+ constructor(cause: unknown) {
+ super('The project was not created.');
+ this.name = 'ProjectCreateAbsentError';
+ this.cause = cause;
+ }
+}
- return false;
+/**
+ * Create a project, resolving the one outcome a bare `POST` cannot report: a create that reached
+ * the server but whose response did not reach us.
+ *
+ * This matters because the caller has already uploaded a board's worth of media by the time it runs.
+ * Getting the answer wrong in one direction orphans those uploads; in the other it *deletes* them,
+ * out from under a project that does exist, leaving every reference in its document dangling.
+ *
+ * A read cannot decide it. `GET` on the chosen id returns 404 while the create transaction is still
+ * committing, which is exactly the window a dropped connection leaves open — so the probe reports
+ * "absent" about a project that is moments from existing. A write can: SQLite has a single writer,
+ * so a second `POST` cannot commit before the first one finishes, and its answer is about a settled
+ * database rather than one mid-transaction.
+ *
+ * - `201` — the first attempt never landed and this one did.
+ * - `409` — the retry ran to completion against the server, so the follow-up `GET` is no longer
+ * racing anything: a record means the first create committed and is adopted; a 404 means the id is
+ * genuinely free and something else (another importer holding the staging board) refused this.
+ * - any other deterministic rejection — the server answered, and answered no.
+ * - another transport failure — still unknown, and unknown must not authorize deletion.
+ */
+export const createProjectSettled = async (
+ request: ProjectCreateRequest,
+ owner: AccountScope
+): Promise<ProjectRecordDTO> => {
+ const projectId = request.project_id;
+
+ /**
+ * A 409 says the id or the board is spoken for, without saying by whom. Because the server has
+ * answered, nothing is mid-commit any more and reading the id is decisive: our own committed
+ * create, or somebody else's board.
+ */
+ const settleConflict = async (conflict: unknown): Promise<ProjectRecordDTO> => {
+ if (projectId === undefined) {
+ throw conflict;
+ }
+
+ try {
+ return await getProject(projectId, owner.signal);
+ } catch (readError) {
+ assertAccountScopeCurrent(owner);
+
+ throw isProjectNotFoundError(readError) ? new ProjectCreateAbsentError(conflict) : conflict;
+ }
+ };
+
+ const classify = (error: unknown): Promise<ProjectRecordDTO> => {
+ if (isProjectConflictError(error)) {
+ return settleConflict(error);
+ }
+
+ throw isRefusal(error) ? new ProjectCreateAbsentError(error) : error;
+ };
+
+ try {
+ return await createProject(request, owner.signal);
} catch (error) {
- return isAccountScopeCurrent(owner) && isProjectNotFoundError(error);
+ assertAccountScopeCurrent(owner);
+
+ // Without an id of our choosing there is nothing to retry idempotently: a second POST would
+ // mint a second project rather than collide with the first.
+ if (projectId === undefined || !isIndeterminate(error)) {
+ return classify(error);
+ }
+
+ try {
+ return await createProject(request, owner.signal);
+ } catch (retryError) {
+ assertAccountScopeCurrent(owner);
+
+ // Still no answer. Unknown must not authorize deletion, so the original failure stands and
+ // the uploads are left where they are: clutter is recoverable, a gutted project is not.
+ if (isIndeterminate(retryError)) {
+ throw error;
+ }
+
+ return classify(retryError);
+ }
}
};
+/** A response arrived and refused the create outright, so nothing was written. */
+const isRefusal = (error: unknown): boolean => error instanceof ApiError && error.status >= 400 && error.status < 500;
+
+/** No response, or one that says nothing about whether the write happened. */
+const 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 });
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
index 1867151a29..767f8b1f4c 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
@@ -2,6 +2,7 @@ import type { AccountScope } from '@platform/state/accountLifecycle';
import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/api';
import type * as apiModule from '@workbench/projects/api';
+import { ProjectCreateAbsentError } from '@workbench/projects/api';
import { createDraftProject } from '@workbench/workbenchState';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -16,10 +17,11 @@ import type * as duplicateProjectModule from './duplicateProject';
* original's image, and a failure before the create undoes exactly what it made.
*/
+// `createProjectSettled` is the seam, not `createProject`: it is what decides whether a create that
+// went unanswered actually landed, and therefore whether the copies below may be deleted.
const api = vi.hoisted(() => ({
- createProject: vi.fn(),
+ createProjectSettled: vi.fn(),
getProject: vi.fn(),
- isProjectConfirmedAbsent: vi.fn(),
isProjectNotFoundError: (error: unknown) =>
typeof error === 'object' && error !== null && 'status' in error && error.status === 404,
}));
@@ -104,7 +106,7 @@ const copiesOf = (names: readonly string[]) => ({
});
const createdData = (): Record<string, unknown> =>
- (api.createProject.mock.calls[0]![0] as { data: Record<string, unknown> }).data;
+ (api.createProjectSettled.mock.calls[0]![0] as { data: Record<string, unknown> }).data;
const restoredLayerName = (): string =>
(
@@ -129,7 +131,7 @@ beforeEach(async () => {
transport.findExistingVideoNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));
transport.starImages.mockImplementation(() => Promise.resolve({ failed: [] }));
transport.starVideos.mockImplementation(() => Promise.resolve({ failed: [] }));
- api.createProject.mockImplementation(
+ api.createProjectSettled.mockImplementation(
(request: { board_id?: string; data: Record<string, unknown>; name: string; project_id: string }) =>
Promise.resolve({
board_id: request.board_id ?? 'server-created-board',
@@ -159,7 +161,10 @@ describe('duplicateProjectRecord', () => {
'staging-board',
owner.signal
);
- expect(api.createProject.mock.calls[0]![0]).toMatchObject({ board_id: 'staging-board', name: 'Source copy' });
+ expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({
+ board_id: 'staging-board',
+ name: 'Source copy',
+ });
expect(result.record.project_id).not.toBe('source');
expect(result.boardItemIssues).toEqual([]);
});
@@ -253,14 +258,13 @@ describe('duplicateProjectRecord', () => {
await duplicateProject.duplicateProjectRecord({ boardItems: [], owner, record: sourceRecord() });
expect(transport.createStagingBoard).not.toHaveBeenCalled();
- expect(api.createProject.mock.calls[0]![0]).not.toHaveProperty('board_id');
+ expect(api.createProjectSettled.mock.calls[0]![0]).not.toHaveProperty('board_id');
});
- it('deletes the copies it made and the staging board when the create fails', async () => {
- const failure = new Error('create rejected');
+ it('deletes the copies it made and the staging board when the create provably did not happen', async () => {
+ const failure = new ProjectCreateAbsentError(new Error('the server refused the create'));
- api.createProject.mockRejectedValue(failure);
- api.isProjectConfirmedAbsent.mockResolvedValueOnce(true);
+ api.createProjectSettled.mockRejectedValue(failure);
await expect(
duplicateProject.duplicateProjectRecord({
@@ -275,11 +279,16 @@ describe('duplicateProjectRecord', () => {
expect(transport.deleteStagingBoard).toHaveBeenCalledWith('staging-board', owner.signal);
});
- it('leaves the copies alone when a rejected create may already have claimed the board', async () => {
+ /**
+ * The outcome that used to be decided by a `GET`, and decided wrongly: the read returns 404 while
+ * the create transaction is still committing, so the copies were deleted out from under a project
+ * that then appeared — with every reference in its document dangling. An unproven absence must
+ * leave the media alone.
+ */
+ it('leaves the copies alone when a rejected create may already have landed', async () => {
const failure = new Error('connection ended after create');
- api.createProject.mockRejectedValue(failure);
- api.isProjectConfirmedAbsent.mockResolvedValueOnce(false);
+ api.createProjectSettled.mockRejectedValue(failure);
await expect(
duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record: sourceRecord() })
@@ -292,10 +301,10 @@ describe('duplicateProjectRecord', () => {
it('does not issue destructive cleanup under a different account', async () => {
const account = await import('@platform/state/accountLifecycle');
- api.createProject.mockImplementation(() => {
+ api.createProjectSettled.mockImplementation(() => {
account.accountLifecycle.activate('duplicate-user-b');
- return Promise.reject(new Error('create rejected'));
+ return Promise.reject(new ProjectCreateAbsentError(new Error('create rejected')));
});
await expect(
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
index ff4c0be63e..3c6576086c 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
@@ -1,7 +1,7 @@
import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/api';
-import { type AccountScope, assertAccountScopeCurrent, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
-import { createProject as apiCreateProject, isProjectConfirmedAbsent } from '@workbench/projects/api';
+import { type AccountScope, assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { createProjectSettled } from '@workbench/projects/api';
import { createProjectId } from '@workbench/projects/ids';
import {
collectLiveAssetRefs,
@@ -22,7 +22,12 @@ import {
isRequestCancellation,
} from './assetTransport';
import { InvkFormatError } from './format';
-import { createRestoredMediaLedger, restoreProjectMedia, rollbackRestoredMedia } from './restoreProjectMedia';
+import {
+ createRestoredMediaLedger,
+ restoreProjectMedia,
+ rollbackRestoredMedia,
+ rollbackUnlessProjectExists,
+} from './restoreProjectMedia';
import { toMediaRefs } from './transfer';
/**
@@ -188,14 +193,14 @@ export const duplicateProjectRecord = async (
assertAccountScopeCurrent(owner);
- const record = await apiCreateProject(
+ const record = await createProjectSettled(
{
data: remapAssetRefs(canonicalDocument, restored.mappings),
name,
project_id: id,
...(stagingBoardId === null ? {} : { board_id: stagingBoardId }),
},
- owner.signal
+ owner
);
didCreateProject = true;
@@ -211,17 +216,9 @@ export const duplicateProjectRecord = async (
},
};
} catch (error) {
- const canRollback =
- !didCreateProject && isAccountScopeCurrent(owner) && (await isProjectConfirmedAbsent(id, owner));
-
- if (canRollback) {
- try {
- await rollbackRestoredMedia(ledger, { signal: owner.signal });
- } catch {
- // Best-effort: the create failure is the actionable result, and must never be replaced by
- // a failed delete request.
- }
- }
+ await rollbackUnlessProjectExists(error, didCreateProject, owner, () =>
+ rollbackRestoredMedia(ledger, { signal: owner.signal })
+ );
throw error;
}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts
index 76d69975da..92e896bb43 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts
@@ -216,6 +216,68 @@ describe('board media', () => {
]);
});
+ /**
+ * The live reference set skips history — `collectLiveAssetRefs` walks past `recentImages`, canvas
+ * snapshots and the queue — but `remapAssetRefs` rewrites the whole document. Gating the *mapping*
+ * on that set therefore left the newest generated result, which is on the board and in the gallery
+ * recents but not yet on canvas, pointing at the source project's image: the copy renders the
+ * original's picture, and deleting the original breaks it with no explanation.
+ */
+ it('remaps a failed board item the document names only from history', async () => {
+ const result = await restore(
+ // No document ref: this name lives in `recentImages`, which the live-ref walker skips.
+ { boardItems: [boardItem({ name: 'newest.png' })], documentRefs: [] },
+ { materializeBoardMedia: freshNameMaterializer({ fail: new Set(['newest.png']) }) }
+ );
+
+ expect(result.mappings.images.get('newest.png')).toBe(`${PROJECT_ID}-missing-image-0`);
+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'newest.png', reason: 'upload-failed' }]);
+ // Still not *reported*: a gallery recent that stops resolving is not something the person lost
+ // from this project, and counting it would inflate every report.
+ expect(result.documentReferenceIssues).toEqual([]);
+ });
+
+ it('reports a failure the materializer raised twice only once', async () => {
+ const result = await restore(
+ { boardItems: [boardItem({ name: 'twice.png' })], documentRefs: [imageRef('twice.png')] },
+ {
+ materializeBoardMedia: (items, _boardId, onItemSettled) => {
+ onItemSettled();
+
+ const failed = items.map((item) => ({ kind: item.kind, name: item.name, reason: 'upload-failed' as const }));
+
+ return Promise.resolve({ failed: [...failed, ...failed], materialized: [] });
+ },
+ }
+ );
+
+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'twice.png', reason: 'upload-failed' }]);
+ expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'twice.png', reason: 'upload-failed' }]);
+ });
+
+ it('keeps two failures the board never described apart', async () => {
+ // No descriptor position to derive from. Collapsing both onto index 0 would merge two unrelated
+ // missing items into one dangling reference.
+ const result = await restore(
+ { boardItems: [boardItem({ name: 'described.png' })] },
+ {
+ materializeBoardMedia: (_items, _boardId, onItemSettled) => {
+ onItemSettled();
+
+ return Promise.resolve({
+ failed: [
+ { kind: 'image' as const, name: 'stray-a.png', reason: 'upload-failed' as const },
+ { kind: 'image' as const, name: 'stray-b.png', reason: 'upload-failed' as const },
+ ],
+ materialized: [],
+ });
+ },
+ }
+ );
+
+ expect(result.mappings.images.get('stray-a.png')).not.toBe(result.mappings.images.get('stray-b.png'));
+ });
+
/** A materializer that answers neither way has still not delivered the media. */
it('treats an unaccounted descriptor as a failure rather than a silent success', async () => {
const result = await restore(
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
index d75cc0418d..8607b08019 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
@@ -1,4 +1,8 @@
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
import { mapWithConcurrency } from '@platform/core/concurrency';
+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { ProjectCreateAbsentError } from '@workbench/projects/api';
import type { InvkBoardItem, InvkMediaKind } from './board';
import type { InvkMediaRef, ProjectTransferIssues } from './transfer';
@@ -44,13 +48,19 @@ import { buildMissingMediaName, createTransferIssueLog, toMediaKey } from './tra
*
* ### A failed board item must not resolve to a stranger
*
- * The dangerous case is an item that is *both* on the board and referenced by the document, whose
+ * The dangerous case is an item that is *both* on the board and named by the document, whose
* materialization fails. Leaving the reference on the old name is not "no worse than before": on the
* same server — every duplication, and every re-import — that name is already taken, by the source
* project's own image. The project would open showing the right picture from the wrong owner, and
* deleting the original would break it with no explanation. So a failed board item forces its
* document references onto {@link buildMissingMediaName}, which resolves to nothing and renders as
* a missing layer, exactly as a dangling v2 reference already does.
+ *
+ * "Named by the document" means anywhere in it. `remapAssetRefs` walks the whole document; the live
+ * reference set does not, because `collectLiveAssetRefs` skips history — `recentImages`, canvas
+ * snapshots, the queue. So the placeholder is written for every failed item, and the live set decides
+ * only what is worth *reporting*: a gallery recent that stops resolving is not something the person
+ * lost from this project, and counting it would inflate every report.
*/
/**
@@ -292,6 +302,26 @@ export const restoreProjectMedia = async (
const boardKeys = new Set(input.boardItems.map(toMediaKey));
/** Descriptor position, so a placeholder name does not depend on the order failures happened in. */
const descriptorIndexes = new Map(input.boardItems.map((item, index) => [toMediaKey(item), index]));
+ /**
+ * A distinct placeholder index for every failed name.
+ *
+ * Descriptor position is the stable answer and is used wherever it exists. A materializer that
+ * reports a failure for a name that was never a descriptor has no position — and collapsing those
+ * onto one index would give two unrelated missing items the same placeholder, quietly merging
+ * them into a single dangling reference. Counting past the descriptors keeps them apart.
+ */
+ let nextUnknownIndex = input.boardItems.length;
+ const missingNameIndex = (key: string): number => {
+ const index = descriptorIndexes.get(key);
+
+ if (index !== undefined) {
+ return index;
+ }
+
+ nextUnknownIndex += 1;
+
+ return nextUnknownIndex - 1;
+ };
const starredKeys = new Set(input.boardItems.filter((item) => item.starred).map(toMediaKey));
// Document-only references are the ones the board does not own; those the board owns are
@@ -388,22 +418,33 @@ export const restoreProjectMedia = async (
}
}
- /** A board item that did not arrive: reported, and forced dangling if the document wanted it. */
+ /** A board item that did not arrive: forced dangling everywhere, and reported where it shows. */
const failBoardItem = (failure: MaterializeFailure): void => {
- settledBoardKeys.add(toMediaKey(failure));
- issues.addBoardItemIssue(failure, failure.reason);
-
const key = toMediaKey(failure);
- if (!documentKeys.has(key)) {
+ if (settledBoardKeys.has(key)) {
return;
}
+ settledBoardKeys.add(key);
+ issues.addBoardItemIssue(failure, failure.reason);
+
+ // Mapped unconditionally, because `remapAssetRefs` rewrites the *whole* document while
+ // `documentKeys` describes only its live references — `collectLiveAssetRefs` deliberately skips
+ // `recentImages`, `snapshots` and the queue. A name left unmapped therefore survives in history,
+ // and on this server that name is already taken: by the source project's own image. The copy
+ // would open showing the right picture from the wrong owner, and deleting the original would
+ // break it with no explanation. Every occurrence goes to the placeholder instead.
kindAdapters[failure.kind].mapping.set(
failure.name,
- buildMissingMediaName(input.projectId, failure.kind, descriptorIndexes.get(key) ?? 0)
+ buildMissingMediaName(input.projectId, failure.kind, missingNameIndex(key))
);
- issues.addDocumentReferenceIssue(failure, failure.reason);
+
+ // Only the live references are *reported*. A gallery recent that no longer resolves is not
+ // something the person lost from this project, and counting it would inflate every report.
+ if (documentKeys.has(key)) {
+ issues.addDocumentReferenceIssue(failure, failure.reason);
+ }
};
for (const failure of boardResult.failed) {
@@ -536,6 +577,40 @@ export const restoreProjectMedia = async (
return { coverImageName, mappings, ...issues.toIssues() };
};
+/**
+ * Run a restore's rollback, but only when the project it was staging certainly does not exist.
+ *
+ * Both directions of this — import and duplication — got here the same way and get it wrong the
+ * same way, so the decision lives once. Three things have to hold before anything is deleted:
+ *
+ * - the create did not already succeed, because after that the media belongs to a real project;
+ * - the failure is one that proves the project is absent, which is what
+ * {@link ProjectCreateAbsentError} means and why the create goes through `createProjectSettled`
+ * rather than a bare `POST`. An unknown outcome must never authorize a deletion: the uploads are
+ * recoverable clutter, whereas a project stripped of its media is not recoverable at all;
+ * - the account has not changed underneath us, so the deletes are aimed at the right server and the
+ * right person.
+ *
+ * The rollback itself is best-effort — the original failure is the actionable result and must not be
+ * replaced by a message about a delete request nobody asked for.
+ */
+export const rollbackUnlessProjectExists = async (
+ error: unknown,
+ didCreateProject: boolean,
+ owner: AccountScope,
+ rollback: () => Promise<void>
+): Promise<void> => {
+ if (didCreateProject || !(error instanceof ProjectCreateAbsentError) || !isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ try {
+ await rollback();
+ } catch {
+ // Best-effort, per the docblock above.
+ }
+};
+
export interface RollbackRestoredMediaDeps {
deleteBoard?: (boardId: string, signal?: AbortSignal) => Promise<void>;
deleteImages?: (imageNames: string[], signal?: AbortSignal) => Promise<void>;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
index 79506d51de..7d01b134ca 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
@@ -3,6 +3,7 @@ import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as libraryModule from './library';
+import type { ProjectPushOutcome } from './projectFlush';
import type * as syncStoreModule from './syncStore';
/**
@@ -66,10 +67,15 @@ const openProject = (projectId: string, calls: string[] = []) => {
close: vi.fn(() => {
calls.push('close');
}),
+ deleteOnServer: vi.fn(() => {
+ calls.push('deleteOnServer');
+
+ return Promise.resolve();
+ }),
flush: vi.fn(() => {
calls.push('flush');
- return Promise.resolve();
+ return Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'acknowledged' });
}),
markDeleted: vi.fn(() => {
calls.push('markDeleted');
@@ -215,30 +221,46 @@ describe('library mutations', () => {
expect(library.getProjectLibrary().summaries[0]?.name).toBe('New name');
});
- it('deletes an open project without letting its autosave recreate it, then closes the tab', async () => {
- api.deleteProject.mockResolvedValue(undefined);
-
+ /**
+ * The DELETE goes through the sync engine's own queue, not beside it. Marking the project stops a
+ * save that has not begun, but a PUT already on the wire is past every check the engine has — it
+ * returns 404 once the DELETE commits, and the engine answers a 404 by forking the local document
+ * into a *new* server project. Queueing is what makes that unreachable rather than unlikely.
+ */
+ it('deletes an open project through the sync engine, then closes the tab', async () => {
const { calls } = openProject('open');
await library.deleteLibraryProject('open');
- expect(calls).toEqual(['markDeleted', 'close']);
- expect(api.deleteProject).toHaveBeenCalledWith('open', expect.any(AbortSignal));
+ expect(calls).toEqual(['deleteOnServer', 'close']);
+ // Never beside the engine: a bare HTTP delete is what could overtake an in-flight push.
+ expect(api.deleteProject).not.toHaveBeenCalled();
+ });
+
+ it('deletes a closed project over HTTP, because no engine holds it', async () => {
+ api.deleteProject.mockResolvedValue(undefined);
+
+ await library.deleteLibraryProject('closed');
+
+ expect(api.deleteProject).toHaveBeenCalledWith('closed', expect.any(AbortSignal));
});
/**
* A project left marked deleted never autosaves again for the rest of the session, and nothing
- * says so. Unmarking belongs here, beside the mark, rather than in each caller's catch — one of
- * the two that had to remember it did not.
+ * says so. Unmarking belongs with the mark, inside the handle, rather than in each caller's catch.
*/
- it('lets an open project save again when its deletion fails', async () => {
- api.deleteProject.mockRejectedValue(new Error('offline'));
+ it('surfaces a failed deletion of an open project to its caller', async () => {
+ const { calls, handle } = openProject('open');
- const { calls } = openProject('open');
+ handle.deleteOnServer.mockImplementation(() => {
+ calls.push('deleteOnServer');
+
+ return Promise.reject(new Error('offline'));
+ });
await expect(library.deleteLibraryProject('open')).rejects.toThrow('offline');
- expect(calls).toEqual(['markDeleted', 'unmarkDeleted']);
+ expect(calls).toEqual(['deleteOnServer']);
});
it('takes a deleted project out of the saved session', async () => {
@@ -288,6 +310,38 @@ describe('library mutations', () => {
expect(calls).toEqual(['flush', 'get']);
});
+ /**
+ * The GET below returns the last *acknowledged* document, which is exactly what the flush exists
+ * to move past. A flush that resolved without landing therefore reads as success and copies stale
+ * bytes, under a clean toast — so an unacknowledged push has to end the operation instead.
+ */
+ it('refuses to duplicate a project whose flush never reached the server', async () => {
+ const { calls, handle } = openProject('source');
+
+ handle.flush.mockImplementation(() => {
+ calls.push('flush');
+
+ return Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'unsynced' });
+ });
+
+ await expect(library.readProjectForDuplication('source', account.accountLifecycle.capture())).rejects.toMatchObject(
+ { name: 'ProjectFlushError', reason: 'unsynced' }
+ );
+
+ expect(calls).toEqual(['flush']);
+ expect(api.getProject).not.toHaveBeenCalled();
+ });
+
+ it('refuses to duplicate a project whose id was taken over by another device', async () => {
+ const { handle } = openProject('source');
+
+ handle.flush.mockResolvedValue({ documentJson: '{}', kind: 'superseded' });
+
+ await expect(library.readProjectForDuplication('source', account.accountLifecycle.capture())).rejects.toMatchObject(
+ { reason: 'superseded' }
+ );
+ });
+
it('duplicates through the shared restore engine and adopts the copy', async () => {
api.getProject.mockResolvedValue({
...summaryDto('source', 'Source', '2026-06-10 10:00:00.000'),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.ts
index 49704b4a39..285e2330f6 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts
@@ -29,6 +29,7 @@ import {
subscribeProjectCovers,
} from './covers';
import { refreshOpenProjects } from './openProjects';
+import { assertProjectFlushed } from './projectFlush';
import { pruneSessionProject } from './session';
import { getOpenProject } from './syncStore';
@@ -208,18 +209,17 @@ export const deleteLibraryProject = async (projectId: string): Promise<void> =>
const owner = captureAccountScope();
const openProject = getOpenProject(projectId);
- // Marked before the request so an autosave in flight cannot recreate the project — and with it a
- // board — between the DELETE and the tab closing.
- openProject?.markDeleted();
-
- try {
+ if (openProject) {
+ // Through the sync engine's queue, not beside it. Marking the project first stops a save that
+ // has not begun, but a PUT already on the wire is past every check the engine has: it comes
+ // back 404 once this DELETE commits, and the engine answers a 404 by forking the local document
+ // into a new server project — a copy of the thing just deleted, pointing at media the deletion
+ // removed. Queueing means the push finishes before the DELETE is sent. Marking and unmarking
+ // are the handle's business too, because a project left marked stops autosaving for the rest of
+ // the session, silently and with no way to notice.
+ await openProject.deleteOnServer();
+ } else {
await apiDeleteProject(projectId, owner.signal);
- } catch (error) {
- // Unmarked here rather than by the caller, because a project left marked stops autosaving for
- // the rest of the session — silently, and with no way to notice. Two of the three call sites
- // had to remember this and one of them did not.
- openProject?.unmarkDeleted();
- throw error;
}
assertAccountScopeCurrent(owner);
@@ -272,10 +272,16 @@ export const renameLibraryProject = async (projectId: string, name: string): Pro
*
* An open project is flushed first and the flush is fatal if it fails. Duplicating what the server
* last acknowledged would silently drop everything the person can see on screen, and a copy that
- * quietly omits the last ten minutes of work is worse than no copy.
+ * quietly omits the last ten minutes of work is worse than no copy — so a flush that did not land,
+ * or that landed under a different id, raises rather than letting the GET below answer for it.
*/
export const readProjectForDuplication = async (projectId: string, owner: AccountScope): Promise<ProjectRecordDTO> => {
- await getOpenProject(projectId)?.flush();
+ const openProject = getOpenProject(projectId);
+
+ if (openProject) {
+ assertProjectFlushed(await openProject.flush());
+ }
+
assertAccountScopeCurrent(owner);
return apiGetProject(projectId, owner.signal);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts
index c01cf17e10..6e07645c62 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ProjectPushOutcome } from './projectFlush';
+
import { createOpenProjectBroker } from './openProjectBroker';
import { getOpenProject } from './syncStore';
@@ -13,7 +15,8 @@ const createHarness = () => {
const listeners = new Set<() => void>();
const deps = {
closeProject: vi.fn(),
- flushProject: vi.fn(() => Promise.resolve()),
+ deleteProject: vi.fn(() => Promise.resolve()),
+ flushProject: vi.fn(() => Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'acknowledged' })),
getOpenProjectIds: vi.fn(() => openIds),
markProjectDeleted: vi.fn(),
renameProject: vi.fn(),
@@ -112,7 +115,7 @@ describe('createOpenProjectBroker', () => {
harness.deps.flushProject.mockImplementation(() => {
order.push('flush');
- return Promise.resolve();
+ return Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'acknowledged' });
});
startBroker(harness.deps);
harness.setOpenIds(['a']);
@@ -123,7 +126,7 @@ describe('createOpenProjectBroker', () => {
expect(order).toEqual(['rename', 'flush']);
});
- it('routes deletion and closing at the project it was published for', () => {
+ it('routes deletion and closing at the project it was published for', async () => {
const harness = createHarness();
startBroker(harness.deps);
@@ -132,12 +135,30 @@ describe('createOpenProjectBroker', () => {
const handle = getOpenProject('a')!;
handle.markDeleted();
+ await handle.deleteOnServer();
handle.close();
expect(harness.deps.markProjectDeleted).toHaveBeenCalledWith('a');
+ expect(harness.deps.deleteProject).toHaveBeenCalledWith('a');
expect(harness.deps.closeProject).toHaveBeenCalledWith('a');
});
+ /**
+ * A rename is already in the reducer and the local snapshot by the time the flush runs, and the
+ * next save retries the push. Failing the rename because the network blipped would undo nothing
+ * and explain less — so the outcome is read by the surfaces that read the project back, not here.
+ */
+ it('does not fail a rename whose flush did not reach the server', async () => {
+ const harness = createHarness();
+
+ harness.deps.flushProject.mockResolvedValue({ documentJson: '{}', kind: 'unsynced' });
+ startBroker(harness.deps);
+ harness.setOpenIds(['a']);
+
+ await expect(getOpenProject('a')!.rename('New name')).resolves.toBeUndefined();
+ expect(harness.deps.renameProject).toHaveBeenCalledWith('a', 'New name');
+ });
+
/**
* The registry is cleared when the account changes. A broker that trusted its own record of what
* it had published would never register those projects again, and every library mutation would
diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts
index 761851076d..ee4454f48c 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts
@@ -1,3 +1,5 @@
+import type { ProjectPushOutcome } from './projectFlush';
+
import { type OpenProjectHandle, registerOpenProject, unregisterOpenProject } from './syncStore';
/**
@@ -16,8 +18,10 @@ import { type OpenProjectHandle, registerOpenProject, unregisterOpenProject } fr
export interface OpenProjectBrokerDeps {
/** Drop the tab. Called after the project is already gone from the server. */
closeProject: (projectId: string) => void;
- /** Push this project's live document and wait for the acknowledgement. */
- flushProject: (projectId: string) => Promise<void>;
+ /** Remove the project from the server, in the sync engine's own queue. */
+ deleteProject: (projectId: string) => Promise<void>;
+ /** Push this project's live document and report whether the server took it. */
+ flushProject: (projectId: string) => Promise<ProjectPushOutcome>;
getOpenProjectIds: () => string[];
/** Stop the autosave recreating a project that is being deleted. */
markProjectDeleted: (projectId: string) => void;
@@ -36,11 +40,16 @@ export const createOpenProjectBroker = (deps: OpenProjectBrokerDeps): OpenProjec
const buildHandle = (projectId: string): OpenProjectHandle => ({
close: () => deps.closeProject(projectId),
+ deleteOnServer: () => deps.deleteProject(projectId),
flush: () => deps.flushProject(projectId),
markDeleted: () => deps.markProjectDeleted(projectId),
// Renaming through the reducer first is what keeps the open document and the server's copy
// telling the same story: the flush that follows carries the new name on the project's own
// revision chain, where a library PUT would have landed beside it and forced a conflict fork.
+ //
+ // The flush outcome is deliberately ignored. The rename is already in the reducer and on the
+ // local snapshot; a push that did not land is retried by the next save, and failing the rename
+ // because the network blipped would undo nothing and explain less.
rename: async (name: string) => {
deps.renameProject(projectId, name);
await deps.flushProject(projectId);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index d964d0240d..8273dbad4d 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -6,8 +6,11 @@ import type * as apiModule from './api';
import type * as coversModule from './covers';
import type * as assetTransportModule from './invk/assetTransport';
import type * as projectFileModule from './projectFile';
+import type { ProjectPushOutcome } from './projectFlush';
import type * as persistenceModule from './syncedPersistence';
+import { ProjectCreateAbsentError } from './api';
+
/**
* The `.invk` workflow end to end: export writes an archive that import reads
* back, an imported project always lands under a fresh id so a file can never
@@ -16,13 +19,12 @@ import type * as persistenceModule from './syncedPersistence';
*/
const api = vi.hoisted(() => ({
- createProject: vi.fn(),
+ createProjectSettled: vi.fn(),
deleteClientStateValue: vi.fn(() => Promise.resolve()),
getClientStateValue: vi.fn(() => Promise.resolve(null)),
getProject: vi.fn(),
// Every export enumerates the project's board; most of these cases do not care what is on it.
getProjectBoardSnapshot: vi.fn((): Promise<{ items: ProjectBoardItemDTO[] }> => Promise.resolve({ items: [] })),
- isProjectConfirmedAbsent: vi.fn(),
isProjectNotFoundError: (error: unknown) =>
typeof error === 'object' && error !== null && 'status' in error && error.status === 404,
setClientStateValue: vi.fn(() => Promise.resolve()),
@@ -137,7 +139,7 @@ const capturedArchive = (): File => {
/** The server answers with the board it claimed, or with the one it created for a boardless create. */
const acceptCreate = (): void => {
- api.createProject.mockImplementation(
+ api.createProjectSettled.mockImplementation(
(request: { board_id?: string; data?: Record<string, unknown>; name: string; project_id?: string }) =>
Promise.resolve({
board_id: request.board_id ?? 'server-created-board',
@@ -245,7 +247,7 @@ describe('exportLibraryProject', () => {
const order: string[] = [];
const flush = vi.fn(() => {
order.push('flush');
- return Promise.resolve();
+ return Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'acknowledged' });
});
api.getProject.mockImplementation(() => {
@@ -260,6 +262,7 @@ describe('exportLibraryProject', () => {
});
registerOpenProject('p1', {
close: vi.fn(),
+ deleteOnServer: vi.fn(),
flush,
markDeleted: vi.fn(),
rename: vi.fn(),
@@ -276,6 +279,37 @@ describe('exportLibraryProject', () => {
expect(order).toEqual(['flush', 'get']);
});
+ /**
+ * The record read below is the last one the server *acknowledged*, which is precisely what the
+ * flush exists to move past. A flush that resolved without landing is therefore indistinguishable
+ * from one that worked: the archive gets built from stale bytes and downloaded under a success
+ * toast, silently missing everything since the last successful autosave.
+ */
+ it('refuses to export a project whose flush never reached the server', async () => {
+ const { registerOpenProject, unregisterOpenProject } = await import('./syncStore');
+
+ registerOpenProject('p1', {
+ close: vi.fn(),
+ deleteOnServer: vi.fn(),
+ flush: vi.fn(() => Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'unsynced' })),
+ markDeleted: vi.fn(),
+ rename: vi.fn(),
+ unmarkDeleted: vi.fn(),
+ });
+
+ try {
+ await expect(projectFile.exportLibraryProject('p1')).rejects.toMatchObject({
+ name: 'ProjectFlushError',
+ reason: 'unsynced',
+ });
+ } finally {
+ unregisterOpenProject('p1');
+ }
+
+ expect(api.getProject).not.toHaveBeenCalled();
+ expect(downloads.downloadBlob).not.toHaveBeenCalled();
+ });
+
it('does not flush a project nothing holds', async () => {
api.getProject.mockResolvedValue({
data: persistence.serializeProjectDocument({ ...createDraftProject([]), name: 'Closed' }),
@@ -425,7 +459,7 @@ describe('importing a project board', () => {
signal: expect.anything(),
});
expect(transport.uploadBoardVideo).toHaveBeenCalledWith(expect.anything(), 'clip.mp4', expect.anything());
- expect(api.createProject.mock.calls[0]![0]).toMatchObject({ board_id: 'staging-board' });
+ expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({ board_id: 'staging-board' });
expect(outcome.boardItemIssues).toEqual([]);
expect(outcome.documentReferenceIssues).toEqual([]);
});
@@ -442,7 +476,7 @@ describe('importing a project board', () => {
acceptCreate();
await projectFile.importProjectFile(await exportedBoardArchive());
- const { data } = api.createProject.mock.calls[0]![0] as {
+ const { data } = api.createProjectSettled.mock.calls[0]![0] as {
data: { canvas: { document: { layers: Array<{ source: { image: { imageName: string } } }> } } };
};
@@ -475,7 +509,7 @@ describe('importing a project board', () => {
);
const outcome = await projectFile.importProjectFile(await exportedBoardArchive());
- const { data } = api.createProject.mock.calls[0]![0] as {
+ const { data } = api.createProjectSettled.mock.calls[0]![0] as {
data: { canvas: { document: { layers: Array<{ source: { image: { imageName: string } } }> } } };
};
const restoredName = data.canvas.document.layers[0]!.source.image.imageName;
@@ -504,7 +538,7 @@ describe('importing a project board', () => {
await projectFile.importProjectFile(capturedArchive());
expect(transport.createStagingBoard).not.toHaveBeenCalled();
- expect(api.createProject.mock.calls[0]![0]).not.toHaveProperty('board_id');
+ expect(api.createProjectSettled.mock.calls[0]![0]).not.toHaveProperty('board_id');
});
it('creates no staging board for a document that will not rehydrate', async () => {
@@ -536,14 +570,13 @@ describe('importing a project board', () => {
it('deletes the media it created and then the staging board when the create fails', async () => {
const account = await import('@platform/state/accountLifecycle');
- const primaryFailure = new Error('project create rejected');
+ const primaryFailure = new ProjectCreateAbsentError(new Error('project create rejected'));
account.accountLifecycle.activate('board-rollback-user');
const archive = await exportedBoardArchive();
- api.createProject.mockRejectedValue(primaryFailure);
- api.isProjectConfirmedAbsent.mockResolvedValueOnce(true);
+ api.createProjectSettled.mockRejectedValue(primaryFailure);
await expect(projectFile.importProjectFile(archive)).rejects.toBe(primaryFailure);
@@ -556,7 +589,7 @@ describe('importing a project board', () => {
account.accountLifecycle.invalidate();
});
- it('leaves the staging board alone when a rejected create may already have claimed it', async () => {
+ it('leaves the staging board alone when a rejected create may already have landed', async () => {
const account = await import('@platform/state/accountLifecycle');
const primaryFailure = new Error('connection ended after create');
@@ -564,8 +597,7 @@ describe('importing a project board', () => {
const archive = await exportedBoardArchive();
- api.createProject.mockRejectedValue(primaryFailure);
- api.isProjectConfirmedAbsent.mockResolvedValueOnce(false);
+ api.createProjectSettled.mockRejectedValue(primaryFailure);
await expect(projectFile.importProjectFile(archive)).rejects.toBe(primaryFailure);
@@ -587,7 +619,10 @@ describe('importProjectFile', () => {
expect(record.project_id).not.toBe(project.id);
expect(record.name).toBe('Exported project');
- const createRequest = api.createProject.mock.calls[0]![0] as { data: Record<string, unknown>; project_id: string };
+ const createRequest = api.createProjectSettled.mock.calls[0]![0] as {
+ data: Record<string, unknown>;
+ project_id: string;
+ };
expect(createRequest.data.id).toBe(createRequest.project_id);
});
@@ -624,7 +659,7 @@ describe('importProjectFile', () => {
await projectFile.importProjectFile(file);
- const { data } = api.createProject.mock.calls[0]![0] as { data: Record<string, unknown> };
+ const { data } = api.createProjectSettled.mock.calls[0]![0] as { data: Record<string, unknown> };
const serialized = JSON.stringify(data);
expect(serialized).not.toContain('theirs-compare.png');
@@ -655,14 +690,14 @@ describe('importProjectFile', () => {
await expect(projectFile.importProjectFile(new File([blob], 'legacy.invk'))).rejects.toMatchObject({
reason: 'legacy-canvas-project',
});
- expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.createProjectSettled).not.toHaveBeenCalled();
});
it('refuses a file that is not an archive before touching the server', async () => {
await expect(projectFile.importProjectFile(new File(['{"some":"json"}'], 'x.invk'))).rejects.toMatchObject({
reason: 'not-a-project',
});
- expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.createProjectSettled).not.toHaveBeenCalled();
});
it('refuses a damaged document before any asset or project mutation', async () => {
@@ -703,7 +738,7 @@ describe('importProjectFile', () => {
expect(transport.findExistingVideoNames).not.toHaveBeenCalled();
expect(transport.uploadArchiveImage).not.toHaveBeenCalled();
expect(transport.uploadArchiveVideo).not.toHaveBeenCalled();
- expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.createProjectSettled).not.toHaveBeenCalled();
expect(covers.recordProjectCover).not.toHaveBeenCalled();
});
@@ -746,7 +781,7 @@ describe('importProjectFile', () => {
await projectFile.importProjectFile(new File([blob], 'legacy.invk'));
- const createRequest = api.createProject.mock.calls[0]![0] as { data: Record<string, unknown> };
+ const createRequest = api.createProjectSettled.mock.calls[0]![0] as { data: Record<string, unknown> };
const invocation = createRequest.data.invocation as { sourceId: string };
const canvas = createRequest.data.canvas as {
document: { layers: Array<{ source: { image: { imageName: string } } }> };
@@ -781,7 +816,7 @@ describe('importProjectFile', () => {
acceptCreate();
const { record } = await projectFile.importProjectFile(file);
- const request = api.createProject.mock.calls[0]![0] as {
+ const request = api.createProjectSettled.mock.calls[0]![0] as {
data: Record<string, unknown>;
name: string;
project_id: string;
@@ -814,7 +849,7 @@ describe('importProjectFile', () => {
const file = new File([contents], 'invalid.invokeproject.json', { type: 'application/json' });
await expect(projectFile.importProjectFile(file)).rejects.toMatchObject({ reason: 'not-a-project' });
- expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.createProjectSettled).not.toHaveBeenCalled();
expect(transport.findExistingImageNames).not.toHaveBeenCalled();
expect(transport.findExistingVideoNames).not.toHaveBeenCalled();
expect(transport.uploadArchiveImage).not.toHaveBeenCalled();
@@ -836,12 +871,11 @@ describe('importProjectFile', () => {
it('rolls back every authoritative uploaded identity when project creation fails without hiding that failure', async () => {
const account = await import('@platform/state/accountLifecycle');
- const primaryFailure = new Error('project create rejected');
+ const primaryFailure = new ProjectCreateAbsentError(new Error('project create rejected'));
account.accountLifecycle.activate('rollback-user');
await projectFile.exportOpenProject(projectWithRestorableAssets());
- api.createProject.mockRejectedValue(primaryFailure);
- api.isProjectConfirmedAbsent.mockResolvedValueOnce(true);
+ api.createProjectSettled.mockRejectedValue(primaryFailure);
transport.deleteArchiveImages.mockRejectedValueOnce(new Error('image cleanup failed'));
transport.deleteArchiveVideos.mockRejectedValueOnce(new Error('video cleanup failed'));
@@ -852,14 +886,13 @@ describe('importProjectFile', () => {
account.accountLifecycle.invalidate();
});
- it('does not roll back when a rejected create may already have committed the project', async () => {
+ it('does not roll back when a rejected create is not proof the project is absent', async () => {
const account = await import('@platform/state/accountLifecycle');
const primaryFailure = new Error('connection ended after create');
account.accountLifecycle.activate('ambiguous-response-user');
await projectFile.exportOpenProject(projectWithRestorableAssets(false));
- api.createProject.mockRejectedValue(primaryFailure);
- api.isProjectConfirmedAbsent.mockResolvedValueOnce(false);
+ api.createProjectSettled.mockRejectedValue(primaryFailure);
await expect(projectFile.importProjectFile(capturedArchive())).rejects.toBe(primaryFailure);
@@ -881,7 +914,7 @@ describe('importProjectFile', () => {
await expect(projectFile.importProjectFile(capturedArchive())).rejects.toThrow('no longer active');
- expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.createProjectSettled).not.toHaveBeenCalled();
expect(transport.deleteArchiveImages).not.toHaveBeenCalled();
expect(transport.deleteArchiveVideos).not.toHaveBeenCalled();
account.accountLifecycle.invalidate();
@@ -892,7 +925,7 @@ describe('importProjectFile', () => {
account.accountLifecycle.activate('ambiguous-create-user-a');
await projectFile.exportOpenProject(projectWithRestorableAssets(false));
- api.createProject.mockImplementation((request: { name: string; project_id?: string }) => {
+ api.createProjectSettled.mockImplementation((request: { name: string; project_id?: string }) => {
account.accountLifecycle.activate('ambiguous-create-user-b');
return Promise.resolve({
@@ -931,7 +964,7 @@ describe('importProjectFile', () => {
contents.resolve(bytes);
await expect(imported).rejects.toThrow('no longer active');
- expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.createProjectSettled).not.toHaveBeenCalled();
account.accountLifecycle.invalidate();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 45a590ba94..4128502855 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -12,10 +12,9 @@ import {
import type { ProjectTransferIssues } from './invk/transfer';
import {
- createProject as apiCreateProject,
+ createProjectSettled,
getProject as apiGetProject,
getProjectBoardSnapshot,
- isProjectConfirmedAbsent,
type ProjectRecordDTO,
} from './api';
import { recordProjectCover } from './covers';
@@ -23,6 +22,7 @@ import { createProjectId } from './ids';
import { INVK_EXTENSION, InvkFormatError } from './invk/format';
import { upsertProjectSummary } from './library';
import { remapAssetRefs, stripInstallationState } from './projectAssets';
+import { assertProjectFlushed } from './projectFlush';
import { getOpenProject } from './syncStore';
export const PROJECT_FILE_KIND = 'invokeai-project';
@@ -203,14 +203,22 @@ const exportProjectDocument = async (
* this — a project card, a gallery board's menu — are reachable while that project is open, and the
* board most likely to be right-clicked is the open project's own. Exporting what the server last
* acknowledged would hand someone a file that silently omits the last ten minutes of their work.
+ *
+ * A flush that does not land therefore ends the export. The archive is built from the record read
+ * below, so an unacknowledged push means the file would be wrong in exactly the way this call
+ * exists to prevent — and wrong invisibly, under a download and a success toast.
*/
export const exportLibraryProject = async (
projectId: string,
options: ProjectFileOptions = {}
): Promise<ProjectExportOutcome> => {
const owner = options.owner ?? captureAccountScope();
+ const openProject = getOpenProject(projectId);
+
+ if (openProject) {
+ assertProjectFlushed(await openProject.flush());
+ }
- await getOpenProject(projectId)?.flush();
assertAccountScopeCurrent(owner);
const record = await apiGetProject(projectId, owner.signal);
@@ -337,14 +345,14 @@ export const importProjectFile = async (
assertAccountScopeCurrent(owner);
const document = restored === null ? canonicalDocument : remapAssetRefs(canonicalDocument, restored.mappings);
- const record = await apiCreateProject(
+ const record = await createProjectSettled(
{
data: document,
name,
project_id: id,
...(stagingBoardId === null ? {} : { board_id: stagingBoardId }),
},
- owner.signal
+ owner
);
didCreateProject = true;
@@ -366,20 +374,12 @@ export const importProjectFile = async (
},
};
} catch (error) {
- const canRollback =
- !didCreateProject &&
- ledger !== null &&
- restoreMedia !== null &&
- isAccountScopeCurrent(owner) &&
- (await isProjectConfirmedAbsent(id, owner));
-
- if (canRollback) {
- try {
- await restoreMedia.rollbackRestoredMedia(ledger, { signal: owner.signal });
- } catch {
- // Cleanup is best-effort. The create/scope failure is the actionable
- // result and must never be replaced by a failed delete request.
- }
+ // Reached through the lazily-loaded module, so a legacy JSON import still never pulls the
+ // restore engine into the graph — it has no media to undo.
+ if (ledger !== null && restoreMedia !== null) {
+ await restoreMedia.rollbackUnlessProjectExists(error, didCreateProject, owner, () =>
+ restoreMedia.rollbackRestoredMedia(ledger, { signal: owner.signal })
+ );
}
throw error;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts
index dd11092e61..2dd6cc50d2 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts
@@ -1,4 +1,5 @@
import { InvkFormatError } from './invk/format';
+import { ProjectFlushError } from './projectFlush';
/**
* Turn a failed project-file read or write into something worth showing.
@@ -17,8 +18,13 @@ import { InvkFormatError } from './invk/format';
* to open" while they were exporting it names the wrong operation and the wrong
* file — theirs, not one they were handed.
*
- * Anything that is not an `InvkFormatError` reached us from the network or the
- * reducer. Those already carry messages meant for people, so they pass through.
+ * `ProjectFlushError` is the third case: not a bad file but a project whose
+ * newest content never reached the server, so there is nothing correct to
+ * export or copy yet. Its own message names the mechanism rather than the fix,
+ * which is the wrong half to show someone.
+ *
+ * Anything else reached us from the network or the reducer. Those already carry
+ * messages meant for people, so they pass through.
*/
export type ProjectFileDirection = 'read' | 'write';
@@ -27,6 +33,10 @@ export const describeProjectFileError = (
t: (key: string) => string,
direction: ProjectFileDirection = 'read'
): string | undefined => {
+ if (error instanceof ProjectFlushError) {
+ return t(error.reason === 'unsynced' ? 'projects.file.notSynced' : 'projects.file.supersededElsewhere');
+ }
+
if (!(error instanceof InvkFormatError)) {
return error instanceof Error ? error.message : undefined;
}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts
new file mode 100644
index 0000000000..90bfb6787e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts
@@ -0,0 +1,73 @@
+/**
+ * What a push to the server actually achieved, as distinct from whether the call threw.
+ *
+ * Its own module rather than part of the sync engine, because the two callers that need it —
+ * `library.ts` for duplication and `projectFile.ts` for export — are modules the sync engine itself
+ * imports. Reaching back into it for this would make that a cycle.
+ *
+ * Every failure the engine can hit is recoverable: the document is cached locally and the next save
+ * retries, which is why a push swallows them all rather than rejecting. But "recoverable" is not the
+ * same as "done", and reading a project back from the server after an unacknowledged push is how an
+ * export or a copy silently ships someone's work minus the last ten minutes of it.
+ */
+
+/** The document the push was carrying, so a caller can compare it with what the engine recorded. */
+export interface ProjectPushOutcomeBase {
+ documentJson: string;
+}
+
+export type ProjectPushOutcome =
+ /** The server holds exactly this document. */
+ | ({ kind: 'acknowledged' } & ProjectPushOutcomeBase)
+ /**
+ * This project id no longer holds our document: it was deleted or overwritten elsewhere, and the
+ * local edits continue under a different id. Reading the id back would read a stranger's version.
+ */
+ | ({ kind: 'superseded' } & ProjectPushOutcomeBase)
+ /** The push did not land. The server still holds whatever it last acknowledged. */
+ | ({ kind: 'unsynced' } & ProjectPushOutcomeBase);
+
+/** Raised where an unacknowledged push must not be treated as a successful one. */
+export class ProjectFlushError extends Error {
+ readonly reason: 'superseded' | 'unsynced';
+
+ constructor(reason: 'superseded' | 'unsynced') {
+ super(
+ reason === 'unsynced'
+ ? 'The project has changes that have not reached the server.'
+ : 'The project was replaced on the server; the local edits continue under another id.'
+ );
+ this.name = 'ProjectFlushError';
+ this.reason = reason;
+ }
+}
+
+/**
+ * Read back only what the server has certainly acknowledged.
+ *
+ * Both callers — export and duplicate — do the same two things: flush the open project, then GET
+ * the record. The GET returns the last *acknowledged* document, so without this the flush's failure
+ * is indistinguishable from its success and the copy is built from stale bytes under a clean
+ * success toast.
+ */
+export const assertProjectFlushed = (outcome: ProjectPushOutcome): void => {
+ if (outcome.kind !== 'acknowledged') {
+ throw new ProjectFlushError(outcome.kind);
+ }
+};
+
+/**
+ * Who a recovery fork *is*, separately from what it holds.
+ *
+ * The fork's `recoveredProject` is built from the document as it was when the push started, so
+ * applying it wholesale overwrites anything edited since. The identity is the only part of it the
+ * local store actually needs: a project that is still open can adopt these four fields and keep its
+ * live content, which is both newer and already what the person is looking at. The snapshot stays
+ * for the case where there is no live project left to re-identify — a tab closed mid-flight.
+ */
+export interface ProjectRecoveredIdentity {
+ id: string;
+ name: string;
+ recoveredAt: string;
+ recoveryOf: string;
+}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
index 4c0716e2c7..16d944961b 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
@@ -1,8 +1,11 @@
import type { Project } from '@workbench/projectContracts';
+import { getProjectWidgetValues } from '@workbench/widgetState';
import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
import { describe, expect, it } from 'vitest';
+import type { ProjectRecoveredIdentity } from './projectFlush';
+
import { applyAuthoritativeProjectBoard } from './projectDocument';
import { createRecoveredDocument, deserializeProjectDocument, serializeProjectDocument } from './syncedPersistence';
@@ -102,15 +105,21 @@ describe('project document serialization', () => {
describe('createRecoveredDocument', () => {
it('keys the fork to the original and stamps the recovery time', () => {
const project = getProject({ name: 'My Project' });
- const { recoveredDocument, recoveredId, recoveredName } = createRecoveredDocument(
+ const { recoveredDocument, recoveredIdentity } = createRecoveredDocument(
project,
serializeProjectDocument(project)
);
expect(recoveredDocument.recoveryOf).toBe(project.id);
- expect(recoveredId.startsWith(`${project.id}-recovered-`)).toBe(true);
- expect(recoveredName).toBe('My Project (recovered)');
+ expect(recoveredIdentity.id.startsWith(`${project.id}-recovered-`)).toBe(true);
+ expect(recoveredIdentity.name).toBe('My Project (recovered)');
expect(typeof recoveredDocument.recoveredAt).toBe('string');
+ // The identity is what the reducer re-labels the live project with, so it has to agree with the
+ // document the server was handed, field for field.
+ expect(recoveredDocument.id).toBe(recoveredIdentity.id);
+ expect(recoveredDocument.name).toBe(recoveredIdentity.name);
+ expect(recoveredDocument.recoveredAt).toBe(recoveredIdentity.recoveredAt);
+ expect(recoveredDocument.recoveryOf).toBe(recoveredIdentity.recoveryOf);
});
it('collapses recovery chains to the root and never stacks name suffixes', () => {
@@ -121,17 +130,20 @@ describe('createRecoveredDocument', () => {
recoveryOf: root.id,
});
- const { recoveredDocument, recoveredName } = createRecoveredDocument(recovery, serializeProjectDocument(recovery));
+ const { recoveredDocument, recoveredIdentity } = createRecoveredDocument(
+ recovery,
+ serializeProjectDocument(recovery)
+ );
expect(recoveredDocument.recoveryOf).toBe(root.id);
- expect(recoveredName).toBe('My Project (recovered)');
+ expect(recoveredIdentity.name).toBe('My Project (recovered)');
});
it('cleans up legacy stacked suffixes', () => {
const project = getProject({ name: 'Project Name #1 (Recovered) (Recovered)' });
- const { recoveredName } = createRecoveredDocument(project, serializeProjectDocument(project));
+ const { recoveredIdentity } = createRecoveredDocument(project, serializeProjectDocument(project));
- expect(recoveredName).toBe('Project Name #1 (recovered)');
+ expect(recoveredIdentity.name).toBe('Project Name #1 (recovered)');
});
});
@@ -174,16 +186,25 @@ describe('renameProject', () => {
});
});
+const recoveredIdentityFor = (projectId: string, name = 'Recovered'): ProjectRecoveredIdentity => ({
+ id: `${projectId}-recovered-abc`,
+ name,
+ recoveredAt: '2026-08-07T00:00:00.000Z',
+ recoveryOf: projectId,
+});
+
describe('reconcileProjectConflict', () => {
it('adopts the server version and continues local work in the recovered fork', () => {
const state = createInitialWorkbenchState();
const original = state.projects[0];
const serverProject = getProject({ id: original.id, name: 'Server version' });
- const recoveredProject = getProject({ id: `${original.id}-recovered-abc`, name: 'Server version (recovered)' });
+ const recoveredIdentity = recoveredIdentityFor(original.id, 'Server version (recovered)');
+ const recoveredProject = getProject({ id: recoveredIdentity.id, name: recoveredIdentity.name });
const withActiveOriginal = { ...state, activeProjectId: original.id };
const next = workbenchReducer(withActiveOriginal, {
projectId: original.id,
+ recoveredIdentity,
recoveredProject,
serverProject,
type: 'reconcileProjectConflict',
@@ -192,13 +213,65 @@ describe('reconcileProjectConflict', () => {
const ids = next.projects.map((project) => project.id);
expect(ids).toContain(original.id);
- expect(ids).toContain(recoveredProject.id);
+ expect(ids).toContain(recoveredIdentity.id);
expect(next.projects.find((project) => project.id === original.id)?.name).toBe('Server version');
// The user keeps looking at their own latest edits.
- expect(next.activeProjectId).toBe(recoveredProject.id);
+ expect(next.activeProjectId).toBe(recoveredIdentity.id);
expect(next.notifications[0]?.title).toBe('Project recovered');
});
+ it('carries the edits made while the save was in flight, not the snapshot it was built from', () => {
+ // The fork's document is serialized when the push starts. Anything edited after that is newer,
+ // and is what the person is looking at — so adopting the snapshot would delete precisely the
+ // work the fork exists to rescue. Staleness is not an edge case here: a save is stale exactly
+ // when something landed mid-flight, which is when this reducer runs.
+ const state = createInitialWorkbenchState();
+ const original = state.projects[0];
+ const live = workbenchReducer(
+ { ...state, activeProjectId: original.id },
+ { boardId: 'edited-after-the-push-started', projectId: original.id, type: 'setGalleryProjectBoardId' }
+ );
+ const recoveredIdentity = recoveredIdentityFor(original.id, 'Snapshot (recovered)');
+
+ const next = workbenchReducer(live, {
+ projectId: original.id,
+ recoveredIdentity,
+ // What the push was carrying: the document as it was before that edit landed.
+ recoveredProject: getProject({ id: recoveredIdentity.id, name: 'Snapshot (recovered)' }),
+ serverProject: getProject({ id: original.id, name: 'Server version' }),
+ type: 'reconcileProjectConflict',
+ });
+
+ const fork = next.projects.find((project) => project.id === recoveredIdentity.id);
+
+ expect(fork).toBeDefined();
+ // The identity is the server's...
+ expect(fork?.name).toBe(recoveredIdentity.name);
+ expect(fork?.recoveryOf).toBe(original.id);
+ expect(fork?.recoveredAt).toBe(recoveredIdentity.recoveredAt);
+ // ...and the content is the live one's.
+ expect(getProjectWidgetValues(fork!, 'gallery').projectBoardId).toBe('edited-after-the-push-started');
+ });
+
+ it('falls back to the pushed snapshot when no live project is left to re-label', () => {
+ // A tab closed while the save was in flight. The snapshot is then the only local copy of the
+ // work, so it is the right answer rather than a stale one.
+ const state = createInitialWorkbenchState();
+ const closedId = 'project-already-closed';
+ const recoveredIdentity = recoveredIdentityFor(closedId, 'Closed (recovered)');
+
+ const next = workbenchReducer(state, {
+ projectId: closedId,
+ recoveredIdentity,
+ recoveredProject: getProject({ id: recoveredIdentity.id, name: 'Closed (recovered)' }),
+ serverProject: getProject({ id: closedId, name: 'Server version' }),
+ type: 'reconcileProjectConflict',
+ });
+
+ expect(next.projects.map((project) => project.id)).toContain(recoveredIdentity.id);
+ expect(next.projects.find((project) => project.id === recoveredIdentity.id)?.name).toBe('Closed (recovered)');
+ });
+
it('leaves the active project alone when the conflicted project is in the background', () => {
const state = createInitialWorkbenchState();
const first = state.projects[0];
@@ -207,6 +280,7 @@ describe('reconcileProjectConflict', () => {
const next = workbenchReducer(withActiveSecond, {
projectId: first.id,
+ recoveredIdentity: recoveredIdentityFor(first.id),
recoveredProject: getProject({ id: `${first.id}-recovered-abc`, name: 'Recovered' }),
serverProject: getProject({ id: first.id, name: 'Server version' }),
type: 'reconcileProjectConflict',
@@ -216,6 +290,35 @@ describe('reconcileProjectConflict', () => {
});
});
+describe('reconcileDeletedProject', () => {
+ it('keeps the live content under the fork identity', () => {
+ const state = createInitialWorkbenchState();
+ const original = state.projects[0];
+ const live = workbenchReducer(
+ { ...state, activeProjectId: original.id },
+ { boardId: 'edited-after-the-push-started', projectId: original.id, type: 'setGalleryProjectBoardId' }
+ );
+ const recoveredIdentity = recoveredIdentityFor(original.id, 'Snapshot (recovered)');
+
+ const next = workbenchReducer(live, {
+ projectId: original.id,
+ recoveredIdentity,
+ recoveredProject: getProject({ id: recoveredIdentity.id, name: 'Snapshot (recovered)' }),
+ type: 'reconcileDeletedProject',
+ });
+
+ // The deletion stands: the original id is gone, replaced in place by the fork.
+ expect(next.projects.map((project) => project.id)).not.toContain(original.id);
+
+ const fork = next.projects.find((project) => project.id === recoveredIdentity.id);
+
+ expect(fork?.name).toBe(recoveredIdentity.name);
+ expect(fork?.recoveryOf).toBe(original.id);
+ expect(getProjectWidgetValues(fork!, 'gallery').projectBoardId).toBe('edited-after-the-push-started');
+ expect(next.activeProjectId).toBe(recoveredIdentity.id);
+ });
+});
+
/**
* SQLite owns which board belongs to which project; the document only caches it. This is the one
* place that writes that cache, so every path — hydration, create, import, duplicate, fork —
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
index 96cc718db9..f5960c24fa 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
@@ -1,6 +1,8 @@
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
+import type { ProjectPushOutcome } from './projectFlush';
+
/**
* The bridge between the project sync layer and everything outside the editor.
*
@@ -59,8 +61,24 @@ registerAccountOwnedResource({
export interface OpenProjectHandle {
/** Close the tab, after the project has been deleted on the server. */
close: () => void;
- /** Push the live document and wait for the server to acknowledge it. */
- flush: () => Promise<void>;
+ /**
+ * Delete the project on the server, from inside the sync engine's mutation queue.
+ *
+ * The queue is the point. Marking the project deleted stops a save that has not begun, but says
+ * nothing to a `PUT` already on the wire — that one returns 404 once the delete commits, and the
+ * engine's answer to a 404 is to fork the local edits into a new server-side project. Deleting
+ * *through* the queue means the in-flight push finishes first, so there is no 404 to misread and
+ * no copy of the project the person just deleted.
+ */
+ deleteOnServer: () => Promise<void>;
+ /**
+ * Push the live document, and report whether the server actually took it.
+ *
+ * Deliberately an outcome rather than a rejection. A push that did not land is recoverable — the
+ * document is cached and the next save retries — so a rename or a closing tab is right to ignore
+ * it. A caller about to read the project back from the server is not: see `assertProjectFlushed`.
+ */
+ flush: () => Promise<ProjectPushOutcome>;
/** Stop the autosave from recreating this project while it is being deleted. */
markDeleted: () => void;
/**
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
index 7e2342bc49..63ca655174 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
@@ -741,6 +741,164 @@ describe('authoritative project boards', () => {
expect(result.projectBoardAssignments).toHaveLength(1);
});
+ /**
+ * The two callers that read a project back from the server — export and duplicate — have to be
+ * able to tell a push that landed from one that merely failed recoverably. Every branch below
+ * resolves, by design; the outcome is the only thing that distinguishes them.
+ */
+ describe('what a flush reports', () => {
+ it('acknowledges a push the server took', async () => {
+ const project = seedServerProject('Synced');
+ const opened = await service.hydrateProjectFromServer(project.id);
+
+ await expect(service.flushProjectToServer({ ...opened!, name: 'Edited' })).resolves.toMatchObject({
+ kind: 'acknowledged',
+ });
+ });
+
+ it('acknowledges a project the server already holds unchanged', async () => {
+ const project = seedServerProject('Synced');
+ const opened = await service.hydrateProjectFromServer(project.id);
+
+ await expect(service.flushProjectToServer(opened!)).resolves.toMatchObject({ kind: 'acknowledged' });
+ });
+
+ it('reports a push the server never took as unsynced', async () => {
+ const project = seedServerProject('Synced');
+ const opened = await service.hydrateProjectFromServer(project.id);
+
+ api.updateProject.mockRejectedValueOnce(new Error('the proxy refused the body'));
+
+ await expect(service.flushProjectToServer({ ...opened!, name: 'Edited' })).resolves.toMatchObject({
+ kind: 'unsynced',
+ });
+ expect(service.hasPendingChanges()).toBe(true);
+ });
+
+ it('reports a fork as superseded, because the id now holds the other version', async () => {
+ const project = seedServerProject('Contested');
+ const opened = await service.hydrateProjectFromServer(project.id);
+
+ // The other device wins the race with content of its own, so this is a genuine divergence
+ // rather than a revision that merely drifted.
+ api.__records.set(project.id, {
+ ...api.__records.get(project.id)!,
+ data: persistence.serializeProjectDocument({ ...project, name: 'Their version' }),
+ name: 'Their version',
+ revision: 99,
+ });
+
+ await expect(service.flushProjectToServer({ ...opened!, name: 'My version' })).resolves.toMatchObject({
+ kind: 'superseded',
+ });
+ });
+
+ it('reports a project deleted elsewhere as superseded', async () => {
+ const project = seedServerProject('Deleted elsewhere');
+ const opened = await service.hydrateProjectFromServer(project.id);
+
+ api.__records.delete(project.id);
+
+ await expect(service.flushProjectToServer({ ...opened!, name: 'Edited locally' })).resolves.toMatchObject({
+ kind: 'superseded',
+ });
+ });
+ });
+
+ /**
+ * The delete is queued behind the push rather than racing it. Were it not, a slow PUT would come
+ * back 404 after the DELETE committed, and the engine's answer to a 404 is to fork — recreating,
+ * server-side, exactly what the person deleted, pointing at media the deletion already removed.
+ */
+ it('does not fork a project this browser is deleting', async () => {
+ const project = seedServerProject('Doomed');
+ const opened = await service.hydrateProjectFromServer(project.id);
+ const edited = { ...opened!, name: 'Edited just before deleting' };
+
+ let releaseUpdate: () => void = () => undefined;
+ const updateReached = new Promise<void>((resolve) => {
+ releaseUpdate = resolve;
+ });
+ const realUpdate = api.updateProject.getMockImplementation()!;
+
+ api.updateProject.mockImplementationOnce(async (...args: Parameters<typeof realUpdate>) => {
+ releaseUpdate();
+ // Long enough for the delete below to be requested while this is still on the wire.
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ return realUpdate(...args);
+ });
+
+ const flush = service.flushProjectToServer(edited);
+
+ await updateReached;
+
+ const deletion = service.deleteProjectOnServer(project.id);
+
+ await Promise.all([flush, deletion]);
+
+ expect(api.__records.has(project.id)).toBe(false);
+ // No "(recovered)" project anywhere: the deletion is the whole answer.
+ expect([...api.__records.keys()]).toEqual([]);
+
+ const result = await service.saveWorkbench(stateWithProjects([edited]));
+
+ expect(result.deletedProjectForks).toEqual([]);
+ expect(api.__records.size).toBe(0);
+ });
+
+ /**
+ * The belt to the queue's braces. Queueing removes the race for every caller that goes through
+ * `deleteProjectOnServer`, but the check at the top of a push runs before its awaits — so a
+ * deletion recorded while a `PUT` is on the wire has to be re-read when that `PUT` comes back 404,
+ * or the fork happens anyway.
+ */
+ it('re-reads the deletion set when a push it started comes back 404', async () => {
+ const project = seedServerProject('Doomed');
+ const opened = await service.hydrateProjectFromServer(project.id);
+ const realUpdate = api.updateProject.getMockImplementation()!;
+
+ api.updateProject.mockImplementationOnce((...args: Parameters<typeof realUpdate>) => {
+ // Exactly the window the check at the top of the push cannot see: the deletion lands after
+ // the request left, so this push is the one that discovers the 404.
+ api.__records.delete(project.id);
+ service.markProjectDeleted(project.id);
+
+ return realUpdate(...args);
+ });
+
+ await expect(service.flushProjectToServer({ ...opened!, name: 'Edited locally' })).resolves.toMatchObject({
+ kind: 'superseded',
+ });
+
+ // No "(recovered)" project was left behind on the server.
+ expect([...api.__records.keys()]).toEqual([]);
+
+ const result = await service.saveWorkbench(stateWithProjects([{ ...opened!, name: 'Edited locally' }]));
+
+ expect(result.deletedProjectForks).toEqual([]);
+ expect(api.__records.size).toBe(0);
+ });
+
+ it('lets a project save again when its deletion fails', async () => {
+ const project = seedServerProject('Survives');
+ const opened = await service.hydrateProjectFromServer(project.id);
+
+ api.deleteProject.mockRejectedValueOnce(new Error('offline'));
+
+ await expect(service.deleteProjectOnServer(project.id)).rejects.toThrow('offline');
+
+ // Its place in the revision chain comes back with it, so the next push is a PUT rather than a
+ // create that has to recover through a 409.
+ const result = await service.saveWorkbench(stateWithProjects([{ ...opened!, name: 'Edited after' }]));
+
+ expect(result.deletedProjectForks).toEqual([]);
+ expect(api.createProject).not.toHaveBeenCalled();
+ expect(api.__records.get(project.id)?.name).toBe('Edited after');
+ });
+
it('never re-creates a project it has already forked', async () => {
// The original stays in the aggregate until the reconciliation reaches it. A push in that
// window would POST the old id back and undo the deletion on every device — the exact outcome
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
index 605c0f7347..a3d061c2a8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
@@ -15,6 +15,8 @@ import {
withAuthoritativeProjectBoard,
} from '@workbench/workbenchState';
+import type { ProjectPushOutcome, ProjectRecoveredIdentity } from './projectFlush';
+
import {
createProject as apiCreateProject,
deleteClientStateValue,
@@ -77,6 +79,7 @@ export interface ProjectConflictResolution {
serverProject: Project;
/** The forked copy carrying the local edits that lost the race. */
recoveredProject: Project;
+ recoveredIdentity: ProjectRecoveredIdentity;
}
/** Local edits rescued from a project that was deleted on another device. */
@@ -84,6 +87,7 @@ export interface ProjectDeletionFork {
projectId: string;
/** The fork carrying the local edits, under a fresh id and its own board. */
recoveredProject: Project;
+ recoveredIdentity: ProjectRecoveredIdentity;
}
/** A board the server assigned to a project this save created. */
@@ -333,21 +337,24 @@ const getRecoveryBaseName = (name: string): string => name.replace(/(\s*\((?:r|R
export const createRecoveredDocument = (
project: Project,
document: Record<string, unknown>
-): { recoveredId: string; recoveredName: string; recoveredDocument: Record<string, unknown> } => {
+): { recoveredIdentity: ProjectRecoveredIdentity; recoveredDocument: Record<string, unknown> } => {
const recoveryOf = project.recoveryOf ?? project.id;
- const recoveredId = `${recoveryOf}-recovered-${Date.now().toString(36)}`;
- const recoveredName = `${getRecoveryBaseName(project.name)} (recovered)`;
+ const recoveredIdentity: ProjectRecoveredIdentity = {
+ id: `${recoveryOf}-recovered-${Date.now().toString(36)}`,
+ name: `${getRecoveryBaseName(project.name)} (recovered)`,
+ recoveredAt: new Date().toISOString(),
+ recoveryOf,
+ };
return {
recoveredDocument: {
...document,
- id: recoveredId,
- name: recoveredName,
- recoveredAt: new Date().toISOString(),
- recoveryOf,
+ id: recoveredIdentity.id,
+ name: recoveredIdentity.name,
+ recoveredAt: recoveredIdentity.recoveredAt,
+ recoveryOf: recoveredIdentity.recoveryOf,
},
- recoveredId,
- recoveredName,
+ recoveredIdentity,
};
};
@@ -399,7 +406,7 @@ const recoverConflictingProject = async (
return { kind: 'failed' };
}
- const { recoveredDocument, recoveredId, recoveredName } = createRecoveredDocument(project, document);
+ const { recoveredDocument, recoveredIdentity } = createRecoveredDocument(project, document);
const recoveredProject = deserializeProjectDocument(recoveredDocument);
if (!recoveredProject) {
@@ -407,17 +414,24 @@ const recoverConflictingProject = async (
}
const created = await apiCreateProject(
- { data: recoveredDocument, name: recoveredName, project_id: recoveredId },
+ { data: recoveredDocument, name: recoveredIdentity.name, project_id: recoveredIdentity.id },
syncState.owner.signal
);
assertOwner(syncState);
- syncState.syncEntries.set(recoveredId, {
+ syncState.syncEntries.set(recoveredIdentity.id, {
pushedDoc: JSON.stringify(recoveredDocument),
revision: created.revision,
});
-
- return { kind: 'forked', resolution: { projectId: project.id, recoveredProject, serverProject } };
+ // Recorded for the same reason the deletion fork records it: the fork is a project the server
+ // created, so its board id exists nowhere else. Without this the fork opens with a gallery bound
+ // to the original's board — which the conflict left in the server version's hands.
+ syncState.pendingBoardAssignments.push({ boardId: created.board_id, projectId: recoveredIdentity.id });
+
+ return {
+ kind: 'forked',
+ resolution: { projectId: project.id, recoveredIdentity, recoveredProject, serverProject },
+ };
} catch {
assertOwner(syncState);
@@ -425,6 +439,12 @@ const recoverConflictingProject = async (
}
};
+type DeletionForkOutcome =
+ | { kind: 'forked'; fork: ProjectDeletionFork }
+ /** The 404 was this browser's own deletion. There is nothing to rescue and nothing went wrong. */
+ | { kind: 'abandoned' }
+ | { kind: 'failed' };
+
/**
* Rescue the local edits of a project the server no longer has.
*
@@ -436,58 +456,81 @@ const forkDeletedProject = async (
syncState: SyncedPersistenceState,
project: Project,
document: Record<string, unknown>
-): Promise<ProjectDeletionFork | null> => {
+): Promise<DeletionForkOutcome> => {
assertOwner(syncState);
- const { recoveredDocument, recoveredId, recoveredName } = createRecoveredDocument(project, document);
+ const { recoveredDocument, recoveredIdentity } = createRecoveredDocument(project, document);
const recoveredProject = deserializeProjectDocument(recoveredDocument);
if (!recoveredProject) {
- return null;
+ return { kind: 'failed' };
}
try {
const created = await apiCreateProject(
- { data: recoveredDocument, name: recoveredName, project_id: recoveredId },
+ { data: recoveredDocument, name: recoveredIdentity.name, project_id: recoveredIdentity.id },
syncState.owner.signal
);
assertOwner(syncState);
- syncState.syncEntries.set(recoveredId, {
+
+ // Re-read after the create, not just before it. `deleteLibraryProject` marks the id before
+ // issuing its DELETE, but a PUT already on the wire is past that check — the 404 that brought us
+ // here can be this browser's own deletion arriving first. Forking on it would resurrect the
+ // project the person just deleted, as a copy pointing at media the deletion already removed.
+ if (syncState.deletedProjectIds.has(project.id)) {
+ try {
+ await apiDeleteProject(recoveredIdentity.id, syncState.owner.signal);
+ } catch {
+ // The fork is an empty private project either way; failing to remove it is clutter, not a
+ // broken state, and it must not replace the deletion's own outcome.
+ }
+
+ assertOwner(syncState);
+ syncState.syncEntries.delete(recoveredIdentity.id);
+
+ return { kind: 'abandoned' };
+ }
+
+ syncState.syncEntries.set(recoveredIdentity.id, {
pushedDoc: JSON.stringify(recoveredDocument),
revision: created.revision,
});
- syncState.pendingBoardAssignments.push({ boardId: created.board_id, projectId: recoveredId });
+ syncState.pendingBoardAssignments.push({ boardId: created.board_id, projectId: recoveredIdentity.id });
- return { projectId: project.id, recoveredProject };
+ return { fork: { projectId: project.id, recoveredIdentity, recoveredProject }, kind: 'forked' };
} catch {
assertOwner(syncState);
- return null;
+ return { kind: 'failed' };
}
};
-const pushProject = async (syncState: SyncedPersistenceState, project: Project): Promise<string> => {
+const pushProject = async (syncState: SyncedPersistenceState, project: Project): Promise<ProjectPushOutcome> => {
assertOwner(syncState);
const { document, json: documentJson } = getSerializedProjectDocument(syncState, project);
const entry = syncState.syncEntries.get(project.id);
- if (
- syncState.deletedProjectIds.has(project.id) ||
- syncState.forkedProjectIds.has(project.id) ||
- entry?.pushedDoc === documentJson
- ) {
- return documentJson;
+ // A deleted or already-forked id holds someone else's answer — the deletion, or the server
+ // version that won the race. Nothing is pushed, and nothing read back under this id would be ours.
+ if (syncState.deletedProjectIds.has(project.id) || syncState.forkedProjectIds.has(project.id)) {
+ return { documentJson, kind: 'superseded' };
+ }
+
+ if (entry?.pushedDoc === documentJson) {
+ return { documentJson, kind: 'acknowledged' };
}
if (!entry) {
if (!(await pushNewProject(syncState, project))) {
assertOwner(syncState);
syncState.hasPending = true;
+
+ return { documentJson, kind: 'unsynced' };
}
assertOwner(syncState);
- return documentJson;
+ return { documentJson, kind: 'acknowledged' };
}
try {
@@ -529,12 +572,20 @@ const pushProject = async (syncState: SyncedPersistenceState, project: Project):
assertOwner(syncState);
// A genuinely concurrent writer; the next save re-evaluates.
syncState.hasPending = true;
+
+ return { documentJson, kind: 'unsynced' };
}
} else if (outcome.kind === 'forked') {
syncState.pendingConflicts.push(outcome.resolution);
+
+ // This id now holds the server's version, not ours.
+ return { documentJson, kind: 'superseded' };
} else if (outcome.kind === 'failed') {
syncState.hasPending = true;
+
+ return { documentJson, kind: 'unsynced' };
}
+ // 'adopted': the server already held these exact bytes, so the push had nothing to do.
} else if (isProjectNotFoundError(error)) {
// Deleted on another device while we held local edits. Re-creating under the same id would
// undo that deletion — the project would reappear on every device, and on this one it would
@@ -542,24 +593,39 @@ const pushProject = async (syncState: SyncedPersistenceState, project: Project):
// the local work survives as a recovered project with its own id and its own board.
syncState.syncEntries.delete(project.id);
- const fork = await forkDeletedProject(syncState, project, document);
+ // Unless the deletion was ours. `markDeleted` runs before the DELETE, but a PUT already on the
+ // wire is past the check at the top of this function, so a fast DELETE can turn our own push
+ // into a 404 — and forking on that resurrects, server-side, exactly what the person deleted.
+ if (syncState.deletedProjectIds.has(project.id)) {
+ return { documentJson, kind: 'superseded' };
+ }
+
+ const outcome = await forkDeletedProject(syncState, project, document);
assertOwner(syncState);
- if (fork === null) {
+ if (outcome.kind === 'failed') {
syncState.hasPending = true;
- } else {
+
+ return { documentJson, kind: 'unsynced' };
+ }
+
+ if (outcome.kind === 'forked') {
// Recorded before the aggregate hears about it, so nothing re-creates the original id in
// the meantime — see `forkedProjectIds`.
syncState.forkedProjectIds.add(project.id);
- syncState.pendingDeletedForks.push(fork);
+ syncState.pendingDeletedForks.push(outcome.fork);
}
+
+ return { documentJson, kind: 'superseded' };
} else {
syncState.hasPending = true;
+
+ return { documentJson, kind: 'unsynced' };
}
}
assertOwner(syncState);
- return documentJson;
+ return { documentJson, kind: 'acknowledged' };
};
const pushSessionState = async (syncState: SyncedPersistenceState, state: WorkbenchState): Promise<void> => {
@@ -742,7 +808,8 @@ const loadFromBackend = async (
export interface SyncedWorkbenchPersistence {
adoptProjectRecord(record: ProjectRecordDTO): Project | null;
clearWorkbench(): Promise<void>;
- flushProjectToServer(project: Project): Promise<void>;
+ deleteProjectOnServer(projectId: string): Promise<void>;
+ flushProjectToServer(project: Project): Promise<ProjectPushOutcome>;
hasPendingChanges(): boolean;
hydrateProjectFromServer(projectId: string): Promise<Project | null>;
loadWorkbench(options?: WorkbenchLoadOptions): Promise<HydratedWorkbenchSnapshot | null>;
@@ -818,6 +885,41 @@ export const createSyncedWorkbenchPersistence = (
return result;
};
+ /**
+ * Sync entries dropped by {@link markDeleted}, kept so a deletion that fails can be undone whole.
+ *
+ * Without this, unmarking restores the project's right to save but not its place in the revision
+ * chain: the next push finds no entry, takes the create path, and has to recover through a 409.
+ */
+ const entriesHeldForDeletion = new Map<string, SyncEntry>();
+
+ const markDeleted = (projectId: string): void => {
+ assertOwner(syncState);
+ syncState.deletedProjectIds.add(projectId);
+
+ const entry = syncState.syncEntries.get(projectId);
+
+ if (entry) {
+ entriesHeldForDeletion.set(projectId, entry);
+ }
+
+ syncState.syncEntries.delete(projectId);
+ persistSyncMap(syncState);
+ };
+
+ const unmarkDeleted = (projectId: string): void => {
+ assertOwner(syncState);
+ syncState.deletedProjectIds.delete(projectId);
+
+ const entry = entriesHeldForDeletion.get(projectId);
+
+ if (entry) {
+ syncState.syncEntries.set(projectId, entry);
+ entriesHeldForDeletion.delete(projectId);
+ persistSyncMap(syncState);
+ }
+ };
+
const adoptProjectRecord = (record: ProjectRecordDTO): Project | null => {
assertOwner(syncState);
const project = deserializeProjectRecord(record);
@@ -845,18 +947,52 @@ export const createSyncedWorkbenchPersistence = (
assertOwner(syncState);
syncState.syncEntries.clear();
syncState.deletedProjectIds.clear();
+ entriesHeldForDeletion.clear();
syncState.lastPushedAccount = null;
syncState.hasPending = false;
});
},
- flushProjectToServer(project): Promise<void> {
+ /**
+ * Remove the project from the server without letting a save race the removal.
+ *
+ * Queued rather than issued directly, which is the whole point: `markProjectDeleted` stops a
+ * push that has not started, but a `PUT` already in flight is past every check the engine has.
+ * That push comes back 404 once the DELETE commits, and the engine's answer to a 404 is to fork
+ * the local document into a *new* server project — resurrecting, as a copy, what the person
+ * just deleted, pointing at media the deletion already removed. Waiting for the queue removes
+ * the race rather than detecting it.
+ */
+ deleteProjectOnServer(projectId): Promise<void> {
+ return enqueueMutation(async () => {
+ markDeleted(projectId);
+
+ try {
+ await apiDeleteProject(projectId, syncState.owner.signal);
+ } catch (error) {
+ assertOwner(syncState);
+ unmarkDeleted(projectId);
+ throw error;
+ }
+
+ assertOwner(syncState);
+ });
+ },
+ flushProjectToServer(project): Promise<ProjectPushOutcome> {
return enqueueMutation(async () => {
// A flush is a targeted push, not a save. Any conflict or fork it produces waits on
// `syncState` for the next save to drain — the flush has no caller to hand them to, and
// they are already true of the server by the time it returns.
- await pushProject(syncState, project);
+ //
+ // What it *does* hand back is whether the push landed. Every caller here has a recoverable
+ // failure on its hands, so this still does not reject; but "recoverable" and "done" are
+ // different answers, and a caller about to read the project back from the server needs the
+ // second one. `assertProjectFlushed` in `./projectFlush` is where that is spent.
+ const outcome = await pushProject(syncState, project);
+
assertOwner(syncState);
persistSyncMap(syncState);
+
+ return outcome;
});
},
hasPendingChanges(): boolean {
@@ -965,10 +1101,7 @@ export const createSyncedWorkbenchPersistence = (
* and removal happens only through the library's explicit delete.
*/
markProjectDeleted(projectId): void {
- assertOwner(syncState);
- syncState.deletedProjectIds.add(projectId);
- syncState.syncEntries.delete(projectId);
- persistSyncMap(syncState);
+ markDeleted(projectId);
},
persistEmptySession(state): Promise<void> {
return enqueueMutation(async () => {
@@ -1011,7 +1144,7 @@ export const createSyncedWorkbenchPersistence = (
for (const project of state.projects) {
assertOwner(syncState);
const lastAckedDoc = syncState.syncEntries.get(project.id)?.pushedDoc ?? null;
- const documentJson = await pushProject(syncState, project);
+ const { documentJson } = await pushProject(syncState, project);
assertOwner(syncState);
const entry = syncState.syncEntries.get(project.id);
@@ -1044,8 +1177,7 @@ export const createSyncedWorkbenchPersistence = (
});
},
unmarkProjectDeleted(projectId): void {
- assertOwner(syncState);
- syncState.deletedProjectIds.delete(projectId);
+ unmarkDeleted(projectId);
},
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
index cebd4ecd9b..a200838584 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
@@ -121,10 +121,13 @@ export const useProjectActions = (): {
try {
// Deletion goes through the library for every surface. For a project the workbench holds it
- // routes through this editor's own sync handle, which is what stops an in-flight autosave
- // recreating the project — and with it a board — between the DELETE and the tab closing.
+ // routes through this editor's own sync handle, which issues the DELETE inside the sync
+ // engine's mutation queue — so a push already on the wire finishes first and cannot come back
+ // 404 and fork the project into a copy of the thing being deleted.
await deleteLibraryProject(project.id);
} catch (error) {
+ // The handle unmarks its own failures; this covers the surfaces that reach a project the
+ // editor does not hold, and is idempotent for the ones it does.
persistenceService.unmarkProjectDeleted(project.id);
notify.error(t('projects.deleteFailed'), error instanceof Error ? error.message : undefined);
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index c618010de0..536cc10f54 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -30,6 +30,7 @@ import type {
WorkbenchNotificationKind,
WorkbenchState,
} from '@workbench/projectContracts';
+import type { ProjectRecoveredIdentity } from '@workbench/projects/projectFlush';
import type { ProjectSettings } from '@workbench/settings/contracts';
import type {
WidgetFailure,
@@ -321,8 +322,19 @@ type WorkbenchReducerAction =
| { type: 'undoProjectChange' }
| { type: 'redoProjectChange' }
| { type: 'hydrateWorkbench'; state: WorkbenchState }
- | { type: 'reconcileProjectConflict'; projectId: string; serverProject: Project; recoveredProject: Project }
- | { type: 'reconcileDeletedProject'; projectId: string; recoveredProject: Project }
+ | {
+ type: 'reconcileProjectConflict';
+ projectId: string;
+ serverProject: Project;
+ recoveredProject: Project;
+ recoveredIdentity: ProjectRecoveredIdentity;
+ }
+ | {
+ type: 'reconcileDeletedProject';
+ projectId: string;
+ recoveredProject: Project;
+ recoveredIdentity: ProjectRecoveredIdentity;
+ }
| { type: 'autosaveStarted' }
| { type: 'autosaveSucceeded'; savedAt: string }
| { type: 'autosaveFailed'; error: string }
@@ -1335,6 +1347,40 @@ export const withAuthoritativeProjectBoard = (project: Project, boardId: string)
values.projectBoardId === boardId ? values : { ...values, projectBoardId: boardId }
);
+/**
+ * The project a recovery fork should become, preferring live content over the snapshot.
+ *
+ * A fork is created by the sync engine from the document it was *pushing* — serialized when the
+ * save began. By the time the answer comes back, anything typed since is newer than that snapshot
+ * and is what the person is looking at. Adopting the snapshot would therefore delete precisely the
+ * edits the fork exists to rescue, and do it in the case the mechanism is most likely to fire: a
+ * save is stale exactly when a keystroke landed while it was in flight.
+ *
+ * So the live project is re-labelled instead. The server-side fork already holds the older document
+ * under this identity, and the sync entry recorded for it says as much, so the next push sees a
+ * difference and sends the current content up its revision chain. Nothing is lost and nothing has
+ * to be merged.
+ *
+ * The snapshot is still the answer when there is no live project — a tab closed while the save was
+ * in flight — because then it is the only copy of that work left anywhere local.
+ */
+const recoverProjectUnderNewIdentity = (
+ localProject: Project | undefined,
+ snapshotProject: Project,
+ identity: ProjectRecoveredIdentity
+): Project =>
+ normalizeWorkbenchProject(
+ localProject
+ ? {
+ ...localProject,
+ id: identity.id,
+ name: identity.name,
+ recoveredAt: identity.recoveredAt,
+ recoveryOf: identity.recoveryOf,
+ }
+ : snapshotProject
+ );
+
const clampPanelSize = (region: WidgetRegion, sizePx: number): number => {
if (region === 'bottom') {
return Math.min(MAX_STATUS_PANEL_SIZE_PX, Math.max(MIN_STATUS_PANEL_SIZE_PX, sizePx));
@@ -3627,9 +3673,13 @@ export const __workbenchReducerInternal = (
// continue in the recovered fork — which stays the active project when
// the user was looking at it.
const normalizedServerProject = normalizeWorkbenchProject(action.serverProject);
- const recoveredProject = normalizeWorkbenchProject(action.recoveredProject);
const localProject = state.projects.find((project) => project.id === action.projectId);
const hasOriginal = localProject !== undefined;
+ const recoveredProject = recoverProjectUnderNewIdentity(
+ localProject,
+ action.recoveredProject,
+ action.recoveredIdentity
+ );
// The server document replaces the local one under the SAME project id, so a
// live engine mirroring that id may hold pixel history for the outgoing
// document. Bump the revision past both sides so the mirror treats the swap
@@ -3669,8 +3719,13 @@ export const __workbenchReducerInternal = (
// revision conflict there is no server version to adopt — the deletion is the server's
// answer. Re-creating the id would undo it everywhere, so the local edits continue under a
// fresh identity and the original simply goes.
- const recoveredProject = normalizeWorkbenchProject(action.recoveredProject);
- const hasOriginal = state.projects.some((project) => project.id === action.projectId);
+ const localProject = state.projects.find((project) => project.id === action.projectId);
+ const hasOriginal = localProject !== undefined;
+ const recoveredProject = recoverProjectUnderNewIdentity(
+ localProject,
+ action.recoveredProject,
+ action.recoveredIdentity
+ );
const projects = hasOriginal
? state.projects.map((project) => (project.id === action.projectId ? recoveredProject : project))
: [...state.projects, recoveredProject];
@@ -3683,7 +3738,7 @@ export const __workbenchReducerInternal = (
},
createNotification({
kind: 'info',
- message: `That project was deleted elsewhere. Your unsaved edits continue in "${recoveredProject.name}".`,
+ message: `That project was deleted elsewhere. Your edits — including anything typed since — continue in "${recoveredProject.name}".`,
title: 'Project recovered',
})
);