Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): apply a save's server outcomes even when the save is stale
Josh Corbett4f13e67cf95b
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.tsindex a84ccb1993..d6b831f925 100644--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts@@ -265,6 +265,68 @@ describe('Workbench persistence runtime', () => {expect(aggregate.events).toContain('save-succeeded:current');});+ it('applies server outcomes from a save that went stale', async () => {+ // A stale save is one whose *snapshot* moved on, which says nothing about what the server+ // answered. The board id in a create response exists nowhere else, and the first save of a new+ // draft is exactly the one an edit is most likely to overtake — so dropping it there leaves the+ // project pointing at no board until the next reload.+ const aggregate = createAggregate();+ const { persistence } = createPersistence(() => Promise.resolve(null));+ const first = deferred<WorkbenchSaveResult>();+ const second = deferred<WorkbenchSaveResult>();+ vi.mocked(persistence.saveWorkbench)+ .mockImplementationOnce(() => first.promise)+ .mockImplementationOnce(() => second.promise);+ const clock = new FakeClock();+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });++ runtime.start();+ await flushPromises();+ aggregate.edit('First');+ clock.runAll();++ // The edit that makes the in-flight save stale.+ aggregate.edit('Second');+ clock.runAll();++ first.resolve({+ ...saveResult(aggregate.state, 'stale'),+ projectBoardAssignments: [{ boardId: 'board-1', projectId: 'project-1' }],+ });+ await flushPromises();++ expect(aggregate.boardAssignments).toEqual([{ boardId: 'board-1', projectId: 'project-1' }]);+ // Still stale for the purposes of the save's own bookkeeping.+ expect(aggregate.events).not.toContain('save-succeeded:stale');++ second.resolve(saveResult(aggregate.state, 'current'));+ await flushPromises();+ expect(aggregate.events).toContain('save-succeeded:current');+ });++ it('ignores server outcomes once disposed', async () => {+ 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('First');+ clock.runAll();+ runtime.dispose();++ pending.resolve({+ ...saveResult(aggregate.state),+ projectBoardAssignments: [{ boardId: 'board-1', projectId: 'project-1' }],+ });+ await flushPromises();++ expect(aggregate.boardAssignments).toEqual([]);+ });+it('keeps one save in flight and coalesces queued edits into the latest state', async () => {const aggregate = createAggregate();const { persistence } = createPersistence(() => Promise.resolve(null));diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.tsindex c24986ae85..aa453c654f 100644--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts@@ -124,14 +124,28 @@ export const createWorkbenchPersistenceRuntime = ({saveGeneration: number,requireCurrentRevision: boolean): void => {- if (isStaleSave(revision, saveGeneration, requireCurrentRevision)) {+ if (disposed) {+ return;+ }++ // Staleness is read before anything is applied, because applying is itself an edit: assigning+ // 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.+ applySaveResult(result);++ if (isStale) {return;}lastSavedRevision = revision;failedRevision = null;scheduledRevision = null;aggregate.saveSucceeded(result.snapshot.savedAt);- applySaveResult(result);publish({ error: null, phase: 'idle' });};diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.tsindex a09f9ec7c0..7e2342bc49 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts@@ -723,4 +723,41 @@ describe('authoritative project boards', () => {{ boardId: `board-for-${fork!.recoveredProject.id}`, projectId: fork!.recoveredProject.id },]);});++ it('carries a flush-time fork to the next save instead of dropping it', async () => {+ // A flush has no caller to return outcomes to — rename, export and duplicate all go through+ // one. If the fork it produced were dropped, the aggregate would never hear about it.+ const project = seedServerProject('Deleted elsewhere');+ const opened = await service.hydrateProjectFromServer(project.id);+ const edited = { ...opened!, name: 'Edited locally' };++ api.__records.delete(project.id);+ await service.flushProjectToServer(edited);++ const result = await service.saveWorkbench(stateWithProjects([edited]));++ expect(result.deletedProjectForks).toHaveLength(1);+ expect(result.deletedProjectForks[0]!.projectId).toBe(project.id);+ expect(result.projectBoardAssignments).toHaveLength(1);+ });++ 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+ // forking exists to avoid.+ const project = seedServerProject('Deleted elsewhere');+ const opened = await service.hydrateProjectFromServer(project.id);+ const edited = { ...opened!, name: 'Edited locally' };++ api.__records.delete(project.id);+ await service.flushProjectToServer(edited);+ expect(api.__records.has(project.id)).toBe(false);++ // The aggregate has not applied the fork yet, so the original is still in the saved state.+ const result = await service.saveWorkbench(stateWithProjects([edited]));++ expect(api.__records.has(project.id)).toBe(false);+ // And the fork is reported exactly once, not once per push.+ expect(result.deletedProjectForks).toHaveLength(1);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex d9c28cc3e7..605c0f7347 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -120,13 +120,31 @@ export interface WorkbenchLoadOptions {interface SyncedPersistenceState {/** Ids deleted in this runtime lifetime, guarding against racing saves. */deletedProjectIds: Set<string>;+ /**+ * Ids that have already been forked because the server no longer had them.+ *+ * The fork exists on the server from the moment it is made, but the original stays in the+ * aggregate until the reconciliation reaches it. In that window `pushProject` would find no sync+ * entry and re-create the project under its old id — undoing the very deletion the fork exists to+ * respect. So a forked id is never pushed again.+ */+ forkedProjectIds: Set<string>;hasPending: boolean;localPersistence: WorkbenchPersistenceService;lastPushedAccount: string | null;/** Immutable owner captured when this synchronization lifetime was constructed. */owner: AccountScope;- /** Boards learned from create responses, drained by the next save. */+ /**+ * What the server said that the aggregate has not been told yet, drained by the next save.+ *+ * A push happens from a save *and* from a targeted flush, and only the save has somewhere to+ * return an outcome to. Holding them here rather than in the caller's local arrays is what makes+ * "the next save carries them" true rather than aspirational: a flush that forks a project or+ * resolves a conflict cannot silently drop the answer.+ */pendingBoardAssignments: ProjectBoardAssignment[];+ pendingConflicts: ProjectConflictResolution[];+ pendingDeletedForks: ProjectDeletionFork[];projectDocumentJsonCache: WeakMap<Project, { document: Record<string, unknown>; json: string }>;/** Server-known projects, keyed by project id. */syncEntries: Map<string, SyncEntry>;@@ -134,11 +152,14 @@ interface SyncedPersistenceState {const createSyncedPersistenceState = (owner: AccountScope): SyncedPersistenceState => ({deletedProjectIds: new Set(),+ forkedProjectIds: new Set(),hasPending: false,localPersistence: createLocalStorageWorkbenchPersistence(owner.storageSuffix),lastPushedAccount: null,owner,pendingBoardAssignments: [],+ pendingConflicts: [],+ pendingDeletedForks: [],projectDocumentJsonCache: new WeakMap(),syncEntries: new Map(),});@@ -446,17 +467,16 @@ const forkDeletedProject = async (}};-const pushProject = async (- syncState: SyncedPersistenceState,- project: Project,- conflicts: ProjectConflictResolution[],- deletedProjectForks: ProjectDeletionFork[]-): Promise<string> => {+const pushProject = async (syncState: SyncedPersistenceState, project: Project): Promise<string> => {assertOwner(syncState);const { document, json: documentJson } = getSerializedProjectDocument(syncState, project);const entry = syncState.syncEntries.get(project.id);- if (syncState.deletedProjectIds.has(project.id) || entry?.pushedDoc === documentJson) {+ if (+ syncState.deletedProjectIds.has(project.id) ||+ syncState.forkedProjectIds.has(project.id) ||+ entry?.pushedDoc === documentJson+ ) {return documentJson;}@@ -511,7 +531,7 @@ const pushProject = async (syncState.hasPending = true;}} else if (outcome.kind === 'forked') {- conflicts.push(outcome.resolution);+ syncState.pendingConflicts.push(outcome.resolution);} else if (outcome.kind === 'failed') {syncState.hasPending = true;}@@ -528,7 +548,10 @@ const pushProject = async (if (fork === null) {syncState.hasPending = true;} else {- deletedProjectForks.push(fork);+ // 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);}} else {syncState.hasPending = true;@@ -828,12 +851,10 @@ export const createSyncedWorkbenchPersistence = (},flushProjectToServer(project): Promise<void> {return enqueueMutation(async () => {- // A flush is a targeted push, not a save: its outcomes are surfaced by the next save,- // which is what carries them to the store.- const conflicts: ProjectConflictResolution[] = [];- const deletedProjectForks: ProjectDeletionFork[] = [];-- await pushProject(syncState, project, conflicts, deletedProjectForks);+ // 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);assertOwner(syncState);persistSyncMap(syncState);});@@ -982,8 +1003,6 @@ export const createSyncedWorkbenchPersistence = (assertOwner(syncState);syncState.hasPending = false;- const conflicts: ProjectConflictResolution[] = [];- const deletedProjectForks: ProjectDeletionFork[] = [];const projectSyncInfos: Record<string, ProjectSyncInfo> = {};await pushSessionState(syncState, state);@@ -992,7 +1011,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, conflicts, deletedProjectForks);+ const documentJson = await pushProject(syncState, project);assertOwner(syncState);const entry = syncState.syncEntries.get(project.id);@@ -1012,14 +1031,14 @@ export const createSyncedWorkbenchPersistence = (persistSyncMap(syncState);reportProjectSync({ hasPendingChanges: syncState.hasPending, projects: projectSyncInfos });- // Drained rather than read: each assignment is applied to the store exactly once.- const projectBoardAssignments = syncState.pendingBoardAssignments.splice(0);-+ // Drained rather than read: each outcome is applied to the store exactly once. The runtime+ // applies what it is handed even when the save it came from went stale, so draining here is+ // safe — nothing is dropped between this call and the reducer.return {- conflicts,- deletedProjectForks,+ conflicts: syncState.pendingConflicts.splice(0),+ deletedProjectForks: syncState.pendingDeletedForks.splice(0),hasPendingChanges: syncState.hasPending,- projectBoardAssignments,+ projectBoardAssignments: syncState.pendingBoardAssignments.splice(0),snapshot,};});