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
feat(canvas): support interactive segment anything sessions
joshistoast6f74a4437b90
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.tsindex 9b1a2e9dc6..1995f13caf 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 } from './samGraph';+import { buildSamGraph, documentToExportLocalSamInput } from './samGraph';const edge = (sourceNodeId: string,@@ -14,28 +14,45 @@ const edge = (source: { field: sourceField, node_id: sourceNodeId },});+const baseNodes = {+ 'sam-output': {+ id: 'sam-output',+ image: { image_name: 'source.png' },+ invert: false,+ is_intermediate: true,+ type: 'apply_tensor_mask_to_image',+ use_cache: true,+ },+ 'sam-source': {+ id: 'sam-source',+ image: { image_name: 'source.png' },+ is_intermediate: true,+ type: 'image',+ use_cache: true,+ },+};+describe('buildSamGraph', () => {- it.each([- ['segment-anything-2-large', false],- ['segment-anything-huge', true],- ] as const)('builds the exact prompt-to-mask graph for %s with refinement=%s', (model, applyPolygonRefinement) => {+ it('builds the exact prompt graph through Grounding DINO', () => {const { graph, outputNodeId } = buildSamGraph({- applyPolygonRefinement,+ applyPolygonRefinement: false,imageName: 'source.png',- model,- prompt: 'cat',+ input: { prompt: ' cat ', type: 'prompt' },+ invert: false,+ model: 'segment-anything-2-large',});expect(outputNodeId).toBe('sam-output');expect(graph).toEqual({edges: [- edge('sam-source', 'image', 'sam-detect', 'image'),edge('sam-source', 'image', 'sam-segment', 'image'),+ edge('sam-source', 'image', 'sam-detect', 'image'),edge('sam-detect', 'collection', 'sam-segment', 'bounding_boxes'),edge('sam-segment', 'mask', 'sam-output', 'mask'),],id: 'select-object-sam',nodes: {+ ...baseNodes,'sam-detect': {detection_threshold: 0.3,id: 'sam-detect',@@ -45,42 +62,186 @@ describe('buildSamGraph', () => {type: 'grounding_dino',use_cache: true,},- 'sam-output': {- id: 'sam-output',- image: { image_name: 'source.png' },- invert: false,- is_intermediate: true,- type: 'apply_tensor_mask_to_image',- use_cache: true,- },'sam-segment': {- apply_polygon_refinement: applyPolygonRefinement,+ apply_polygon_refinement: false,id: 'sam-segment',is_intermediate: true,mask_filter: 'largest',- model,+ model: 'segment-anything-2-large',type: 'segment_anything',use_cache: true,},- 'sam-source': {- id: 'sam-source',- image: { image_name: 'source.png' },- is_intermediate: true,- type: 'image',- use_cache: true,+ },+ });+ });++ it('builds the exact point-only visual graph with include and exclude labels', () => {+ const { graph } = buildSamGraph({+ applyPolygonRefinement: false,+ imageName: 'source.png',+ input: {+ bbox: null,+ excludePoints: [{ x: 7, y: 8 }],+ includePoints: [+ { x: 1, y: 2 },+ { x: 3, y: 4 },+ ],+ type: 'visual',+ },+ invert: false,+ model: 'segment-anything-2-large',+ });++ expect(graph.edges).toEqual([+ edge('sam-source', 'image', 'sam-segment', 'image'),+ edge('sam-segment', 'mask', 'sam-output', 'mask'),+ ]);+ expect(graph.nodes['sam-segment']).toEqual({+ apply_polygon_refinement: false,+ id: 'sam-segment',+ is_intermediate: true,+ mask_filter: 'largest',+ model: 'segment-anything-2-large',+ point_lists: [+ {+ points: [+ { label: 1, x: 1, y: 2 },+ { label: 1, x: 3, y: 4 },+ { label: -1, x: 7, y: 8 },+ ],},+ ],+ type: 'segment_anything',+ use_cache: true,+ });+ });++ it('builds the exact bbox-only visual graph', () => {+ const { graph } = buildSamGraph({+ applyPolygonRefinement: false,+ imageName: 'source.png',+ input: {+ bbox: { height: 20, width: 10, x: 2, y: 3 },+ excludePoints: [],+ includePoints: [],+ type: 'visual',},+ invert: false,+ model: 'segment-anything-2-large',});++ expect(graph.nodes['sam-segment']).toMatchObject({+ bounding_boxes: [{ x_max: 12, x_min: 2, y_max: 23, y_min: 3 }],+ });+ expect(graph.nodes['sam-segment']).not.toHaveProperty('point_lists');});- it('rejects a blank object prompt', () => {+ it('aligns point and bbox lists for a combined visual graph', () => {+ const { graph } = buildSamGraph({+ applyPolygonRefinement: true,+ imageName: 'source.png',+ input: {+ bbox: { height: 4, width: 3, x: 2, y: 1 },+ excludePoints: [],+ includePoints: [{ x: 3, y: 2 }],+ type: 'visual',+ },+ invert: true,+ model: 'segment-anything-huge',+ });++ expect(graph.nodes['sam-segment']).toMatchObject({+ apply_polygon_refinement: true,+ bounding_boxes: [{ x_max: 5, x_min: 2, y_max: 5, y_min: 1 }],+ model: 'segment-anything-huge',+ point_lists: [{ points: [{ label: 1, x: 3, y: 2 }] }],+ });+ expect(graph.nodes['sam-output']).toMatchObject({ invert: true });+ });++ it.each([+ { prompt: ' ', type: 'prompt' } as const,+ { bbox: null, excludePoints: [], includePoints: [], type: 'visual' } as const,+ {+ bbox: { height: 2, width: -1, x: 0, y: 0 },+ excludePoints: [],+ includePoints: [],+ type: 'visual',+ } as const,+ ])('rejects invalid input $type', (input) => {expect(() =>buildSamGraph({applyPolygonRefinement: false,imageName: 'source.png',+ input,+ invert: false,model: 'segment-anything-2-large',- prompt: ' ',})- ).toThrow('A Segment Anything object prompt is required.');+ ).toThrow(input.type === 'prompt' ? 'A Segment Anything object prompt is required.' : 'visual input is required');+ });+});++describe('documentToExportLocalSamInput', () => {+ it('subtracts a nonzero export origin, rounds points, and clips them to pixel bounds', () => {+ expect(+ documentToExportLocalSamInput(+ {+ bbox: null,+ excludePoints: [{ x: 111.6, y: 210.4 }],+ includePoints: [+ { x: 99, y: 199 },+ { x: 105.4, y: 205.6 },+ ],+ type: 'visual',+ },+ { height: 10, width: 12, x: 100, y: 200 }+ )+ ).toEqual({+ bbox: null,+ excludePoints: [{ x: 11, y: 9 }],+ includePoints: [+ { x: 0, y: 0 },+ { x: 5, y: 6 },+ ],+ type: 'visual',+ });+ });++ it('clips bbox edges in export-local coordinates', () => {+ expect(+ documentToExportLocalSamInput(+ {+ bbox: { height: 30, width: 40, x: 90, y: 190 },+ excludePoints: [],+ includePoints: [],+ type: 'visual',+ },+ { height: 20, width: 30, x: 100, y: 200 }+ )+ ).toEqual({+ bbox: { height: 20, width: 30, x: 0, y: 0 },+ excludePoints: [],+ includePoints: [],+ type: 'visual',+ });+ });++ it('drops a bbox fully outside the export and leaves prompt input unchanged', () => {+ const prompt = { prompt: 'cat', type: 'prompt' } as const;+ expect(documentToExportLocalSamInput(prompt, { height: 20, width: 30, x: 100, y: 200 })).toBe(prompt);+ const converted = documentToExportLocalSamInput(+ {+ bbox: { height: 5, width: 5, x: 10, y: 20 },+ excludePoints: [],+ includePoints: [],+ type: 'visual',+ },+ { height: 20, width: 30, x: 100, y: 200 }+ );+ expect(converted.type).toBe('visual');+ if (converted.type !== 'visual') {+ throw new Error('Expected visual SAM input.');+ }+ expect(converted.bbox).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.tsindex 488b41ba51..7ad81f125a 100644--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts@@ -1,13 +1,24 @@+import type { Rect, Vec2 } from '@workbench/canvas-engine/types';import type { BackendGraphContract } from '@workbench/types';import { addEdge, addNode } from '@workbench/generation/graphBuilder';export type SamModel = 'segment-anything-2-large' | 'segment-anything-huge';+export type SamInput =+ | { type: 'prompt'; prompt: string }+ | {+ type: 'visual';+ includePoints: readonly Vec2[];+ excludePoints: readonly Vec2[];+ bbox?: Rect | null;+ };+export interface BuildSamGraphOptions {imageName: string;- prompt: string;+ input: SamInput;model: SamModel;+ invert: boolean;applyPolygonRefinement: boolean;}@@ -16,10 +27,55 @@ export interface BuiltSamGraph {outputNodeId: string;}+const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));++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)+ );+};++/** Converts document-space visual prompts to the pixel coordinates of a bounded layer export. */+export const documentToExportLocalSamInput = (input: SamInput, exportRect: Rect): SamInput => {+ if (input.type === 'prompt') {+ return input;+ }++ 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),+ });+ let bbox: Rect | null = null;+ if (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);+ const yMax = clamp(Math.round(input.bbox.y + input.bbox.height - exportRect.y), 0, exportRect.height);+ if (xMax > xMin && yMax > yMin) {+ bbox = { height: yMax - yMin, width: xMax - xMin, x: xMin, y: yMin };+ }+ }++ return {+ bbox,+ excludePoints: input.excludePoints.map(convertPoint),+ includePoints: input.includePoints.map(convertPoint),+ type: 'visual',+ };+};+export const buildSamGraph = (options: BuildSamGraphOptions): BuiltSamGraph => {- const prompt = options.prompt.trim();- if (!prompt) {- throw new Error('A Segment Anything object prompt is required.');+ if (!isSamInputValid(options.input)) {+ throw new Error(+ options.input.type === 'prompt'+ ? 'A Segment Anything object prompt is required.'+ : 'A Segment Anything visual input is required.'+ );}const graph: BackendGraphContract = { edges: [], id: 'select-object-sam', nodes: {} };@@ -28,14 +84,28 @@ export const buildSamGraph = (options: BuildSamGraphOptions): BuiltSamGraph => {image: { image_name: options.imageName },type: 'image',});- const detect = addNode(graph, {- detection_threshold: 0.3,- id: 'sam-detect',- model: 'grounding-dino-base',- prompt,- type: 'grounding_dino',- });+ const points =+ options.input.type === 'visual'+ ? [+ ...options.input.includePoints.map(({ x, y }) => ({ label: 1, x, y })),+ ...options.input.excludePoints.map(({ x, y }) => ({ label: -1, x, y })),+ ]+ : [];+ const bbox = options.input.type === 'visual' ? options.input.bbox : null;const segment = addNode(graph, {+ ...(points.length > 0 ? { point_lists: [{ points }] } : {}),+ ...(bbox+ ? {+ bounding_boxes: [+ {+ x_max: bbox.x + bbox.width,+ x_min: bbox.x,+ y_max: bbox.y + bbox.height,+ y_min: bbox.y,+ },+ ],+ }+ : {}),apply_polygon_refinement: options.applyPolygonRefinement,id: 'sam-segment',mask_filter: 'largest',@@ -45,13 +115,22 @@ export const buildSamGraph = (options: BuildSamGraphOptions): BuiltSamGraph => {const output = addNode(graph, {id: 'sam-output',image: { image_name: options.imageName },- invert: false,+ invert: options.invert,type: 'apply_tensor_mask_to_image',});- addEdge(graph, source, 'image', detect, 'image');addEdge(graph, source, 'image', segment, 'image');- addEdge(graph, detect, 'collection', segment, 'bounding_boxes');+ if (options.input.type === 'prompt') {+ const detect = addNode(graph, {+ detection_threshold: 0.3,+ id: 'sam-detect',+ model: 'grounding-dino-base',+ prompt: options.input.prompt.trim(),+ type: 'grounding_dino',+ });+ addEdge(graph, source, 'image', detect, 'image');+ addEdge(graph, detect, 'collection', segment, 'bounding_boxes');+ }addEdge(graph, segment, 'mask', output, 'mask');return { graph, outputNodeId: output.id };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.tsindex 69dae7ea70..78391934a9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts@@ -7,10 +7,10 @@ import type {ReplaceSelectionFromImageResult,} from '@workbench/canvas-engine/engine';import type { Rect } from '@workbench/canvas-engine/types';-import type { SamModel } from '@workbench/generation/canvas/samGraph';+import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';import type { CanvasImageRef } from '@workbench/types';-import { buildSamGraph } from '@workbench/generation/canvas/samGraph';+import { buildSamGraph, documentToExportLocalSamInput } from '@workbench/generation/canvas/samGraph';export type SelectObjectTarget = 'selection' | 'inpaint_mask' | 'regional_guidance';@@ -50,8 +50,11 @@ export interface SelectObjectRunnerDeps {export interface RunSelectObjectOptions {layerId: string;- prompt: string;+ input?: SamInput;+ /** Prompt-only compatibility seam for the current dialog. */+ prompt?: string;model: SamModel;+ invert?: boolean;applyPolygonRefinement: boolean;signal?: AbortSignal;deps: SelectObjectRunnerDeps;@@ -60,30 +63,73 @@ export interface RunSelectObjectOptions {const isAbortError = (error: unknown): boolean => error instanceof Error && error.name === 'AbortError';const errorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));-export const runSelectObject = async (options: RunSelectObjectOptions): Promise<SelectObjectRunResult> => {- if (options.signal?.aborted) {+export interface SelectObjectPreparedSource {+ guard: LayerExportGuard;+ imageName: string;+ rect: Rect;+}++export type PrepareSelectObjectSourceResult =+ | { status: 'ready'; source: SelectObjectPreparedSource }+ | Exclude<SelectObjectRunResult, SelectObjectReadyResult>;++export const prepareSelectObjectSource = async (+ layerId: string,+ deps: Pick<SelectObjectRunnerDeps, 'exportLayer' | 'uploadIntermediate'>,+ signal?: AbortSignal+): Promise<PrepareSelectObjectSourceResult> => {+ if (signal?.aborted) {return { status: 'aborted' };}try {- const exported = await options.deps.exportLayer(options.layerId);- if (options.signal?.aborted) {+ const exported = await deps.exportLayer(layerId);+ if (signal?.aborted) {return { status: 'aborted' };}if (exported.status !== 'ok') {return exported;}-- const uploaded = await options.deps.uploadIntermediate(exported.blob, options.signal);- if (options.signal?.aborted) {+ const uploaded = await deps.uploadIntermediate(exported.blob, signal);+ if (signal?.aborted) {+ return { status: 'aborted' };+ }+ return {+ source: { guard: exported.guard, imageName: uploaded.imageName, rect: exported.rect },+ status: 'ready',+ };+ } catch (error) {+ if (signal?.aborted || isAbortError(error)) {return { status: 'aborted' };}+ return { message: errorMessage(error), status: 'failed' };+ }+};++export interface ProcessSelectObjectSourceOptions {+ source: SelectObjectPreparedSource;+ input: SamInput;+ model: SamModel;+ invert: boolean;+ applyPolygonRefinement: boolean;+ signal?: AbortSignal;+ runGraph: SelectObjectRunnerDeps['runGraph'];+}++export const processSelectObjectSource = async (+ options: ProcessSelectObjectSourceOptions+): Promise<SelectObjectRunResult> => {+ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }+ try {const built = buildSamGraph({applyPolygonRefinement: options.applyPolygonRefinement,- imageName: uploaded.imageName,+ imageName: options.source.imageName,+ input: documentToExportLocalSamInput(options.input, options.source.rect),+ invert: options.invert,model: options.model,- prompt: options.prompt,});- const output = await options.deps.runGraph({+ const output = await options.runGraph({graph: built.graph,outputNodeId: built.outputNodeId,signal: options.signal,@@ -92,9 +138,13 @@ export const runSelectObject = async (options: RunSelectObjectOptions): Promise<return { status: 'aborted' };}return {- guard: exported.guard,- image: { height: exported.rect.height, imageName: output.imageName, width: exported.rect.width },- rect: exported.rect,+ guard: options.source.guard,+ image: {+ height: options.source.rect.height,+ imageName: output.imageName,+ width: options.source.rect.width,+ },+ rect: options.source.rect,status: 'ready',};} catch (error) {@@ -105,6 +155,22 @@ export const runSelectObject = async (options: RunSelectObjectOptions): Promise<}};+export const runSelectObject = async (options: RunSelectObjectOptions): Promise<SelectObjectRunResult> => {+ const prepared = await prepareSelectObjectSource(options.layerId, options.deps, options.signal);+ if (prepared.status !== 'ready') {+ return prepared;+ }+ return processSelectObjectSource({+ applyPolygonRefinement: options.applyPolygonRefinement,+ input: options.input ?? { prompt: options.prompt ?? '', type: 'prompt' },+ invert: options.invert ?? false,+ model: options.model,+ runGraph: options.deps.runGraph,+ signal: options.signal,+ source: prepared.source,+ });+};+export type SelectObjectRouteResult = ReplaceSelectionFromImageResult | CommitMaskImageResult;export interface SelectObjectRouteDeps {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.tsnew file mode 100644index 0000000000..8574ab4676--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts@@ -0,0 +1,285 @@+import type { LayerExportGuard } from '@workbench/canvas-engine/engine';+import type { CanvasRasterLayerContractV2 } from '@workbench/types';++import { createCanvasOperationController } from '@workbench/canvas-engine/canvasOperationController';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { SelectObjectSessionDeps } from './selectObjectSession';++import { createSelectObjectSession } from './selectObjectSession';++const layer: CanvasRasterLayerContractV2 = {+ blendMode: 'normal',+ id: 'source',+ isEnabled: true,+ isLocked: false,+ name: 'Source',+ opacity: 1,+ source: { fill: '#fff', height: 12, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 16 },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: -5, y: 7 },+ type: 'raster',+};+const guard: LayerExportGuard = {+ cacheVersion: 3,+ documentGeneration: 4,+ layer,+ layerId: layer.id,+ projectId: 'p1',+};+const replacementGuard: LayerExportGuard = { ...guard, cacheVersion: 4 };+const rect = { height: 12, width: 16, x: -5, y: 7 };+const blob = new Blob(['source'], { type: 'image/png' });++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+};++const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {}) => {+ let currentGuard: LayerExportGuard | null = guard;+ const controller = createCanvasOperationController({ isGuardCurrent: (candidate) => candidate === currentGuard });+ const deps: SelectObjectSessionDeps<string> = {+ controller,+ decodePreview: vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),+ exportLayer: vi.fn(() => Promise.resolve({ blob, guard: currentGuard ?? guard, rect, status: 'ok' as const })),+ 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' })),+ ...overrides,+ };+ const session = createSelectObjectSession({ deps, layerId: layer.id, projectId: 'p1' });+ session.update({ input: { prompt: 'cat', type: 'prompt' } });+ return {+ controller,+ deps,+ session,+ setCurrentGuard(next: LayerExportGuard | null) {+ currentGuard = next;+ },+ };+};++afterEach(() => {+ vi.useRealTimers();+});++describe('createSelectObjectSession', () => {+ it('exposes the complete default processing state', () => {+ const { session } = createHarness();++ expect(session.getSnapshot()).toMatchObject({+ applyPolygonRefinement: false,+ autoProcess: false,+ error: null,+ input: { prompt: 'cat', type: 'prompt' },+ invert: false,+ isolatedPreview: true,+ model: 'segment-anything-2-large',+ preview: null,+ sourceGuard: null,+ status: 'ready',+ });+ });++ it('reuses an uploaded export only while its exact guard remains current', async () => {+ const harness = createHarness();++ await expect(harness.session.process()).resolves.toBe('published');+ harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });+ await expect(harness.session.process()).resolves.toBe('published');++ expect(harness.deps.exportLayer).toHaveBeenCalledTimes(1);+ expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(1);+ expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);+ expect(harness.session.getSnapshot().sourceGuard).toBe(guard);++ harness.setCurrentGuard(replacementGuard);+ vi.mocked(harness.deps.exportLayer).mockResolvedValue({+ blob,+ guard: replacementGuard,+ rect,+ status: 'ok',+ });+ harness.session.update({ input: { prompt: 'bird', type: 'prompt' } });+ await expect(harness.session.process()).resolves.toBe('published');++ expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);+ expect(harness.session.getSnapshot().sourceGuard).toBe(replacementGuard);+ });++ it.each(['source', 'layer', 'project', 'document'] as const)(+ 'invalidates the cached export and preview on %s invalidation',+ async (kind) => {+ const harness = createHarness();+ await harness.session.process();+ vi.mocked(harness.deps.cleanupPreview).mockClear();++ if (kind === 'source') {+ harness.controller.invalidateSource('p1', layer.id);+ } else if (kind === 'layer') {+ harness.controller.invalidateLayer('p1', layer.id);+ } else if (kind === 'project') {+ harness.controller.invalidateProject('p1');+ } else {+ harness.controller.invalidateDocument('p1');+ }++ expect(harness.session.getSnapshot()).toMatchObject({ preview: null, sourceGuard: null, status: 'ready' });+ expect(harness.deps.cleanupPreview).toHaveBeenCalledOnce();+ }+ );++ it('deduplicates an identical stable input hash after publication', async () => {+ const harness = createHarness();++ await expect(harness.session.process()).resolves.toBe('published');+ await expect(harness.session.process()).resolves.toBe('deduped');++ expect(harness.deps.runGraph).toHaveBeenCalledOnce();+ });++ it('debounces auto-processing for one second and manual processing runs immediately', async () => {+ vi.useFakeTimers();+ const harness = createHarness();+ harness.session.update({ autoProcess: true });+ harness.session.update({ input: { prompt: 'first', type: 'prompt' } });+ await vi.advanceTimersByTimeAsync(500);+ harness.session.update({ input: { prompt: 'second', type: 'prompt' } });+ await vi.advanceTimersByTimeAsync(999);+ expect(harness.deps.exportLayer).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());++ harness.session.update({ input: { prompt: 'manual', type: 'prompt' } });+ await expect(harness.session.process()).resolves.toBe('published');+ expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);+ });++ 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 harness = createHarness({+ runGraph: vi+ .fn()+ .mockImplementationOnce(() => older.promise)+ .mockImplementationOnce(() => newer.promise),+ });+ const oldPending = harness.session.process();+ await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());+ harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });+ const newPending = harness.session.process();+ await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledTimes(2));++ newer.resolve({ imageName: 'new.png', origin: 'new' });+ await expect(newPending).resolves.toBe('published');+ older.resolve({ imageName: 'old.png', origin: 'old' });+ await expect(oldPending).resolves.toBe('stale');++ expect(harness.deps.publishPreview).toHaveBeenCalledOnce();+ expect(harness.session.getSnapshot().preview?.image.imageName).toBe('new.png');+ });++ it.each(['export', 'upload', 'queue', 'decode'] as const)(+ 'cancels safely at the %s boundary without starting later work',+ async (boundary) => {+ const wait = deferred<unknown>();+ const harness = createHarness({+ decodePreview:+ boundary === 'decode'+ ? vi.fn(() => wait.promise as Promise<string>)+ : vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),+ exportLayer:+ boundary === 'export'+ ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportLayer']>)+ : vi.fn(() => Promise.resolve({ blob, guard, rect, status: 'ok' as const })),+ runGraph:+ boundary === 'queue'+ ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['runGraph']>)+ : vi.fn(() => Promise.resolve({ imageName: 'result.png', origin: 'test' })),+ uploadIntermediate:+ boundary === 'upload'+ ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['uploadIntermediate']>)+ : vi.fn(() => Promise.resolve({ imageName: 'input.png' })),+ });+ const pending = harness.session.process();+ await vi.waitFor(() => {+ const fn =+ boundary === 'export'+ ? harness.deps.exportLayer+ : boundary === 'upload'+ ? harness.deps.uploadIntermediate+ : boundary === 'queue'+ ? harness.deps.runGraph+ : harness.deps.decodePreview;+ expect(fn).toHaveBeenCalledOnce();+ });++ harness.session.cancel();+ if (boundary === 'export') {+ wait.resolve({ blob, guard, rect, status: 'ok' });+ } else if (boundary === 'upload') {+ wait.resolve({ imageName: 'input.png' });+ } else if (boundary === 'queue') {+ wait.resolve({ imageName: 'result.png', origin: 'test' });+ } else {+ wait.resolve('decoded');+ }++ await expect(pending).resolves.toBe('stale');+ expect(harness.deps.publishPreview).not.toHaveBeenCalled();+ expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(boundary === 'export' ? 0 : 1);+ expect(harness.deps.runGraph).toHaveBeenCalledTimes(boundary === 'export' || boundary === 'upload' ? 0 : 1);+ expect(harness.deps.decodePreview).toHaveBeenCalledTimes(+ boundary === 'export' || boundary === 'upload' || boundary === 'queue' ? 0 : 1+ );+ }+ );++ it('suppresses a decoded preview when the source guard becomes stale', async () => {+ const decode = deferred<string>();+ const harness = createHarness({ decodePreview: vi.fn(() => decode.promise) });+ const pending = harness.session.process();+ await vi.waitFor(() => expect(harness.deps.decodePreview).toHaveBeenCalledOnce());++ harness.setCurrentGuard(null);+ decode.resolve('decoded');++ await expect(pending).resolves.toBe('stale');+ expect(harness.deps.publishPreview).not.toHaveBeenCalled();+ expect(harness.session.getSnapshot()).toMatchObject({ preview: null, sourceGuard: null, status: 'ready' });+ });++ it('reset cancels work and scheduling, clears preview/cache, and restores defaults', async () => {+ vi.useFakeTimers();+ const graph = deferred<{ imageName: string; origin: string }>();+ 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' });++ await expect(pending).resolves.toBe('stale');+ expect(harness.session.getSnapshot()).toEqual({+ applyPolygonRefinement: false,+ autoProcess: false,+ error: null,+ input: { prompt: '', type: 'prompt' },+ invert: false,+ isolatedPreview: true,+ model: 'segment-anything-2-large',+ preview: null,+ sourceGuard: null,+ status: 'ready',+ });+ await vi.runAllTimersAsync();+ expect(harness.deps.runGraph).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.tsnew file mode 100644index 0000000000..beb392afce--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts@@ -0,0 +1,354 @@+import type { RunUtilityGraphOptions, UtilityGraphResult } from '@workbench/canvas-engine/backend/utilityQueue';+import type {+ CanvasOperationController,+ CanvasOperationRunResult,+ CanvasOperationSession,+} from '@workbench/canvas-engine/canvasOperationController';+import type { ExportBakedLayerBlobResult, LayerExportGuard } from '@workbench/canvas-engine/engine';+import type { Rect } from '@workbench/canvas-engine/types';+import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';++import { isSamInputValid } from '@workbench/generation/canvas/samGraph';++import type { SelectObjectPreparedSource, SelectObjectReadyResult } from './layerImageResult';++import { prepareSelectObjectSource, processSelectObjectSource } from './layerImageResult';++export type SelectObjectSessionStatus = 'ready' | 'scheduled' | 'processing' | 'error';++export interface SelectObjectSessionPreview<T> {+ data: T;+ guard: LayerExportGuard;+ image: SelectObjectReadyResult['image'];+ inputHash: string;+ isolated: boolean;+ rect: Rect;+ sourceImageName: string;+}++export interface SelectObjectSessionState<T> {+ input: SamInput;+ model: SamModel;+ invert: boolean;+ applyPolygonRefinement: boolean;+ autoProcess: boolean;+ isolatedPreview: boolean;+ status: SelectObjectSessionStatus;+ error: string | null;+ preview: SelectObjectSessionPreview<T> | null;+ sourceGuard: LayerExportGuard | null;+}++export interface SelectObjectSessionDeps<T> {+ controller: CanvasOperationController;+ exportLayer(layerId: string): Promise<ExportBakedLayerBlobResult>;+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;+ runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>): Promise<UtilityGraphResult>;+ decodePreview(result: SelectObjectReadyResult, signal: AbortSignal): Promise<T>;+ publishPreview(preview: SelectObjectSessionPreview<T>): undefined;+ cleanupPreview(): void;+ isGuardCurrent(guard: LayerExportGuard): boolean;+}++export interface CreateSelectObjectSessionOptions<T> {+ projectId: string;+ layerId: string;+ deps: SelectObjectSessionDeps<T>;+}++export type SelectObjectSessionProcessResult = CanvasOperationRunResult | 'deduped' | 'invalid';++export interface SelectObjectSession<T> {+ getSnapshot(): SelectObjectSessionState<T>;+ subscribe(listener: () => void): () => void;+ update(+ changes: Partial<+ Pick<+ SelectObjectSessionState<T>,+ 'applyPolygonRefinement' | 'autoProcess' | 'input' | 'invert' | 'isolatedPreview' | 'model'+ >+ >+ ): void;+ process(): Promise<SelectObjectSessionProcessResult>;+ reset(): void;+ cancel(): void;+}++const defaultState = <T>(): SelectObjectSessionState<T> => ({+ applyPolygonRefinement: false,+ autoProcess: false,+ error: null,+ input: { prompt: '', type: 'prompt' },+ invert: false,+ isolatedPreview: true,+ model: 'segment-anything-2-large',+ preview: null,+ sourceGuard: null,+ status: 'ready',+});++const stableInputHash = <T>(state: SelectObjectSessionState<T>): string => {+ const input =+ state.input.type === 'prompt'+ ? ['prompt', state.input.prompt.trim()]+ : [+ 'visual',+ state.input.includePoints.map(({ x, y }) => [x, y]),+ state.input.excludePoints.map(({ x, y }) => [x, y]),+ state.input.bbox+ ? [state.input.bbox.x, state.input.bbox.y, state.input.bbox.width, state.input.bbox.height]+ : null,+ ];+ return JSON.stringify([input, state.model, state.invert, state.applyPolygonRefinement, state.isolatedPreview]);+};++const resultError = (result: Exclude<Awaited<ReturnType<typeof prepareSelectObjectSource>>, { status: 'ready' }>) =>+ result.status === 'failed' ? result.message : `Select Object source is ${result.status}.`;++export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOptions<T>): SelectObjectSession<T> => {+ const { deps, layerId, projectId } = options;+ let state = defaultState<T>();+ let source: SelectObjectPreparedSource | null = null;+ let operation: CanvasOperationSession | null = null;+ let operationGuard: LayerExportGuard | null = null;+ let sourceController: AbortController | null = null;+ let requestToken = 0;+ let lastPublishedHash: string | null = null;+ let pendingHash: string | null = null;+ let pendingProcess: Promise<SelectObjectSessionProcessResult> | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ let startingOperation = false;+ const listeners = new Set<() => void>();++ const publishState = (next: SelectObjectSessionState<T>): void => {+ state = next;+ for (const listener of listeners) {+ listener();+ }+ };++ const clearTimer = (): void => {+ if (timer !== null) {+ clearTimeout(timer);+ timer = null;+ }+ };++ const clearSource = (): void => {+ source = null;+ operation = null;+ operationGuard = null;+ lastPublishedHash = null;+ publishState({ ...state, preview: null, sourceGuard: null, status: 'ready' });+ };++ deps.controller.subscribe(() => {+ if (!startingOperation && operation && deps.controller.getSnapshot().status === 'idle') {+ sourceController?.abort();+ sourceController = null;+ clearSource();+ }+ });++ const cleanupPreview = (): void => {+ deps.cleanupPreview();+ if (state.preview) {+ publishState({ ...state, preview: null });+ }+ };++ const schedule = (): void => {+ clearTimer();+ if (!state.autoProcess || !isSamInputValid(state.input)) {+ if (state.status === 'scheduled') {+ publishState({ ...state, status: 'ready' });+ }+ return;+ }+ publishState({ ...state, error: null, status: 'scheduled' });+ timer = setTimeout(() => {+ timer = null;+ void process();+ }, 1_000);+ };++ const ensureSource = async (signal: AbortSignal): Promise<SelectObjectPreparedSource> => {+ if (source && deps.isGuardCurrent(source.guard)) {+ return source;+ }+ source = null;+ const prepared = await prepareSelectObjectSource(layerId, deps, signal);+ if (prepared.status !== 'ready') {+ throw new Error(resultError(prepared));+ }+ if (signal.aborted || !deps.isGuardCurrent(prepared.source.guard)) {+ throw new DOMException('Select Object source became stale.', 'AbortError');+ }+ source = prepared.source;+ return source;+ };++ const runRequest = async (+ token: number,+ hash: string,+ requestState: SelectObjectSessionState<T>,+ controller: AbortController+ ): Promise<SelectObjectSessionProcessResult> => {+ try {+ const preparedSource = await ensureSource(controller.signal);+ if (controller.signal.aborted || token !== requestToken) {+ return 'stale';+ }++ if (operationGuard !== preparedSource.guard || !operation) {+ startingOperation = true;+ const nextOperation = deps.controller.start({+ cleanupPreview,+ guard: preparedSource.guard,+ identity: { kind: 'select-object', layerId, projectId },+ });+ startingOperation = false;+ if (!nextOperation) {+ clearSource();+ return 'stale';+ }+ operation = nextOperation;+ operationGuard = preparedSource.guard;+ }++ publishState({ ...state, sourceGuard: preparedSource.guard, status: 'processing' });+ const result = await operation.run(+ async (signal) => {+ const processed = await processSelectObjectSource({+ applyPolygonRefinement: requestState.applyPolygonRefinement,+ input: requestState.input,+ invert: requestState.invert,+ model: requestState.model,+ runGraph: deps.runGraph,+ signal,+ source: preparedSource,+ });+ if (processed.status !== 'ready') {+ 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}.`+ );+ }+ const data = await deps.decodePreview(processed, signal);+ if (signal.aborted) {+ throw new DOMException('Select Object preview decode was aborted.', 'AbortError');+ }+ return {+ data,+ guard: processed.guard,+ image: processed.image,+ inputHash: hash,+ isolated: requestState.isolatedPreview,+ rect: processed.rect,+ sourceImageName: preparedSource.imageName,+ } satisfies SelectObjectSessionPreview<T>;+ },+ (preview) => {+ deps.publishPreview(preview);+ lastPublishedHash = hash;+ publishState({ ...state, error: null, preview, sourceGuard: preview.guard, status: 'ready' });+ return undefined;+ }+ );+ if (token !== requestToken) {+ return 'stale';+ }+ if (result === 'error') {+ const controllerState = deps.controller.getSnapshot();+ publishState({+ ...state,+ error: controllerState.status === 'active' ? controllerState.error : 'Select Object processing failed.',+ status: 'error',+ });+ } else if (result === 'stale' && !deps.isGuardCurrent(preparedSource.guard)) {+ clearSource();+ }+ return result;+ } catch (cause) {+ if (+ controller.signal.aborted ||+ token !== requestToken ||+ (cause instanceof Error && cause.name === 'AbortError')+ ) {+ return 'stale';+ }+ publishState({ ...state, error: cause instanceof Error ? cause.message : String(cause), status: 'error' });+ return 'error';+ }+ };++ const process = (): Promise<SelectObjectSessionProcessResult> => {+ clearTimer();+ if (!isSamInputValid(state.input)) {+ publishState({ ...state, error: 'A Segment Anything input is required.', status: 'error' });+ return Promise.resolve('invalid');+ }+ const hash = stableInputHash(state);+ if (hash === pendingHash && pendingProcess) {+ return pendingProcess;+ }+ if (hash === lastPublishedHash) {+ return Promise.resolve('deduped');+ }++ requestToken += 1;+ const token = requestToken;+ sourceController?.abort();+ const controller = new AbortController();+ sourceController = controller;+ pendingHash = hash;+ publishState({ ...state, error: null, status: 'processing' });+ const requestState = state;+ const promise = runRequest(token, hash, requestState, controller).finally(() => {+ if (token === requestToken) {+ sourceController = null;+ pendingHash = null;+ pendingProcess = null;+ }+ });+ pendingProcess = promise;+ return promise;+ };++ const cancelCurrent = (): void => {+ clearTimer();+ requestToken += 1;+ sourceController?.abort();+ sourceController = null;+ pendingHash = null;+ pendingProcess = null;+ operation?.cancel();+ operation = null;+ operationGuard = null;+ source = null;+ lastPublishedHash = null;+ };++ return {+ cancel: () => {+ cancelCurrent();+ publishState({ ...state, error: null, preview: null, sourceGuard: null, status: 'ready' });+ },+ getSnapshot: () => state,+ process,+ reset: () => {+ cancelCurrent();+ publishState(defaultState<T>());+ },+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ update: (changes) => {+ publishState({ ...state, ...changes, error: null });+ schedule();+ },+ };+};