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(canvas): scope the paint barrier to document writes and never wait on open edits

Josh Corbettcd88a86da86e
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index f221e324a7..890ff90f4d 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -450,7 +450,7 @@
"allSavedAlreadyOpen": "All saved projects are already open.",
"activeRunsMustFinish": "Wait for active queue runs to finish first.",
"closeProjectLabel": "Close {{name}}",
- "canvasPixelsNotSaved": "Unsaved canvas changes could not be uploaded, so the project stays open with them. {{reason}}",
+ "canvasPixelsNotSaved": "The project stays open because its canvas changes are not saved yet. {{reason}}",
"closeBlocked": "Project not closed",
"couldNotOpen": "Could not open project",
"couldNotOpenDescription": "\"{{name}}\" could not be loaded from the server.",
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
index 587eeadc7c..be6eea5d61 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
@@ -10,6 +10,8 @@ import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from '
import { createContext, use, useEffect, useSyncExternalStore, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
+import type { ProjectPushOutcome } from './projects/projectFlush';
+
import { WorkbenchSplashScreen } from './components/WorkbenchSplashScreen';
import { WorkbenchUnavailableScreen } from './components/WorkbenchUnavailableScreen';
import { createExtensionRegistry, type ExtensionRegistry } from './extensions/extensionRegistry';
@@ -118,17 +120,17 @@ export const WorkbenchProvider = ({
}
},
deleteProject: (projectId) => persistence.deleteProjectOnServer(projectId),
- flushProject: async (projectId) => {
- // Unsaved canvas pixels reach the document before it is pushed; a failure rejects the flush.
- await liveCanvasEngines.flushPendingPixels(projectId);
+ flushPixels: (projectId) => liveCanvasEngines.flushPendingPixels(projectId),
+ flushProject: (projectId) => {
const project = store.getSnapshot().projects.find((candidate) => candidate.id === projectId);
// Unopened projects have no local edits; their ids reflect server acknowledgements.
return project
? persistence.flushProjectToServer(project)
- : { documentJson: '', kind: 'acknowledged' as const };
+ : Promise.resolve<ProjectPushOutcome>({ documentJson: '', kind: 'acknowledged' });
},
getOpenProjectIds: () => store.getSnapshot().projects.map((project) => project.id),
+ getProject: (projectId) => store.getSnapshot().projects.find((candidate) => candidate.id === projectId),
markProjectDeleted: (projectId) => {
persistence.markProjectDeleted(projectId);
},
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index e7f2cafe80..6293c8ca5b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -176,7 +176,7 @@ The capability returns `exported`, `nothing`, `too-large`, `not-ready`, `over-bu
Lifecycle states are `active`, `cooling`, `cool`, and `disposed`. Losing the final registry reference immediately detaches input/render targets, cancels background PSD work and rasterization, releases the old generation's reservations, and starts a dirty-pixel flush. Successful, still-current flushes release every derived and group surface and each base cache that no read lease pins and no session holds, then trim history. Failed flushes retain dirty pixels and remain retryable; the registry retains the engine and retries after another grace period, disposing it only after a `cooled` result. Reacquisition increments the lifecycle generation so late flush or grace-period work cannot clean up or dispose a live engine. Operation-owned reservations and pins survive these generation transitions until their owning operation settles.
-Pushing an open project's document (close, export, copy, rename) first crosses its engine's paint barrier through the Workbench's `LiveCanvasEngines` registry, and close crosses it again after the push so pixels painted meanwhile are not lost; if unsaved pixels cannot be persisted the project stays open with its engine state intact. Disposal cancels outstanding work and releases every resource category: caches, decoded bitmaps, reservations, pins and outstanding snapshots.
+Operations that write an open project's document elsewhere (close, export, duplicate) first cross its engine's paint barrier through the open-project handle and the Workbench's `LiveCanvasEngines` registry; close crosses it again after the push so pixels painted meanwhile are not lost. These barriers do not wait on an edit that holds dirty pixels (a session, gesture or suspension): they fail fast and ask the user to finish or cancel it, and if unsaved pixels cannot be persisted the project stays open with its engine state intact. Rename keeps its tolerant flush. Invocation waits for short-lived holds. Disposal cancels outstanding work and releases every resource category: caches, decoded bitmaps, reservations, pins and outstanding snapshots.
Caller-owned `CanvasRasterSnapshot` objects are not reconstructible lifecycle caches. They remain usable through cooldown and continue to count against detached bytes until released. Final engine disposal force-releases them.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 79d9f420d9..b4918efb04 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -404,7 +404,11 @@ export interface CanvasLifecycleCapability {
beginCooldown(): Promise<'cooled' | 'dirty'>;
dispose(): void;
getLifecycleState(): CanvasLifecycleState;
- flushPendingUploads(): Promise<void>;
+ /**
+ * Persists unsaved pixels. With `waitForHeldPixels: false` it rejects instead of waiting while an open edit
+ * holds dirty pixels.
+ */
+ flushPendingUploads(options?: { readonly waitForHeldPixels?: boolean }): Promise<void>;
}
export type CanvasEditCapability = CanvasEditGate;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/persistenceController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/persistenceController.ts
index 8193ed12db..ede6df96c6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/persistenceController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/persistenceController.ts
@@ -1,4 +1,4 @@
-import type { BitmapStore } from '@workbench/canvas-engine/document/bitmapStore';
+import type { BitmapStore, FlushPendingUploadsOptions } from '@workbench/canvas-engine/document/bitmapStore';
export class PersistenceController {
readonly store: BitmapStore;
@@ -8,8 +8,8 @@ export class PersistenceController {
this.store = store;
}
- flush(): Promise<void> {
- return this.store.flushPendingUploads();
+ flush(options?: FlushPendingUploadsOptions): Promise<void> {
+ return this.store.flushPendingUploads(options);
}
dispose(): void {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
index 400bb20585..4b498b639f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
@@ -180,8 +180,9 @@ export class RasterExportController {
if (isEmpty(entry.rect)) {
return { status: 'empty' };
}
+ const lease = this.lease(currentLayer, entry, pin);
leased = true;
- return this.applyAdjustments(this.lease(currentLayer, entry, pin), options.applyAdjustments === true);
+ return this.applyAdjustments(lease, options.applyAdjustments === true);
} finally {
if (!leased) {
pin.release();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
index f0e0bb811a..1f35103d18 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
@@ -717,6 +717,37 @@ describe('createBitmapStore', () => {
h.store.dispose();
});
+ it('fails fast instead of waiting when the caller cannot wait on an open edit', async () => {
+ const h = createHarness();
+ h.store.markLayerDirty(LAYER);
+ const release = h.store.suspendLayer(LAYER);
+
+ await expect(h.store.flushPendingUploads({ waitForHeldPixels: false })).rejects.toMatchObject({
+ layerIds: [LAYER],
+ reason: 'held',
+ });
+ expect(h.store.hasPendingWork(LAYER)).toBe(true);
+
+ release();
+ await h.store.flushPendingUploads({ waitForHeldPixels: false });
+ expect(h.dispatch).toHaveBeenCalledOnce();
+ h.store.dispose();
+ });
+
+ it('fails fast on pixels a session defers instead of polling', async () => {
+ let busy = true;
+ const h = createHarness({ trimLayerPixels: () => (busy ? 'deferred' : 'kept') });
+ h.store.markLayerDirty(LAYER);
+
+ await expect(h.store.flushPendingUploads({ waitForHeldPixels: false })).rejects.toMatchObject({ reason: 'held' });
+ expect(h.uploadImage).not.toHaveBeenCalled();
+
+ busy = false;
+ await h.store.flushPendingUploads({ waitForHeldPixels: false });
+ expect(h.uploadImage).toHaveBeenCalledOnce();
+ h.store.dispose();
+ });
+
it.each(['reset', 'dispose'] as const)('%s settles barriers waiting on suspended dirty work', async (ending) => {
const h = createHarness();
h.store.markLayerDirty(LAYER);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
index b1bd6d603a..99341dd82a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
@@ -30,16 +30,31 @@ export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
/** Short barrier poll while another canvas operation transiently owns pixels. */
export const DEFAULT_DEFERRED_RETRY_MS = 50;
+/** Unsaved pixels the barrier could not persist: uploads `failed`, or an open edit `held` them. */
export class BitmapPersistenceError extends Error {
readonly layerIds: readonly string[];
-
- constructor(layerIds: readonly string[]) {
- super(`Canvas pixel persistence failed for ${layerIds.length} layer${layerIds.length === 1 ? '' : 's'}.`);
+ readonly reason: 'failed' | 'held';
+
+ constructor(layerIds: readonly string[], reason: 'failed' | 'held' = 'failed') {
+ super(
+ reason === 'held'
+ ? 'Finish or cancel the current canvas edit first.'
+ : `Canvas pixel persistence failed for ${layerIds.length} layer${layerIds.length === 1 ? '' : 's'}.`
+ );
this.name = 'BitmapPersistenceError';
this.layerIds = [...layerIds];
+ this.reason = reason;
}
}
+export interface FlushPendingUploadsOptions {
+ /**
+ * Whether to wait while an open edit (a session, gesture or suspension) holds dirty pixels. Document pushes
+ * that the user cannot see through pass false and fail fast instead.
+ */
+ readonly waitForHeldPixels?: boolean;
+}
+
/** Injectable timer seam (defaults to the global timers). */
export interface BitmapStoreTimers {
setTimeout(handler: () => void, ms: number): number;
@@ -126,7 +141,7 @@ export interface BitmapStore {
/** Cancels pending persistence and invalidates an in-flight result for one layer. */
discardLayer(layerId: string): void;
/** Flushes every dirty layer immediately and resolves once all in-flight uploads settle. */
- flushPendingUploads(): Promise<void>;
+ flushPendingUploads(options?: FlushPendingUploadsOptions): Promise<void>;
/**
* Detects the most recently applied paint ref so the engine skips self-echo rasterization. Different refs
* rerasterize. Null is never an echo: clearing must collapse cache bounds.
@@ -650,9 +665,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
/** Safety net against a genuine infinite loop; real barrier calls settle in a handful of rounds. */
const MAX_BARRIER_ITERATIONS = 10_000;
- const flushPendingUploads = async (): Promise<void> => {
+ const flushPendingUploads = async ({ waitForHeldPixels = true }: FlushPendingUploadsOptions = {}): Promise<void> => {
// Flush dirty layers and await in-flight work until newer strokes also persist. Do not retry failures within
- // this barrier; poll deferred ownership until pixels are released.
+ // this barrier; poll deferred ownership until pixels are released, unless the caller cannot wait.
const blockedThisBarrier = new Set<string>();
for (let iteration = 0; iteration < MAX_BARRIER_ITERATIONS; iteration += 1) {
const toFlush = Array.from(dirty).filter((layerId) => !blockedThisBarrier.has(layerId) && !isSuspended(layerId));
@@ -662,7 +677,11 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
}
const ops = [...inFlight.values()];
if (ops.length === 0) {
- if (Array.from(dirty).some((layerId) => isSuspended(layerId))) {
+ const suspendedLayerIds = Array.from(dirty).filter((layerId) => isSuspended(layerId));
+ if (suspendedLayerIds.length > 0) {
+ if (!waitForHeldPixels) {
+ throw new BitmapPersistenceError(suspendedLayerIds, 'held');
+ }
await waitForSuspensionChange();
continue;
}
@@ -675,15 +694,18 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
return;
}
await Promise.all(ops);
- let deferredThisRound = false;
+ const deferredLayerIds: string[] = [];
for (const layerId of toFlush) {
if (dirty.has(layerId) && dirtyReason.get(layerId) === 'failure') {
blockedThisBarrier.add(layerId);
} else if (dirty.has(layerId) && dirtyReason.get(layerId) === 'deferred') {
- deferredThisRound = true;
+ deferredLayerIds.push(layerId);
}
}
- if (deferredThisRound) {
+ if (deferredLayerIds.length > 0) {
+ if (!waitForHeldPixels) {
+ throw new BitmapPersistenceError(deferredLayerIds, 'held');
+ }
await sleep(DEFAULT_DEFERRED_RETRY_MS);
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 753667b375..918786edb3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -2558,7 +2558,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
activate,
beginCooldown,
dispose,
- flushPendingUploads: () => persistenceController.flush(),
+ flushPendingUploads: (options) => persistenceController.flush(options),
getLifecycleState: () => lifecycleState,
};
const layerController = new LayerController({
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
index 42df80249a..42d2dc6146 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.ts
@@ -142,7 +142,8 @@ export const createEngineRegistry = (
const engine = createCanvasEngine({ projectId, ...deps });
const releaseLiveEngine =
liveEngines?.register(projectId, {
- flushPendingPixels: () => engine.lifecycle.flushPendingUploads(),
+ // Document pushes cannot wait on an edit the user may never finish.
+ flushPendingPixels: () => engine.lifecycle.flushPendingUploads({ waitForHeldPixels: false }),
heldAssets: () => engine.history.getHeldAssetRefs(),
subscribe: (listener) => engine.interaction.subscribe('historyEpoch', listener),
}) ?? (() => undefined);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
index e96acfee4f..a1b9e8ffc4 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
@@ -2216,6 +2216,8 @@ describe('durable project persistence', () => {
close: vi.fn(),
deleteOnServer: vi.fn(() => Promise.resolve()),
flush: vi.fn(() => Promise.resolve({ documentJson: '', kind: 'acknowledged' as const })),
+ current: vi.fn(() => undefined),
+ flushPixels: vi.fn(() => Promise.resolve()),
markDeleted: vi.fn(),
rename: vi.fn(() => Promise.resolve()),
unmarkDeleted: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
index d10c8d4165..d58b4b595b 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
@@ -98,6 +98,12 @@ const openProject = (projectId: string, calls: string[] = []) => {
return Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'acknowledged' });
}),
+ current: vi.fn(() => undefined),
+ flushPixels: vi.fn(() => {
+ calls.push('flushPixels');
+
+ return Promise.resolve();
+ }),
markDeleted: vi.fn(() => {
calls.push('markDeleted');
}),
@@ -352,7 +358,7 @@ describe('library mutations', () => {
await library.readAcknowledgedProject('source', account.accountLifecycle.capture());
- expect(calls).toEqual(['flush', 'get']);
+ expect(calls).toEqual(['flushPixels', 'flush', 'get']);
});
/** An unacknowledged flush must abort duplication rather than copy stale server bytes. */
@@ -370,7 +376,7 @@ describe('library mutations', () => {
reason: 'unsynced',
});
- expect(calls).toEqual(['flush']);
+ expect(calls).toEqual(['flushPixels', 'flush']);
expect(api.getProject).not.toHaveBeenCalled();
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.ts
index a979fcaf99..f2b6f6e306 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts
@@ -263,11 +263,13 @@ export const renameLibraryProject = async (projectId: string, name: string): Pro
upsertProjectSummary({ id: updated.project_id, name: updated.name, revision: updated.revision }, owner);
};
-/** Export/copy requires an acknowledged flush before reading server bytes. */
+/** Export/copy requires the paint barrier and an acknowledged flush before reading server bytes. */
export const readAcknowledgedProject = async (projectId: string, owner: AccountScope): Promise<ProjectRecordDTO> => {
const openProject = getOpenProject(projectId);
if (openProject) {
+ // Written bytes must include canvas pixels that only the live engine holds.
+ await openProject.flushPixels();
assertProjectFlushed(await openProject.flush());
}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts
index ba8c509508..476fef35fb 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts
@@ -12,8 +12,10 @@ const createHarness = () => {
const deps = {
closeProject: vi.fn(),
deleteProject: vi.fn(() => Promise.resolve()),
+ flushPixels: vi.fn(() => Promise.resolve()),
flushProject: vi.fn(() => Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'acknowledged' })),
getOpenProjectIds: vi.fn(() => openIds),
+ getProject: vi.fn(() => undefined),
markProjectDeleted: vi.fn(),
renameProject: vi.fn(),
unmarkProjectDeleted: vi.fn(),
@@ -119,6 +121,8 @@ describe('createOpenProjectBroker', () => {
expect(harness.deps.renameProject).toHaveBeenCalledWith('a', 'New name');
expect(order).toEqual(['rename', 'flush']);
+ // A rename never waits on, or fails with, the canvas paint barrier.
+ expect(harness.deps.flushPixels).not.toHaveBeenCalled();
});
it('routes deletion and closing at the project it was published for', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts
index a3b13dc9d7..2232ebdf11 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 { Project } from '@workbench/projectContracts';
+
import type { ProjectPushOutcome } from './projectFlush';
import { type OpenProjectHandle, registerOpenProject, unregisterOpenProject } from './syncStore';
@@ -10,6 +12,9 @@ export interface OpenProjectBrokerDeps {
deleteProject: (projectId: string) => Promise<void>;
/** Push this project's live document and report whether the server took it. */
flushProject: (projectId: string) => Promise<ProjectPushOutcome>;
+ /** Persist the project's unsaved canvas pixels into its document. */
+ flushPixels: (projectId: string) => Promise<void>;
+ getProject: (projectId: string) => Project | undefined;
getOpenProjectIds: () => string[];
/** Stop the autosave recreating a project that is being deleted. */
markProjectDeleted: (projectId: string) => void;
@@ -30,6 +35,8 @@ export const createOpenProjectBroker = (deps: OpenProjectBrokerDeps): OpenProjec
close: () => deps.closeProject(projectId),
deleteOnServer: () => deps.deleteProject(projectId),
flush: () => deps.flushProject(projectId),
+ current: () => deps.getProject(projectId),
+ flushPixels: () => deps.flushPixels(projectId),
markDeleted: () => deps.markProjectDeleted(projectId),
// Rename through the reducer's revision chain; an unacknowledged flush remains recoverable.
rename: async (name: string) => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 263faae85a..a4b51d06b8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -174,6 +174,43 @@ describe('exportOpenProject', () => {
expect(downloads.downloadBlob.mock.calls[0]![1]).toBe('My project.invk');
});
+ it("writes an open project's document after its canvas pixels reach it", async () => {
+ const { registerOpenProject, unregisterOpenProject } = await import('./syncStore');
+ const requested = { ...createDraftProject([]), name: 'Before barrier' };
+ const order: string[] = [];
+ api.getProject.mockResolvedValue({
+ data: persistence.serializeProjectDocument(requested),
+ name: requested.name,
+ project_id: requested.id,
+ revision: 1,
+ });
+ registerOpenProject(requested.id, {
+ close: vi.fn(),
+ current: vi.fn(() => {
+ order.push('current');
+ return { ...requested, name: 'After barrier' };
+ }),
+ deleteOnServer: vi.fn(),
+ flush: vi.fn(() => Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'acknowledged' })),
+ flushPixels: vi.fn(() => {
+ order.push('flushPixels');
+ return Promise.resolve();
+ }),
+ markDeleted: vi.fn(),
+ rename: vi.fn(),
+ unmarkDeleted: vi.fn(),
+ });
+
+ try {
+ await projectFile.exportOpenProject(requested);
+ } finally {
+ unregisterOpenProject(requested.id);
+ }
+
+ expect(order.slice(0, 2)).toEqual(['flushPixels', 'current']);
+ expect(downloads.downloadBlob.mock.calls[0]![1]).toBe('After barrier.invk');
+ });
+
/** Include a positive transport probe so negative server-call assertions cannot pass vacuously. */
it('reaches the server through the mocked transport', async () => {
api.getProject.mockResolvedValue({
@@ -291,6 +328,11 @@ describe('exportLibraryProject', () => {
close: vi.fn(),
deleteOnServer: vi.fn(),
flush,
+ current: vi.fn(() => undefined),
+ flushPixels: vi.fn(() => {
+ order.push('flushPixels');
+ return Promise.resolve();
+ }),
markDeleted: vi.fn(),
rename: vi.fn(),
unmarkDeleted: vi.fn(),
@@ -303,7 +345,7 @@ describe('exportLibraryProject', () => {
}
expect(flush).toHaveBeenCalledTimes(1);
- expect(order).toEqual(['flush', 'get']);
+ expect(order).toEqual(['flushPixels', 'flush', 'get']);
});
/** Require an acknowledged flush before reading/exporting server bytes. */
@@ -314,6 +356,8 @@ describe('exportLibraryProject', () => {
close: vi.fn(),
deleteOnServer: vi.fn(),
flush: vi.fn(() => Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'unsynced' })),
+ current: vi.fn(() => undefined),
+ flushPixels: vi.fn(() => Promise.resolve()),
markDeleted: vi.fn(),
rename: vi.fn(),
unmarkDeleted: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 5750d207e8..25cb9c15de 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -169,17 +169,22 @@ export const exportLibraryProject = async (
/** Export an open project from its live in-memory document. */
export const exportOpenProject = async (
- project: Project,
+ requested: Project,
options: ProjectFileOptions = {}
): Promise<ProjectExportOutcome> => {
const owner = options.owner ?? captureAccountScope();
+ const open = getOpenProject(requested.id);
+ // The file is written from the live document, which holds the canvas pixels only after this barrier.
+ await open?.flushPixels();
+ assertAccountScopeCurrent(owner);
+ const project = open?.current() ?? requested;
const { serializeProjectDocument } = await import('./projectDocument');
const document = serializeProjectDocument(project);
assertAccountScopeCurrent(owner);
// Use the acknowledged server compatibility floor; offline fallback uses live canvas requirements.
- const record = getOpenProject(project.id) ? await readAcknowledgedProject(project.id, owner) : null;
+ const record = open ? await readAcknowledgedProject(project.id, owner) : null;
const minimumCanvasSchemaVersion = Math.max(
getProjectCanvasSchemaRequirement(document),
record?.minimum_canvas_schema_version ?? 1
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
index 1ce49fce3a..54e3848633 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
@@ -1,3 +1,5 @@
+import type { Project } from '@workbench/projectContracts';
+
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
@@ -53,6 +55,10 @@ export interface OpenProjectHandle {
deleteOnServer: () => Promise<void>;
/** Flush returns an acknowledgement outcome; callers reading server bytes must assert success. */
flush: () => Promise<ProjectPushOutcome>;
+ /** Persists unsaved canvas pixels into the document; rejects when they cannot be saved. */
+ flushPixels: () => Promise<void>;
+ /** The live project as the editor holds it now. */
+ current: () => Project | undefined;
/** Stop the autosave from recreating this project while it is being deleted. */
markDeleted: () => void;
/** Unmark failed deletes so autosave can resume. */