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): harden sam processing feedback

joshistoast4edf679b7421
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.test.ts
index 8f21909daf..181ab2d1c7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.test.ts
@@ -151,11 +151,87 @@ describe('runUtilityGraph — await + settle', () => {
enqueue: okEnqueue,
graph: { edges: [], id: 'g', nodes: {} },
hub: fake.hub,
+ reconcileCompletedOutput: () => Promise.resolve(null),
});
fake.emit('queue_item_status_changed', statusEvent('completed'));
await expect(promise).rejects.toMatchObject({ name: 'UtilityQueueError', reason: 'no-output' });
});
+ it('reconciles the target output when completed status arrives before invocation_complete', async () => {
+ const fake = createFakeHub();
+ const reconcileCompletedOutput = vi.fn(() =>
+ Promise.resolve({ height: 48, imageName: 'reconciled.png', width: 64 })
+ );
+ const promise = runUtilityGraph({
+ createId: () => UTIL_ID,
+ enqueue: okEnqueue,
+ graph: { edges: [], id: 'g', nodes: {} },
+ hub: fake.hub,
+ outputNodeId: 'control_filter',
+ reconcileCompletedOutput,
+ });
+
+ fake.emit('queue_item_status_changed', statusEvent('completed'));
+
+ await expect(promise).resolves.toEqual({
+ height: 48,
+ imageName: 'reconciled.png',
+ origin: ORIGIN,
+ width: 64,
+ });
+ expect(reconcileCompletedOutput).toHaveBeenCalledExactlyOnceWith([1], 'control_filter');
+ expect(fake.handlerCount('invocation_complete')).toBe(0);
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(0);
+ });
+
+ it('rejects no-output after deterministic completed-item reconciliation finds no target output', async () => {
+ const fake = createFakeHub();
+ const reconcileCompletedOutput = vi.fn(() => Promise.resolve(null));
+ const promise = runUtilityGraph({
+ createId: () => UTIL_ID,
+ enqueue: okEnqueue,
+ graph: { edges: [], id: 'g', nodes: {} },
+ hub: fake.hub,
+ outputNodeId: 'control_filter',
+ reconcileCompletedOutput,
+ });
+
+ await Promise.resolve();
+ fake.emit('queue_item_status_changed', statusEvent('completed'));
+
+ await expect(promise).rejects.toMatchObject({ reason: 'no-output' });
+ expect(reconcileCompletedOutput).toHaveBeenCalledOnce();
+ });
+
+ it('aborts and fully cleans up while completed-output reconciliation is pending', async () => {
+ const fake = createFakeHub();
+ const reconciliation = createDeferred<{ height: number; imageName: string; width: number } | null>();
+ const controller = new AbortController();
+ const cancel = vi.fn(() => Promise.resolve());
+ const promise = runUtilityGraph({
+ cancel,
+ createId: () => UTIL_ID,
+ enqueue: okEnqueue,
+ graph: { edges: [], id: 'g', nodes: {} },
+ hub: fake.hub,
+ outputNodeId: 'control_filter',
+ reconcileCompletedOutput: () => reconciliation.promise,
+ signal: controller.signal,
+ });
+ await Promise.resolve();
+ fake.emit('queue_item_status_changed', statusEvent('completed'));
+
+ controller.abort();
+
+ await expect(promise).rejects.toMatchObject({ reason: 'aborted' });
+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledExactlyOnceWith([1]));
+ expect(fake.handlerCount('invocation_complete')).toBe(0);
+ expect(fake.handlerCount('queue_item_status_changed')).toBe(0);
+ reconciliation.resolve({ height: 48, imageName: 'late.png', width: 64 });
+ await Promise.resolve();
+ expect(fake.detachCount).toBe(2);
+ });
+
it('rejects with the failure reason + message on a failed item', async () => {
const fake = createFakeHub();
const promise = runUtilityGraph({
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.ts
index 34901903cd..5e2392b73f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/backend/utilityQueue.ts
@@ -30,7 +30,7 @@ import type { SocketHub } from '@workbench/backend/socketHub';
import type { BackendGraphContract } from '@workbench/types';
import { buildUtilityQueueItemOrigin } from '@workbench/backend/events';
-import { cancelQueueItems, enqueueUtilityGraph } from '@workbench/generation/api';
+import { cancelQueueItems, enqueueUtilityGraph, getQueueItem } from '@workbench/generation/api';
/** The default time a utility graph may run before it is abandoned. */
export const DEFAULT_UTILITY_QUEUE_TIMEOUT_MS = 120_000;
@@ -55,6 +55,14 @@ export type UtilityEnqueue = (request: {
/** The cancellation seam: best-effort cancels accepted backend item ids. */
export type UtilityCancel = (itemIds: number[]) => Promise<void>;
+type UtilityImageOutput = { height: number; imageName: string; width: number };
+
+/** Deterministically reads a completed queue item's target output. */
+export type UtilityCompletedOutputReconciler = (
+ itemIds: number[],
+ outputNodeId?: string
+) => Promise<UtilityImageOutput | null>;
+
/** Dependencies for {@link runUtilityGraph} (all injectable for tests). */
export interface RunUtilityGraphOptions {
/** The graph to enqueue and await. */
@@ -76,6 +84,8 @@ export interface RunUtilityGraphOptions {
signal?: AbortSignal;
/** Injectable id source (defaults to `crypto.randomUUID`). */
createId?: () => string;
+ /** Injectable completed-item reconciliation seam. */
+ reconcileCompletedOutput?: UtilityCompletedOutputReconciler;
}
/** The resolved result of a utility graph: its single output image. */
@@ -88,17 +98,17 @@ export interface UtilityGraphResult {
}
/** Extracts the current backend ImageOutput fields from a completion payload. */
-const extractImageOutput = (
- result: InvocationCompleteEvent['result'] | undefined
-): { height: number; imageName: string; width: number } | null => {
+const extractImageOutput = (result: InvocationCompleteEvent['result'] | undefined): UtilityImageOutput | null => {
const output = result as { height?: unknown; image?: { image_name?: unknown }; width?: unknown } | undefined;
if (
typeof output?.image?.image_name !== 'string' ||
typeof output.width !== 'number' ||
!Number.isFinite(output.width) ||
+ !Number.isInteger(output.width) ||
output.width <= 0 ||
typeof output.height !== 'number' ||
!Number.isFinite(output.height) ||
+ !Number.isInteger(output.height) ||
output.height <= 0
) {
return null;
@@ -106,6 +116,24 @@ const extractImageOutput = (
return { height: output.height, imageName: output.image.image_name, width: output.width };
};
+const reconcileUtilityCompletedOutput: UtilityCompletedOutputReconciler = async (itemIds, outputNodeId) => {
+ for (const itemId of itemIds) {
+ const item = await getQueueItem(itemId);
+ const results = item.session?.results ?? {};
+ const preparedSourceMapping = item.session?.prepared_source_mapping ?? {};
+ for (const [preparedNodeId, result] of Object.entries(results)) {
+ if (outputNodeId && (preparedSourceMapping[preparedNodeId] ?? preparedNodeId) !== outputNodeId) {
+ continue;
+ }
+ const output = extractImageOutput(result as InvocationCompleteEvent['result']);
+ if (output) {
+ return output;
+ }
+ }
+ }
+ return null;
+};
+
/**
* Runs `graph` on the utility queue and resolves with its output image metadata.
* Never routes into project state (isolated origin). Rejects with a
@@ -116,6 +144,7 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
const enqueue = options.enqueue ?? enqueueUtilityGraph;
const cancel = options.cancel ?? cancelQueueItems;
const timeoutMs = options.timeoutMs ?? DEFAULT_UTILITY_QUEUE_TIMEOUT_MS;
+ const reconcileCompletedOutput = options.reconcileCompletedOutput ?? reconcileUtilityCompletedOutput;
const utilityId = (options.createId ?? (() => crypto.randomUUID()))();
const origin = buildUtilityQueueItemOrigin(utilityId);
@@ -125,6 +154,8 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
let cancellationRequested = false;
let cancellationStarted = false;
let enqueueResult: { itemIds: number[]; enqueued: number } | null = null;
+ let completionReceived = false;
+ let reconciliationStarted = false;
const detachers: Array<() => void> = [];
let timer: ReturnType<typeof setTimeout> | null = null;
@@ -185,6 +216,35 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
reject(error);
};
+ const reconcileCompletion = (): void => {
+ if (settled || !completionReceived || reconciliationStarted || enqueueResult === null) {
+ return;
+ }
+ if (capturedOutput) {
+ settleResolve(capturedOutput);
+ return;
+ }
+ reconciliationStarted = true;
+ void reconcileCompletedOutput([...enqueueResult.itemIds], outputNodeId)
+ .then((output) => {
+ if (settled) {
+ return;
+ }
+ if (capturedOutput) {
+ settleResolve(capturedOutput);
+ } else if (output) {
+ settleResolve(output);
+ } else {
+ settleReject(new UtilityQueueError('no-output', 'The utility graph produced no output image.'));
+ }
+ })
+ .catch(() => {
+ if (!settled) {
+ settleReject(new UtilityQueueError('no-output', 'The utility graph output could not be reconciled.'));
+ }
+ });
+ };
+
function onAbort(): void {
if (settled) {
return;
@@ -206,6 +266,9 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
const output = extractImageOutput(event.result);
if (output) {
capturedOutput = output;
+ if (completionReceived) {
+ settleResolve(output);
+ }
}
})
);
@@ -216,11 +279,8 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
return;
}
if (event.status === 'completed') {
- if (capturedOutput) {
- settleResolve(capturedOutput);
- } else {
- settleReject(new UtilityQueueError('no-output', 'The utility graph produced no output image.'));
- }
+ completionReceived = true;
+ reconcileCompletion();
} else if (event.status === 'failed') {
settleReject(new UtilityQueueError('failed', event.error_message ?? 'The utility graph failed.'));
} else if (event.status === 'canceled') {
@@ -255,6 +315,8 @@ export const runUtilityGraph = (options: RunUtilityGraphOptions): Promise<Utilit
cancelAcceptedItems();
if (!settled && result.enqueued === 0) {
settleReject(new UtilityQueueError('enqueue', 'The backend queue did not accept the utility graph.'));
+ } else {
+ reconcileCompletion();
}
})
.catch((error: unknown) => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 6d98547c36..e99382c724 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -23,7 +23,7 @@ import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbe
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';
import type { BitmapStore } from './document/bitmapStore';
-import type { CanvasEngine, EngineStore } from './engine';
+import type { CanvasEngine, CanvasEngineOptions, EngineStore } from './engine';
import type { StrokeCommittedEvent } from './tools/tool';
import { createBitmapStore } from './document/bitmapStore';
@@ -12632,10 +12632,11 @@ describe('Select Object canvas engine integration', () => {
const createSamHarness = async (
options: {
backend?: StubRasterBackend;
+ bbox?: CanvasDocumentContractV2['bbox'];
imageResolver?: (imageName: string, signal?: AbortSignal) => Promise<Blob>;
layers?: CanvasLayerContract[];
- runGraph?: () => Promise<{ imageName: string; origin: string }>;
- uploadIntermediate?: (blob: Blob, signal?: AbortSignal) => Promise<{ imageName: string }>;
+ runGraph?: NonNullable<CanvasEngineOptions['selectObjectDeps']>['runGraph'];
+ uploadIntermediate?: NonNullable<CanvasEngineOptions['selectObjectDeps']>['uploadIntermediate'];
} = {}
) => {
const raf = createControllableRaf();
@@ -12650,15 +12651,25 @@ describe('Select Object canvas engine integration', () => {
vi.stubGlobal('removeEventListener', (type: string, listener: (event: Event) => void) => {
windowListeners.get(type)?.delete(listener);
});
- const reactive = createReactiveStore(samDocument(options.layers));
+ const bbox = options.bbox ?? { height: 100, width: 100, x: 0, y: 0 };
+ const reactive = createReactiveStore({ ...samDocument(options.layers), bbox });
const engine = createCanvasEngine({
- backend: options.backend ?? createTestStubRasterBackend(),
+ backend: options.backend ?? {
+ ...createTestStubRasterBackend(),
+ createImageBitmap: () =>
+ Promise.resolve({ close: () => undefined, height: bbox.height, width: bbox.width } as unknown as ImageBitmap),
+ },
bitmapStore: createSpyBitmapStore(),
imageResolver: options.imageResolver ?? (() => Promise.resolve(new Blob())),
projectId: 'p1',
selectObjectDeps: {
- runGraph: options.runGraph ?? (() => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' })),
- uploadIntermediate: options.uploadIntermediate ?? (() => Promise.resolve({ imageName: 'sam-source.png' })),
+ runGraph:
+ options.runGraph ??
+ (() =>
+ Promise.resolve({ height: bbox.height, imageName: 'sam-mask.png', origin: 'test', width: bbox.width })),
+ uploadIntermediate:
+ options.uploadIntermediate ??
+ (() => Promise.resolve({ height: bbox.height, imageName: 'sam-source.png', width: bbox.width })),
},
store: reactive.store,
});
@@ -12684,13 +12695,19 @@ describe('Select Object canvas engine integration', () => {
const document = { ...samDocument([samLayer('source', -5)]), bbox };
const reactive = createReducerBackedStore(document);
const engine = createCanvasEngine({
- backend,
+ backend: {
+ ...backend,
+ createImageBitmap: () =>
+ Promise.resolve({ close: () => undefined, height: bbox.height, width: bbox.width } as unknown as ImageBitmap),
+ },
bitmapStore: createSpyBitmapStore(),
imageResolver,
projectId: reactive.projectId,
selectObjectDeps: {
- runGraph: () => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }),
- uploadIntermediate: () => Promise.resolve({ imageName: 'sam-source.png' }),
+ runGraph: () =>
+ Promise.resolve({ height: bbox.height, imageName: 'sam-mask.png', origin: 'test', width: bbox.width }),
+ uploadIntermediate: () =>
+ Promise.resolve({ height: bbox.height, imageName: 'sam-source.png', width: bbox.width }),
},
store: reactive.store,
});
@@ -12758,6 +12775,113 @@ describe('Select Object canvas engine integration', () => {
h.engine.dispose();
});
+ it('runs transformed multilayer bbox composite through upload, local visual graph, metadata, and decoded rect', async () => {
+ const bbox = { height: 30, width: 40, x: -11, y: 7 };
+ const base = createTestStubRasterBackend();
+ const surfaces: StubRasterSurface[] = [];
+ const backend: StubRasterBackend = {
+ ...base,
+ createImageBitmap: () =>
+ Promise.resolve({ close: () => undefined, height: bbox.height, width: bbox.width } as unknown as ImageBitmap),
+ createSurface: (width, height) => {
+ const surface = base.createSurface(width, height);
+ surfaces.push(surface);
+ return surface;
+ },
+ };
+ const uploadIntermediate = vi.fn(async (source: Blob) => {
+ expect(await source.text()).toBe('stub-surface-40x30');
+ return { height: 30, imageName: 'composite.png', width: 40 };
+ });
+ const runGraph = vi.fn<NonNullable<CanvasEngineOptions['selectObjectDeps']>['runGraph']>((options) => {
+ expect(options.graph.nodes['sam-segment']).toMatchObject({
+ bounding_boxes: [{ x_max: 25, x_min: 5, y_max: 20, y_min: 5 }],
+ point_lists: [{ points: [{ label: 1, x: 10, y: 10 }] }],
+ });
+ return Promise.resolve({ height: 30, imageName: 'mask.png', origin: 'test', width: 40 });
+ });
+ const imageResolver = vi.fn(() => Promise.resolve(new Blob(['mask'])));
+ const lower = { ...samLayer('lower', -6), transform: { rotation: 0, scaleX: 1.5, scaleY: 1, x: -6, y: 9 } };
+ const upper = { ...samLayer('upper', 4), transform: { rotation: 15, scaleX: 1, scaleY: 0.75, x: 4, y: 11 } };
+ const h = await createSamHarness({
+ backend,
+ bbox,
+ imageResolver,
+ layers: [upper, lower],
+ runGraph,
+ uploadIntermediate,
+ });
+ expect(h.engine.startSelectObject()).toBe('started');
+ h.engine.updateSelectObjectSession({
+ input: {
+ bbox: { height: 15, width: 20, x: -6, y: 12 },
+ excludePoints: [],
+ includePoints: [{ x: -1, y: 17 }],
+ type: 'visual',
+ },
+ });
+
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');
+ h.raf.flush();
+
+ expect(uploadIntermediate).toHaveBeenCalledOnce();
+ expect(runGraph).toHaveBeenCalledOnce();
+ expect(imageResolver).toHaveBeenCalledWith('mask.png', expect.any(AbortSignal));
+ expect(surfaces.some((surface) => surface.width === 40 && surface.height === 30)).toBe(true);
+ expect(h.overlay.surface.callLog).toContainEqual({
+ args: [expect.anything(), -11, 7, 40, 30],
+ op: 'drawImage',
+ });
+ h.engine.dispose();
+ });
+
+ it('builds the prompt path and reports a decoded preview', async () => {
+ const runGraph = vi.fn<NonNullable<CanvasEngineOptions['selectObjectDeps']>['runGraph']>((options) => {
+ expect(options.graph.nodes['sam-detect']).toMatchObject({ prompt: 'red car', type: 'grounding_dino' });
+ return Promise.resolve({ height: 100, imageName: 'prompt-mask.png', origin: 'test', width: 100 });
+ });
+ const h = await createSamHarness({ runGraph });
+ h.engine.startSelectObject();
+ h.engine.updateSelectObjectSession({ input: { prompt: ' red car ', type: 'prompt' } });
+
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');
+
+ expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: true, status: 'ready' });
+ h.engine.dispose();
+ });
+
+ it('rejects SAM metadata dimensions that do not match the decoded preview rect', async () => {
+ const h = await createSamHarness({
+ runGraph: () => Promise.resolve({ height: 99, imageName: 'bad-mask.png', origin: 'test', width: 100 }),
+ });
+ h.engine.startSelectObject();
+ h.engine.updateSelectObjectSession({ input: { prompt: 'cat', type: 'prompt' } });
+
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('error');
+
+ expect(h.engine.stores.samSession.get()).toMatchObject({
+ error: 'SAM output dimensions 100x99 do not match 100x100.',
+ hasPreview: false,
+ status: 'error',
+ });
+ h.engine.dispose();
+ });
+
+ it('reports preview decode failures without publishing a stale surface', async () => {
+ const h = await createSamHarness({ imageResolver: () => Promise.reject(new Error('preview decode failed')) });
+ h.engine.startSelectObject();
+ h.engine.updateSelectObjectSession({ input: { prompt: 'cat', type: 'prompt' } });
+
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('error');
+
+ expect(h.engine.stores.samSession.get()).toMatchObject({
+ error: 'preview decode failed',
+ hasPreview: false,
+ status: 'error',
+ });
+ h.engine.dispose();
+ });
+
it('applies the guarded preview to selection and exits only after success', async () => {
const { backend, surfaces } = createOpaqueSamBackend();
const h = await createCommittingSamHarness(() => Promise.resolve(new Blob()), backend);
@@ -12847,7 +12971,7 @@ describe('Select Object canvas engine integration', () => {
});
it('interrupts Select Object processing on an external lock without losing inputs or operation', async () => {
- const graph = createDeferred<{ imageName: string; origin: string }>();
+ const graph = createDeferred<{ height: number; imageName: string; origin: string; width: number }>();
const runGraph = vi.fn(() => graph.promise);
const h = await createSamHarness({ runGraph });
expect(h.engine.startSelectObject()).toBe('started');
@@ -12857,7 +12981,7 @@ describe('Select Object canvas engine integration', () => {
await vi.waitFor(() => expect(runGraph).toHaveBeenCalledOnce());
h.engine.setInteractionLocked(true);
- graph.resolve({ imageName: 'late.png', origin: 'test' });
+ graph.resolve({ height: 100, imageName: 'late.png', origin: 'test', width: 100 });
await expect(pending).resolves.toBe('stale');
expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: false, input, invert: true, status: 'ready' });
@@ -13038,8 +13162,8 @@ describe('Select Object canvas engine integration', () => {
imageResolver: () => Promise.resolve(new Blob()),
projectId: reactive.projectId,
selectObjectDeps: {
- runGraph: () => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }),
- uploadIntermediate: () => Promise.resolve({ imageName: 'sam-source.png' }),
+ runGraph: () => Promise.resolve({ height: 100, imageName: 'sam-mask.png', origin: 'test', width: 100 }),
+ uploadIntermediate: () => Promise.resolve({ height: 100, imageName: 'sam-source.png', width: 100 }),
},
store: reactive.store,
});
@@ -13074,8 +13198,8 @@ describe('Select Object canvas engine integration', () => {
imageResolver: () => Promise.resolve(new Blob()),
projectId: reactive.projectId,
selectObjectDeps: {
- runGraph: () => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }),
- uploadIntermediate: () => Promise.resolve({ imageName: 'sam-source.png' }),
+ runGraph: () => Promise.resolve({ height: 100, imageName: 'sam-mask.png', origin: 'test', width: 100 }),
+ uploadIntermediate: () => Promise.resolve({ height: 100, imageName: 'sam-source.png', width: 100 }),
},
store: reactive.store,
});
@@ -13113,8 +13237,8 @@ describe('Select Object canvas engine integration', () => {
imageResolver: () => Promise.resolve(new Blob()),
projectId: reactive.projectId,
selectObjectDeps: {
- runGraph: () => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }),
- uploadIntermediate: () => Promise.resolve({ imageName: 'sam-source.png' }),
+ runGraph: () => Promise.resolve({ height: 100, imageName: 'sam-mask.png', origin: 'test', width: 100 }),
+ uploadIntermediate: () => Promise.resolve({ height: 100, imageName: 'sam-source.png', width: 100 }),
},
store: reactive.store,
});
@@ -13219,8 +13343,8 @@ describe('Select Object canvas engine integration', () => {
imageResolver: () => Promise.resolve(new Blob()),
projectId: reducer.projectId,
selectObjectDeps: {
- runGraph: () => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }),
- uploadIntermediate: () => Promise.resolve({ imageName: 'sam-source.png' }),
+ runGraph: () => Promise.resolve({ height: 100, imageName: 'sam-mask.png', origin: 'test', width: 100 }),
+ uploadIntermediate: () => Promise.resolve({ height: 100, imageName: 'sam-source.png', width: 100 }),
},
store: reducer.store,
});
@@ -13302,7 +13426,9 @@ describe('Select Object canvas engine integration', () => {
});
it('processes a sole bbox near-edge point after canonicalizing it to the last bbox pixel', async () => {
- const runGraph = vi.fn(() => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }));
+ const runGraph = vi.fn(() =>
+ Promise.resolve({ height: 100, imageName: 'sam-mask.png', origin: 'test', width: 100 })
+ );
const h = await createSamHarness({ runGraph });
h.engine.startSelectObject();
@@ -13380,8 +13506,10 @@ describe('Select Object canvas engine integration', () => {
it('does not omit a stale outside cache when its new source may enter the bbox', async () => {
const nextImage = createDeferred<Blob>();
- const uploadIntermediate = vi.fn(() => Promise.resolve({ imageName: 'sam-source.png' }));
- const runGraph = vi.fn(() => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }));
+ const uploadIntermediate = vi.fn(() => Promise.resolve({ height: 100, imageName: 'sam-source.png', width: 100 }));
+ const runGraph = vi.fn(() =>
+ Promise.resolve({ height: 100, imageName: 'sam-mask.png', origin: 'test', width: 100 })
+ );
const outside = {
...samLayer('moving-source'),
source: {
@@ -13414,7 +13542,7 @@ describe('Select Object canvas engine integration', () => {
});
const firstProcess = h.engine.processSelectObjectSession();
- await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('processing'));
+ await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('preparing-composite'));
expect(runGraph).not.toHaveBeenCalled();
expect(uploadIntermediate).not.toHaveBeenCalled();
nextImage.resolve(new Blob(['inside']));
@@ -13503,7 +13631,7 @@ describe('Select Object canvas engine integration', () => {
input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },
});
const pending = h.engine.processSelectObjectSession();
- await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('processing'));
+ await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('rendering-preview'));
image.resolve(new Blob());
await vi.waitFor(() => expect(backend.createImageBitmap).toHaveBeenCalledOnce());
@@ -13633,7 +13761,12 @@ describe('Select Object canvas engine integration', () => {
mask: { bitmap: { height: 10, imageName: 'mask.png', width: 10 }, fill: { color: '#fff', style: 'solid' } },
type: 'inpaint_mask',
};
- const h = await createSamHarness({ backend, layers: [mask, control, raster] });
+ const h = await createSamHarness({
+ backend,
+ layers: [mask, control, raster],
+ runGraph: () => Promise.resolve({ height: 70, imageName: 'sam-mask.png', origin: 'test', width: 80 }),
+ uploadIntermediate: () => Promise.resolve({ height: 70, imageName: 'sam-source.png', width: 80 }),
+ });
h.setDocument({ ...h.engine.getDocument()!, bbox: { height: 70, width: 80, x: 10, y: 15 } });
const rasterExport = await h.engine.exportLayerPixels('raster');
const controlExport = await h.engine.exportLayerPixels('control');
@@ -13693,7 +13826,7 @@ describe('Select Object canvas engine integration', () => {
});
it('owns only the latest session and suppresses in-flight work from the replaced session', async () => {
- const output = createDeferred<{ imageName: string; origin: string }>();
+ const output = createDeferred<{ height: number; imageName: string; origin: string; width: number }>();
const layers = [samLayer('first'), samLayer('second', 30)];
const h = await createSamHarness({ layers, runGraph: () => output.promise });
h.engine.startSelectObject();
@@ -13701,12 +13834,12 @@ describe('Select Object canvas engine integration', () => {
input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },
});
const pending = h.engine.processSelectObjectSession();
- await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('processing'));
+ await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('processing-sam'));
h.setDocument({ ...h.engine.getDocument()!, selectedLayerId: 'second' });
expect(h.engine.startSelectObject()).toBe('started');
expect(h.engine.stores.samSession.get()).not.toBeNull();
- output.resolve({ imageName: 'late.png', origin: 'late' });
+ output.resolve({ height: 100, imageName: 'late.png', origin: 'late', width: 100 });
await expect(pending).resolves.toBe('stale');
expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: false });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index cce0455d26..c1d1f03f50 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -357,12 +357,12 @@ export interface CanvasEngineOptions {
imageResolver: ImageResolver;
/** Injectable Select Object queue/upload seams; production defaults use the utility queue. */
selectObjectDeps?: {
- uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;
+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ height: number; imageName: string; width: number }>;
runGraph(options: {
graph: Parameters<typeof runUtilityGraph>[0]['graph'];
outputNodeId?: string;
signal?: AbortSignal;
- }): Promise<Pick<UtilityGraphResult, 'imageName' | 'origin'>>;
+ }): Promise<UtilityGraphResult>;
};
/** Injectable filter queue/upload seams; production defaults use intermediate canvas images and the utility queue. */
filterDeps?: {
@@ -3162,7 +3162,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
const ctx = surface.ctx;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, surface.width, surface.height);
- ctx.drawImage(bitmap, 0, 0, surface.width, surface.height);
+ ctx.drawImage(bitmap, 0, 0);
ctx.globalCompositeOperation = 'source-in';
ctx.fillStyle = '#38bdf8';
ctx.fillRect(0, 0, surface.width, surface.height);
@@ -3257,7 +3257,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (signal?.aborted) {
throw new DOMException('Select Object upload was aborted.', 'AbortError');
}
- return { imageName: uploaded.imageName };
+ return uploaded;
},
},
projectId,
@@ -3321,8 +3321,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
const preview = state?.preview;
if (
!state ||
- state.status === 'processing' ||
- state.status === 'scheduled' ||
+ (state.status !== 'ready' && state.status !== 'error') ||
!preview ||
preview.guard !== selectObjectGuard
) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index 26b6cc31f5..6df17bb5a2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -248,7 +248,15 @@ export interface SamSessionSnapshot {
applyPolygonRefinement: boolean;
autoProcess: boolean;
isolatedPreview: boolean;
- status: 'ready' | 'scheduled' | 'processing' | 'committing' | 'error';
+ status:
+ | 'ready'
+ | 'scheduled'
+ | 'preparing-composite'
+ | 'uploading'
+ | 'processing-sam'
+ | 'rendering-preview'
+ | 'committing'
+ | 'error';
error: string | null;
hasPreview: boolean;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts
index 7c4161c85c..0ed04c4293 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts
@@ -34,7 +34,7 @@ describe('getSamActionEligibility', () => {
it('permits Apply and Save only for a current ready preview', () => {
expect(getSamActionEligibility(snapshot({ hasPreview: true }))).toMatchObject({ canApply: true, canSave: true });
- expect(getSamActionEligibility(snapshot({ hasPreview: true, status: 'processing' }))).toMatchObject({
+ expect(getSamActionEligibility(snapshot({ hasPreview: true, status: 'processing-sam' }))).toMatchObject({
canApply: false,
canProcess: false,
canSave: false,
@@ -52,7 +52,7 @@ describe('getSamActionEligibility', () => {
});
it('keeps Cancel available while processing and Reset available for every active session', () => {
- expect(getSamActionEligibility(snapshot({ status: 'processing' }))).toMatchObject({
+ expect(getSamActionEligibility(snapshot({ status: 'processing-sam' }))).toMatchObject({
canCancel: true,
canReset: true,
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx
index dc72d0269e..8e85148935 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx
@@ -27,7 +27,11 @@ export const getSamActionEligibility = (
session: SamSessionSnapshot,
isExternalInteractionLocked = false
): SamActionEligibility => {
- const isProcessing = session.status === 'processing';
+ const isProcessing =
+ session.status === 'preparing-composite' ||
+ session.status === 'uploading' ||
+ session.status === 'processing-sam' ||
+ session.status === 'rendering-preview';
const isCommitting = session.status === 'committing';
const actionsBlocked = isCommitting || isExternalInteractionLocked;
const hasReadyPreview = session.hasPreview && !isProcessing && !actionsBlocked;
@@ -127,7 +131,11 @@ export const SamOptions = ({
}
const eligibility = getSamActionEligibility(session, isExternalInteractionLocked);
- const isProcessing = session.status === 'processing';
+ const isProcessing =
+ session.status === 'preparing-composite' ||
+ session.status === 'uploading' ||
+ session.status === 'processing-sam' ||
+ session.status === 'rendering-preview';
return (
<HStack align="center" gap="2" maxW="calc(100vw - 2rem)" overflowX="auto">
@@ -248,6 +256,9 @@ export const SamOptions = ({
<Button disabled={!eligibility.canCancel} size="xs" variant="ghost" onClick={cancel}>
{t('common.cancel')}
</Button>
+ <Text fontSize="2xs" role="status">
+ {session.status.replaceAll('-', ' ')}
+ </Text>
{session.error ? (
<Text color="fg.error" fontSize="2xs" role="alert">
{session.error}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.ts
new file mode 100644
index 0000000000..9bbf75ee47
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.ts
@@ -0,0 +1,95 @@
+import type { CanvasCompositeExportGuard } from '@workbench/canvas-engine/engine';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { prepareSelectObjectSource, processSelectObjectSource } from './layerImageResult';
+
+const rect = { height: 12, width: 16, x: -5, y: 7 };
+const guard = {
+ bbox: rect,
+ candidates: [],
+ documentFingerprint: 'document:1',
+ documentGeneration: 1,
+ participants: [],
+ projectId: 'p1',
+} satisfies CanvasCompositeExportGuard;
+
+describe('Select Object image processing', () => {
+ it('carries exact upload dimensions into the prepared source', async () => {
+ await expect(
+ prepareSelectObjectSource({
+ exportComposite: () => Promise.resolve({ blob: new Blob(), guard, rect, status: 'ok' }),
+ uploadIntermediate: () => Promise.resolve({ height: 12, imageName: 'source.png', width: 16 }),
+ })
+ ).resolves.toEqual({
+ source: { guard, height: 12, imageName: 'source.png', rect, width: 16 },
+ status: 'ready',
+ });
+ });
+
+ it.each([
+ { height: 12, width: 15 },
+ { height: 12.5, width: 16 },
+ { height: 0, width: 16 },
+ { height: Number.NaN, width: 16 },
+ ])('rejects upload dimensions that do not exactly match the bbox: $width x $height', async (dimensions) => {
+ await expect(
+ prepareSelectObjectSource({
+ exportComposite: () => Promise.resolve({ blob: new Blob(), guard, rect, status: 'ok' }),
+ uploadIntermediate: () => Promise.resolve({ ...dimensions, imageName: 'source.png' }),
+ })
+ ).resolves.toMatchObject({ status: 'dimension-mismatch' });
+ });
+
+ it('rejects a visual input made empty by export-local conversion before enqueue', async () => {
+ const runGraph = vi.fn();
+ await expect(
+ processSelectObjectSource({
+ applyPolygonRefinement: false,
+ input: {
+ bbox: null,
+ excludePoints: [],
+ includePoints: [{ x: 100, y: 100 }],
+ type: 'visual',
+ },
+ invert: false,
+ model: 'segment-anything-2-large',
+ runGraph,
+ source: { guard, height: 12, imageName: 'source.png', rect, width: 16 },
+ })
+ ).resolves.toEqual({ status: 'invalid-input' });
+ expect(runGraph).not.toHaveBeenCalled();
+ });
+
+ it('rejects a prepared source whose threaded upload dimensions no longer match its bbox', async () => {
+ const runGraph = vi.fn();
+ await expect(
+ processSelectObjectSource({
+ applyPolygonRefinement: false,
+ input: { prompt: 'cat', type: 'prompt' },
+ invert: false,
+ model: 'segment-anything-2-large',
+ runGraph,
+ source: { guard, height: 12, imageName: 'source.png', rect, width: 15 },
+ })
+ ).resolves.toMatchObject({ status: 'dimension-mismatch' });
+ expect(runGraph).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { height: 12, width: 15 },
+ { height: 11.5, width: 16 },
+ { height: Number.POSITIVE_INFINITY, width: 16 },
+ ])('rejects mismatched SAM ImageOutput metadata without returning a stretchable preview', async (dimensions) => {
+ await expect(
+ processSelectObjectSource({
+ applyPolygonRefinement: false,
+ input: { prompt: 'cat', type: 'prompt' },
+ invert: false,
+ model: 'segment-anything-2-large',
+ runGraph: () => Promise.resolve({ ...dimensions, imageName: 'mask.png', origin: 'test' }),
+ source: { guard, height: 12, imageName: 'source.png', rect, width: 16 },
+ })
+ ).resolves.toMatchObject({ status: 'dimension-mismatch' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts
index 8b80a233ed..b8e138aaac 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts
@@ -4,7 +4,7 @@ import type { Rect } from '@workbench/canvas-engine/types';
import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';
import type { CanvasImageRef } from '@workbench/types';
-import { buildSamGraph, documentToExportLocalSamInput } from '@workbench/generation/canvas/samGraph';
+import { buildSamGraph, documentToExportLocalSamInput, isSamInputValid } from '@workbench/generation/canvas/samGraph';
export interface SelectObjectReadyResult {
status: 'ready';
@@ -16,14 +16,14 @@ export interface SelectObjectReadyResult {
export type SelectObjectRunResult =
| SelectObjectReadyResult
| { status: 'aborted' | 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' }
+ | { status: 'invalid-input' }
+ | { status: 'dimension-mismatch'; message: string }
| { status: 'failed'; message: string };
export interface SelectObjectRunnerDeps {
exportComposite(): Promise<ExportCanvasCompositeBlobResult>;
- uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;
- runGraph(
- options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>
- ): Promise<Pick<UtilityGraphResult, 'imageName' | 'origin'>>;
+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ height: number; imageName: string; width: number }>;
+ runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>): Promise<UtilityGraphResult>;
}
const isAbortError = (error: unknown): boolean => error instanceof Error && error.name === 'AbortError';
@@ -32,7 +32,9 @@ const errorMessage = (error: unknown): string => (error instanceof Error ? error
export interface SelectObjectPreparedSource {
guard: CanvasCompositeExportGuard;
imageName: string;
+ height: number;
rect: Rect;
+ width: number;
}
export type PrepareSelectObjectSourceResult =
@@ -41,7 +43,8 @@ export type PrepareSelectObjectSourceResult =
export const prepareSelectObjectSource = async (
deps: Pick<SelectObjectRunnerDeps, 'exportComposite' | 'uploadIntermediate'>,
- signal?: AbortSignal
+ signal?: AbortSignal,
+ onPhase?: (phase: 'uploading') => void
): Promise<PrepareSelectObjectSourceResult> => {
if (signal?.aborted) {
return { status: 'aborted' };
@@ -54,12 +57,25 @@ export const prepareSelectObjectSource = async (
if (exported.status !== 'ok') {
return exported;
}
+ onPhase?.('uploading');
const uploaded = await deps.uploadIntermediate(exported.blob, signal);
if (signal?.aborted) {
return { status: 'aborted' };
}
+ if (!hasExactDimensions(uploaded, exported.rect)) {
+ return {
+ message: `Uploaded Select Object source dimensions ${String(uploaded.width)}x${String(uploaded.height)} do not match ${exported.rect.width}x${exported.rect.height}.`,
+ status: 'dimension-mismatch',
+ };
+ }
return {
- source: { guard: exported.guard, imageName: uploaded.imageName, rect: exported.rect },
+ source: {
+ guard: exported.guard,
+ height: uploaded.height,
+ imageName: uploaded.imageName,
+ rect: exported.rect,
+ width: uploaded.width,
+ },
status: 'ready',
};
} catch (error) {
@@ -78,8 +94,22 @@ export interface ProcessSelectObjectSourceOptions {
applyPolygonRefinement: boolean;
signal?: AbortSignal;
runGraph: SelectObjectRunnerDeps['runGraph'];
+ onPhase?: (phase: 'processing-sam') => void;
}
+const hasExactDimensions = (
+ value: { height: number; width: number },
+ expected: { height: number; width: number }
+): boolean =>
+ Number.isFinite(value.width) &&
+ Number.isInteger(value.width) &&
+ value.width > 0 &&
+ Number.isFinite(value.height) &&
+ Number.isInteger(value.height) &&
+ value.height > 0 &&
+ value.width === expected.width &&
+ value.height === expected.height;
+
export const processSelectObjectSource = async (
options: ProcessSelectObjectSourceOptions
): Promise<SelectObjectRunResult> => {
@@ -87,13 +117,24 @@ export const processSelectObjectSource = async (
return { status: 'aborted' };
}
try {
+ if (!hasExactDimensions(options.source, options.source.rect)) {
+ return {
+ message: `Uploaded Select Object source dimensions ${String(options.source.width)}x${String(options.source.height)} do not match ${options.source.rect.width}x${options.source.rect.height}.`,
+ status: 'dimension-mismatch',
+ };
+ }
+ const input = documentToExportLocalSamInput(options.input, options.source.rect);
+ if (!isSamInputValid(input)) {
+ return { status: 'invalid-input' };
+ }
const built = buildSamGraph({
applyPolygonRefinement: options.applyPolygonRefinement,
imageName: options.source.imageName,
- input: documentToExportLocalSamInput(options.input, options.source.rect),
+ input,
invert: options.invert,
model: options.model,
});
+ options.onPhase?.('processing-sam');
const output = await options.runGraph({
graph: built.graph,
outputNodeId: built.outputNodeId,
@@ -102,12 +143,18 @@ export const processSelectObjectSource = async (
if (options.signal?.aborted) {
return { status: 'aborted' };
}
+ if (!hasExactDimensions(output, options.source.rect)) {
+ return {
+ message: `SAM output dimensions ${String(output.width)}x${String(output.height)} do not match ${options.source.rect.width}x${options.source.rect.height}.`,
+ status: 'dimension-mismatch',
+ };
+ }
return {
guard: options.source.guard,
image: {
- height: options.source.rect.height,
+ height: output.height,
imageName: output.imageName,
- width: options.source.rect.width,
+ width: output.width,
},
rect: options.source.rect,
status: 'ready',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts
index 2c057876ce..fa07352a13 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts
@@ -68,8 +68,10 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})
isGuardCurrent: (candidate) => candidate === currentGuard,
publishPreview: vi.fn((): undefined => undefined),
cleanupPreview: vi.fn(),
- runGraph: vi.fn(() => Promise.resolve({ imageName: 'result.png', origin: 'webv2:util:test' })),
- uploadIntermediate: vi.fn(() => Promise.resolve({ imageName: 'input.png' })),
+ runGraph: vi.fn(() =>
+ Promise.resolve({ height: 12, imageName: 'result.png', origin: 'webv2:util:test', width: 16 })
+ ),
+ uploadIntermediate: vi.fn(() => Promise.resolve({ height: 12, imageName: 'input.png', width: 16 })),
...overrides,
};
const session = createSelectObjectSession({ deps, projectId: 'p1' });
@@ -110,6 +112,40 @@ describe('createSelectObjectSession', () => {
});
});
+ it('reports phases from the composite, upload, SAM, render, and ready boundaries', async () => {
+ const harness = createHarness();
+ const phases: string[] = [];
+ harness.session.subscribe(() => phases.push(harness.session.getSnapshot().status));
+
+ await expect(harness.session.process()).resolves.toBe('published');
+
+ expect(phases).toEqual(['preparing-composite', 'uploading', 'processing-sam', 'rendering-preview', 'ready']);
+ });
+
+ it('does not publish a stale request phase after a replacement retry starts', async () => {
+ const oldUpload = deferred<{ height: number; imageName: string; width: number }>();
+ const harness = createHarness({
+ uploadIntermediate: vi
+ .fn()
+ .mockImplementationOnce(() => oldUpload.promise)
+ .mockResolvedValueOnce({ height: 12, imageName: 'new-source.png', width: 16 }),
+ });
+ const phases: string[] = [];
+ harness.session.subscribe(() => phases.push(harness.session.getSnapshot().status));
+ const oldPending = harness.session.process();
+ await vi.waitFor(() => expect(harness.session.getSnapshot().status).toBe('uploading'));
+
+ harness.controller.invalidateSource('p1', layer.id);
+ const newPending = harness.session.process();
+ await expect(newPending).resolves.toBe('published');
+ const readyIndex = phases.lastIndexOf('ready');
+ oldUpload.resolve({ height: 12, imageName: 'old-source.png', width: 16 });
+ await expect(oldPending).resolves.toBe('stale');
+
+ expect(phases.slice(readyIndex + 1)).toEqual([]);
+ expect(harness.session.getSnapshot()).toMatchObject({ status: 'ready' });
+ });
+
it('contains subscriber exceptions so healthy subscribers and processing continue', async () => {
const harness = createHarness();
const throwing = vi.fn(() => {
@@ -156,6 +192,22 @@ describe('createSelectObjectSession', () => {
expect(harness.session.getSnapshot()).toEqual(expect.objectContaining({ error: 'graph failed', status: 'error' }));
});
+ it('retries the same input after a dimension mismatch and publishes the corrected output', async () => {
+ const runGraph = vi
+ .fn()
+ .mockResolvedValueOnce({ height: 12, imageName: 'bad.png', origin: 'test', width: 15 })
+ .mockResolvedValueOnce({ height: 12, imageName: 'good.png', origin: 'test', width: 16 });
+ const harness = createHarness({ runGraph });
+
+ await expect(harness.session.process()).resolves.toBe('error');
+ expect(harness.session.getSnapshot()).toMatchObject({ preview: null, status: 'error' });
+ await expect(harness.session.process()).resolves.toBe('published');
+
+ expect(runGraph).toHaveBeenCalledTimes(2);
+ expect(harness.session.getSnapshot()).toMatchObject({ error: null, status: 'ready' });
+ expect(harness.session.getSnapshot().preview?.image.imageName).toBe('good.png');
+ });
+
it('reports routing failures without discarding the preview and Reset clears the error', async () => {
const harness = createHarness();
await harness.session.process();
@@ -227,8 +279,8 @@ describe('createSelectObjectSession', () => {
);
it('starts an immediate same-input retry after invalidation when old work ignores abort', async () => {
- const older = deferred<{ imageName: string; origin: string }>();
- const newer = deferred<{ imageName: string; origin: string }>();
+ const older = deferred<{ height: number; imageName: string; origin: string; width: number }>();
+ const newer = deferred<{ height: number; imageName: string; origin: string; width: number }>();
const harness = createHarness({
runGraph: vi
.fn()
@@ -244,11 +296,11 @@ describe('createSelectObjectSession', () => {
expect(newPending).not.toBe(oldPending);
await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledTimes(2));
expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);
- older.resolve({ imageName: 'old.png', origin: 'old' });
+ older.resolve({ height: 12, imageName: 'old.png', origin: 'old', width: 16 });
await expect(oldPending).resolves.toBe('stale');
expect(harness.session.process()).toBe(newPending);
- newer.resolve({ imageName: 'new.png', origin: 'new' });
+ newer.resolve({ height: 12, imageName: 'new.png', origin: 'new', width: 16 });
await expect(newPending).resolves.toBe('published');
expect(harness.session.getSnapshot().preview?.image.imageName).toBe('new.png');
await expect(harness.session.process()).resolves.toBe('deduped');
@@ -281,12 +333,12 @@ describe('createSelectObjectSession', () => {
});
it('starts an immediate same-input retry when invalidation aborts an upload that ignores its signal', async () => {
- const oldUpload = deferred<{ imageName: string }>();
+ const oldUpload = deferred<{ height: number; imageName: string; width: number }>();
const harness = createHarness({
uploadIntermediate: vi
.fn()
.mockImplementationOnce(() => oldUpload.promise)
- .mockImplementationOnce(() => Promise.resolve({ imageName: 'new-input.png' })),
+ .mockImplementationOnce(() => Promise.resolve({ height: 12, imageName: 'new-input.png', width: 16 })),
});
const oldPending = harness.session.process();
await vi.waitFor(() => expect(harness.deps.uploadIntermediate).toHaveBeenCalledOnce());
@@ -299,7 +351,7 @@ describe('createSelectObjectSession', () => {
expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);
expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);
expect(harness.deps.runGraph).toHaveBeenCalledOnce();
- oldUpload.resolve({ imageName: 'old-input.png' });
+ oldUpload.resolve({ height: 12, imageName: 'old-input.png', width: 16 });
await expect(oldPending).resolves.toBe('stale');
expect(harness.session.getSnapshot().preview?.sourceImageName).toBe('new-input.png');
await expect(harness.session.process()).resolves.toBe('deduped');
@@ -335,7 +387,7 @@ describe('createSelectObjectSession', () => {
it('transitions an identical scheduled auto-run back to processing when work is already in flight', async () => {
vi.useFakeTimers();
- const graph = deferred<{ imageName: string; origin: string }>();
+ const graph = deferred<{ height: number; imageName: string; origin: string; width: number }>();
const harness = createHarness({ runGraph: vi.fn(() => graph.promise) });
const pending = harness.session.process();
await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());
@@ -344,10 +396,10 @@ describe('createSelectObjectSession', () => {
expect(harness.session.getSnapshot().status).toBe('scheduled');
await vi.advanceTimersByTimeAsync(1_000);
- expect(harness.session.getSnapshot()).toMatchObject({ error: null, status: 'processing' });
+ expect(harness.session.getSnapshot()).toMatchObject({ error: null, status: 'processing-sam' });
expect(vi.getTimerCount()).toBe(0);
expect(harness.deps.runGraph).toHaveBeenCalledOnce();
- graph.resolve({ imageName: 'result.png', origin: 'test' });
+ graph.resolve({ height: 12, imageName: 'result.png', origin: 'test', width: 16 });
await expect(pending).resolves.toBe('published');
});
@@ -384,7 +436,7 @@ describe('createSelectObjectSession', () => {
it('immediately stales a delayed auto-run when input changes before the replacement debounce', async () => {
vi.useFakeTimers();
- const oldGraph = deferred<{ imageName: string; origin: string }>();
+ const oldGraph = deferred<{ height: number; imageName: string; origin: string; width: number }>();
const harness = createHarness({ runGraph: vi.fn(() => oldGraph.promise) });
harness.session.update({ autoProcess: true });
await vi.advanceTimersByTimeAsync(1_000);
@@ -392,7 +444,7 @@ describe('createSelectObjectSession', () => {
harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });
expect(harness.session.getSnapshot()).toMatchObject({ preview: null, status: 'scheduled' });
- oldGraph.resolve({ imageName: 'old.png', origin: 'old' });
+ oldGraph.resolve({ height: 12, imageName: 'old.png', origin: 'old', width: 16 });
await vi.advanceTimersByTimeAsync(999);
expect(harness.deps.publishPreview).not.toHaveBeenCalled();
@@ -406,7 +458,7 @@ describe('createSelectObjectSession', () => {
['refinement', { applyPolygonRefinement: true }],
] as const)('immediately aborts in-flight work and clears preview for a %s update', async (_label, update) => {
const signals: AbortSignal[] = [];
- const graph = deferred<{ imageName: string; origin: string }>();
+ const graph = deferred<{ height: number; imageName: string; origin: string; width: number }>();
const harness = createHarness({
runGraph: vi.fn((options) => {
if (options.signal) {
@@ -422,7 +474,7 @@ describe('createSelectObjectSession', () => {
expect(signals[0]?.aborted).toBe(true);
expect(harness.session.getSnapshot().preview).toBeNull();
- graph.resolve({ imageName: 'stale.png', origin: 'stale' });
+ graph.resolve({ height: 12, imageName: 'stale.png', origin: 'stale', width: 16 });
await expect(pending).resolves.toBe('stale');
expect(harness.deps.publishPreview).not.toHaveBeenCalled();
});
@@ -445,7 +497,7 @@ describe('createSelectObjectSession', () => {
});
it('changes isolation during processing without aborting or rerunning the request', async () => {
- const graph = deferred<{ imageName: string; origin: string }>();
+ const graph = deferred<{ height: number; imageName: string; origin: string; width: number }>();
const signals: AbortSignal[] = [];
const harness = createHarness({
runGraph: vi.fn((options) => {
@@ -459,7 +511,7 @@ describe('createSelectObjectSession', () => {
await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());
harness.session.update({ isolatedPreview: false });
- graph.resolve({ imageName: 'result.png', origin: 'test' });
+ graph.resolve({ height: 12, imageName: 'result.png', origin: 'test', width: 16 });
await expect(pending).resolves.toBe('published');
expect(signals[0]?.aborted).toBe(false);
@@ -498,8 +550,8 @@ describe('createSelectObjectSession', () => {
});
it('publishes only the latest request when graph completions arrive out of order', async () => {
- const older = deferred<{ imageName: string; origin: string }>();
- const newer = deferred<{ imageName: string; origin: string }>();
+ const older = deferred<{ height: number; imageName: string; origin: string; width: number }>();
+ const newer = deferred<{ height: number; imageName: string; origin: string; width: number }>();
const harness = createHarness({
runGraph: vi
.fn()
@@ -512,9 +564,9 @@ describe('createSelectObjectSession', () => {
const newPending = harness.session.process();
await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledTimes(2));
- newer.resolve({ imageName: 'new.png', origin: 'new' });
+ newer.resolve({ height: 12, imageName: 'new.png', origin: 'new', width: 16 });
await expect(newPending).resolves.toBe('published');
- older.resolve({ imageName: 'old.png', origin: 'old' });
+ older.resolve({ height: 12, imageName: 'old.png', origin: 'old', width: 16 });
await expect(oldPending).resolves.toBe('stale');
expect(harness.deps.publishPreview).toHaveBeenCalledOnce();
@@ -537,11 +589,11 @@ describe('createSelectObjectSession', () => {
runGraph:
boundary === 'queue'
? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['runGraph']>)
- : vi.fn(() => Promise.resolve({ imageName: 'result.png', origin: 'test' })),
+ : vi.fn(() => Promise.resolve({ height: 12, imageName: 'result.png', origin: 'test', width: 16 })),
uploadIntermediate:
boundary === 'upload'
? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['uploadIntermediate']>)
- : vi.fn(() => Promise.resolve({ imageName: 'input.png' })),
+ : vi.fn(() => Promise.resolve({ height: 12, imageName: 'input.png', width: 16 })),
});
const pending = harness.session.process();
await vi.waitFor(() => {
@@ -560,9 +612,9 @@ describe('createSelectObjectSession', () => {
if (boundary === 'export') {
wait.resolve({ blob, guard, rect, status: 'ok' });
} else if (boundary === 'upload') {
- wait.resolve({ imageName: 'input.png' });
+ wait.resolve({ height: 12, imageName: 'input.png', width: 16 });
} else if (boundary === 'queue') {
- wait.resolve({ imageName: 'result.png', origin: 'test' });
+ wait.resolve({ height: 12, imageName: 'result.png', origin: 'test', width: 16 });
} else {
wait.resolve('decoded');
}
@@ -593,11 +645,11 @@ describe('createSelectObjectSession', () => {
runGraph:
boundary === 'queue'
? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['runGraph']>)
- : vi.fn(() => Promise.resolve({ imageName: 'result.png', origin: 'test' })),
+ : vi.fn(() => Promise.resolve({ height: 12, imageName: 'result.png', origin: 'test', width: 16 })),
uploadIntermediate:
boundary === 'upload'
? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['uploadIntermediate']>)
- : vi.fn(() => Promise.resolve({ imageName: 'input.png' })),
+ : vi.fn(() => Promise.resolve({ height: 12, imageName: 'input.png', width: 16 })),
});
harness.session.update({ input: { prompt: 'keep me', type: 'prompt' }, invert: true });
const pending = harness.session.process();
@@ -617,9 +669,9 @@ describe('createSelectObjectSession', () => {
if (boundary === 'export') {
wait.resolve({ blob, guard, rect, status: 'ok' });
} else if (boundary === 'upload') {
- wait.resolve({ imageName: 'input.png' });
+ wait.resolve({ height: 12, imageName: 'input.png', width: 16 });
} else if (boundary === 'queue') {
- wait.resolve({ imageName: 'result.png', origin: 'test' });
+ wait.resolve({ height: 12, imageName: 'result.png', origin: 'test', width: 16 });
} else {
wait.resolve('decoded');
}
@@ -652,14 +704,14 @@ describe('createSelectObjectSession', () => {
it('reset cancels work and scheduling, clears preview/cache, and restores defaults', async () => {
vi.useFakeTimers();
- const graph = deferred<{ imageName: string; origin: string }>();
+ const graph = deferred<{ height: number; imageName: string; origin: string; width: number }>();
const harness = createHarness({ runGraph: vi.fn(() => graph.promise) });
harness.session.update({ autoProcess: true, invert: true, model: 'segment-anything-huge' });
const pending = harness.session.process();
await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());
harness.session.reset();
- graph.resolve({ imageName: 'late.png', origin: 'test' });
+ graph.resolve({ height: 12, imageName: 'late.png', origin: 'test', width: 16 });
await expect(pending).resolves.toBe('stale');
expect(harness.session.getSnapshot()).toEqual({
@@ -713,7 +765,7 @@ describe('createSelectObjectSession', () => {
});
it('dispose aborts in-flight processing and suppresses its completion', async () => {
- const graph = deferred<{ imageName: string; origin: string }>();
+ const graph = deferred<{ height: number; imageName: string; origin: string; width: number }>();
const signals: AbortSignal[] = [];
const harness = createHarness({
runGraph: vi.fn((options) => {
@@ -729,7 +781,7 @@ describe('createSelectObjectSession', () => {
harness.session.dispose();
expect(signals[0]?.aborted).toBe(true);
- graph.resolve({ imageName: 'late.png', origin: 'late' });
+ graph.resolve({ height: 12, imageName: 'late.png', origin: 'late', width: 16 });
await expect(pending).resolves.toBe('stale');
expect(harness.deps.publishPreview).not.toHaveBeenCalled();
expect(harness.unsubscribe).toHaveBeenCalledOnce();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts
index f3e83ae59b..ed7e5f9069 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts
@@ -14,7 +14,14 @@ import type { SelectObjectPreparedSource, SelectObjectReadyResult } from './laye
import { prepareSelectObjectSource, processSelectObjectSource } from './layerImageResult';
-export type SelectObjectSessionStatus = 'ready' | 'scheduled' | 'processing' | 'error';
+export type SelectObjectSessionStatus =
+ | 'ready'
+ | 'scheduled'
+ | 'preparing-composite'
+ | 'uploading'
+ | 'processing-sam'
+ | 'rendering-preview'
+ | 'error';
export interface SelectObjectSessionPreview<T> {
data: T;
@@ -44,10 +51,8 @@ export interface SelectObjectSessionDeps<T> {
captureGuard(): CanvasCompositeExportGuard | null;
controller: CanvasOperationController;
exportComposite(): Promise<ExportCanvasCompositeBlobResult>;
- uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;
- runGraph(
- options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>
- ): Promise<Pick<UtilityGraphResult, 'imageName' | 'origin'>>;
+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ height: number; imageName: string; width: number }>;
+ runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>): Promise<UtilityGraphResult>;
decodePreview(result: SelectObjectReadyResult, signal: AbortSignal): Promise<T>;
publishPreview(preview: SelectObjectSessionPreview<T>): undefined;
cleanupPreview(): void;
@@ -109,7 +114,7 @@ const stableInputHash = <T>(state: SelectObjectSessionState<T>): string => {
};
const resultError = (result: Exclude<Awaited<ReturnType<typeof prepareSelectObjectSource>>, { status: 'ready' }>) =>
- result.status === 'failed' ? result.message : `Select Object source is ${result.status}.`;
+ 'message' in result ? result.message : `Select Object source is ${result.status}.`;
export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOptions<T>): SelectObjectSession<T> => {
const { deps, projectId } = options;
@@ -120,6 +125,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
let requestToken = 0;
let lastPublishedHash: string | null = null;
let pendingHash: string | null = null;
+ let pendingPhase: SelectObjectSessionStatus | null = null;
let pendingProcess: Promise<SelectObjectSessionProcessResult> | null = null;
let timer: ReturnType<typeof setTimeout> | null = null;
let startingOperation = false;
@@ -149,9 +155,17 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
}
};
+ const publishPhase = (token: number, status: SelectObjectSessionStatus): void => {
+ if (!disposed && token === requestToken) {
+ pendingPhase = status;
+ publishState({ ...state, error: null, status });
+ }
+ };
+
const clearSource = (): void => {
requestToken += 1;
pendingHash = null;
+ pendingPhase = null;
pendingProcess = null;
source = null;
operation = null;
@@ -209,13 +223,14 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
const ensureSource = async (
guard: CanvasCompositeExportGuard,
- signal: AbortSignal
+ signal: AbortSignal,
+ token: number
): Promise<SelectObjectPreparedSource> => {
if (source?.guard === guard && isGuardCurrent(guard)) {
return source;
}
source = null;
- const prepared = await prepareSelectObjectSource(deps, signal);
+ const prepared = await prepareSelectObjectSource(deps, signal, (phase) => publishPhase(token, phase));
if (prepared.status !== 'ready') {
throw new Error(resultError(prepared));
}
@@ -253,10 +268,11 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
operationGuard = guard;
}
- publishState({ ...state, sourceGuard: guard, status: 'processing' });
+ pendingPhase = 'preparing-composite';
+ publishState({ ...state, sourceGuard: guard, status: 'preparing-composite' });
const result = await operation.run(
async (signal) => {
- const preparedSource = await ensureSource(guard, signal);
+ const preparedSource = await ensureSource(guard, signal, token);
if (signal.aborted || token !== requestToken) {
throw new DOMException('Select Object source preparation was aborted.', 'AbortError');
}
@@ -266,6 +282,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
invert: requestState.invert,
model: requestState.model,
runGraph: deps.runGraph,
+ onPhase: (phase) => publishPhase(token, phase),
signal,
source: preparedSource,
});
@@ -273,10 +290,9 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
if (processed.status === 'aborted') {
throw new DOMException('Select Object processing was aborted.', 'AbortError');
}
- throw new Error(
- processed.status === 'failed' ? processed.message : `Select Object is ${processed.status}.`
- );
+ throw new Error('message' in processed ? processed.message : `Select Object is ${processed.status}.`);
}
+ publishPhase(token, 'rendering-preview');
const data = await deps.decodePreview(processed, signal);
if (signal.aborted) {
throw new DOMException('Select Object preview decode was aborted.', 'AbortError');
@@ -355,7 +371,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
}
const hash = stableInputHash(state);
if (hash === pendingHash && pendingProcess) {
- publishState({ ...state, error: null, status: 'processing' });
+ publishState({ ...state, error: null, status: pendingPhase ?? 'preparing-composite' });
return pendingProcess;
}
if (
@@ -378,11 +394,11 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
return Promise.resolve('error');
}
pendingHash = hash;
- publishState({ ...state, error: null, status: 'processing' });
const requestState = state;
const promise = runRequest(token, hash, requestState, guard).finally(() => {
if (token === requestToken) {
pendingHash = null;
+ pendingPhase = null;
pendingProcess = null;
}
});
@@ -394,6 +410,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
clearTimer();
requestToken += 1;
pendingHash = null;
+ pendingPhase = null;
pendingProcess = null;
operation?.cancel();
operation = null;
@@ -405,6 +422,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
const invalidateProcessingState = (): void => {
requestToken += 1;
pendingHash = null;
+ pendingPhase = null;
pendingProcess = null;
lastPublishedHash = null;
operation?.reset();
@@ -429,6 +447,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
clearTimer();
requestToken += 1;
pendingHash = null;
+ pendingPhase = null;
pendingProcess = null;
lastPublishedHash = null;
unsubscribeController?.();
@@ -446,11 +465,12 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
getSnapshot: () => state,
interruptProcessing: () => {
clearTimer();
- if (disposed || (state.status !== 'processing' && state.status !== 'scheduled')) {
+ if (disposed || state.status === 'ready' || state.status === 'error') {
return;
}
requestToken += 1;
pendingHash = null;
+ pendingPhase = null;
pendingProcess = null;
lastPublishedHash = null;
operation?.interruptProcessing();