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(canvas): guard sam export preparation
joshistoast53c946009832
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex e467fd12b2..414ede5a2c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -896,6 +896,19 @@ describe('createCanvasEngine', () => {engine.dispose();});+ it('captures the current layer export guard synchronously after its cache is ready', async () => {+ const { engine } = createEngine();+ await engine.exportLayerPixels('a');++ const guard = engine.captureLayerExportGuard('a');++ expect(guard).not.toBeNull();+ expect(guard).toMatchObject({ layerId: 'a', projectId: 'p1' });+ expect(engine.isLayerExportGuardCurrent(guard!)).toBe(true);+ expect(engine.captureLayerExportGuard('missing')).toBeNull();+ engine.dispose();+ });+it('invalidates a LayerExportGuard when the immutable layer contract changes', async () => {const document = makeDoc();const { setDocument, store } = createReactiveStore(document);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex d973c56eab..13419e5718 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -457,6 +457,8 @@ export interface CanvasEngine {): Promise<ExportBakedLayerPixelsResult>;/** Encodes {@link exportBakedLayerPixels} as a PNG blob for save/copy/upload actions. */exportBakedLayerBlob(layerId: string, options?: ExportBakedLayerPixelsOptions): Promise<ExportBakedLayerBlobResult>;+ /** Captures the exact current layer/cache/document/project snapshot when its cache is ready. */+ captureLayerExportGuard(layerId: string): LayerExportGuard | null;/** True only while the exact exported layer/cache/document/project snapshot remains live. */isLayerExportGuardCurrent(guard: LayerExportGuard): boolean;/**@@ -1430,6 +1432,26 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return !!entry && liveLayer === guard.layer && entry.version === guard.cacheVersion;};+ const captureCurrentLayerExportGuard = (layerId: string): LayerExportGuard | null => {+ const document = mirror.getDocument();+ const layer = document?.layers.find((candidate) => candidate.id === layerId);+ const source = layer ? renderableSourceOf(layer) : null;+ const entry = layerCache.get(layerId);+ if (+ !layer ||+ !source ||+ !isSupportedExportSource(source) ||+ !entry ||+ entry.stale ||+ isCurrentRasterizationJob(layer) ||+ isEmpty(entry.rect)+ ) {+ return null;+ }+ const guard = captureLayerExportGuard(layer, entry);+ return isLayerExportGuardCurrent(guard) ? guard : null;+ };+canvasOperations = createCanvasOperationController({ isGuardCurrent: isLayerExportGuardCurrent });const ensureLayerCaches = (doc: CanvasDocumentContractV2): void => {@@ -5330,6 +5352,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {applyTransform,booleanMergeRasterLayers,canvasOperations,+ captureLayerExportGuard: captureCurrentLayerExportGuard,clearCaches,clearHistory,clearMask,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.tsindex 16f43d5c7b..88d463d541 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts@@ -55,6 +55,7 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})}),};const deps: SelectObjectSessionDeps<string> = {+ captureGuard: vi.fn(() => currentGuard),controller,decodePreview: vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),exportLayer: vi.fn(() => Promise.resolve({ blob, guard: currentGuard ?? guard, rect, status: 'ok' as const })),@@ -236,6 +237,56 @@ describe('createSelectObjectSession', () => {expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);});+ it('starts an immediate same-input retry when invalidation aborts an export that ignores its signal', async () => {+ const oldExport = deferred<Awaited<ReturnType<SelectObjectSessionDeps<string>['exportLayer']>>>();+ const harness = createHarness({+ exportLayer: vi+ .fn()+ .mockImplementationOnce(() => oldExport.promise)+ .mockImplementationOnce(() => Promise.resolve({ blob, guard, rect, status: 'ok' as const })),+ });+ const oldPending = harness.session.process();+ await vi.waitFor(() => expect(harness.deps.exportLayer).toHaveBeenCalledOnce());++ harness.controller.invalidateSource('p1', layer.id);+ const newPending = harness.session.process();++ expect(newPending).not.toBe(oldPending);+ await expect(newPending).resolves.toBe('published');+ expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.uploadIntermediate).toHaveBeenCalledOnce();+ expect(harness.deps.runGraph).toHaveBeenCalledOnce();+ oldExport.resolve({ blob, guard, rect, status: 'ok' });+ await expect(oldPending).resolves.toBe('stale');+ expect(harness.session.getSnapshot().preview?.image.imageName).toBe('result.png');+ await expect(harness.session.process()).resolves.toBe('deduped');+ });++ it('starts an immediate same-input retry when invalidation aborts an upload that ignores its signal', async () => {+ const oldUpload = deferred<{ imageName: string }>();+ const harness = createHarness({+ uploadIntermediate: vi+ .fn()+ .mockImplementationOnce(() => oldUpload.promise)+ .mockImplementationOnce(() => Promise.resolve({ imageName: 'new-input.png' })),+ });+ const oldPending = harness.session.process();+ await vi.waitFor(() => expect(harness.deps.uploadIntermediate).toHaveBeenCalledOnce());++ harness.controller.invalidateSource('p1', layer.id);+ const newPending = harness.session.process();++ expect(newPending).not.toBe(oldPending);+ await expect(newPending).resolves.toBe('published');+ expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);+ expect(harness.deps.runGraph).toHaveBeenCalledOnce();+ oldUpload.resolve({ imageName: 'old-input.png' });+ await expect(oldPending).resolves.toBe('stale');+ expect(harness.session.getSnapshot().preview?.sourceImageName).toBe('new-input.png');+ await expect(harness.session.process()).resolves.toBe('deduped');+ });+it('deduplicates an identical stable input hash after publication', async () => {const harness = createHarness();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.tsindex 7332649bf3..53aee18b13 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts@@ -40,6 +40,7 @@ export interface SelectObjectSessionState<T> {}export interface SelectObjectSessionDeps<T> {+ captureGuard(layerId: string): LayerExportGuard | null;controller: CanvasOperationController;exportLayer(layerId: string): Promise<ExportBakedLayerBlobResult>;uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;@@ -112,7 +113,6 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOlet source: SelectObjectPreparedSource | null = null;let operation: CanvasOperationSession | null = null;let operationGuard: LayerExportGuard | null = null;- let sourceController: AbortController | null = null;let requestToken = 0;let lastPublishedHash: string | null = null;let pendingHash: string | null = null;@@ -147,8 +147,6 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOconst clearSource = (): void => {requestToken += 1;- sourceController?.abort();- sourceController = null;pendingHash = null;pendingProcess = null;source = null;@@ -166,6 +164,13 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO}};+ const isSameGuard = (left: LayerExportGuard, right: LayerExportGuard): boolean =>+ left.projectId === right.projectId &&+ left.layerId === right.layerId &&+ left.layer === right.layer &&+ left.cacheVersion === right.cacheVersion &&+ left.documentGeneration === right.documentGeneration;+unsubscribeController = deps.controller.subscribe(() => {if (disposed) {return;@@ -200,8 +205,8 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO}, 1_000);};- const ensureSource = async (signal: AbortSignal): Promise<SelectObjectPreparedSource> => {- if (source && isGuardCurrent(source.guard)) {+ const ensureSource = async (guard: LayerExportGuard, signal: AbortSignal): Promise<SelectObjectPreparedSource> => {+ if (source?.guard === guard && isGuardCurrent(guard)) {return source;}source = null;@@ -209,10 +214,10 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOif (prepared.status !== 'ready') {throw new Error(resultError(prepared));}- if (signal.aborted || !isGuardCurrent(prepared.source.guard)) {+ if (signal.aborted || !isGuardCurrent(guard) || !isSameGuard(prepared.source.guard, guard)) {throw new DOMException('Select Object source became stale.', 'AbortError');}- source = prepared.source;+ source = { ...prepared.source, guard };return source;};@@ -220,33 +225,36 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOtoken: number,hash: string,requestState: SelectObjectSessionState<T>,- controller: AbortController+ guard: LayerExportGuard): Promise<SelectObjectSessionProcessResult> => {try {- const preparedSource = await ensureSource(controller.signal);- if (controller.signal.aborted || token !== requestToken) {- return 'stale';- }-- if (operationGuard !== preparedSource.guard || !operation) {+ if (operationGuard !== guard || !operation) {startingOperation = true;- const nextOperation = deps.controller.start({- cleanupPreview,- guard: preparedSource.guard,- identity: { kind: 'select-object', layerId, projectId },- });- startingOperation = false;+ let nextOperation: CanvasOperationSession | null = null;+ try {+ nextOperation = deps.controller.start({+ cleanupPreview,+ guard,+ identity: { kind: 'select-object', layerId, projectId },+ });+ } finally {+ startingOperation = false;+ }if (!nextOperation) {clearSource();return 'stale';}operation = nextOperation;- operationGuard = preparedSource.guard;+ operationGuard = guard;}- publishState({ ...state, sourceGuard: preparedSource.guard, status: 'processing' });+ publishState({ ...state, sourceGuard: guard, status: 'processing' });const result = await operation.run(async (signal) => {+ const preparedSource = await ensureSource(guard, signal);+ if (signal.aborted || token !== requestToken) {+ throw new DOMException('Select Object source preparation was aborted.', 'AbortError');+ }const processed = await processSelectObjectSource({applyPolygonRefinement: requestState.applyPolygonRefinement,input: requestState.input,@@ -295,16 +303,12 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOerror: controllerState.status === 'active' ? controllerState.error : 'Select Object processing failed.',status: 'error',});- } else if (result === 'stale' && !isGuardCurrent(preparedSource.guard)) {+ } else if (result === 'stale' && !isGuardCurrent(guard)) {clearSource();}return result;} catch (cause) {- if (- controller.signal.aborted ||- token !== requestToken ||- (cause instanceof Error && cause.name === 'AbortError')- ) {+ if (token !== requestToken || (cause instanceof Error && cause.name === 'AbortError')) {return 'stale';}publishState({ ...state, error: cause instanceof Error ? cause.message : String(cause), status: 'error' });@@ -323,8 +327,6 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO}if (state.sourceGuard && !isGuardCurrent(state.sourceGuard)) {requestToken += 1;- sourceController?.abort();- sourceController = null;operation?.cancel();if (!operation && state.preview) {cleanupPreview();@@ -356,15 +358,16 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOrequestToken += 1;const token = requestToken;- sourceController?.abort();- const controller = new AbortController();- sourceController = controller;+ const guard = operationGuard && isGuardCurrent(operationGuard) ? operationGuard : deps.captureGuard(layerId);+ if (!guard || !isGuardCurrent(guard)) {+ publishState({ ...state, error: 'Select Object source is not ready.', status: 'error' });+ return Promise.resolve('error');+ }pendingHash = hash;publishState({ ...state, error: null, status: 'processing' });const requestState = state;- const promise = runRequest(token, hash, requestState, controller).finally(() => {+ const promise = runRequest(token, hash, requestState, guard).finally(() => {if (token === requestToken) {- sourceController = null;pendingHash = null;pendingProcess = null;}@@ -376,8 +379,6 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOconst cancelCurrent = (): void => {clearTimer();requestToken += 1;- sourceController?.abort();- sourceController = null;pendingHash = null;pendingProcess = null;operation?.cancel();@@ -389,8 +390,6 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOconst invalidateProcessingState = (): void => {requestToken += 1;- sourceController?.abort();- sourceController = null;pendingHash = null;pendingProcess = null;lastPublishedHash = null;@@ -415,8 +414,6 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOdisposed = true;clearTimer();requestToken += 1;- sourceController?.abort();- sourceController = null;pendingHash = null;pendingProcess = null;lastPublishedHash = null;