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): reset and reuse sam sources

joshistoastd91ee66d9d12
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 a8e745f2c8..aa3850c40d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -12921,6 +12921,92 @@ describe('Select Object canvas engine integration', () => {
h.engine.dispose();
});
+ it('resets edited inputs and point mode immediately after launch without requiring a preview guard', async () => {
+ const h = await createSamHarness();
+ expect(h.engine.startSelectObject()).toBe('started');
+ h.engine.updateSelectObjectSession({
+ input: {
+ bbox: { height: 10, width: 10, x: 1, y: 2 },
+ excludePoints: [{ x: 4, y: 5 }],
+ includePoints: [{ x: 2, y: 3 }],
+ type: 'visual',
+ },
+ invert: true,
+ pointLabel: 'exclude',
+ });
+
+ expect(h.engine.resetSelectObjectSession()).toBe('updated');
+
+ expect(h.engine.stores.samSession.get()).toMatchObject({
+ error: null,
+ hasPreview: false,
+ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },
+ invert: false,
+ pointLabel: 'include',
+ status: 'ready',
+ });
+ expect(h.engine.canvasOperations.getSnapshot()).toMatchObject({ status: 'active' });
+ h.engine.dispose();
+ });
+
+ it('resets after a first not-ready Process while preserving lifecycle ownership', async () => {
+ const bbox = { height: 100, width: 100, x: 0, y: 0 };
+ const reactive = createReactiveStore(samDocument());
+ const engine = createCanvasEngine({
+ backend: withSamPreviewBitmapDimensions(createTestStubRasterBackend()),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ selectObjectDeps: {
+ runGraph: () => Promise.resolve({ height: 100, imageName: 'mask.png', origin: 'test', width: 100 }),
+ uploadIntermediate: () => Promise.resolve({ height: 100, imageName: 'source.png', width: 100 }),
+ },
+ store: reactive.store,
+ });
+ expect(engine.startSelectObject()).toBe('started');
+ engine.updateSelectObjectSession({ input: { prompt: 'cat', type: 'prompt' }, invert: true });
+ await expect(engine.processSelectObjectSession()).resolves.toBe('error');
+ expect(engine.stores.samSession.get()).toMatchObject({ error: { code: 'not-ready' }, status: 'error' });
+
+ expect(engine.resetSelectObjectSession()).toBe('updated');
+
+ expect(engine.stores.samSession.get()).toMatchObject({
+ error: null,
+ hasPreview: false,
+ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },
+ invert: false,
+ pointLabel: 'include',
+ status: 'ready',
+ });
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({ status: 'active' });
+ expect(engine.getDocument()?.bbox).toEqual(bbox);
+ engine.dispose();
+ });
+
+ it('reuses one uploaded composite across fresh engine guards for point, invert, and refinement changes', async () => {
+ const uploadIntermediate = vi.fn(() => Promise.resolve({ height: 100, imageName: 'source.png', width: 100 }));
+ const runGraph = vi.fn(() => Promise.resolve({ height: 100, imageName: 'mask.png', origin: 'test', width: 100 }));
+ const h = await createSamHarness({ runGraph, uploadIntermediate });
+ expect(h.engine.startSelectObject()).toBe('started');
+ h.engine.updateSelectObjectSession({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 2, y: 2 }], type: 'visual' },
+ });
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');
+
+ h.engine.updateSelectObjectSession({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 3, y: 3 }], type: 'visual' },
+ });
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');
+ h.engine.updateSelectObjectSession({ invert: true });
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');
+ h.engine.updateSelectObjectSession({ applyPolygonRefinement: true });
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');
+
+ expect(uploadIntermediate).toHaveBeenCalledOnce();
+ expect(runGraph).toHaveBeenCalledTimes(4);
+ h.engine.dispose();
+ });
+
it('starts from every visible participant without changing the selected layer', async () => {
const h = await createSamHarness({ layers: [samLayer('first'), samLayer('second', 30)] });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 00596ed90b..e950eee60f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -944,6 +944,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
let selectObjectSession: SelectObjectSession<RasterSurface> | null = null;
let selectObjectUnsubscribe: (() => void) | null = null;
let selectObjectControllerUnsubscribe: (() => void) | null = null;
+ let selectObjectLifecycleGuard: SelectObjectLifecycleGuard | null = null;
let selectObjectGuard: CanvasCompositeExportGuard | null = null;
let selectObjectSourceRect: Rect | null = null;
let selectObjectPointLabel: SamPointLabel = 'include';
@@ -3262,6 +3263,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
selectObjectUnsubscribe = null;
selectObjectControllerUnsubscribe?.();
selectObjectControllerUnsubscribe = null;
+ selectObjectLifecycleGuard = null;
selectObjectGuard = null;
selectObjectSourceRect = null;
selectObjectPointLabel = 'include';
@@ -3291,6 +3293,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
clearOwnedFilterSession();
clearOwnedSelectObjectSession();
+ selectObjectLifecycleGuard = lifecycleGuard;
selectObjectGuard = null;
selectObjectSourceRect = { ...lifecycleGuard.bbox };
const operation = canvasOperations.start({
@@ -3299,6 +3302,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
identity: { kind: 'select-object', projectId },
});
if (!operation) {
+ selectObjectLifecycleGuard = null;
selectObjectGuard = null;
selectObjectSourceRect = null;
return 'not-ready';
@@ -3568,11 +3572,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return 'blocked';
}
const session = selectObjectSession;
- const guard = selectObjectGuard;
- if (!session || !guard) {
+ const lifecycleGuard = selectObjectLifecycleGuard;
+ const operation = canvasOperations.getSnapshot();
+ if (
+ !session ||
+ !lifecycleGuard ||
+ !isSelectObjectLifecycleGuardCurrent(lifecycleGuard) ||
+ operation.status !== 'active' ||
+ operation.identity.kind !== 'select-object' ||
+ operation.identity.projectId !== projectId
+ ) {
return 'stale';
}
invalidateSelectObjectCommit();
+ selectObjectGuard = null;
selectObjectPointLabel = 'include';
session.reset();
session.update({ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' } });
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 a35298478b..e2131d323a 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
@@ -79,6 +79,10 @@ describe('getSamActionEligibility', () => {
canCancel: true,
canReset: true,
});
+ expect(getSamActionEligibility(snapshot({ error: { code: 'not-ready' }, status: 'error' }))).toMatchObject({
+ canReset: true,
+ });
+ expect(getSamActionEligibility(snapshot({ status: 'ready' }))).toMatchObject({ canReset: true });
});
it('disables every mutating control while committing and keeps Cancel available', () => {
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 0767744be6..cfbaa76581 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts
@@ -35,6 +35,12 @@ const replacementGuard: CanvasCompositeExportGuard = {
documentFingerprint: 'document:4',
participants: [{ cacheVersion: 4, layer, layerId: layer.id }],
};
+const cloneGuard = (source: CanvasCompositeExportGuard = guard): CanvasCompositeExportGuard => ({
+ ...source,
+ bbox: { ...source.bbox },
+ candidates: source.candidates.map((candidate) => ({ ...candidate })),
+ participants: source.participants.map((participant) => ({ ...participant })),
+});
const lifecycleGuard: SelectObjectLifecycleGuard = {
bbox: guard.bbox,
documentGeneration: guard.documentGeneration,
@@ -346,6 +352,72 @@ describe('createSelectObjectSession', () => {
expect(harness.session.getSnapshot().sourceGuard).toBe(replacementGuard);
});
+ it('rebinds a prepared source across fresh structurally equal guards without another export or upload', async () => {
+ let currentGuard = cloneGuard();
+ const harness = createHarness({
+ captureGuard: () => currentGuard,
+ exportComposite: vi.fn(() => Promise.resolve({ blob, guard: currentGuard, rect, status: 'ok' as const })),
+ isGuardCurrent: (candidate) =>
+ candidate.documentFingerprint === currentGuard.documentFingerprint &&
+ candidate.documentGeneration === currentGuard.documentGeneration,
+ });
+ harness.session.update({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: -4, y: 8 }], type: 'visual' },
+ });
+
+ await expect(harness.session.process()).resolves.toBe('published');
+ for (const update of [
+ { input: { bbox: null, excludePoints: [], includePoints: [{ x: -3, y: 9 }], type: 'visual' as const } },
+ { invert: true },
+ { applyPolygonRefinement: true },
+ ]) {
+ currentGuard = cloneGuard();
+ harness.session.update(update);
+ await expect(harness.session.process()).resolves.toBe('published');
+ expect(harness.session.getSnapshot().sourceGuard).toBe(currentGuard);
+ }
+
+ expect(harness.deps.exportComposite).toHaveBeenCalledOnce();
+ expect(harness.deps.uploadIntermediate).toHaveBeenCalledOnce();
+ expect(harness.deps.runGraph).toHaveBeenCalledTimes(4);
+ });
+
+ it.each([
+ ['bbox', { ...cloneGuard(), bbox: { ...guard.bbox, x: guard.bbox.x + 1 }, documentFingerprint: 'bbox:4' }],
+ [
+ 'cache participant',
+ {
+ ...cloneGuard(replacementGuard),
+ documentFingerprint: 'cache:4',
+ },
+ ],
+ [
+ 'document generation',
+ {
+ ...cloneGuard(),
+ documentFingerprint: 'document:5',
+ documentGeneration: guard.documentGeneration + 1,
+ },
+ ],
+ ] as const)('does not reuse the prepared source after a changed %s guard', async (_label, nextGuard) => {
+ let currentGuard: CanvasCompositeExportGuard = guard;
+ const harness = createHarness({
+ captureGuard: () => currentGuard,
+ exportComposite: vi.fn(() =>
+ Promise.resolve({ blob, guard: currentGuard, rect: currentGuard.bbox, status: 'ok' as const })
+ ),
+ isGuardCurrent: (candidate) => candidate === currentGuard,
+ });
+ await expect(harness.session.process()).resolves.toBe('published');
+
+ currentGuard = nextGuard;
+ harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });
+ await expect(harness.session.process()).resolves.toBe('published');
+
+ expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);
+ expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);
+ });
+
it.each(['layer', 'project', 'document'] as const)(
'invalidates the cached export and preview on %s invalidation',
async (kind) => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts
index f821efb18e..19f683e485 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts
@@ -220,10 +220,32 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
}
};
- const isSameGuard = (left: CanvasCompositeExportGuard, right: CanvasCompositeExportGuard): boolean =>
- left.projectId === right.projectId &&
- left.documentFingerprint === right.documentFingerprint &&
- left.documentGeneration === right.documentGeneration;
+ const isSameGuard = (left: CanvasCompositeExportGuard, right: CanvasCompositeExportGuard): boolean => {
+ const sameParticipants = (
+ leftParticipants: CanvasCompositeExportGuard['candidates'],
+ rightParticipants: CanvasCompositeExportGuard['candidates']
+ ): boolean =>
+ leftParticipants.length === rightParticipants.length &&
+ leftParticipants.every((participant, index) => {
+ const other = rightParticipants[index];
+ return (
+ participant.layerId === other?.layerId &&
+ participant.layer === other.layer &&
+ participant.cacheVersion === other.cacheVersion
+ );
+ });
+ return (
+ left.projectId === right.projectId &&
+ left.documentGeneration === right.documentGeneration &&
+ left.documentFingerprint === right.documentFingerprint &&
+ left.bbox.x === right.bbox.x &&
+ left.bbox.y === right.bbox.y &&
+ left.bbox.width === right.bbox.width &&
+ left.bbox.height === right.bbox.height &&
+ sameParticipants(left.candidates, right.candidates) &&
+ sameParticipants(left.participants, right.participants)
+ );
+ };
unsubscribeController = deps.controller.subscribe(() => {
if (!disposed && deps.controller.getSnapshot().status === 'idle') {
@@ -254,7 +276,8 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO
signal: AbortSignal,
token: number
): Promise<SelectObjectPreparedSource> => {
- if (source?.guard === guard && isGuardCurrent(guard)) {
+ if (source && isSameGuard(source.guard, guard) && isGuardCurrent(source.guard) && isGuardCurrent(guard)) {
+ source = { ...source, guard };
return source;
}
source = null;