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.

feat(webv2): route open-project mutations through the sync engine

Josh Corbette35652b52835
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 8925702818..1393489954 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -405,8 +405,8 @@
"createNewProject": "Create new project",
"deleteFailed": "Delete failed",
"deleteProject": "Delete project",
+ "deleteProjectBoardNote": "Its board goes with it; the images and videos it held return to Uncategorized.",
"deleteProjectCardBody": "Delete \"{{name}}\"? The project is removed from the server permanently.",
- "deleteProjectOpenWarning": "It is currently open in the editor — unsaved changes there can recreate it.",
"deleteProjectQuestion": "Delete project?",
"deleteProjectTabBody": "Delete \"{{name}}\"? The project and its saved copy on the server are removed permanently. To keep it in your library, close the tab instead.",
"deleteProjectWithEllipsis": "Delete project…",
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
index 89df824436..64644e39c1 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
@@ -11,6 +11,7 @@ import { createContext, use, useEffect, useSyncExternalStore, useState, type Rea
import { WorkbenchSplashScreen } from './components/WorkbenchSplashScreen';
import { createExtensionRegistry, type ExtensionRegistry } from './extensions/extensionRegistry';
import { createWorkbenchPersistenceRuntime } from './persistenceRuntime';
+import { createOpenProjectBroker } from './projects/openProjectBroker';
import {
createSyncedWorkbenchPersistence,
type SyncedWorkbenchPersistence,
@@ -76,8 +77,35 @@ export const WorkbenchProvider = ({
persistence,
signal: owner.signal,
});
+ // Published for the whole life of the mount, so a library surface rendered beside the editor
+ // mutates an open project through the sync engine rather than beside it.
+ const openProjectBroker = createOpenProjectBroker({
+ closeProject: (projectId) => {
+ store.commands.projects.close(projectId);
+ },
+ flushProject: async (projectId) => {
+ const project = store.getSnapshot().projects.find((candidate) => candidate.id === projectId);
+
+ if (project) {
+ await persistence.flushProjectToServer(project);
+ }
+ },
+ getOpenProjectIds: () => store.getSnapshot().projects.map((project) => project.id),
+ markProjectDeleted: (projectId) => {
+ persistence.markProjectDeleted(projectId);
+ },
+ renameProject: (projectId, name) => {
+ store.commands.projects.rename(projectId, name);
+ },
+ subscribe: store.subscribe,
+ });
+
persistenceRuntime.start();
- return () => persistenceRuntime.dispose();
+
+ return () => {
+ openProjectBroker.dispose();
+ persistenceRuntime.dispose();
+ };
});
return (
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
index f0b55a5c9e..b8ebd89c5e 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
@@ -5,7 +5,6 @@ import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
import { MenuContent } from '@platform/ui/Menu';
import { RenameDialog } from '@platform/ui/RenameDialog';
import { Link } from '@tanstack/react-router';
-import { useOpenProjectsSelector } from '@workbench/projects/openProjects';
import { ArrowRightIcon, CopyIcon, FileDownIcon, PencilIcon, PinIcon, PinOffIcon, Trash2Icon } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -49,14 +48,6 @@ export const ProjectActionsMenu = ({
const { t } = useTranslation();
const [isRenameOpen, setIsRenameOpen] = useState(false);
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
- /**
- * Deleting a project another tab still has open with unsaved edits does not
- * stick: that tab's next autosave sees a 404 and deliberately recreates the
- * project rather than discard the work. That policy is right, but silently
- * losing a delete is not — so say so before confirming.
- */
- const isProjectOpen = useOpenProjectsSelector((snapshot) => snapshot.ids?.includes(projectId) ?? false);
-
const projectSearch = useMemo(() => ({ project: projectId }), [projectId]);
const positioning = useMemo(
() =>
@@ -103,11 +94,10 @@ export const ProjectActionsMenu = ({
/>
<ConfirmDialog
- body={
- isProjectOpen
- ? `${t('projects.deleteProjectCardBody', { name: projectName })} ${t('projects.deleteProjectOpenWarning')}`
- : t('projects.deleteProjectCardBody', { name: projectName })
- }
+ // No "it is open, so it may come back" caveat any more: an open project is deleted through
+ // the editor's own sync handle, so the deletion is final either way. What is worth saying
+ // instead is what else goes — the project's board — and what does not.
+ body={`${t('projects.deleteProjectCardBody', { name: projectName })} ${t('projects.deleteProjectBoardNote')}`}
confirmLabel={t('projects.deleteProject')}
isOpen={isDeleteOpen}
title={t('projects.deleteProjectQuestion')}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
index bc7d500aab..de9223581c 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 * as syncStoreModule from './syncStore';
/**
* The project library store: summaries normalized at the boundary, sorted by
@@ -13,14 +14,17 @@ import type * as libraryModule from './library';
const api = vi.hoisted(() => ({
createProject: vi.fn(),
deleteProject: vi.fn(),
+ getClientStateValue: vi.fn(() => Promise.resolve<string | null>(null)),
getProject: vi.fn(),
listProjects: vi.fn(),
+ setClientStateValue: vi.fn(() => Promise.resolve()),
updateProject: vi.fn(),
}));
vi.mock('./api', () => api);
let library: typeof libraryModule;
+let syncStore: typeof syncStoreModule;
let account: typeof accountLifecycleModule;
const summaryDto = (id: string, name: string, updatedAt: string) => ({
@@ -38,11 +42,42 @@ beforeEach(async () => {
api.getProject.mockReset();
api.listProjects.mockReset();
api.updateProject.mockReset();
+ api.getClientStateValue.mockReset();
+ api.getClientStateValue.mockResolvedValue(null);
+ api.setClientStateValue.mockReset();
+ api.setClientStateValue.mockResolvedValue(undefined);
library = await import('./library');
+ syncStore = await import('./syncStore');
account = await import('@platform/state/accountLifecycle');
});
+/** A stand-in for the editor holding a project, with every call recorded in order. */
+const openProject = (projectId: string, calls: string[] = []) => {
+ const handle = {
+ close: vi.fn(() => {
+ calls.push('close');
+ }),
+ flush: vi.fn(() => {
+ calls.push('flush');
+
+ return Promise.resolve();
+ }),
+ markDeleted: vi.fn(() => {
+ calls.push('markDeleted');
+ }),
+ rename: vi.fn((name: string) => {
+ calls.push(`rename:${name}`);
+
+ return Promise.resolve();
+ }),
+ };
+
+ syncStore.registerOpenProject(projectId, handle);
+
+ return { calls, handle };
+};
+
describe('refreshProjectLibrary', () => {
it('normalizes SQLite timestamps to ISO and sorts newest first', async () => {
api.listProjects.mockResolvedValue([
@@ -150,6 +185,83 @@ describe('library mutations', () => {
expect(library.getProjectLibrary().summaries[0]?.name).toBe('New name');
});
+ /**
+ * The invariant: a project the workbench holds is mutated through the sync engine, everything
+ * else over HTTP. A library PUT beside an open project's revision chain used to fork it into a
+ * conflict copy, and would now rename its board from outside the transaction that owns both.
+ */
+ it('renames an open project through the editor rather than over HTTP', async () => {
+ api.listProjects.mockResolvedValue([summaryDto('open', 'Old name', '2026-06-10 10:00:00.000')]);
+ await library.refreshProjectLibrary();
+
+ const { handle } = openProject('open');
+
+ await library.renameLibraryProject('open', 'New name');
+
+ expect(handle.rename).toHaveBeenCalledWith('New name');
+ expect(api.getProject).not.toHaveBeenCalled();
+ expect(api.updateProject).not.toHaveBeenCalled();
+ 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);
+
+ const { calls } = openProject('open');
+
+ await library.deleteLibraryProject('open');
+
+ expect(calls).toEqual(['markDeleted', 'close']);
+ expect(api.deleteProject).toHaveBeenCalledWith('open', expect.any(AbortSignal));
+ });
+
+ it('takes a deleted project out of the saved session', async () => {
+ api.deleteProject.mockResolvedValue(undefined);
+ api.getClientStateValue.mockResolvedValue(
+ JSON.stringify({
+ account: { userId: 'user-a' },
+ activeProjectId: 'doomed',
+ openProjectIds: ['doomed', 'kept'],
+ })
+ );
+
+ await library.deleteLibraryProject('doomed');
+
+ const [, blob] = api.setClientStateValue.mock.calls.at(-1) as unknown as [string, string];
+
+ // The next boot would otherwise try to hydrate a project the server no longer has.
+ expect(JSON.parse(blob)).toMatchObject({ activeProjectId: 'kept', openProjectIds: ['kept'] });
+ });
+
+ it('leaves the session alone when the deleted project was not open', async () => {
+ api.deleteProject.mockResolvedValue(undefined);
+ api.getClientStateValue.mockResolvedValue(
+ JSON.stringify({ account: {}, activeProjectId: 'kept', openProjectIds: ['kept'] })
+ );
+
+ await library.deleteLibraryProject('closed');
+
+ expect(api.setClientStateValue).not.toHaveBeenCalled();
+ });
+
+ /** A copy of what the server last acknowledged would silently drop what is on screen. */
+ it('flushes an open project before reading it for duplication', async () => {
+ const { calls } = openProject('source');
+
+ api.getProject.mockImplementation(() => {
+ calls.push('get');
+
+ return Promise.resolve({
+ ...summaryDto('source', 'Source', '2026-06-10 10:00:00.000'),
+ data: { id: 'source', layout: {}, name: 'Source' },
+ });
+ });
+
+ await library.readProjectForDuplication('source', account.accountLifecycle.capture());
+
+ expect(calls).toEqual(['flush', 'get']);
+ });
+
it('duplicateLibraryProject copies under a fresh id', 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 6969a83e81..eae14dd397 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts
@@ -15,6 +15,7 @@ import {
getProject as apiGetProject,
listProjects,
updateProject as apiUpdateProject,
+ type ProjectRecordDTO,
type ProjectSummaryDTO,
} from './api';
import {
@@ -25,6 +26,9 @@ import {
subscribeProjectCovers,
} from './covers';
import { createProjectId } from './ids';
+import { refreshOpenProjects } from './openProjects';
+import { pruneSessionProject } from './session';
+import { getOpenProject } from './syncStore';
/**
* The project library: every project saved on the server for the current
@@ -188,23 +192,52 @@ export const upsertProjectSummary = (
});
};
-/** Permanently remove a project from the server. The only deletion path. */
+/**
+ * Every mutation below branches on one question: does the workbench currently hold this project?
+ *
+ * If it does, the mutation goes through {@link getOpenProject} — the sync engine — and if it does
+ * not, it goes over HTTP. A library write landing beside an open project's revision chain used to
+ * fork it into a conflict copy; now that a project's board renames with it, such a write would
+ * rename the board too, from outside the transaction that is supposed to own both.
+ */
+
+/** Permanently remove a project from the server, its board with it. The only deletion path. */
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();
await apiDeleteProject(projectId, owner.signal);
assertAccountScopeCurrent(owner);
+ openProject?.close();
forgetProjectCover(projectId, owner);
store.patchSnapshot({ summaries: store.getSnapshot().summaries.filter((summary) => summary.id !== projectId) });
+
+ // The saved session outlives the editor, so a deleted project has to leave it here or the next
+ // boot tries to open something the server no longer has.
+ await pruneSessionProject(projectId, owner.signal);
+ await refreshOpenProjects();
};
/**
- * Rename a project that is not open in the editor. Open projects rename
- * through the workbench reducer instead, so their document and the autosave
- * revision chain stay consistent.
+ * Rename a project. An open one renames through the reducer so its document, its revision chain and
+ * its board stay in step; a closed one is a read-modify-write against the server.
*/
export const renameLibraryProject = async (projectId: string, name: string): Promise<void> => {
const owner = captureAccountScope();
+ const openProject = getOpenProject(projectId);
+
+ if (openProject) {
+ await openProject.rename(name);
+ assertAccountScopeCurrent(owner);
+ // The flush has already told the server; this only keeps the grid from waiting for a refetch.
+ upsertProjectSummary({ id: projectId, name, revision: null }, owner);
+
+ return;
+ }
+
const record = await apiGetProject(projectId, owner.signal);
assertAccountScopeCurrent(owner);
@@ -222,10 +255,33 @@ export const renameLibraryProject = async (projectId: string, name: string): Pro
upsertProjectSummary({ id: updated.project_id, name: updated.name, revision: updated.revision }, owner);
};
+/**
+ * The acknowledged record for a project about to be copied.
+ *
+ * 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.
+ */
+export const readProjectForDuplication = async (projectId: string, owner: AccountScope): Promise<ProjectRecordDTO> => {
+ await getOpenProject(projectId)?.flush();
+ assertAccountScopeCurrent(owner);
+
+ return apiGetProject(projectId, owner.signal);
+};
+
+/** Adopt a project this account just created elsewhere (an import, a duplication). */
+export const adoptCreatedProject = (record: ProjectRecordDTO, owner: AccountScope): ProjectSummary => {
+ const summary = toSummary(record);
+
+ upsertProjectSummary({ id: summary.id, name: summary.name, revision: summary.revision }, owner);
+
+ return summary;
+};
+
/** Copy a project under a fresh id; returns the new summary. */
export const duplicateLibraryProject = async (projectId: string): Promise<ProjectSummary> => {
const owner = captureAccountScope();
- const record = await apiGetProject(projectId, owner.signal);
+ const record = await readProjectForDuplication(projectId, owner);
assertAccountScopeCurrent(owner);
const newId = createProjectId();
@@ -238,10 +294,8 @@ export const duplicateLibraryProject = async (projectId: string): Promise<Projec
},
owner.signal
);
- assertAccountScopeCurrent(owner);
- const summary = toSummary(created);
- upsertProjectSummary({ id: summary.id, name: summary.name, revision: summary.revision }, owner);
+ assertAccountScopeCurrent(owner);
- return summary;
+ return adoptCreatedProject(created, owner);
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts
new file mode 100644
index 0000000000..4171aecad0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts
@@ -0,0 +1,121 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createOpenProjectBroker } from './openProjectBroker';
+import { getOpenProject } from './syncStore';
+
+/**
+ * The registry has to say exactly which projects the editor holds: it is what decides whether a
+ * library mutation goes through the sync engine or over HTTP, and a stale entry would put a write
+ * on the wrong side of that.
+ */
+
+const createHarness = () => {
+ const listeners = new Set<() => void>();
+ const deps = {
+ closeProject: vi.fn(),
+ flushProject: vi.fn(() => Promise.resolve()),
+ getOpenProjectIds: vi.fn(() => openIds),
+ markProjectDeleted: vi.fn(),
+ renameProject: vi.fn(),
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+
+ return () => listeners.delete(listener);
+ },
+ };
+ let openIds: string[] = [];
+
+ return {
+ deps,
+ setOpenIds: (ids: string[]) => {
+ openIds = ids;
+
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ };
+};
+
+describe('createOpenProjectBroker', () => {
+ beforeEach(async () => {
+ const account = await import('@platform/state/accountLifecycle');
+
+ account.accountLifecycle.activate('broker-user');
+ });
+
+ it('publishes a handle for every project the editor already holds', () => {
+ const harness = createHarness();
+
+ harness.setOpenIds(['a', 'b']);
+ createOpenProjectBroker(harness.deps);
+
+ expect(getOpenProject('a')).not.toBeNull();
+ expect(getOpenProject('b')).not.toBeNull();
+ expect(getOpenProject('c')).toBeNull();
+ });
+
+ it('follows the open set as tabs come and go', () => {
+ const harness = createHarness();
+ const broker = createOpenProjectBroker(harness.deps);
+
+ harness.setOpenIds(['a']);
+ expect(getOpenProject('a')).not.toBeNull();
+
+ harness.setOpenIds(['b']);
+ expect(getOpenProject('a')).toBeNull();
+ expect(getOpenProject('b')).not.toBeNull();
+
+ broker.dispose();
+ });
+
+ /** The handle is the mounted editor's. When the editor goes, every mutation must fall back to HTTP. */
+ it('withdraws every handle when the editor unmounts', () => {
+ const harness = createHarness();
+ const broker = createOpenProjectBroker(harness.deps);
+
+ harness.setOpenIds(['a', 'b']);
+ broker.dispose();
+
+ expect(getOpenProject('a')).toBeNull();
+ expect(getOpenProject('b')).toBeNull();
+
+ // And it stops listening: a later change must not resurrect them.
+ harness.setOpenIds(['a']);
+ expect(getOpenProject('a')).toBeNull();
+ });
+
+ it('renames through the reducer and then flushes, in that order', async () => {
+ const harness = createHarness();
+ const order: string[] = [];
+
+ harness.deps.renameProject.mockImplementation(() => order.push('rename'));
+ harness.deps.flushProject.mockImplementation(() => {
+ order.push('flush');
+
+ return Promise.resolve();
+ });
+ createOpenProjectBroker(harness.deps);
+ harness.setOpenIds(['a']);
+
+ await getOpenProject('a')!.rename('New name');
+
+ expect(harness.deps.renameProject).toHaveBeenCalledWith('a', 'New name');
+ expect(order).toEqual(['rename', 'flush']);
+ });
+
+ it('routes deletion and closing at the project it was published for', () => {
+ const harness = createHarness();
+
+ createOpenProjectBroker(harness.deps);
+ harness.setOpenIds(['a']);
+
+ const handle = getOpenProject('a')!;
+
+ handle.markDeleted();
+ handle.close();
+
+ expect(harness.deps.markProjectDeleted).toHaveBeenCalledWith('a');
+ expect(harness.deps.closeProject).toHaveBeenCalledWith('a');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts
new file mode 100644
index 0000000000..7ebe4e4228
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts
@@ -0,0 +1,81 @@
+import { type OpenProjectHandle, registerOpenProject, unregisterOpenProject } from './syncStore';
+
+/**
+ * Publishes one {@link OpenProjectHandle} per open tab, for the whole life of the mounted editor.
+ *
+ * The registry has to say exactly which projects the workbench holds, because that is what decides
+ * whether the library mutates a project through the sync engine or over HTTP — and a registry that
+ * disagreed with the tabs would put a write on the wrong side of the invariant. So it is derived
+ * from workbench state on every change rather than maintained by open and close call sites, which
+ * is a rule that cannot drift as new ways to open a project are added.
+ *
+ * The dependencies are plain functions rather than the store and the persistence service. This
+ * module belongs to the project layer, which the workbench shell wires up; taking the aggregates
+ * themselves would invert that.
+ */
+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>;
+ getOpenProjectIds: () => string[];
+ /** Stop the autosave recreating a project that is being deleted. */
+ markProjectDeleted: (projectId: string) => void;
+ renameProject: (projectId: string, name: string) => void;
+ subscribe: (listener: () => void) => () => void;
+}
+
+export interface OpenProjectBroker {
+ dispose: () => void;
+}
+
+export const createOpenProjectBroker = (deps: OpenProjectBrokerDeps): OpenProjectBroker => {
+ const published = new Set<string>();
+
+ const buildHandle = (projectId: string): OpenProjectHandle => ({
+ close: () => deps.closeProject(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.
+ rename: async (name: string) => {
+ deps.renameProject(projectId, name);
+ await deps.flushProject(projectId);
+ },
+ });
+
+ const sync = (): void => {
+ const openIds = new Set(deps.getOpenProjectIds());
+
+ for (const projectId of published) {
+ if (!openIds.has(projectId)) {
+ unregisterOpenProject(projectId);
+ published.delete(projectId);
+ }
+ }
+
+ for (const projectId of openIds) {
+ if (!published.has(projectId)) {
+ registerOpenProject(projectId, buildHandle(projectId));
+ published.add(projectId);
+ }
+ }
+ };
+
+ sync();
+
+ const unsubscribe = deps.subscribe(sync);
+
+ return {
+ dispose: () => {
+ unsubscribe();
+
+ for (const projectId of published) {
+ unregisterOpenProject(projectId);
+ }
+
+ published.clear();
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/session.ts b/invokeai/frontend/webv2/src/workbench/projects/session.ts
index 15bcda6c63..8dd860600e 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/session.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/session.ts
@@ -2,7 +2,7 @@ import type { LaunchpadIntentId } from '@workbench/launchpad/intents';
import type { AccountState, WorkbenchState } from '@workbench/projectContracts';
import type { WorkbenchPreferences } from '@workbench/settings/contracts';
-import { getClientStateValue } from './api';
+import { getClientStateValue, setClientStateValue } from './api';
/**
* The per-user session blob in the client-state KV: the editor session — which
@@ -80,6 +80,41 @@ export const fetchSessionBlob = async (signal?: AbortSignal): Promise<WorkbenchS
}
};
+/**
+ * Take a deleted project out of the saved session.
+ *
+ * A project is deleted from surfaces that may not have the editor mounted, and the session blob is
+ * what the `/app` guard and the Launchpad's "open" grouping read. Leaving the id there means the
+ * next boot tries to hydrate a project the server no longer has, and the Launchpad shows it as
+ * open until something else rewrites the blob.
+ *
+ * Best-effort and silent: the deletion has already happened, and failing to tidy the session after
+ * it is not a reason to tell someone their project was not deleted.
+ */
+export const pruneSessionProject = async (projectId: string, signal?: AbortSignal): Promise<void> => {
+ try {
+ const blob = await fetchSessionBlob(signal);
+
+ if (!blob?.openProjectIds?.includes(projectId)) {
+ return;
+ }
+
+ const openProjectIds = blob.openProjectIds.filter((id) => id !== projectId);
+
+ await setClientStateValue(
+ SESSION_STATE_KEY,
+ JSON.stringify({
+ account: blob.account,
+ activeProjectId: blob.activeProjectId === projectId ? (openProjectIds[0] ?? '') : blob.activeProjectId,
+ openProjectIds,
+ } satisfies WorkbenchSessionBlob),
+ signal
+ );
+ } catch {
+ signal?.throwIfAborted();
+ }
+};
+
/**
* Cheap pre-mount peek for the /app route guard: would any tabs open?
* `null` means "could not tell" (no blob yet, a pre-split blob, or the
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
index 1d119993a3..18102b4dcd 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
@@ -2,9 +2,24 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
/**
- * Read-only window into the project sync layer for shell surfaces (the
- * Project panel's debug section). Written exclusively by `syncedPersistence`
- * after each load/save pass; everything here is informational.
+ * The bridge between the project sync layer and everything outside the editor.
+ *
+ * Two things live here. {@link ProjectSyncSnapshot} is a read-only window for shell surfaces (the
+ * Project panel's debug section), written by `syncedPersistence` after each load/save pass.
+ * {@link OpenProjectHandle} is the other direction: a way for non-workbench code to mutate a project
+ * the workbench is currently holding, *through* the sync engine rather than behind its back.
+ *
+ * ### One invariant, replacing three races
+ *
+ * A project the workbench holds is mutated only through the sync engine; every other project is
+ * mutated over HTTP. The library used to GET-and-PUT unconditionally, which meant renaming an open
+ * project landed a write beside its revision chain — the next autosave then saw a revision it did
+ * not expect and forked the project into a conflict copy. Duplicating one copied whatever the
+ * server last acknowledged, which is not what the person could see on screen. And deleting one
+ * raced the autosave that was about to recreate it.
+ *
+ * Now that a project's board commits with its name, a stray write is worse still: it renames the
+ * board too. So the branch is explicit, and there is exactly one of it per operation.
*/
export interface ProjectSyncInfo {
@@ -34,6 +49,44 @@ registerAccountOwnedResource({
name: 'project-sync',
});
+/**
+ * What a mounted editor can do to a project it holds, for callers that are not the editor.
+ *
+ * Every method routes through the workbench reducer or the sync engine, so the project's document,
+ * its revision chain and its board stay in step. The handle exists only while the project is open;
+ * `getOpenProject` returning `null` is the signal to go over HTTP instead.
+ */
+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>;
+ /** Stop the autosave from recreating this project while it is being deleted. */
+ markDeleted: () => void;
+ /** Rename through the reducer, then flush — so the project and its board rename together. */
+ rename: (name: string) => Promise<void>;
+}
+
+const openProjects = new Map<string, OpenProjectHandle>();
+
+registerAccountOwnedResource({
+ clear: () => {
+ openProjects.clear();
+ },
+ name: 'open-project-handles',
+});
+
+export const registerOpenProject = (projectId: string, handle: OpenProjectHandle): void => {
+ openProjects.set(projectId, handle);
+};
+
+export const unregisterOpenProject = (projectId: string): void => {
+ openProjects.delete(projectId);
+};
+
+/** The mounted editor's handle on this project, or `null` when nothing holds it. */
+export const getOpenProject = (projectId: string): OpenProjectHandle | null => openProjects.get(projectId) ?? null;
+
export const useProjectSync = (): ProjectSyncSnapshot => store.useSnapshot();
export const useProjectSyncSelector = store.useSelector;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
index 78513fe03d..e972e4a514 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
@@ -112,11 +112,11 @@ export const useProjectActions = (): {
const deleteProject = async (project: Project): Promise<void> => {
flushGenerateDrafts();
- // Marked before the request so an in-flight autosave cannot recreate the
- // project server-side between the DELETE and the tab closing.
- persistenceService.markProjectDeleted(project.id);
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.
await deleteLibraryProject(project.id);
} catch (error) {
persistenceService.unmarkProjectDeleted(project.id);
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx
index aab3cd3a33..b60d9fae7a 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx
@@ -244,7 +244,7 @@ export const ProjectSwitcher = () => {
<RenameDialog initialName={renameTarget.name} isOpen onClose={closeRenameDialog} onSubmit={renameProject} />
) : null}
<ConfirmDialog
- body={t('projects.deleteProjectTabBody', { name: deleteTarget?.name ?? '' })}
+ body={`${t('projects.deleteProjectTabBody', { name: deleteTarget?.name ?? '' })} ${t('projects.deleteProjectBoardNote')}`}
confirmLabel={t('projects.deleteProject')}
isOpen={deleteTarget !== null}
title={t('projects.deleteProjectQuestion')}