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): harden interactive sam processing
joshistoast51555d8fa5f0
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.tsindex 1995f13caf..4297f0f95e 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.ts@@ -2,7 +2,7 @@ import type { BackendGraphEdgeContract } from '@workbench/types';import { describe, expect, it } from 'vitest';-import { buildSamGraph, documentToExportLocalSamInput } from './samGraph';+import { buildSamGraph, documentToExportLocalSamInput, isSamDocumentInputValid, isSamInputValid } from './samGraph';const edge = (sourceNodeId: string,@@ -179,10 +179,77 @@ describe('buildSamGraph', () => {})).toThrow(input.type === 'prompt' ? 'A Segment Anything object prompt is required.' : 'visual input is required');});++ it.each([+ {+ bbox: null,+ excludePoints: [],+ includePoints: [{ x: 1.5, y: 2 }],+ type: 'visual',+ },+ {+ bbox: null,+ excludePoints: [{ x: Number.NaN, y: 2 }],+ includePoints: [],+ type: 'visual',+ },+ {+ bbox: null,+ excludePoints: [],+ includePoints: [{ x: 1, y: Number.POSITIVE_INFINITY }],+ type: 'visual',+ },+ {+ bbox: { height: 2, width: 1.5, x: 0, y: 0 },+ excludePoints: [],+ includePoints: [],+ type: 'visual',+ },+ {+ bbox: { height: 2, width: 1, x: Number.NEGATIVE_INFINITY, y: 0 },+ excludePoints: [],+ includePoints: [],+ type: 'visual',+ },+ {+ bbox: { height: 2, width: 1.5, x: 0, y: 0 },+ excludePoints: [],+ includePoints: [{ x: 1, y: 2 }],+ type: 'visual',+ },+ {+ bbox: { height: 2, width: Number.MAX_VALUE, x: Number.MAX_VALUE, y: 0 },+ excludePoints: [],+ includePoints: [],+ type: 'visual',+ },+ ] as const)('rejects backend-invalid coordinates %#', (input) => {+ expect(isSamInputValid(input)).toBe(false);+ expect(() =>+ buildSamGraph({+ applyPolygonRefinement: false,+ imageName: 'source.png',+ input,+ invert: false,+ model: 'segment-anything-2-large',+ })+ ).toThrow('visual input is required');+ });++ it('rejects a non-finite document bbox even when a finite point is present', () => {+ expect(+ isSamDocumentInputValid({+ bbox: { height: 2, width: Number.POSITIVE_INFINITY, x: 0, y: 0 },+ excludePoints: [],+ includePoints: [{ x: 1.25, y: 2.75 }],+ type: 'visual',+ })+ ).toBe(false);+ });});describe('documentToExportLocalSamInput', () => {- it('subtracts a nonzero export origin, rounds points, and clips them to pixel bounds', () => {+ it('subtracts a nonzero export origin, rounds finite points, and discards points outside the export', () => {expect(documentToExportLocalSamInput({@@ -198,10 +265,36 @@ describe('documentToExportLocalSamInput', () => {)).toEqual({bbox: null,- excludePoints: [{ x: 11, y: 9 }],+ excludePoints: [],+ includePoints: [{ x: 5, y: 6 }],+ type: 'visual',+ });+ });++ it('keeps inside edge points while discarding non-finite and outside points', () => {+ expect(+ documentToExportLocalSamInput(+ {+ bbox: null,+ excludePoints: [+ { x: Number.NaN, y: 10 },+ { x: 20, y: Number.POSITIVE_INFINITY },+ ],+ includePoints: [+ { x: 10, y: 20 },+ { x: 21.9, y: 29.9 },+ { x: 22, y: 25 },+ ],+ type: 'visual',+ },+ { height: 10, width: 12, x: 10, y: 20 }+ )+ ).toEqual({+ bbox: null,+ excludePoints: [],includePoints: [{ x: 0, y: 0 },- { x: 5, y: 6 },+ { x: 11, y: 9 },],type: 'visual',});@@ -243,5 +336,24 @@ describe('documentToExportLocalSamInput', () => {throw new Error('Expected visual SAM input.');}expect(converted.bbox).toBeNull();+ expect(isSamInputValid(converted)).toBe(false);+ });++ it.each([+ { height: 0, width: 30, x: 100, y: 200 },+ { height: 20, width: 0, x: 100, y: 200 },+ ])('produces an invalid empty visual input for a zero-size export %#', (exportRect) => {+ const converted = documentToExportLocalSamInput(+ {+ bbox: null,+ excludePoints: [{ x: 101, y: 201 }],+ includePoints: [],+ type: 'visual',+ },+ exportRect+ );++ expect(converted).toEqual({ bbox: null, excludePoints: [], includePoints: [], type: 'visual' });+ expect(isSamInputValid(converted)).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.tsindex 7ad81f125a..756ef67664 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts@@ -29,15 +29,46 @@ export interface BuiltSamGraph {const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));+const isFinitePoint = ({ x, y }: Vec2): boolean => Number.isFinite(x) && Number.isFinite(y);+const isIntegerPoint = (point: Vec2): boolean =>+ isFinitePoint(point) && Number.isInteger(point.x) && Number.isInteger(point.y);+const isFiniteBox = (bbox: Rect): boolean =>+ Number.isFinite(bbox.x) &&+ Number.isFinite(bbox.y) &&+ Number.isFinite(bbox.width) &&+ Number.isFinite(bbox.height) &&+ bbox.width > 0 &&+ bbox.height > 0 &&+ Number.isFinite(bbox.x + bbox.width) &&+ Number.isFinite(bbox.y + bbox.height) &&+ bbox.x + bbox.width > bbox.x &&+ bbox.y + bbox.height > bbox.y;+const isIntegerBox = (bbox: Rect): boolean =>+ isFiniteBox(bbox) &&+ Number.isInteger(bbox.x) &&+ Number.isInteger(bbox.y) &&+ Number.isInteger(bbox.width) &&+ Number.isInteger(bbox.height);++/** Validates document-space inputs before scheduling or stable hashing. */+export const isSamDocumentInputValid = (input: SamInput): boolean => {+ if (input.type === 'prompt') {+ return input.prompt.trim().length > 0;+ }+ const points = [...input.includePoints, ...input.excludePoints];+ const hasBox = input.bbox !== null && input.bbox !== undefined;+ const boxIsValid = input.bbox === null || input.bbox === undefined || isFiniteBox(input.bbox);+ return points.every(isFinitePoint) && boxIsValid && (points.length > 0 || hasBox);+};+export const isSamInputValid = (input: SamInput): boolean => {if (input.type === 'prompt') {return input.prompt.trim().length > 0;}- return (- input.includePoints.length > 0 ||- input.excludePoints.length > 0 ||- (input.bbox !== null && input.bbox !== undefined && input.bbox.width > 0 && input.bbox.height > 0)- );+ const points = [...input.includePoints, ...input.excludePoints];+ const hasBox = input.bbox !== null && input.bbox !== undefined;+ const boxIsValid = input.bbox === null || input.bbox === undefined || isIntegerBox(input.bbox);+ return points.every(isIntegerPoint) && boxIsValid && (points.length > 0 || hasBox);};/** Converts document-space visual prompts to the pixel coordinates of a bounded layer export. */@@ -46,12 +77,29 @@ export const documentToExportLocalSamInput = (input: SamInput, exportRect: Rect)return input;}+ if (+ !Number.isFinite(exportRect.x) ||+ !Number.isFinite(exportRect.y) ||+ !Number.isInteger(exportRect.width) ||+ !Number.isInteger(exportRect.height) ||+ exportRect.width <= 0 ||+ exportRect.height <= 0+ ) {+ return { bbox: null, excludePoints: [], includePoints: [], type: 'visual' };+ }+const convertPoint = ({ x, y }: Vec2): Vec2 => ({x: clamp(Math.round(x - exportRect.x), 0, exportRect.width - 1),y: clamp(Math.round(y - exportRect.y), 0, exportRect.height - 1),});+ const isPointInsideExport = ({ x, y }: Vec2): boolean =>+ isFinitePoint({ x, y }) &&+ x >= exportRect.x &&+ x < exportRect.x + exportRect.width &&+ y >= exportRect.y &&+ y < exportRect.y + exportRect.height;let bbox: Rect | null = null;- if (input.bbox) {+ if (input.bbox && isFiniteBox(input.bbox)) {const xMin = clamp(Math.round(input.bbox.x - exportRect.x), 0, exportRect.width);const yMin = clamp(Math.round(input.bbox.y - exportRect.y), 0, exportRect.height);const xMax = clamp(Math.round(input.bbox.x + input.bbox.width - exportRect.x), 0, exportRect.width);@@ -63,8 +111,8 @@ export const documentToExportLocalSamInput = (input: SamInput, exportRect: Rect)return {bbox,- excludePoints: input.excludePoints.map(convertPoint),- includePoints: input.includePoints.map(convertPoint),+ excludePoints: input.excludePoints.filter(isPointInsideExport).map(convertPoint),+ includePoints: input.includePoints.filter(isPointInsideExport).map(convertPoint),type: 'visual',};};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.tsindex 8574ab4676..10dd32f583 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts@@ -144,6 +144,20 @@ describe('createSelectObjectSession', () => {expect(harness.deps.runGraph).toHaveBeenCalledOnce();});+ it('does not deduplicate the same hash after its exact source guard is replaced', async () => {+ const harness = createHarness();+ await expect(harness.session.process()).resolves.toBe('published');++ harness.setCurrentGuard(replacementGuard);+ vi.mocked(harness.deps.exportLayer).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });++ await expect(harness.session.process()).resolves.toBe('published');+ expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);+ expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);+ expect(harness.session.getSnapshot().sourceGuard).toBe(replacementGuard);+ });+it('debounces auto-processing for one second and manual processing runs immediately', async () => {vi.useFakeTimers();const harness = createHarness();@@ -161,6 +175,82 @@ describe('createSelectObjectSession', () => {expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);});+ 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 harness = createHarness({ runGraph: vi.fn(() => oldGraph.promise) });+ harness.session.update({ autoProcess: true });+ await vi.advanceTimersByTimeAsync(1_000);+ await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());++ harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });+ expect(harness.session.getSnapshot()).toMatchObject({ preview: null, status: 'scheduled' });+ oldGraph.resolve({ imageName: 'old.png', origin: 'old' });+ await vi.advanceTimersByTimeAsync(999);++ expect(harness.deps.publishPreview).not.toHaveBeenCalled();+ expect(harness.deps.runGraph).toHaveBeenCalledOnce();+ });++ it.each([+ ['input', { input: { prompt: 'dog', type: 'prompt' as const } }],+ ['model', { model: 'segment-anything-huge' as const }],+ ['invert', { invert: true }],+ ['refinement', { applyPolygonRefinement: true }],+ ['preview isolation', { isolatedPreview: false }],+ ] 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 harness = createHarness({+ runGraph: vi.fn((options) => {+ if (options.signal) {+ signals.push(options.signal);+ }+ return graph.promise;+ }),+ });+ const pending = harness.session.process();+ await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());++ harness.session.update(update);++ expect(signals[0]?.aborted).toBe(true);+ expect(harness.session.getSnapshot().preview).toBeNull();+ graph.resolve({ imageName: 'stale.png', origin: 'stale' });+ await expect(pending).resolves.toBe('stale');+ expect(harness.deps.publishPreview).not.toHaveBeenCalled();+ });++ it('clears an already-published preview as soon as processing input changes', async () => {+ const harness = createHarness();+ await harness.session.process();+ vi.mocked(harness.deps.cleanupPreview).mockClear();++ harness.session.update({ model: 'segment-anything-huge' });++ expect(harness.session.getSnapshot()).toMatchObject({ preview: null, status: 'ready' });+ expect(harness.deps.cleanupPreview).toHaveBeenCalledOnce();+ });++ it('rejects non-finite document input before hashing or scheduling work', async () => {+ vi.useFakeTimers();+ const harness = createHarness();+ harness.session.update({ autoProcess: true });+ harness.session.update({+ input: {+ bbox: null,+ excludePoints: [],+ includePoints: [{ x: Number.NaN, y: 1 }],+ type: 'visual',+ },+ });++ await expect(harness.session.process()).resolves.toBe('invalid');+ await vi.runAllTimersAsync();+ expect(harness.deps.exportLayer).not.toHaveBeenCalled();+ expect(harness.deps.runGraph).not.toHaveBeenCalled();+ });+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 }>();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.tsindex beb392afce..0608cf864e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts@@ -8,7 +8,7 @@ import type { ExportBakedLayerBlobResult, LayerExportGuard } from '@workbench/caimport type { Rect } from '@workbench/canvas-engine/types';import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';-import { isSamInputValid } from '@workbench/generation/canvas/samGraph';+import { isSamDocumentInputValid } from '@workbench/generation/canvas/samGraph';import type { SelectObjectPreparedSource, SelectObjectReadyResult } from './layerImageResult';@@ -142,6 +142,14 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOpublishState({ ...state, preview: null, sourceGuard: null, status: 'ready' });};+ const isGuardCurrent = (guard: LayerExportGuard): boolean => {+ try {+ return deps.isGuardCurrent(guard);+ } catch {+ return false;+ }+ };+deps.controller.subscribe(() => {if (!startingOperation && operation && deps.controller.getSnapshot().status === 'idle') {sourceController?.abort();@@ -159,7 +167,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOconst schedule = (): void => {clearTimer();- if (!state.autoProcess || !isSamInputValid(state.input)) {+ if (!state.autoProcess || !isSamDocumentInputValid(state.input)) {if (state.status === 'scheduled') {publishState({ ...state, status: 'ready' });}@@ -173,7 +181,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO};const ensureSource = async (signal: AbortSignal): Promise<SelectObjectPreparedSource> => {- if (source && deps.isGuardCurrent(source.guard)) {+ if (source && isGuardCurrent(source.guard)) {return source;}source = null;@@ -181,7 +189,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOif (prepared.status !== 'ready') {throw new Error(resultError(prepared));}- if (signal.aborted || !deps.isGuardCurrent(prepared.source.guard)) {+ if (signal.aborted || !isGuardCurrent(prepared.source.guard)) {throw new DOMException('Select Object source became stale.', 'AbortError');}source = prepared.source;@@ -267,7 +275,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOerror: controllerState.status === 'active' ? controllerState.error : 'Select Object processing failed.',status: 'error',});- } else if (result === 'stale' && !deps.isGuardCurrent(preparedSource.guard)) {+ } else if (result === 'stale' && !isGuardCurrent(preparedSource.guard)) {clearSource();}return result;@@ -286,15 +294,38 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOconst process = (): Promise<SelectObjectSessionProcessResult> => {clearTimer();- if (!isSamInputValid(state.input)) {+ if (!isSamDocumentInputValid(state.input)) {publishState({ ...state, error: 'A Segment Anything input is required.', status: 'error' });return Promise.resolve('invalid');}+ if (state.sourceGuard && !isGuardCurrent(state.sourceGuard)) {+ requestToken += 1;+ sourceController?.abort();+ sourceController = null;+ operation?.cancel();+ if (!operation && state.preview) {+ cleanupPreview();+ }+ source = null;+ operation = null;+ operationGuard = null;+ pendingHash = null;+ pendingProcess = null;+ lastPublishedHash = null;+ publishState({ ...state, preview: null, sourceGuard: null, status: 'ready' });+ }const hash = stableInputHash(state);if (hash === pendingHash && pendingProcess) {return pendingProcess;}- if (hash === lastPublishedHash) {+ if (+ hash === lastPublishedHash &&+ state.preview !== null &&+ state.sourceGuard === state.preview.guard &&+ source?.guard === state.preview.guard &&+ operationGuard === state.preview.guard &&+ isGuardCurrent(state.preview.guard)+ ) {return Promise.resolve('deduped');}@@ -331,6 +362,19 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOlastPublishedHash = null;};+ const invalidateProcessingState = (): void => {+ requestToken += 1;+ sourceController?.abort();+ sourceController = null;+ pendingHash = null;+ pendingProcess = null;+ lastPublishedHash = null;+ operation?.reset();+ if (!operation && state.preview) {+ cleanupPreview();+ }+ };+return {cancel: () => {cancelCurrent();@@ -347,7 +391,22 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOreturn () => listeners.delete(listener);},update: (changes) => {- publishState({ ...state, ...changes, error: null });+ const processingChanged =+ ('input' in changes && changes.input !== state.input) ||+ ('model' in changes && changes.model !== state.model) ||+ ('invert' in changes && changes.invert !== state.invert) ||+ ('applyPolygonRefinement' in changes && changes.applyPolygonRefinement !== state.applyPolygonRefinement) ||+ ('isolatedPreview' in changes && changes.isolatedPreview !== state.isolatedPreview);+ if (processingChanged) {+ invalidateProcessingState();+ }+ publishState({+ ...state,+ ...changes,+ error: null,+ preview: processingChanged ? null : state.preview,+ status: processingChanged ? 'ready' : state.status,+ });schedule();},};