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): create masks with segment anything
joshistoastf061653ac93f
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 397139dd77..8fb02c0fa4 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1177,6 +1177,7 @@"rename": "Rename layer","reorder": "Reorder layer","saveLayerToAssets": "Save layer to assets",+ "selectObject": "Select object","show": "Show layer","toggleAutoNegative": "Toggle auto-negative","toggleLock": "Toggle lock",@@ -1257,6 +1258,36 @@"title": "Filter","unsupported": "This layer content cannot be filtered."},+ "selectObject": {+ "aborted": "Object selection was canceled.",+ "busy": "Finish the current canvas interaction, then try again.",+ "cancel": "Cancel",+ "durabilityFailure": "The object mask could not be preserved: {{message}}",+ "disabled": "Enable the layer before selecting an object.",+ "empty": "This layer has no content to select.",+ "failed": "Object selection failed: {{message}}",+ "inpaintMaskSuccess": "Created an inpaint mask from the selected object.",+ "locked": "Unlock the layer before selecting an object.",+ "model": "Segment Anything model",+ "modelHuge": "SAM Huge",+ "modelSam2Large": "SAM 2 Large",+ "missing": "The source layer no longer exists.",+ "notReady": "The layer content is still loading. Try again shortly.",+ "prompt": "Object prompt",+ "promptPlaceholder": "Describe the object to select…",+ "refine": "Refine mask edges",+ "regionalGuidanceSuccess": "Created a regional guidance mask from the selected object.",+ "run": "Run",+ "running": "Selecting object…",+ "selectionSuccess": "Selected the object on the canvas.",+ "stale": "The source layer changed while selecting the object. Run it again.",+ "target": "Output",+ "targetInpaintMask": "Inpaint mask",+ "targetRegionalGuidance": "Regional guidance",+ "targetSelection": "Selection",+ "title": "Select object",+ "unsupported": "This layer content cannot be used for object selection."+ },"addLayer": "Add layer","adjustments": {"brightness": "Brightness",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex e93fe5a532..50803f6511 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -5497,6 +5497,808 @@ describe('commitRasterFilterResult', () => {});});+describe('replaceSelectionFromImage', () => {+ const resultImage = { height: 10, imageName: 'sam-result.png', width: 10 };+ const resultRect = { height: 10, width: 10, x: -7, y: 13 };++ const sourceLayer = (): CanvasRasterLayerContractV2 => ({+ blendMode: 'normal',+ id: 'sam-source',+ isEnabled: true,+ isLocked: false,+ name: 'SAM source',+ opacity: 1,+ source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: -7, y: 13 },+ type: 'raster',+ });++ const sourceDocument = (layer: CanvasLayerContract = sourceLayer()): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ layers: [layer],+ selectedLayerId: layer.id,+ version: 2,+ width: 100,+ });++ const alphaBackend = (alpha: number): StubRasterBackend => {+ const base = createTestStubRasterBackend();+ return {+ ...base,+ createSurface: (width, height) => {+ const surface = base.createSurface(width, height);+ Object.defineProperty(surface.ctx, 'getImageData', {+ value: (_x: number, _y: number, readWidth: number, readHeight: number) => {+ const data = new Uint8ClampedArray(readWidth * readHeight * 4);+ for (let index = 3; index < data.length; index += 4) {+ data[index] = alpha;+ }+ return { colorSpace: 'srgb', data, height: readHeight, width: readWidth } as ImageData;+ },+ });+ return surface;+ },+ };+ };++ const createHarness = async ({+ alpha = 0,+ backend = alphaBackend(alpha),+ imageResolver = () => Promise.resolve(new Blob()),+ seedSelection = true,+ }: {+ alpha?: number;+ backend?: StubRasterBackend;+ imageResolver?: (imageName: string, signal?: AbortSignal) => Promise<Blob>;+ seedSelection?: boolean;+ } = {}) => {+ vi.stubGlobal('Path2D', class FakePath2D {});+ const layer = sourceLayer();+ const document = sourceDocument(layer);+ const reactive = createReactiveStore(document);+ const engine = createCanvasEngine({ backend, imageResolver, projectId: 'p1', store: reactive.store });+ const exported = await engine.exportLayerPixels(layer.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an export guard');+ }+ if (seedSelection) {+ engine.selectAll();+ }+ (reactive.store.dispatch as Mock).mockClear();+ return { ...reactive, document, engine, guard: exported.guard, layer };+ };++ const createPendingHarness = async () => {+ const decoded = createDeferred<Blob>();+ const harness = await createHarness({ imageResolver: () => decoded.promise });+ const pending = harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect);+ return { ...harness, decoded, pending };+ };++ it('decodes and places a non-empty alpha result into the transient selection', async () => {+ const imageResolver = vi.fn((_imageName: string, _signal?: AbortSignal) => Promise.resolve(new Blob()));+ const harness = await createHarness({ alpha: 255, imageResolver, seedSelection: false });++ await expect(harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect)).resolves.toEqual({+ status: 'selected',+ });+ expect(imageResolver).toHaveBeenCalledWith(resultImage.imageName, undefined);+ expect(harness.engine.stores.hasSelection.get()).toBe(true);+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('reports selected when a has-selection observer throws after the replacement is applied', async () => {+ const harness = await createHarness({ alpha: 255, seedSelection: false });+ const unsubscribeFault = harness.engine.stores.hasSelection.subscribe(() => {+ throw new Error('selection state observer failed');+ });++ await expect(harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect)).resolves.toEqual({+ status: 'selected',+ });++ expect(harness.engine.stores.hasSelection.get()).toBe(true);+ unsubscribeFault();+ harness.engine.dispose();+ });++ it('reports selected and clears derived selection state for an empty mask without clearing the prior surface', async () => {+ const base = alphaBackend(0);+ const surfaces: StubRasterSurface[] = [];+ const backend: StubRasterBackend = {+ ...base,+ createSurface: (width, height) => {+ const surface = base.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ };+ const harness = await createHarness({ backend });+ const priorMask = surfaces.at(-1);+ if (!priorMask) {+ throw new Error('expected a seeded selection surface');+ }+ const priorMaskClear = vi.fn(() => {+ throw new Error('prior selection surface must not be cleared');+ });+ Object.defineProperty(priorMask.ctx, 'clearRect', { value: priorMaskClear });++ await expect(harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect)).resolves.toEqual({+ status: 'selected',+ });++ expect(priorMaskClear).not.toHaveBeenCalled();+ expect(harness.engine.stores.hasSelection.get()).toBe(false);+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('closes the decoded bitmap and preserves selection when replacement-surface allocation fails', async () => {+ const base = alphaBackend(255);+ const close = vi.fn();+ let failAllocation = false;+ const backend: StubRasterBackend = {+ ...base,+ createImageBitmap: vi.fn(() =>+ Promise.resolve({ close, height: resultImage.height, width: resultImage.width } as unknown as ImageBitmap)+ ),+ createSurface: (width, height) => {+ if (failAllocation) {+ throw new Error('selection surface allocation failed');+ }+ return base.createSurface(width, height);+ },+ };+ const harness = await createHarness({ backend });+ failAllocation = true;++ await expect(harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect)).resolves.toEqual({+ message: 'selection surface allocation failed',+ status: 'failed',+ });++ expect(close).toHaveBeenCalledOnce();+ expect(harness.engine.stores.hasSelection.get()).toBe(true);+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns aborted before decode without touching the existing selection', async () => {+ const imageResolver = vi.fn(() => Promise.resolve(new Blob()));+ const harness = await createHarness({ imageResolver });+ const controller = new AbortController();+ controller.abort();++ await expect(+ harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect, controller.signal)+ ).resolves.toEqual({ status: 'aborted' });+ expect(imageResolver).not.toHaveBeenCalled();+ expect(harness.engine.stores.hasSelection.get()).toBe(true);+ harness.engine.dispose();+ });++ it('returns aborted when cancellation lands during image resolution', async () => {+ const decoded = createDeferred<Blob>();+ const harness = await createHarness({ imageResolver: () => decoded.promise });+ const controller = new AbortController();++ const pending = harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect, controller.signal);+ controller.abort();+ decoded.resolve(new Blob());++ await expect(pending).resolves.toEqual({ status: 'aborted' });+ expect(harness.engine.stores.hasSelection.get()).toBe(true);+ harness.engine.dispose();+ });++ it('returns aborted and closes the bitmap when cancellation lands during bitmap decode', async () => {+ const bitmap = createDeferred<ImageBitmap>();+ const close = vi.fn();+ const backend = { ...alphaBackend(0), createImageBitmap: vi.fn(() => bitmap.promise) };+ const harness = await createHarness({ backend });+ const controller = new AbortController();++ const pending = harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect, controller.signal);+ await vi.waitFor(() => expect(backend.createImageBitmap).toHaveBeenCalledOnce());+ controller.abort();+ bitmap.resolve({ close, height: 10, width: 10 } as unknown as ImageBitmap);++ await expect(pending).resolves.toEqual({ status: 'aborted' });+ expect(close).toHaveBeenCalledOnce();+ expect(harness.engine.stores.hasSelection.get()).toBe(true);+ harness.engine.dispose();+ });++ it('returns failed on decode failure without touching the existing selection', async () => {+ const harness = await createHarness({ imageResolver: () => Promise.reject(new Error('SAM decode failed')) });++ await expect(harness.engine.replaceSelectionFromImage(harness.guard, resultImage, resultRect)).resolves.toEqual({+ message: 'SAM decode failed',+ status: 'failed',+ });+ expect(harness.engine.stores.hasSelection.get()).toBe(true);+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it.each([+ {+ expected: 'missing',+ label: 'source deletion',+ mutate: (harness: Awaited<ReturnType<typeof createHarness>>) =>+ harness.setDocument({ ...harness.document, layers: [] }),+ },+ {+ expected: 'stale',+ label: 'source contract edit',+ mutate: (harness: Awaited<ReturnType<typeof createHarness>>) =>+ harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, opacity: 0.5 }] }),+ },+ {+ expected: 'locked',+ label: 'source lock',+ mutate: (harness: Awaited<ReturnType<typeof createHarness>>) =>+ harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, isLocked: true }] }),+ },+ {+ expected: 'unsupported',+ label: 'source type change',+ mutate: (harness: Awaited<ReturnType<typeof createHarness>>) => {+ const { source: _source, ...base } = harness.layer;+ const mask: CanvasInpaintMaskLayerContract = {+ ...base,+ mask: { bitmap: null, fill: { color: '#fff', style: 'solid' } },+ type: 'inpaint_mask',+ };+ harness.setDocument({ ...harness.document, layers: [mask] });+ },+ },+ {+ expected: 'stale',+ label: 'active project switch',+ mutate: (harness: Awaited<ReturnType<typeof createHarness>>) => harness.setActiveProjectId('p2'),+ },+ {+ expected: 'stale',+ label: 'document replacement reusing the layer',+ mutate: (harness: Awaited<ReturnType<typeof createHarness>>) => harness.setDocument({ ...harness.document }, 1),+ },+ ] as const)('refuses $label without mutating the selection', async ({ expected, mutate }) => {+ const harness = await createPendingHarness();+ mutate(harness);+ const selectionAfterExternalChange = harness.engine.stores.hasSelection.get();+ harness.decoded.resolve(new Blob());++ await expect(harness.pending).resolves.toEqual({ status: expected });+ expect(harness.engine.stores.hasSelection.get()).toBe(selectionAfterExternalChange);+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns busy for an open pointer gesture without mutating the selection', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const harness = await createPendingHarness();+ const screen = createInputCanvas();+ const overlay = createInputCanvas();+ harness.engine.attach(screen.element, overlay.element);+ raf.flush();+ overlay.fire('pointerdown', pointerAt(5, 5));+ harness.decoded.resolve(new Blob());++ await expect(harness.pending).resolves.toEqual({ status: 'busy' });+ expect(harness.engine.stores.hasSelection.get()).toBe(true);+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ harness.engine.dispose();+ });++ it('returns stale after an unpersisted paint-cache edit without mutating the selection', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ vi.stubGlobal('Path2D', class FakePath2D {});+ const decoded = createDeferred<Blob>();+ const document = paintDoc();+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: alphaBackend(0),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => decoded.promise,+ projectId,+ store,+ });+ const screen = createInputCanvas();+ const overlay = createInputCanvas();+ engine.attach(screen.element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ engine.setTool('brush');+ overlay.fire('pointerdown', pointerAt(5, 5));+ overlay.fire('pointermove', pointerAt(8, 8));+ overlay.fire('pointerup', pointerAt(8, 8, { buttons: 0 }));+ const exported = await engine.exportLayerPixels('paint1');+ if (exported.status !== 'ok') {+ throw new Error('expected live paint pixels');+ }+ engine.selectAll();+ const pending = engine.replaceSelectionFromImage(exported.guard, resultImage, resultRect);++ overlay.fire('pointerdown', pointerAt(15, 15));+ overlay.fire('pointermove', pointerAt(18, 18));+ overlay.fire('pointerup', pointerAt(18, 18, { buttons: 0 }));+ decoded.resolve(new Blob());++ await expect(pending).resolves.toEqual({ status: 'stale' });+ expect(engine.stores.hasSelection.get()).toBe(true);+ engine.dispose();+ });+});++describe('commitMaskImageResult', () => {+ const resultImage = { height: 12, imageName: 'durable-sam-result.png', width: 16 };+ const resultRect = { height: 12, width: 16, x: -5, y: 7 };++ const source = (): 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 existingInpaint = (): CanvasInpaintMaskLayerContract => ({+ blendMode: 'normal',+ id: 'existing-mask',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' } },+ name: 'Inpaint Mask 1',+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ });++ const existingRegional = (): CanvasLayerContract => ({+ autoNegative: false,+ blendMode: 'normal',+ id: 'existing-region',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#83d683', style: 'solid' } },+ name: 'Regional Guidance 1',+ negativePrompt: null,+ opacity: 0.5,+ positivePrompt: null,+ referenceImages: [],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'regional_guidance',+ });++ const docFor = (target: 'inpaint_mask' | 'regional_guidance'): CanvasDocumentContractV2 => {+ const layer = source();+ const below = { ...source(), id: 'below', name: 'Below' };+ return {+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ layers: [target === 'inpaint_mask' ? existingInpaint() : existingRegional(), layer, below],+ selectedLayerId: below.id,+ version: 2,+ width: 100,+ };+ };++ it.each([+ {+ expected: {+ blendMode: 'normal',+ isEnabled: true,+ isLocked: false,+ mask: {+ bitmap: resultImage,+ fill: { color: '#e07575', style: 'diagonal' },+ offset: { x: -5, y: 7 },+ },+ name: 'Inpaint Mask 2',+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ },+ target: 'inpaint_mask',+ },+ {+ expected: {+ autoNegative: false,+ blendMode: 'normal',+ isEnabled: true,+ isLocked: false,+ mask: {+ bitmap: resultImage,+ fill: { color: '#fae150', style: 'solid' },+ offset: { x: -5, y: 7 },+ },+ name: 'Regional Guidance 2',+ negativePrompt: null,+ opacity: 0.5,+ positivePrompt: null,+ referenceImages: [],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'regional_guidance',+ },+ target: 'regional_guidance',+ },+ ] as const)(+ 'adds a complete $target directly above the source with one exact history entry',+ async ({ expected, target }) => {+ const document = docFor(target);+ const { projectId, store } = createReducerBackedStore(document);+ const bitmapStore = createSpyBitmapStore();+ const imageResolver = vi.fn(() => Promise.resolve(new Blob()));+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore,+ imageResolver,+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels('source');+ if (exported.status !== 'ok') {+ throw new Error('expected an export guard');+ }++ const result = await engine.commitMaskImageResult({+ guard: exported.guard,+ image: resultImage,+ rect: resultRect,+ target,+ });++ expect(result.status).toBe('committed');+ if (result.status !== 'committed') {+ throw new Error('expected a committed mask');+ }+ const created = engine.getDocument()!.layers.find((layer) => layer.id === result.layerId)!;+ expect(created).toEqual({ ...expected, id: result.layerId });+ expect(engine.getDocument()!.layers.map((layer) => layer.id)).toEqual([+ document.layers[0]!.id,+ result.layerId,+ 'source',+ 'below',+ ]);+ expect(engine.getDocument()!.selectedLayerId).toBe(result.layerId);+ expect(imageResolver).not.toHaveBeenCalled();+ expect(bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(engine.stores.canUndo.get()).toBe(true);++ engine.undo();+ expect(engine.getDocument()).toEqual(document);+ expect(engine.getDocument()!.selectedLayerId).toBe('below');+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);++ engine.redo();+ expect(engine.getDocument()!.layers.find((layer) => layer.id === result.layerId)).toEqual(created);+ expect(engine.getDocument()!.selectedLayerId).toBe(result.layerId);+ expect(engine.stores.canUndo.get()).toBe(true);+ expect(engine.stores.canRedo.get()).toBe(false);+ engine.dispose();+ }+ );++ it('commits and refreshes the document mirror when an earlier observer throws after the reducer adds the mask', async () => {+ const document = docFor('inpaint_mask');+ const { projectId, store } = createReducerBackedStore(document);+ const unsubscribeFault = store.subscribe(() => {+ throw new Error('earlier mask observer failed');+ });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels('source');+ if (exported.status !== 'ok') {+ throw new Error('expected an export guard');+ }++ const result = await engine.commitMaskImageResult({+ guard: exported.guard,+ image: resultImage,+ rect: resultRect,+ target: 'inpaint_mask',+ });+ unsubscribeFault();++ expect(result.status).toBe('committed');+ if (result.status !== 'committed') {+ throw new Error('expected a committed mask');+ }+ expect(engine.getDocument()).toBe(+ store.getState().projects.find((project) => project.id === projectId)!.canvas.document+ );+ expect(engine.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(true);+ expect(engine.stores.canUndo.get()).toBe(true);++ engine.undo();+ expect(engine.getDocument()).toEqual(document);+ engine.dispose();+ });++ it('finishes mask undo exactly when document observers throw after both reducer mutations', async () => {+ const document = docFor('regional_guidance');+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels('source');+ if (exported.status !== 'ok') {+ throw new Error('expected an export guard');+ }+ const result = await engine.commitMaskImageResult({+ guard: exported.guard,+ image: resultImage,+ rect: resultRect,+ target: 'regional_guidance',+ });+ if (result.status !== 'committed') {+ throw new Error('expected a committed mask');+ }+ const unsubscribeFault = store.subscribe(() => {+ throw new Error('mask undo observer failed');+ });++ expect(() => engine.undo()).not.toThrow();++ expect(engine.getDocument()).toEqual(document);+ expect(engine.getDocument()!.selectedLayerId).toBe('below');+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);+ unsubscribeFault();+ engine.dispose();+ });++ it('keeps mask undo failure-atomic when restoring the prior selection fails before reducer application', async () => {+ const document = docFor('inpaint_mask');+ const { dispatch, projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels('source');+ if (exported.status !== 'ok') {+ throw new Error('expected an export guard');+ }+ const result = await engine.commitMaskImageResult({+ guard: exported.guard,+ image: resultImage,+ rect: resultRect,+ target: 'inpaint_mask',+ });+ if (result.status !== 'committed') {+ throw new Error('expected a committed mask');+ }+ const committedDocument = structuredClone(engine.getDocument()!);+ const reducerDispatch = dispatch.getMockImplementation();+ if (!reducerDispatch) {+ throw new Error('expected reducer-backed dispatch');+ }+ let failSelection = true;+ dispatch.mockImplementation((action: WorkbenchAction) => {+ if (failSelection && action.type === 'setCanvasSelectedLayer') {+ failSelection = false;+ throw new Error('mask selection restore failed');+ }+ reducerDispatch(action);+ });++ expect(() => engine.undo()).toThrow('mask selection restore failed');++ expect(engine.getDocument()).toEqual(committedDocument);+ expect(engine.stores.canUndo.get()).toBe(true);+ expect(engine.stores.canRedo.get()).toBe(false);++ engine.undo();+ expect(engine.getDocument()).toEqual(document);+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);+ engine.dispose();+ });++ it('keeps mask undo retryable when removal fails after restoring the prior selection', async () => {+ const document = docFor('regional_guidance');+ const { dispatch, projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const exported = await engine.exportLayerPixels('source');+ if (exported.status !== 'ok') {+ throw new Error('expected an export guard');+ }+ const result = await engine.commitMaskImageResult({+ guard: exported.guard,+ image: resultImage,+ rect: resultRect,+ target: 'regional_guidance',+ });+ if (result.status !== 'committed') {+ throw new Error('expected a committed mask');+ }+ const reducerDispatch = dispatch.getMockImplementation();+ if (!reducerDispatch) {+ throw new Error('expected reducer-backed dispatch');+ }+ let failRemoval = true;+ dispatch.mockImplementation((action: WorkbenchAction) => {+ if (failRemoval && action.type === 'removeCanvasLayers') {+ failRemoval = false;+ throw new Error('mask removal failed');+ }+ reducerDispatch(action);+ });++ expect(() => engine.undo()).toThrow('mask removal failed');++ expect(engine.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(true);+ expect(engine.getDocument()!.selectedLayerId).toBe('below');+ expect(engine.stores.canUndo.get()).toBe(true);+ expect(engine.stores.canRedo.get()).toBe(false);++ engine.undo();+ expect(engine.getDocument()).toEqual(document);+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);+ engine.dispose();+ });++ const guardHarness = async () => {+ const layer = source();+ const document: CanvasDocumentContractV2 = { ...docFor('inpaint_mask'), layers: [layer] };+ const reactive = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store: reactive.store,+ });+ const exported = await engine.exportLayerPixels(layer.id);+ if (exported.status !== 'ok') {+ throw new Error('expected an export guard');+ }+ (reactive.store.dispatch as Mock).mockClear();+ return { ...reactive, document, engine, guard: exported.guard, layer };+ };++ it('returns aborted before any mask mutation', async () => {+ const harness = await guardHarness();+ const controller = new AbortController();+ controller.abort();++ await expect(+ harness.engine.commitMaskImageResult({+ guard: harness.guard,+ image: resultImage,+ rect: resultRect,+ signal: controller.signal,+ target: 'inpaint_mask',+ })+ ).resolves.toEqual({ status: 'aborted' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ expect(harness.engine.stores.canUndo.get()).toBe(false);+ harness.engine.dispose();+ });++ it.each([+ {+ expected: 'missing',+ label: 'source deletion',+ mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) =>+ harness.setDocument({ ...harness.document, layers: [] }),+ },+ {+ expected: 'stale',+ label: 'source contract edit',+ mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) =>+ harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, opacity: 0.4 }] }),+ },+ {+ expected: 'locked',+ label: 'source lock',+ mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) =>+ harness.setDocument({ ...harness.document, layers: [{ ...harness.layer, isLocked: true }] }),+ },+ {+ expected: 'unsupported',+ label: 'source type change',+ mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) => {+ const { source: _source, ...base } = harness.layer;+ const mask: CanvasInpaintMaskLayerContract = {+ ...base,+ mask: { bitmap: null, fill: { color: '#fff', style: 'solid' } },+ type: 'inpaint_mask',+ };+ harness.setDocument({ ...harness.document, layers: [mask] });+ },+ },+ {+ expected: 'stale',+ label: 'active project switch',+ mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) => harness.setActiveProjectId('p2'),+ },+ {+ expected: 'stale',+ label: 'document replacement',+ mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) => harness.setDocument({ ...harness.document }, 1),+ },+ {+ expected: 'stale',+ label: 'cache invalidation',+ mutate: (harness: Awaited<ReturnType<typeof guardHarness>>) => harness.engine.clearCaches(),+ },+ ] as const)('refuses $label without adding a mask or history', async ({ expected, mutate }) => {+ const harness = await guardHarness();+ await mutate(harness);++ await expect(+ harness.engine.commitMaskImageResult({+ guard: harness.guard,+ image: resultImage,+ rect: resultRect,+ target: 'regional_guidance',+ })+ ).resolves.toEqual({ status: expected });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ expect(harness.engine.stores.canUndo.get()).toBe(false);+ harness.engine.dispose();+ });++ it('returns busy during an open pointer gesture without adding a mask', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const harness = await guardHarness();+ const screen = createInputCanvas();+ const overlay = createInputCanvas();+ harness.engine.attach(screen.element, overlay.element);+ raf.flush();+ overlay.fire('pointerdown', pointerAt(5, 5));++ await expect(+ harness.engine.commitMaskImageResult({+ guard: harness.guard,+ image: resultImage,+ rect: resultRect,+ target: 'inpaint_mask',+ })+ ).resolves.toEqual({ status: 'busy' });+ expect(harness.store.dispatch).not.toHaveBeenCalled();+ expect(harness.engine.stores.canUndo.get()).toBe(false);+ harness.engine.dispose();+ });+});+describe('setFilterPreview', () => {const emptyDoc = (): CanvasDocumentContractV2 => ({background: 'transparent',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 99502c78ad..719b2a4f80 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -94,6 +94,14 @@ import {transformOverlayGeometry,} from '@workbench/canvas-engine/transform/transformMath';import { createViewport, MAX_DPR, type Viewport } from '@workbench/canvas-engine/viewport';+import {+ createInpaintMaskFromImage,+ createRegionalGuidanceFromImage,+ DEFAULT_INPAINT_MASK_FILL,+ nextInpaintMaskName,+ nextRegionalGuidanceFillColor,+ nextRegionalGuidanceName,+} from '@workbench/widgets/layers/layerOps';import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';@@ -156,6 +164,25 @@ export interface CommitRasterFilterOptions {signal?: AbortSignal;}+export type ReplaceSelectionFromImageResult =+ | { status: 'selected' }+ | { status: 'aborted' | 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' }+ | { status: 'failed'; message: string };++export type MaskImageResultTarget = 'inpaint_mask' | 'regional_guidance';++export interface CommitMaskImageResultOptions {+ guard: LayerExportGuard;+ image: CanvasImageRef;+ rect: Rect;+ target: MaskImageResultTarget;+ signal?: AbortSignal;+}++export type CommitMaskImageResult =+ | { status: 'committed'; layerId: string }+ | { status: 'aborted' | 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' };+/*** Result of {@link CanvasEngine.exportRasterLayersToPsd}: `'exported'` on* success, `'nothing'` when there are no raster layers with content, `'too-large'`@@ -409,6 +436,8 @@ export interface CanvasEngine {cropLayerToBbox(layerId: string): Promise<CropLayerResult>;/** Commits a durable raster-filter result only while its export guard remains current. */commitRasterFilterResult(options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult>;+ /** Adds a durable SAM image as a new mask layer while its source export guard remains current. */+ commitMaskImageResult(options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult>;/** Creates a new raster paint layer above `layerId` from that layer's baked pixels. */copyLayerToRaster(layerId: string): Promise<string | null>;/**@@ -502,6 +531,13 @@ export interface CanvasEngine {selectAll(): void;/** Clears the selection (`mod+d` / Escape when idle). */deselect(): void;+ /** Replaces the transient selection from a guarded alpha-bearing image result. */+ replaceSelectionFromImage(+ guard: LayerExportGuard,+ image: CanvasImageRef,+ rect: Rect,+ signal?: AbortSignal+ ): Promise<ReplaceSelectionFromImageResult>;/** Inverts the selection within the document (`mod+shift+i`). */invertSelection(): void;/** Clears an inpaint/regional mask as one undoable edit, preserving its non-pixel settings. */@@ -950,9 +986,24 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {let antsPhase = 0;const onSelectionChanged = (): void => {- stores.hasSelection.set(selection.hasSelection());- updateAntsAnimation();- scheduler.invalidate({ overlay: true });+ // Selection state is already authoritative before this notification runs.+ // Keep each derived UI/render notification independent and best-effort so a+ // faulty observer cannot make an applied selection report false failure.+ try {+ stores.hasSelection.set(selection.hasSelection());+ } catch {+ // The scalar store commits before notifying observers.+ }+ try {+ updateAntsAnimation();+ } catch {+ // A later selection mutation/attach transition reconciles animation.+ }+ try {+ scheduler.invalidate({ overlay: true });+ } catch {+ // The next render invalidation will draw the authoritative selection.+ }};const selection: SelectionState = createSelectionState({@@ -2511,6 +2562,41 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {installGeneratedPaintCache(prepared, persist);};+ const getReducerDocument = (): CanvasDocumentContractV2 | null =>+ store.getState().projects.find((project) => project.id === projectId)?.canvas.document ?? null;++ const dispatchPreparedMutation = (+ action: WorkbenchAction,+ isApplied: () => boolean,+ isMirrored: () => boolean+ ): void => {+ try {+ store.dispatch(action);+ } catch (error) {+ // Store subscribers run after the reducer has accepted an action. A+ // faulty observer must not strand an applied document mutation before+ // its matching engine state and history are published. Preserve real+ // reducer/dispatch failures by swallowing only when the exact intended+ // postcondition is visible in the authoritative reducer state.+ if (!isApplied()) {+ throw error;+ }+ // Notification may have been interrupted before DocumentMirror's+ // subscriber ran. Reconcile it synchronously from authoritative state+ // before publishing follow-up state or history.+ try {+ mirror.refresh();+ } catch (refreshError) {+ if (!isMirrored()) {+ throw refreshError;+ }+ }+ if (!isMirrored()) {+ throw error;+ }+ }+ };+const captureLayerCache = (layer: CanvasLayerContract,doc: CanvasDocumentContractV2@@ -2606,6 +2692,157 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return true;};+ const replaceSelectionFromImage = async (+ guard: LayerExportGuard,+ image: CanvasImageRef,+ rect: Rect,+ signal?: AbortSignal+ ): Promise<ReplaceSelectionFromImageResult> => {+ if (signal?.aborted) {+ return { status: 'aborted' };+ }+ try {+ const blob = await imageResolver(image.imageName, signal);+ if (signal?.aborted) {+ return { status: 'aborted' };+ }+ const bitmap = await backend.createImageBitmap(blob);+ if (signal?.aborted) {+ bitmap.close();+ return { status: 'aborted' };+ }+ let pixels: RasterSurface;+ try {+ // Allocation belongs to the decoded bitmap's lifetime too. If it throws,+ // the finally block must still release the browser bitmap.+ pixels = backend.createSurface(image.width, image.height);+ pixels.ctx.setTransform(1, 0, 0, 1, 0, 0);+ pixels.ctx.clearRect(0, 0, image.width, image.height);+ pixels.ctx.drawImage(bitmap, 0, 0, image.width, image.height);+ } finally {+ bitmap.close();+ }+ if (signal?.aborted) {+ return { status: 'aborted' };+ }++ const document = mirror.getDocument();+ const liveLayer = document?.layers.find((candidate) => candidate.id === guard.layerId);+ if (!document || !liveLayer) {+ return { status: 'missing' };+ }+ if (liveLayer.isLocked) {+ return { status: 'locked' };+ }+ if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {+ return { status: 'unsupported' };+ }+ if (pipeline.isGestureActive()) {+ return { status: 'busy' };+ }+ if (!isLayerExportGuardCurrent(guard)) {+ return { status: 'stale' };+ }+ if (signal?.aborted) {+ return { status: 'aborted' };+ }++ selection.replaceMask({ rect: { ...rect }, surface: pixels });+ return { status: 'selected' };+ } catch (error) {+ if (signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {+ return { status: 'aborted' };+ }+ return { message: error instanceof Error ? error.message : String(error), status: 'failed' };+ }+ };++ const commitMaskImageResult = (options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult> => {+ if (options.signal?.aborted) {+ return Promise.resolve({ status: 'aborted' });+ }+ const document = mirror.getDocument();+ const liveLayer = document?.layers.find((candidate) => candidate.id === options.guard.layerId);+ if (!document || !liveLayer) {+ return Promise.resolve({ status: 'missing' });+ }+ if (liveLayer.isLocked) {+ return Promise.resolve({ status: 'locked' });+ }+ if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {+ return Promise.resolve({ status: 'unsupported' });+ }+ if (pipeline.isGestureActive()) {+ return Promise.resolve({ status: 'busy' });+ }+ if (!isLayerExportGuardCurrent(options.guard)) {+ return Promise.resolve({ status: 'stale' });+ }+ if (options.signal?.aborted) {+ return Promise.resolve({ status: 'aborted' });+ }++ const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);+ if (sourceIndex < 0) {+ return Promise.resolve({ status: 'missing' });+ }+ const names = document.layers.map((layer) => layer.name);+ const layerId = createLayerId();+ const layer =+ options.target === 'inpaint_mask'+ ? createInpaintMaskFromImage({+ fill: DEFAULT_INPAINT_MASK_FILL,+ id: layerId,+ image: options.image,+ name: nextInpaintMaskName(names),+ rect: options.rect,+ })+ : createRegionalGuidanceFromImage({+ fill: {+ color: nextRegionalGuidanceFillColor(+ document.layers.filter((candidate) => candidate.type === 'regional_guidance').length+ ),+ style: 'solid',+ },+ id: layerId,+ image: options.image,+ name: nextRegionalGuidanceName(names),+ rect: options.rect,+ });+ const selectedLayerId = document.selectedLayerId;+ const apply = (): void =>+ dispatchPreparedMutation(+ { index: sourceIndex, layer, type: 'addCanvasLayer' },+ () => getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,+ () => mirror.getDocument()?.layers.some((candidate) => candidate === layer) === true+ );++ endNudgeBurst();+ apply();+ history.push({+ bytes: 256,+ label: options.target === 'inpaint_mask' ? 'Create inpaint mask from object' : 'Create region from object',+ redo: apply,+ replayFailureAtomic: true,+ undo: () => {+ // Restore selection first. It is idempotent, so a pre-dispatch removal+ // failure leaves the history entry retryable without duplicating a+ // structural mutation or losing the caller's prior selection.+ dispatchPreparedMutation(+ { id: selectedLayerId, type: 'setCanvasSelectedLayer' },+ () => getReducerDocument()?.selectedLayerId === selectedLayerId,+ () => mirror.getDocument()?.selectedLayerId === selectedLayerId+ );+ dispatchPreparedMutation(+ { ids: [layerId], type: 'removeCanvasLayers' },+ () => getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,+ () => mirror.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false+ );+ },+ });+ return Promise.resolve({ layerId, status: 'committed' });+ };+const commitRasterFilterResult = async (options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult> => {if (options.signal?.aborted) {return { status: 'aborted' };@@ -2657,42 +2894,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const image = structuredClone(options.image);const rect = { ...options.rect };const paintSource = { bitmap: image, offset: { x: rect.x, y: rect.y }, type: 'paint' } as const;- const getReducerDocument = (): CanvasDocumentContractV2 | null =>- store.getState().projects.find((project) => project.id === projectId)?.canvas.document ?? null;- const dispatchPreparedMutation = (- action: WorkbenchAction,- isApplied: () => boolean,- isMirrored: () => boolean- ): void => {- try {- store.dispatch(action);- } catch (error) {- // Store subscribers run after the reducer has accepted an action. A- // faulty observer must not strand an applied document mutation before- // its already-prepared cache and history are published. Preserve real- // reducer/dispatch failures by swallowing only when the exact intended- // postcondition is visible in the authoritative reducer state.- if (!isApplied()) {- throw error;- }- // Notification may have been interrupted before DocumentMirror's- // subscriber ran. Reconcile it synchronously from authoritative state- // before publishing cache/history so the engine cannot commit against- // a stale document. Observer errors after mirror convergence are- // ancillary and must not veto the applied reducer mutation.- try {- mirror.refresh();- } catch (refreshError) {- if (!isMirrored()) {- throw refreshError;- }- }- if (!isMirrored()) {- throw error;- }- }- };-if (options.mode === 'replace') {const beforePixels = captureLayerCache(liveLayer, document);if (!beforePixels || beforePixels === 'not-ready') {@@ -4400,6 +4601,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {commitOpenTextSession,commitLayerConversion,commitLayerCopy,+ commitMaskImageResult,commitRasterFilterResult,commitStructural,commitTextEdit,@@ -4434,6 +4636,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {openTextCreate,openTextEdit,rasterizeLayer,+ replaceSelectionFromImage,setTextEditContentReader,updateTextEditStyle,getViewport: () => viewport,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.tsindex dbcfdc27c5..9393d41e02 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts@@ -1,5 +1,5 @@import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';-import type { Rect } from '@workbench/canvas-engine/types';+import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { createSelectionState, type SelectionState } from '@workbench/canvas-engine/selection/selectionState';@@ -12,6 +12,25 @@ const rectBounds = (x: number, y: number, w: number, h: number): Rect => ({ heig/** A fake Path2D carrier (Path2D is absent in node); the stub ctx just records it. */const fakePath = (id: string): Path2D => ({ id }) as unknown as Path2D;+const imageData = (alphas: readonly number[]): ImageData => {+ const data = new Uint8ClampedArray(alphas.length * 4);+ alphas.forEach((alpha, index) => {+ data[index * 4] = index + 1;+ data[index * 4 + 1] = index + 11;+ data[index * 4 + 2] = index + 21;+ data[index * 4 + 3] = alpha;+ });+ return { colorSpace: 'srgb', data, height: 2, width: 2 } as ImageData;+};++const placedMask = (alphas: readonly number[]): { placed: PlacedSurface; pixels: ImageData } => {+ const backend = createTestStubRasterBackend();+ const surface = backend.createSurface(2, 2);+ const pixels = imageData(alphas);+ Object.defineProperty(surface.ctx, 'getImageData', { value: () => pixels });+ return { pixels, placed: { rect: rectBounds(7, -3, 2, 2), surface } };+};+const createHarness = (docSize: { width: number; height: number } | null = DOC) => {const backend = createTestStubRasterBackend();const onChange = vi.fn();@@ -136,6 +155,134 @@ describe('selectionState: selectAll / invert / clear', () => {});});+describe('selectionState: replaceMask', () => {+ it('replaces prior pixels with an isolated, pixel-exact alpha mask at its world rect', () => {+ const { selection, onChange } = createHarness();+ selection.selectAll(rectBounds(0, 0, 50, 50));+ const previousSurface = selection.mask()!.surface;+ const source = placedMask([0, 64, 255, 0]);+ onChange.mockClear();++ selection.replaceMask(source.placed);++ expect(selection.hasSelection()).toBe(true);+ expect(selection.bounds()).toEqual(source.placed.rect);+ expect(selection.mask()?.rect).toEqual(source.placed.rect);+ expect(selection.mask()?.surface).not.toBe(source.placed.surface);+ expect(selection.mask()?.surface).not.toBe(previousSurface);+ expect(selection.antsPaths()).toEqual([{ d: 'M 7 -3 L 9 -3 L 9 -1 L 7 -1 Z' } as unknown as Path2D]);++ const put = maskLog(selection).find((entry) => entry.op === 'putImageData');+ const copied = put?.args[0] as ImageData | undefined;+ expect(copied).toBeDefined();+ expect(copied).not.toBe(source.pixels);+ expect([...copied!.data]).toEqual([...source.pixels.data]);++ source.pixels.data.fill(0);+ expect(copied!.data.filter((_, index) => index % 4 === 3)).toEqual(new Uint8ClampedArray([0, 64, 255, 0]));+ expect(onChange).toHaveBeenCalledOnce();+ });++ it('clears the selection when the replacement has no alpha', () => {+ const { selection, onChange } = createHarness();+ selection.selectAll(rectBounds(0, 0, 50, 50));+ onChange.mockClear();++ selection.replaceMask(placedMask([0, 0, 0, 0]).placed);++ expect(selection.hasSelection()).toBe(false);+ expect(selection.bounds()).toBeNull();+ expect(selection.mask()).toBeNull();+ expect(selection.antsPaths()).toEqual([]);+ expect(onChange).toHaveBeenCalledOnce();+ });++ it('detaches an empty replacement without touching the prior mask surface', () => {+ const { selection, onChange } = createHarness();+ selection.selectAll(rectBounds(1, 2, 30, 40));+ const before = selection.mask()!;+ const beforePath = selection.antsPaths()[0];+ const previousLogLength = (before.surface as StubRasterSurface).callLog.length;+ const clearRect = vi.fn(() => {+ throw new Error('prior selection surface must not be cleared');+ });+ Object.defineProperty(before.surface.ctx, 'clearRect', { value: clearRect });+ onChange.mockClear();++ expect(() => selection.replaceMask(placedMask([0, 0, 0, 0]).placed)).not.toThrow();++ expect(clearRect).not.toHaveBeenCalled();+ expect((before.surface as StubRasterSurface).callLog).toHaveLength(previousLogLength);+ expect(before.rect).toEqual(rectBounds(1, 2, 30, 40));+ expect(beforePath).toBeDefined();+ expect(selection.hasSelection()).toBe(false);+ expect(selection.bounds()).toBeNull();+ expect(selection.mask()).toBeNull();+ expect(selection.antsPaths()).toEqual([]);+ expect(onChange).toHaveBeenCalledOnce();+ });++ it('preserves the exact prior selection when staging replacement pixels fails', () => {+ const { backend, selection, onChange } = createHarness();+ selection.selectAll(rectBounds(1, 2, 30, 40));+ const before = selection.mask()!;+ const beforePaths = selection.antsPaths();+ const createSurface = backend.createSurface;+ vi.spyOn(backend, 'createSurface').mockImplementation((width, height) => {+ const surface = createSurface(width, height);+ Object.defineProperty(surface.ctx, 'putImageData', {+ value: () => {+ throw new Error('selection pixel staging failed');+ },+ });+ return surface;+ });+ onChange.mockClear();++ expect(() => selection.replaceMask(placedMask([0, 64, 255, 0]).placed)).toThrow('selection pixel staging failed');++ expect(selection.mask()?.surface).toBe(before.surface);+ expect(selection.mask()?.rect).toEqual(before.rect);+ expect(selection.bounds()).toEqual(before.rect);+ expect(selection.antsPaths()).toHaveLength(beforePaths.length);+ expect(selection.antsPaths()[0]).toBe(beforePaths[0]);+ expect(selection.hasSelection()).toBe(true);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('preserves the exact prior selection when staging its ants path fails', () => {+ const backend = createTestStubRasterBackend();+ const onChange = vi.fn();+ let failPath = false;+ const selection = createSelectionState({+ backend,+ createPath2D: (d) => {+ if (failPath) {+ throw new Error('selection path staging failed');+ }+ return { d } as unknown as Path2D;+ },+ getDocumentSize: () => DOC,+ onChange,+ });+ selection.selectAll(rectBounds(1, 2, 30, 40));+ const before = selection.mask()!;+ const beforePaths = selection.antsPaths();+ failPath = true;+ onChange.mockClear();++ expect(() => selection.replaceMask(placedMask([0, 64, 255, 0]).placed)).toThrow('selection path staging failed');++ expect(selection.mask()?.surface).toBe(before.surface);+ expect(selection.mask()?.rect).toEqual(before.rect);+ expect(selection.bounds()).toEqual(before.rect);+ expect(selection.antsPaths()).toHaveLength(beforePaths.length);+ expect(selection.antsPaths()[0]).toBe(beforePaths[0]);+ expect(selection.hasSelection()).toBe(true);+ expect(onChange).not.toHaveBeenCalled();+ });+});+describe('selectionState: teardown + guards', () => {it('commit is a no-op with no document size', () => {const { selection, onChange } = createHarness(null);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.tsindex 35975b33fd..679180198e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts@@ -65,6 +65,8 @@ export interface SelectionState {containsPoint(p: Vec2): boolean;/** Applies a committed lasso path against the mask with the given boolean op. */commit(commit: SelectionCommit): void;+ /** Replaces the selection with an alpha-bearing surface placed in document space. */+ replaceMask(mask: PlacedSurface): void;/** Selects the whole `domain` rectangle (the engine passes `content ∪ bbox`). */selectAll(domain: Rect): void;/**@@ -205,6 +207,58 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =onChange();};+ const replaceMask = (next: PlacedSurface): void => {+ const rect = roundOut(next.rect);+ const publishEmptyReplacement = (): void => {+ // Replacing from a valid empty alpha result should not clear the old+ // surface in place: clearSurface() is fallible and would run after the+ // logical selection flags had already changed. Detach the old surface and+ // atomically publish an empty selection instead; it is reclaimed by GC.+ mask = null;+ maskRect = null;+ commits = [];+ selectionBounds = null;+ selected = false;+ onChange();+ };+ if (isEmpty(rect) || next.surface.width <= 0 || next.surface.height <= 0) {+ publishEmptyReplacement();+ return;+ }++ const source = next.surface.ctx.getImageData(0, 0, next.surface.width, next.surface.height);+ let hasAlpha = false;+ for (let index = 3; index < source.data.length; index += 4) {+ if (source.data[index] !== 0) {+ hasAlpha = true;+ break;+ }+ }+ if (!hasAlpha) {+ publishEmptyReplacement();+ return;+ }++ const copiedData = new Uint8ClampedArray(source.data);+ const copied =+ typeof ImageData === 'undefined'+ ? ({ colorSpace: source.colorSpace, data: copiedData, height: source.height, width: source.width } as ImageData)+ : new ImageData(copiedData, source.width, source.height);+ // Prepare every fallible replacement artifact before publishing any state.+ // If allocation, pixel upload, or Path2D construction fails, the exact prior+ // selection remains authoritative and the engine may safely report failure.+ const nextMask = backend.createSurface(rect.width, rect.height);+ nextMask.ctx.putImageData(copied, 0, 0);+ const nextPath = rectPath(createPath2D, rect);++ mask = nextMask;+ maskRect = rect;+ commits = [{ bounds: rect, op: 'replace', path: nextPath }];+ selectionBounds = rect;+ selected = true;+ onChange();+ };+const commit = (next: SelectionCommit): void => {if (!getDocumentSize()) {// No active document ⇒ no selection surface to build.@@ -339,6 +393,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =hasSelection: () => selected,invert,mask: () => (selected && mask && maskRect ? { rect: maskRect, surface: mask } : null),+ replaceMask,selectAll,};};diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.tsnew file mode 100644index 0000000000..9b1a2e9dc6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.test.ts@@ -0,0 +1,86 @@+import type { BackendGraphEdgeContract } from '@workbench/types';++import { describe, expect, it } from 'vitest';++import { buildSamGraph } from './samGraph';++const edge = (+ sourceNodeId: string,+ sourceField: string,+ targetNodeId: string,+ targetField: string+): BackendGraphEdgeContract => ({+ destination: { field: targetField, node_id: targetNodeId },+ source: { field: sourceField, node_id: sourceNodeId },+});++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) => {+ const { graph, outputNodeId } = buildSamGraph({+ applyPolygonRefinement,+ imageName: 'source.png',+ model,+ prompt: 'cat',+ });++ 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-detect', 'collection', 'sam-segment', 'bounding_boxes'),+ edge('sam-segment', 'mask', 'sam-output', 'mask'),+ ],+ id: 'select-object-sam',+ nodes: {+ 'sam-detect': {+ detection_threshold: 0.3,+ id: 'sam-detect',+ is_intermediate: true,+ model: 'grounding-dino-base',+ prompt: 'cat',+ 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,+ id: 'sam-segment',+ is_intermediate: true,+ mask_filter: 'largest',+ model,+ 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('rejects a blank object prompt', () => {+ expect(() =>+ buildSamGraph({+ applyPolygonRefinement: false,+ imageName: 'source.png',+ model: 'segment-anything-2-large',+ prompt: ' ',+ })+ ).toThrow('A Segment Anything object prompt is required.');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.tsnew file mode 100644index 0000000000..488b41ba51--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts@@ -0,0 +1,58 @@+import type { BackendGraphContract } from '@workbench/types';++import { addEdge, addNode } from '@workbench/generation/graphBuilder';++export type SamModel = 'segment-anything-2-large' | 'segment-anything-huge';++export interface BuildSamGraphOptions {+ imageName: string;+ prompt: string;+ model: SamModel;+ applyPolygonRefinement: boolean;+}++export interface BuiltSamGraph {+ graph: BackendGraphContract;+ outputNodeId: string;+}++export const buildSamGraph = (options: BuildSamGraphOptions): BuiltSamGraph => {+ const prompt = options.prompt.trim();+ if (!prompt) {+ throw new Error('A Segment Anything object prompt is required.');+ }++ const graph: BackendGraphContract = { edges: [], id: 'select-object-sam', nodes: {} };+ const source = addNode(graph, {+ id: 'sam-source',+ 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 segment = addNode(graph, {+ apply_polygon_refinement: options.applyPolygonRefinement,+ id: 'sam-segment',+ mask_filter: 'largest',+ model: options.model,+ type: 'segment_anything',+ });+ const output = addNode(graph, {+ id: 'sam-output',+ image: { image_name: options.imageName },+ invert: false,+ 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');+ addEdge(graph, segment, 'mask', output, 'mask');++ return { graph, outputNodeId: output.id };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex bb4b7b55a5..0a3eab3d71 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -30,6 +30,7 @@ import { useTranslation } from 'react-i18next';import type { LayerContextMenuItem, LayerContextMenuSection, LayerContextSubmenuId } from './layerContextMenuLayout';import type { LayerMoveKind } from './layerGroups';+import type { LayerMenuDialogKind, LayerMenuDialogState } from './layerMenuState';import type { LayerPropertiesSection } from './layerPropertiesRequestStore';import {@@ -70,6 +71,7 @@ import {getRegionalGuidanceReferenceImagePatch,} from './layerOps';import { requestLayerProperties } from './layerPropertiesRequestStore';+import { SelectObjectDialog } from './SelectObjectDialog';type MenuPositioning = ComponentProps<typeof Menu.Root>['positioning'];type MenuOpenChange = ComponentProps<typeof Menu.Root>['onOpenChange'];@@ -143,12 +145,12 @@ interface LayerMenuProps {lazyMount?: boolean;unmountOnExit?: boolean;/**- * Controlled rename-in-flight state. When provided (canvas right-click), the- * parent owns it so the rename dialog survives the menu closing (F1). Undefined- * ⇒ the menu keeps this state internally (panel).+ * Controlled sibling-dialog state. When provided (canvas right-click), the+ * parent owns it so dialogs survive the menu closing. Undefined means the menu+ * keeps this state internally (panel).*/- isRenaming?: boolean;- onRenamingChange?: (isRenaming: boolean) => void;+ dialogKind?: LayerMenuDialogKind | null;+ onDialogKindChange?: (kind: LayerMenuDialogKind | null) => void;}/**@@ -178,8 +180,8 @@ const LayerMenu = ({onOpenChange,lazyMount,unmountOnExit,- isRenaming: controlledRenaming,- onRenamingChange,+ dialogKind: controlledDialogKind,+ onDialogKindChange,}: LayerMenuProps) => {const { t } = useTranslation();const notify = useNotify();@@ -198,16 +200,16 @@ const LayerMenu = ({const hasSupportedContent = engine? engine.hasExportableLayerContent(layer.id): hasPureExportableLayerContent(layer, document);- const [internalRenaming, setInternalRenaming] = useState(false);- // Controlled (canvas) vs. uncontrolled (panel): the canvas parent owns the flag- // so the rename dialog outlives the menu closing. The panel keeps it internally.- const isRenaming = controlledRenaming ?? internalRenaming;- const setRenaming = useCallback(- (next: boolean) => {- setInternalRenaming(next);- onRenamingChange?.(next);+ const [internalDialogKind, setInternalDialogKind] = useState<LayerMenuDialogKind | null>(null);+ // Controlled (canvas) vs. uncontrolled (panel): the canvas parent owns the+ // dialog kind so its sibling survives menu close; panel rows keep it locally.+ const dialogKind = controlledDialogKind !== undefined ? controlledDialogKind : internalDialogKind;+ const setDialogKind = useCallback(+ (next: LayerMenuDialogKind | null) => {+ setInternalDialogKind(next);+ onDialogKindChange?.(next);},- [onRenamingChange]+ [onDialogKindChange]);const patchBase = useCallback(@@ -372,8 +374,9 @@ const LayerMenu = ({patchBase(t('widgets.layers.actions.toggleLock'), { isLocked: !layer.isLocked }, { isLocked: layer.isLocked });}, [layer.isLocked, patchBase, t]);- const openRename = useCallback(() => setRenaming(true), [setRenaming]);- const closeRename = useCallback(() => setRenaming(false), [setRenaming]);+ const openRename = useCallback(() => setDialogKind('rename'), [setDialogKind]);+ const closeDialog = useCallback(() => setDialogKind(null), [setDialogKind]);+ const openSelectObject = useCallback(() => setDialogKind('select-object'), [setDialogKind]);const submitRename = useCallback((name: string) => {patchBase(t('widgets.layers.actions.rename'), { name }, { name: layer.name });@@ -586,6 +589,7 @@ const LayerMenu = ({mergeDown: handleMerge,openProperties: handleOpenProperties,openRename,+ openSelectObject,patchConfig: handleLayerConfigAction,rasterize: handleRasterize,reorder: (kind, actionId) => reorder(kind, getActionLabel(actionId)),@@ -614,6 +618,7 @@ const LayerMenu = ({handleToggleVisibility,handleTransform,openRename,+ openSelectObject,reorder,]);@@ -663,13 +668,16 @@ const LayerMenu = ({</Menu.Root><RenameDialoginitialName={layer.name}- isOpen={isRenaming}+ isOpen={dialogKind === 'rename'}label={t('widgets.layers.actions.rename')}submitLabel={t('widgets.layers.actions.rename')}title={t('widgets.layers.actions.rename')}- onClose={closeRename}+ onClose={closeDialog}onSubmit={submitRename}/>+ {dialogKind === 'select-object' ? (+ <SelectObjectDialog engine={engine} isOpen layerId={layer.id} onClose={closeDialog} />+ ) : null}</>);};@@ -721,12 +729,10 @@ export const CanvasLayerContextMenu = ({target: CanvasLayerContextMenuTarget | null;onClose: () => void;}) => {- // The layer a pending rename is anchored to. Captured when the dialog opens (the- // live `target` is still set then) and cleared when it closes — set only inside- // the rename callback, never during render, so the rename dialog survives the menu- // closing (which nulls `target`).- const [renameTarget, setRenameTarget] = useState<CanvasLayerContextMenuTarget | null>(null);- const renderTarget = resolveMenuTargetForRender(target, renameTarget);+ // The layer a pending sibling dialog is anchored to. Captured while the live+ // target still exists, then retained until the dialog closes.+ const [dialogState, setDialogState] = useState<LayerMenuDialogState | null>(null);+ const renderTarget = resolveMenuTargetForRender(target, dialogState);const index = renderTarget ? layers.findIndex((entry) => entry.id === renderTarget.layerId) : -1;const layer = index >= 0 ? layers[index] : undefined;@@ -748,9 +754,9 @@ export const CanvasLayerContextMenu = ({},[onClose]);- const handleRenamingChange = useCallback(- (renaming: boolean) => {- setRenameTarget(renaming ? target : null);+ const handleDialogKindChange = useCallback(+ (kind: LayerMenuDialogKind | null) => {+ setDialogState(kind && target ? { kind, target } : null);},[target]);@@ -763,9 +769,9 @@ export const CanvasLayerContextMenu = ({<LayerMenukey={renderTarget.layerId}dispatch={dispatch}+ dialogKind={dialogState?.kind ?? null}engine={engine}index={index}- isRenaming={renameTarget !== null}layer={layer}layers={layers}lazyMount@@ -775,7 +781,7 @@ export const CanvasLayerContextMenu = ({positioning={positioning}unmountOnExitonOpenChange={handleOpenChange}- onRenamingChange={handleRenamingChange}+ onDialogKindChange={handleDialogKindChange}/>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/SelectObjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/SelectObjectDialog.tsxnew file mode 100644index 0000000000..39dc3392cb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/SelectObjectDialog.tsx@@ -0,0 +1,395 @@+import type { SelectValueChangeDetails } from '@chakra-ui/react';+import type { CanvasEngine } from '@workbench/canvas-engine/engine';+import type { SamModel } from '@workbench/generation/canvas/samGraph';+import type { ChangeEvent, FormEvent } from 'react';++import { chakra, createListCollection, Dialog, Input, Portal, Stack, Switch, Text } from '@chakra-ui/react';+import { socketHub } from '@workbench/backend/socketHub';+import { runUtilityGraph } from '@workbench/canvas-engine/backend/utilityQueue';+import { Button, CloseButton, Field, Select } from '@workbench/components/ui';+import { makeImageDurable } from '@workbench/gallery/api';+import { useNotify } from '@workbench/useNotify';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { createLayerActionSession } from './layerActionSession';+import {+ createDefaultSelectObjectOptions,+ isSelectObjectPromptValid,+ routeSelectObjectResult,+ runSelectObject,+ type SelectObjectRouteResult,+ type SelectObjectRunResult,+ type SelectObjectTarget,+} from './layerImageResult';++interface SelectObjectDialogProps {+ engine: CanvasEngine | null;+ isOpen: boolean;+ layerId: string;+ onClose(): void;+}++const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;++const messageOf = (result: { message: string }): string => result.message;++export const SelectObjectDialog = ({ engine, isOpen, layerId, onClose }: SelectObjectDialogProps) => {+ const { t } = useTranslation();+ const notify = useNotify();+ const defaults = createDefaultSelectObjectOptions();+ const [session] = useState(createLayerActionSession);+ const [prompt, setPrompt] = useState(defaults.prompt);+ const [model, setModel] = useState<SamModel>(defaults.model);+ const [applyPolygonRefinement, setApplyPolygonRefinement] = useState(defaults.applyPolygonRefinement);+ const [target, setTarget] = useState<SelectObjectTarget>(defaults.target);+ const [isRunning, setIsRunning] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const modelCollection = useMemo(+ () =>+ createListCollection<{ label: string; value: SamModel }>({+ items: [+ { label: t('widgets.layers.selectObject.modelSam2Large'), value: 'segment-anything-2-large' },+ { label: t('widgets.layers.selectObject.modelHuge'), value: 'segment-anything-huge' },+ ],+ }),+ [t]+ );+ const targetCollection = useMemo(+ () =>+ createListCollection<{ label: string; value: SelectObjectTarget }>({+ items: [+ { label: t('widgets.layers.selectObject.targetSelection'), value: 'selection' },+ { label: t('widgets.layers.selectObject.targetInpaintMask'), value: 'inpaint_mask' },+ { label: t('widgets.layers.selectObject.targetRegionalGuidance'), value: 'regional_guidance' },+ ],+ }),+ [t]+ );+ const modelValue = useMemo(() => [model], [model]);+ const targetValue = useMemo(() => [target], [target]);++ const reset = useCallback(() => {+ const next = createDefaultSelectObjectOptions();+ setPrompt(next.prompt);+ setModel(next.model);+ setApplyPolygonRefinement(next.applyPolygonRefinement);+ setTarget(next.target);+ setError(null);+ setIsRunning(false);+ }, []);++ const close = useCallback(() => {+ session.cancel();+ reset();+ onClose();+ }, [onClose, reset, session]);++ const contentRef = useCallback(+ (node: HTMLDivElement | null) => {+ if (!node) {+ return;+ }+ return () => {+ session.cancel();+ };+ },+ [session]+ );++ const handleOpenChange = useCallback(+ ({ open }: { open: boolean }) => {+ if (!open) {+ close();+ }+ },+ [close]+ );+ const handlePromptChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {+ setPrompt(event.currentTarget.value);+ setError(null);+ }, []);+ const handleModelChange = useCallback(({ value }: SelectValueChangeDetails) => {+ const next = value[0] as SamModel | undefined;+ if (next) {+ setModel(next);+ }+ }, []);+ const handleTargetChange = useCallback(({ value }: SelectValueChangeDetails) => {+ const next = value[0] as SelectObjectTarget | undefined;+ if (next) {+ setTarget(next);+ }+ }, []);+ const handleRefinementChange = useCallback(({ checked }: { checked: boolean }) => {+ setApplyPolygonRefinement(checked);+ }, []);++ const showRunFailure = useCallback(+ (result: Exclude<SelectObjectRunResult, { status: 'ready' }>) => {+ switch (result.status) {+ case 'aborted':+ setError(t('widgets.layers.selectObject.aborted'));+ return;+ case 'missing':+ case 'disabled':+ case 'unsupported':+ case 'empty':+ case 'not-ready':+ setError(+ t(+ result.status === 'not-ready'+ ? 'widgets.layers.selectObject.notReady'+ : `widgets.layers.selectObject.${result.status}`+ )+ );+ return;+ case 'failed':+ setError(t('widgets.layers.selectObject.failed', { message: messageOf(result) }));+ return;+ }+ },+ [t]+ );++ const showRouteResult = useCallback(+ (result: SelectObjectRouteResult, requestedTarget: SelectObjectTarget): boolean => {+ switch (result.status) {+ case 'selected':+ notify.success(t('widgets.layers.selectObject.selectionSuccess'));+ return true;+ case 'committed':+ notify.success(+ t(+ requestedTarget === 'inpaint_mask'+ ? 'widgets.layers.selectObject.inpaintMaskSuccess'+ : 'widgets.layers.selectObject.regionalGuidanceSuccess'+ )+ );+ return true;+ case 'aborted':+ setError(t('widgets.layers.selectObject.aborted'));+ return false;+ case 'missing':+ case 'stale':+ setError(t('widgets.layers.selectObject.stale'));+ return false;+ case 'locked':+ case 'unsupported':+ case 'busy':+ setError(t(`widgets.layers.selectObject.${result.status}`));+ return false;+ case 'failed':+ setError(+ t(+ requestedTarget === 'selection'+ ? 'widgets.layers.selectObject.failed'+ : 'widgets.layers.selectObject.durabilityFailure',+ { message: messageOf(result) }+ )+ );+ return false;+ }+ },+ [notify, t]+ );++ const runContext = useMemo(+ () => ({+ applyPolygonRefinement,+ close,+ engine,+ layerId,+ model,+ prompt,+ session,+ showRouteResult,+ showRunFailure,+ target,+ }),+ [applyPolygonRefinement, close, engine, layerId, model, prompt, session, showRouteResult, showRunFailure, target]+ );++ const run = useCallback(async (): Promise<void> => {+ const {+ applyPolygonRefinement,+ close,+ engine,+ layerId,+ model,+ prompt,+ session,+ showRouteResult,+ showRunFailure,+ target,+ } = runContext;+ if (!engine || !isSelectObjectPromptValid(prompt)) {+ return;+ }+ const request = session.begin();+ if (!request) {+ return;+ }+ const requestedTarget = target;+ setError(null);+ setIsRunning(true);+ try {+ const executorDeps = engine.getCompositeExecutorDeps();+ const result = await runSelectObject({+ applyPolygonRefinement,+ deps: {+ exportLayer: () => engine.exportBakedLayerBlob(layerId, { includeDisabled: true }),+ runGraph: (options) => runUtilityGraph({ ...options, hub: socketHub }),+ uploadIntermediate: async (blob, signal) => {+ if (signal?.aborted) {+ throw new DOMException('Object selection aborted', 'AbortError');+ }+ const uploaded = await executorDeps.uploadImage(blob);+ if (signal?.aborted) {+ throw new DOMException('Object selection aborted', 'AbortError');+ }+ return { imageName: uploaded.imageName };+ },+ },+ layerId,+ model,+ prompt,+ signal: request.signal,+ });+ if (!session.isCurrent(request.token)) {+ return;+ }+ if (result.status !== 'ready') {+ showRunFailure(result);+ return;+ }+ const routed = await routeSelectObjectResult({+ deps: {+ commitMaskImageResult: (options) => engine.commitMaskImageResult(options),+ makeImageDurable,+ replaceSelectionFromImage: (guard, image, rect, signal) =>+ engine.replaceSelectionFromImage(guard, image, rect, signal),+ },+ isCurrent: () => session.isCurrent(request.token),+ result,+ signal: request.signal,+ target: requestedTarget,+ });+ if (!session.isCurrent(request.token)) {+ return;+ }+ if (showRouteResult(routed, requestedTarget)) {+ close();+ }+ } finally {+ if (session.isCurrent(request.token)) {+ setIsRunning(false);+ }+ session.finish(request.token);+ }+ }, [runContext]);++ const handleSubmit = useCallback(+ (event: FormEvent<HTMLFormElement>): void => {+ event.preventDefault();+ void run();+ },+ [run]+ );++ const canRun = engine !== null && !isRunning && isSelectObjectPromptValid(prompt);++ return (+ <Dialog.Root lazyMount open={isOpen} placement="center" size="sm" unmountOnExit onOpenChange={handleOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content ref={contentRef} bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" color="fg">+ <chakra.form onSubmit={handleSubmit}>+ <Dialog.Header>+ <Dialog.Title fontSize="sm" fontWeight="700">+ {t('widgets.layers.selectObject.title')}+ </Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="4">+ <Field id="select-object-prompt" label={t('widgets.layers.selectObject.prompt')} required>+ <Input+ autoFocus+ aria-label={t('widgets.layers.selectObject.prompt')}+ autoComplete="off"+ disabled={isRunning}+ name="selectObjectPrompt"+ placeholder={t('widgets.layers.selectObject.promptPlaceholder')}+ size="sm"+ value={prompt}+ onChange={handlePromptChange}+ />+ </Field>+ <Field label={t('widgets.layers.selectObject.model')}>+ <Select+ aria-label={t('widgets.layers.selectObject.model')}+ collection={modelCollection}+ disabled={isRunning}+ positioning={SELECT_POSITIONING}+ size="sm"+ value={modelValue}+ onValueChange={handleModelChange}+ />+ </Field>+ <Field label={t('widgets.layers.selectObject.target')}>+ <Select+ aria-label={t('widgets.layers.selectObject.target')}+ collection={targetCollection}+ disabled={isRunning}+ positioning={SELECT_POSITIONING}+ size="sm"+ value={targetValue}+ onValueChange={handleTargetChange}+ />+ </Field>+ <Switch.Root+ checked={applyPolygonRefinement}+ disabled={isRunning}+ size="sm"+ onCheckedChange={handleRefinementChange}+ >+ <Switch.HiddenInput />+ <Switch.Control>+ <Switch.Thumb />+ </Switch.Control>+ <Switch.Label>+ <Text fontSize="xs">{t('widgets.layers.selectObject.refine')}</Text>+ </Switch.Label>+ </Switch.Root>+ {error ? (+ <Text color="fg.error" fontSize="xs" role="alert">+ {error}+ </Text>+ ) : null}+ {isRunning ? (+ <Text color="fg.muted" fontSize="xs" role="status">+ {t('widgets.layers.selectObject.running')}+ </Text>+ ) : null}+ </Stack>+ </Dialog.Body>+ <Dialog.Footer gap="2">+ <Button size="xs" type="button" variant="ghost" onClick={close}>+ {t('widgets.layers.selectObject.cancel')}+ </Button>+ <Button disabled={!canRun} loading={isRunning} size="xs" type="submit" variant="solid">+ {t('widgets.layers.selectObject.run')}+ </Button>+ </Dialog.Footer>+ </chakra.form>+ <Dialog.CloseTrigger asChild>+ <CloseButton aria-label={t('widgets.layers.selectObject.cancel')} color="fg.muted" size="sm" />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerActionSession.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerActionSession.test.tsnew file mode 100644index 0000000000..40deb1c6b1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerActionSession.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { createLayerActionSession } from './layerActionSession';++describe('createLayerActionSession', () => {+ it('allows only one request at a time and permits a new request after current finish', () => {+ const session = createLayerActionSession();+ const first = session.begin();++ expect(first).not.toBeNull();+ expect(session.begin()).toBeNull();+ expect(session.isCurrent(first!.token)).toBe(true);+ session.finish(first!.token);+ expect(session.isCurrent(first!.token)).toBe(false);+ expect(session.begin()).not.toBeNull();+ });++ it('cancel aborts and invalidates the active request while keeping the session reusable', () => {+ const session = createLayerActionSession();+ const first = session.begin()!;++ session.cancel();++ expect(first.signal.aborted).toBe(true);+ expect(session.isCurrent(first.token)).toBe(false);+ const second = session.begin();+ expect(second).not.toBeNull();+ expect(second!.token).not.toBe(first.token);+ });++ it('ignores stale finish so an old completion cannot clear the current request', () => {+ const session = createLayerActionSession();+ const first = session.begin()!;+ session.cancel();+ const second = session.begin()!;++ session.finish(first.token);++ expect(session.isCurrent(second.token)).toBe(true);+ expect(session.begin()).toBeNull();+ });++ it('rejects a late completion after close/cancel invalidates its token', () => {+ const session = createLayerActionSession();+ const request = session.begin()!;+ const wasCurrent = () => session.isCurrent(request.token);++ session.cancel();++ expect(wasCurrent()).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerActionSession.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerActionSession.tsnew file mode 100644index 0000000000..6f24b0437c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerActionSession.ts@@ -0,0 +1,39 @@+export interface LayerActionRequest {+ token: number;+ signal: AbortSignal;+}++export interface LayerActionSession {+ begin(): LayerActionRequest | null;+ cancel(): void;+ finish(token: number): void;+ isCurrent(token: number): boolean;+}++export const createLayerActionSession = (): LayerActionSession => {+ let nextToken = 0;+ let active: { controller: AbortController; token: number } | null = null;++ return {+ begin: () => {+ if (active) {+ return null;+ }+ const controller = new AbortController();+ const token = ++nextToken;+ active = { controller, token };+ return { signal: controller.signal, token };+ },+ cancel: () => {+ nextToken += 1;+ active?.controller.abort();+ active = null;+ },+ finish: (token) => {+ if (active?.token === token) {+ active = null;+ }+ },+ isCurrent: (token) => active?.token === token && !active.controller.signal.aborted,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex 78df6165c5..67270c3969 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -88,6 +88,7 @@ const makeEffects = (): LayerContextActionEffects => ({mergeDown: vi.fn(),openProperties: vi.fn(),openRename: vi.fn(),+ openSelectObject: vi.fn(),patchConfig: vi.fn(),rasterize: vi.fn(),reorder: vi.fn(),@@ -181,6 +182,34 @@ describe('layer context action registry', () => {'widgets.layers.rasterFilter.stale','widgets.layers.rasterFilter.title','widgets.layers.rasterFilter.unsupported',+ 'widgets.layers.selectObject.aborted',+ 'widgets.layers.selectObject.busy',+ 'widgets.layers.selectObject.cancel',+ 'widgets.layers.selectObject.durabilityFailure',+ 'widgets.layers.selectObject.disabled',+ 'widgets.layers.selectObject.empty',+ 'widgets.layers.selectObject.failed',+ 'widgets.layers.selectObject.locked',+ 'widgets.layers.selectObject.model',+ 'widgets.layers.selectObject.modelHuge',+ 'widgets.layers.selectObject.modelSam2Large',+ 'widgets.layers.selectObject.missing',+ 'widgets.layers.selectObject.notReady',+ 'widgets.layers.selectObject.prompt',+ 'widgets.layers.selectObject.promptPlaceholder',+ 'widgets.layers.selectObject.refine',+ 'widgets.layers.selectObject.run',+ 'widgets.layers.selectObject.running',+ 'widgets.layers.selectObject.selectionSuccess',+ 'widgets.layers.selectObject.inpaintMaskSuccess',+ 'widgets.layers.selectObject.regionalGuidanceSuccess',+ 'widgets.layers.selectObject.stale',+ 'widgets.layers.selectObject.target',+ 'widgets.layers.selectObject.targetInpaintMask',+ 'widgets.layers.selectObject.targetRegionalGuidance',+ 'widgets.layers.selectObject.targetSelection',+ 'widgets.layers.selectObject.title',+ 'widgets.layers.selectObject.unsupported',];for (const key of keys) {@@ -201,6 +230,16 @@ describe('layer context action registry', () => {expect(transform).toHaveBeenCalledOnce();});+ it('opens Select Object through the registry without starting work itself', () => {+ const effects = makeEffects();+ const context = makeRuntimeContext(rasterLayer, { effects });++ getLayerContextActionDefinition('select-object').handler(context);++ expect(effects.openSelectObject).toHaveBeenCalledOnce();+ expect(Object.values(effects).filter((effect) => effect.mock.calls.length > 0)).toEqual([effects.openSelectObject]);+ });+it('dispatches parameterized registry handlers through injected effects', () => {const effects = makeEffects();const context = makeRuntimeContext(rasterLayer, { effects });@@ -244,6 +283,33 @@ describe('getLayerContextActions', () => {expect(Boolean(action)).toBe(expected);});+ it.each([+ ['raster', true],+ ['control', true],+ ['inpaint_mask', false],+ ['regional_guidance', false],+ ] as const)('exposes Select Object only for exportable %s content', (type, expected) => {+ const action = getLayerContextActions(makeState(makeLayer(type))).find((item) => item.id === 'select-object');+ expect(Boolean(action)).toBe(expected);+ });++ it('hides Select Object without supported source content', () => {+ expect(+ getLayerContextActions(makeState(rasterLayer, { hasSupportedContent: false })).some(+ (action) => action.id === 'select-object'+ )+ ).toBe(false);+ });++ it.each([+ ['missing engine', { hasEngine: false }],+ ['locked layer', { layer: { ...rasterLayer, isLocked: true } }],+ ['locked interaction', { interactionLocked: true }],+ ] as const)('disables Select Object for %s', (_label, overrides) => {+ const layer = 'layer' in overrides ? overrides.layer : rasterLayer;+ expect(byId(getLayerContextActions(makeState(layer, overrides)), 'select-object').isDisabled).toBe(true);+ });+it('disables transform for a hidden layer', () => {const hidden = { ...rasterLayer, isEnabled: false };expect(byId(getLayerContextActions(makeState(hidden)), 'transform').isDisabled).toBe(true);@@ -302,6 +368,7 @@ describe('getLayerContextActions', () => {'crop-to-bbox','extract-masked-area','filter',+ 'select-object','intersect','cutout','cutaway',@@ -348,6 +415,7 @@ describe('getLayerContextActions', () => {'fit-to-bbox','adjustments','filter',+ 'select-object','crop-to-bbox','convert-to-control','intersect',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex 878d4ee211..8995b6f402 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -18,6 +18,7 @@ import {MergeIcon,PencilIcon,SaveIcon,+ ScanSearchIcon,SlidersHorizontalIcon,Trash2Icon,} from 'lucide-react';@@ -43,6 +44,7 @@ export type LayerContextActionId =| 'crop-to-bbox'| 'extract-masked-area'| 'filter'+ | 'select-object'| 'intersect'| 'cutout'| 'cutaway'@@ -85,6 +87,7 @@ export interface LayerContextActionEffects {reorder(kind: LayerMoveKind, actionId: LayerContextActionId): void;duplicate(): void;openRename(): void;+ openSelectObject(): void;transform(): void;fitToBbox(): void;openProperties(section: LayerPropertiesSection): void;@@ -414,6 +417,18 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinisection: 'primary',supportedLayerTypes: RASTER_AND_CONTROL,},+ {+ defaultLabel: 'Select object',+ handler: ({ effects }) => effects.openSelectObject(),+ icon: ScanSearchIcon,+ id: 'select-object',+ isEnabled: hasMutablePixels,+ isVisible: (context) => context.hasSupportedContent,+ labelKey: 'widgets.layers.actions.selectObject',+ order: 41,+ section: 'primary',+ supportedLayerTypes: RASTER_AND_CONTROL,+ },{defaultLabel: 'Toggle transparency effect',getDefaultLabel: (context) =>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex e6ca396396..2ad190f45d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -63,7 +63,11 @@ describe('getLayerContextMenuLayout', () => {items: ['arrange(move-to-front,move-forward,move-backward,move-to-back)', 'duplicate'],presentation: 'row',},- { id: 'primary', items: ['transform', 'rename', 'fit-to-bbox', 'adjustments', 'filter'], presentation: 'list' },+ {+ id: 'primary',+ items: ['transform', 'rename', 'fit-to-bbox', 'adjustments', 'filter', 'select-object'],+ presentation: 'list',+ },{id: 'operations',items: [@@ -109,7 +113,7 @@ describe('getLayerContextMenuLayout', () => {expect(summarize(control)[1]).toEqual({id: 'primary',- items: ['transform', 'rename', 'fit-to-bbox', 'filter', 'control-transparency-effect'],+ items: ['transform', 'rename', 'fit-to-bbox', 'filter', 'select-object', 'control-transparency-effect'],presentation: 'list',});expect(summarize(control)[2]).toEqual({diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.tsnew file mode 100644index 0000000000..ed5e06bcc9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.ts@@ -0,0 +1,378 @@+import type { LayerExportGuard } from '@workbench/canvas-engine/engine';+import type { CanvasRasterLayerContractV2 } from '@workbench/types';++import { describe, expect, it, vi } from 'vitest';++import type { SelectObjectRouteDeps, SelectObjectRunnerDeps } from './layerImageResult';++import {+ createDefaultSelectObjectOptions,+ isSelectObjectPromptValid,+ routeSelectObjectResult,+ runSelectObject,+} from './layerImageResult';++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 rect = { height: 12, width: 16, x: -5, y: 7 };+const blob = new Blob(['source'], { type: 'image/png' });+const ready = {+ guard,+ image: { height: 12, imageName: 'sam-output.png', width: 16 },+ rect,+ status: 'ready' as const,+};++const createDeferred = <T>(): { promise: Promise<T>; resolve(value: T): void } => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+};++const createRunnerDeps = (overrides: Partial<SelectObjectRunnerDeps> = {}): SelectObjectRunnerDeps => ({+ exportLayer: vi.fn(() => Promise.resolve({ blob, guard, rect, status: 'ok' as const })),+ runGraph: vi.fn(() => Promise.resolve({ imageName: 'sam-output.png', origin: 'webv2:util:test' })),+ uploadIntermediate: vi.fn(() => Promise.resolve({ imageName: 'sam-input.png' })),+ ...overrides,+});++describe('select-object defaults and validation', () => {+ it('defaults to SAM 2 Large, no polygon refinement, and a transient selection', () => {+ expect(createDefaultSelectObjectOptions()).toEqual({+ applyPolygonRefinement: false,+ model: 'segment-anything-2-large',+ prompt: '',+ target: 'selection',+ });+ });++ it('requires a non-blank object prompt', () => {+ expect(isSelectObjectPromptValid(' ')).toBe(false);+ expect(isSelectObjectPromptValid(' cat ')).toBe(true);+ });+});++describe('runSelectObject', () => {+ it('exports, uploads, builds, and runs the exact SAM utility graph in order', async () => {+ const calls: string[] = [];+ const controller = new AbortController();+ const deps = createRunnerDeps({+ exportLayer: vi.fn((layerId) => {+ expect(layerId).toBe('source');+ calls.push('export');+ return Promise.resolve({ blob, guard, rect, status: 'ok' as const });+ }),+ runGraph: vi.fn(({ graph, outputNodeId, signal }) => {+ calls.push('run');+ expect(outputNodeId).toBe('sam-output');+ expect(signal).toBe(controller.signal);+ expect(graph.nodes['sam-detect']).toMatchObject({+ detection_threshold: 0.3,+ prompt: 'cat',+ type: 'grounding_dino',+ });+ expect(graph.nodes['sam-segment']).toMatchObject({+ apply_polygon_refinement: true,+ model: 'segment-anything-huge',+ type: 'segment_anything',+ });+ return Promise.resolve({ imageName: 'sam-output.png', origin: 'webv2:util:test' });+ }),+ uploadIntermediate: vi.fn((receivedBlob, signal) => {+ expect(receivedBlob).toBe(blob);+ expect(signal).toBe(controller.signal);+ calls.push('upload');+ return Promise.resolve({ imageName: 'sam-input.png' });+ }),+ });++ await expect(+ runSelectObject({+ applyPolygonRefinement: true,+ deps,+ layerId: 'source',+ model: 'segment-anything-huge',+ prompt: ' cat ',+ signal: controller.signal,+ })+ ).resolves.toEqual(ready);+ expect(calls).toEqual(['export', 'upload', 'run']);+ });++ it.each(['missing', 'disabled', 'unsupported', 'empty', 'not-ready'] as const)(+ 'forwards an export %s status without uploading',+ async (status) => {+ const deps = createRunnerDeps({ exportLayer: vi.fn(() => Promise.resolve({ status })) });++ await expect(+ runSelectObject({+ applyPolygonRefinement: false,+ deps,+ layerId: 'source',+ model: 'segment-anything-2-large',+ prompt: 'cat',+ })+ ).resolves.toEqual({ status });+ expect(deps.uploadIntermediate).not.toHaveBeenCalled();+ expect(deps.runGraph).not.toHaveBeenCalled();+ }+ );++ it.each(['before export', 'after export', 'after upload', 'after graph'] as const)(+ 'returns aborted $label and starts no later boundary',+ async (label) => {+ const controller = new AbortController();+ if (label === 'before export') {+ controller.abort();+ }+ const deps = createRunnerDeps({+ exportLayer: vi.fn(() => {+ if (label === 'after export') {+ controller.abort();+ }+ return Promise.resolve({ blob, guard, rect, status: 'ok' as const });+ }),+ runGraph: vi.fn(() => {+ if (label === 'after graph') {+ controller.abort();+ }+ return Promise.resolve({ imageName: 'sam-output.png', origin: 'webv2:util:test' });+ }),+ uploadIntermediate: vi.fn(() => {+ if (label === 'after upload') {+ controller.abort();+ }+ return Promise.resolve({ imageName: 'sam-input.png' });+ }),+ });++ await expect(+ runSelectObject({+ applyPolygonRefinement: false,+ deps,+ layerId: 'source',+ model: 'segment-anything-2-large',+ prompt: 'cat',+ signal: controller.signal,+ })+ ).resolves.toEqual({ status: 'aborted' });+ expect(deps.exportLayer).toHaveBeenCalledTimes(label === 'before export' ? 0 : 1);+ expect(deps.uploadIntermediate).toHaveBeenCalledTimes(+ label === 'before export' || label === 'after export' ? 0 : 1+ );+ expect(deps.runGraph).toHaveBeenCalledTimes(label === 'after graph' ? 1 : 0);+ }+ );++ it('maps AbortError to aborted and unexpected errors to failed', async () => {+ const aborted = createRunnerDeps({+ uploadIntermediate: vi.fn(() => Promise.reject(new DOMException('', 'AbortError'))),+ });+ const failed = createRunnerDeps({ runGraph: vi.fn(() => Promise.reject(new Error('SAM graph failed'))) });+ const options = {+ applyPolygonRefinement: false,+ layerId: 'source',+ model: 'segment-anything-2-large' as const,+ prompt: 'cat',+ };++ await expect(runSelectObject({ ...options, deps: aborted })).resolves.toEqual({ status: 'aborted' });+ await expect(runSelectObject({ ...options, deps: failed })).resolves.toEqual({+ message: 'SAM graph failed',+ status: 'failed',+ });+ });+});++describe('routeSelectObjectResult', () => {+ const createDeps = () => ({+ commitMaskImageResult: vi.fn<SelectObjectRouteDeps['commitMaskImageResult']>(() =>+ Promise.resolve({ layerId: 'new-mask', status: 'committed' as const })+ ),+ makeImageDurable: vi.fn<SelectObjectRouteDeps['makeImageDurable']>(() => Promise.resolve()),+ replaceSelectionFromImage: vi.fn<SelectObjectRouteDeps['replaceSelectionFromImage']>(() =>+ Promise.resolve({ status: 'selected' as const })+ ),+ });++ it('routes selection without making the intermediate image durable', async () => {+ const deps = createDeps();+ const signal = new AbortController().signal;++ await expect(+ routeSelectObjectResult({ deps, isCurrent: () => true, result: ready, signal, target: 'selection' })+ ).resolves.toEqual({ status: 'selected' });+ expect(deps.replaceSelectionFromImage).toHaveBeenCalledWith(guard, ready.image, rect, signal);+ expect(deps.makeImageDurable).not.toHaveBeenCalled();+ expect(deps.commitMaskImageResult).not.toHaveBeenCalled();+ });++ it('preserves an authoritative selected result when the session invalidates after the engine mutation', async () => {+ const deps = createDeps();+ let current = true;+ deps.replaceSelectionFromImage.mockImplementation(() => {+ current = false;+ return Promise.resolve({ status: 'selected' });+ });++ await expect(+ routeSelectObjectResult({+ deps,+ isCurrent: () => current,+ result: ready,+ signal: new AbortController().signal,+ target: 'selection',+ })+ ).resolves.toEqual({ status: 'selected' });+ });++ it.each(['inpaint_mask', 'regional_guidance'] as const)(+ 'makes the image durable before committing %s',+ async (target) => {+ const calls: string[] = [];+ const deps = createDeps();+ deps.makeImageDurable.mockImplementation(() => {+ calls.push('durable');+ return Promise.resolve();+ });+ deps.commitMaskImageResult.mockImplementation((options) => {+ calls.push('commit');+ expect(options).toEqual({ guard, image: ready.image, rect, signal: expect.any(AbortSignal), target });+ return Promise.resolve({ layerId: 'new-mask', status: 'committed' as const });+ });++ await expect(+ routeSelectObjectResult({+ deps,+ isCurrent: () => true,+ result: ready,+ signal: new AbortController().signal,+ target,+ })+ ).resolves.toEqual({ layerId: 'new-mask', status: 'committed' });+ expect(calls).toEqual(['durable', 'commit']);+ expect(deps.replaceSelectionFromImage).not.toHaveBeenCalled();+ }+ );++ it('does not commit when cancellation lands during durability promotion', async () => {+ const durable = createDeferred<void>();+ const controller = new AbortController();+ const deps = createDeps();+ deps.makeImageDurable.mockReturnValue(durable.promise);+ const pending = routeSelectObjectResult({+ deps,+ isCurrent: () => true,+ result: ready,+ signal: controller.signal,+ target: 'inpaint_mask',+ });+ controller.abort();+ durable.resolve();++ await expect(pending).resolves.toEqual({ status: 'aborted' });+ expect(deps.commitMaskImageResult).not.toHaveBeenCalled();+ });++ it('rejects a stale session after durability promotion without committing', async () => {+ const deps = createDeps();+ let current = true;+ deps.makeImageDurable.mockImplementation(() => {+ current = false;+ return Promise.resolve();+ });++ await expect(+ routeSelectObjectResult({+ deps,+ isCurrent: () => current,+ result: ready,+ signal: new AbortController().signal,+ target: 'regional_guidance',+ })+ ).resolves.toEqual({ status: 'stale' });+ expect(deps.commitMaskImageResult).not.toHaveBeenCalled();+ });++ it('preserves an authoritative committed result when the session invalidates after the engine mutation', async () => {+ const deps = createDeps();+ let current = true;+ deps.commitMaskImageResult.mockImplementation(() => {+ current = false;+ return Promise.resolve({ layerId: 'new-mask', status: 'committed' });+ });++ await expect(+ routeSelectObjectResult({+ deps,+ isCurrent: () => current,+ result: ready,+ signal: new AbortController().signal,+ target: 'regional_guidance',+ })+ ).resolves.toEqual({ layerId: 'new-mask', status: 'committed' });+ });++ it('maps durability and dependency failures without a late mutation', async () => {+ const durability = createDeps();+ durability.makeImageDurable.mockRejectedValue(new Error('promotion failed'));+ const selection = createDeps();+ selection.replaceSelectionFromImage.mockRejectedValue(new Error('selection failed'));++ await expect(+ routeSelectObjectResult({+ deps: durability,+ isCurrent: () => true,+ result: ready,+ signal: new AbortController().signal,+ target: 'inpaint_mask',+ })+ ).resolves.toEqual({ message: 'promotion failed', status: 'failed' });+ expect(durability.commitMaskImageResult).not.toHaveBeenCalled();+ await expect(+ routeSelectObjectResult({+ deps: selection,+ isCurrent: () => true,+ result: ready,+ signal: new AbortController().signal,+ target: 'selection',+ })+ ).resolves.toEqual({ message: 'selection failed', status: 'failed' });+ });++ it.each(['aborted', 'missing', 'locked', 'stale', 'unsupported', 'busy'] as const)(+ 'forwards engine status %s exhaustively',+ async (status) => {+ const deps = createDeps();+ deps.commitMaskImageResult.mockResolvedValue({ status });++ await expect(+ routeSelectObjectResult({+ deps,+ isCurrent: () => true,+ result: ready,+ signal: new AbortController().signal,+ target: 'inpaint_mask',+ })+ ).resolves.toEqual({ status });+ }+ );+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.tsnew file mode 100644index 0000000000..69dae7ea70--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts@@ -0,0 +1,186 @@+import type { RunUtilityGraphOptions, UtilityGraphResult } from '@workbench/canvas-engine/backend/utilityQueue';+import type {+ CommitMaskImageResult,+ CommitMaskImageResultOptions,+ ExportBakedLayerBlobResult,+ LayerExportGuard,+ ReplaceSelectionFromImageResult,+} from '@workbench/canvas-engine/engine';+import type { Rect } from '@workbench/canvas-engine/types';+import type { SamModel } from '@workbench/generation/canvas/samGraph';+import type { CanvasImageRef } from '@workbench/types';++import { buildSamGraph } from '@workbench/generation/canvas/samGraph';++export type SelectObjectTarget = 'selection' | 'inpaint_mask' | 'regional_guidance';++export interface SelectObjectOptions {+ applyPolygonRefinement: boolean;+ model: SamModel;+ prompt: string;+ target: SelectObjectTarget;+}++export const createDefaultSelectObjectOptions = (): SelectObjectOptions => ({+ applyPolygonRefinement: false,+ model: 'segment-anything-2-large',+ prompt: '',+ target: 'selection',+});++export const isSelectObjectPromptValid = (prompt: string): boolean => prompt.trim().length > 0;++export interface SelectObjectReadyResult {+ status: 'ready';+ image: CanvasImageRef;+ rect: Rect;+ guard: LayerExportGuard;+}++export type SelectObjectRunResult =+ | SelectObjectReadyResult+ | { status: 'aborted' | 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' }+ | { status: 'failed'; message: string };++export interface SelectObjectRunnerDeps {+ exportLayer(layerId: string): Promise<ExportBakedLayerBlobResult>;+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;+ runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>): Promise<UtilityGraphResult>;+}++export interface RunSelectObjectOptions {+ layerId: string;+ prompt: string;+ model: SamModel;+ applyPolygonRefinement: boolean;+ signal?: AbortSignal;+ deps: SelectObjectRunnerDeps;+}++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) {+ return { status: 'aborted' };+ }+ try {+ const exported = await options.deps.exportLayer(options.layerId);+ if (options.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) {+ return { status: 'aborted' };+ }+ const built = buildSamGraph({+ applyPolygonRefinement: options.applyPolygonRefinement,+ imageName: uploaded.imageName,+ model: options.model,+ prompt: options.prompt,+ });+ const output = await options.deps.runGraph({+ graph: built.graph,+ outputNodeId: built.outputNodeId,+ signal: options.signal,+ });+ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }+ return {+ guard: exported.guard,+ image: { height: exported.rect.height, imageName: output.imageName, width: exported.rect.width },+ rect: exported.rect,+ status: 'ready',+ };+ } catch (error) {+ if (options.signal?.aborted || isAbortError(error)) {+ return { status: 'aborted' };+ }+ return { message: errorMessage(error), status: 'failed' };+ }+};++export type SelectObjectRouteResult = ReplaceSelectionFromImageResult | CommitMaskImageResult;++export interface SelectObjectRouteDeps {+ replaceSelectionFromImage(+ guard: LayerExportGuard,+ image: CanvasImageRef,+ rect: Rect,+ signal?: AbortSignal+ ): Promise<ReplaceSelectionFromImageResult>;+ makeImageDurable(imageName: string): Promise<void>;+ commitMaskImageResult(options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult>;+}++export interface RouteSelectObjectResultOptions {+ result: SelectObjectReadyResult;+ target: SelectObjectTarget;+ signal: AbortSignal;+ isCurrent(): boolean;+ deps: SelectObjectRouteDeps;+}++const canceledRoute = (signal: AbortSignal, isCurrent: () => boolean): { status: 'aborted' | 'stale' } | null => {+ if (signal.aborted) {+ return { status: 'aborted' };+ }+ if (!isCurrent()) {+ return { status: 'stale' };+ }+ return null;+};++export const routeSelectObjectResult = async (+ options: RouteSelectObjectResultOptions+): Promise<SelectObjectRouteResult> => {+ const canceled = canceledRoute(options.signal, options.isCurrent);+ if (canceled) {+ return canceled;+ }+ try {+ if (options.target === 'selection') {+ const result = await options.deps.replaceSelectionFromImage(+ options.result.guard,+ options.result.image,+ options.result.rect,+ options.signal+ );+ // Once the engine reports an authoritative mutation result, preserve it.+ // A late dialog-session invalidation may suppress UI updates, but must not+ // relabel an already-applied selection as canceled or stale.+ return result;+ }++ await options.deps.makeImageDurable(options.result.image.imageName);+ const afterDurability = canceledRoute(options.signal, options.isCurrent);+ if (afterDurability) {+ return afterDurability;+ }+ const beforeCommit = canceledRoute(options.signal, options.isCurrent);+ if (beforeCommit) {+ return beforeCommit;+ }+ const result = await options.deps.commitMaskImageResult({+ guard: options.result.guard,+ image: options.result.image,+ rect: options.result.rect,+ signal: options.signal,+ target: options.target,+ });+ // The engine owns the final abort/guard check immediately before mutation.+ // Do not overwrite a committed result if the UI session invalidates after+ // that authoritative mutation has completed.+ return result;+ } catch (error) {+ if (options.signal.aborted || isAbortError(error)) {+ return { status: 'aborted' };+ }+ return { message: errorMessage(error), status: 'failed' };+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.test.tsindex 7fbfab1cf7..08b714ea5c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.test.ts@@ -2,7 +2,11 @@ import { describe, expect, it } from 'vitest';import type { CanvasLayerContextMenuTarget } from './LayerContextMenu';-import { createLayerMenuTargetFromContextEvent, resolveMenuTargetForRender } from './layerMenuState';+import {+ createLayerMenuTargetFromContextEvent,+ type LayerMenuDialogKind,+ resolveMenuTargetForRender,+} from './layerMenuState';const target = (layerId: string): CanvasLayerContextMenuTarget => ({ layerId, x: 10, y: 20 });@@ -12,18 +16,27 @@ describe('resolveMenuTargetForRender', () => {expect(resolveMenuTargetForRender(live, null)).toBe(live);});- it('renders nothing with no live target and no pending rename', () => {+ it('renders nothing with no live target and no pending dialog', () => {expect(resolveMenuTargetForRender(null, null)).toBeNull();});- it('falls back to the captured rename target after the menu closes (F1: dialog survives)', () => {- const renaming = target('a');- expect(resolveMenuTargetForRender(null, renaming)).toBe(renaming);- });+ it.each(['rename', 'select-object', 'run-workflow'] as const)(+ 'falls back to the captured %s target after the menu closes',+ (kind: LayerMenuDialogKind) => {+ const dialogTarget = target('a');+ expect(resolveMenuTargetForRender(null, { kind, target: dialogTarget })).toBe(dialogTarget);+ }+ );- it('prefers the live target over the rename target when both exist', () => {+ it('prefers the live target over a pending dialog target when both exist', () => {const live = target('b');- expect(resolveMenuTargetForRender(live, target('a'))).toBe(live);+ expect(resolveMenuTargetForRender(live, { kind: 'select-object', target: target('a') })).toBe(live);+ });++ it('clears the sticky target after dialog close', () => {+ const dialogState = { kind: 'select-object', target: target('a') } as const;+ expect(resolveMenuTargetForRender(null, dialogState)).toBe(dialogState.target);+ expect(resolveMenuTargetForRender(null, null)).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.tsindex ba6f7e30e5..1313ae6ce9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts@@ -3,17 +3,21 @@ import type { CanvasLayerContextMenuTarget } from './LayerContextMenu';/*** Which layer the canvas right-click menu should render for.*- * Choosing "Rename" closes the menu, which nulls the live `target`. But the rename- * dialog is a sibling of the menu inside the same subtree — if the wrapper stopped- * rendering the moment `target` went null, the dialog would unmount before it ever- * painted (the F1 bug). So while a rename is in flight the wrapper keeps a captured- * `renameTarget` (set when the dialog opens, cleared when it closes) and falls back- * to it, keeping the subtree — and thus the dialog — mounted until the rename ends.+ * Opening a sibling dialog closes the menu, which nulls the live `target`. The+ * wrapper keeps a captured dialog target until that dialog closes so the shared+ * subtree remains mounted for rename, Select Object, and future workflow actions.*/+export type LayerMenuDialogKind = 'rename' | 'select-object' | 'run-workflow';++export interface LayerMenuDialogState {+ kind: LayerMenuDialogKind;+ target: CanvasLayerContextMenuTarget;+}+export const resolveMenuTargetForRender = (liveTarget: CanvasLayerContextMenuTarget | null,- renameTarget: CanvasLayerContextMenuTarget | null-): CanvasLayerContextMenuTarget | null => liveTarget ?? renameTarget;+ dialogState: LayerMenuDialogState | null+): CanvasLayerContextMenuTarget | null => liveTarget ?? dialogState?.target ?? null;export interface LayerContextMenuEvent {clientX: number;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.tsindex b5552075b2..2f885be5a8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts@@ -22,7 +22,9 @@ import {copyRegionalGuidanceToInpaintMask,createControlLayer,createEmptyPaintLayer,+ createInpaintMaskFromImage,createInpaintMaskLayer,+ createRegionalGuidanceFromImage,createRegionalGuidanceLayer,createRegionalGuidanceLayerWithRefImage,createRegionalReferenceImage,@@ -210,6 +212,67 @@ describe('createInpaintMaskLayer', () => {});});+describe('image-backed mask layer factories', () => {+ const image = { height: 13, imageName: 'selected-object.png', width: 17 };+ const rect = { height: 13, width: 17, x: -4, y: 9 };++ it('builds a complete inpaint mask contract with the image at the world rect', () => {+ expect(+ createInpaintMaskFromImage({+ fill: { color: '#123456', style: 'crosshatch' },+ id: 'mask-result',+ image,+ name: 'Inpaint Mask 2',+ rect,+ })+ ).toEqual({+ blendMode: 'normal',+ id: 'mask-result',+ isEnabled: true,+ isLocked: false,+ mask: {+ bitmap: image,+ fill: { color: '#123456', style: 'crosshatch' },+ offset: { x: -4, y: 9 },+ },+ name: 'Inpaint Mask 2',+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ });+ });++ it('builds a complete regional-guidance contract with preserved defaults', () => {+ expect(+ createRegionalGuidanceFromImage({+ fill: { color: '#83d683', style: 'solid' },+ id: 'regional-result',+ image,+ name: 'Regional Guidance 3',+ rect,+ })+ ).toEqual({+ autoNegative: false,+ blendMode: 'normal',+ id: 'regional-result',+ isEnabled: true,+ isLocked: false,+ mask: {+ bitmap: image,+ fill: { color: '#83d683', style: 'solid' },+ offset: { x: -4, y: 9 },+ },+ name: 'Regional Guidance 3',+ negativePrompt: null,+ opacity: 0.5,+ positivePrompt: null,+ referenceImages: [],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'regional_guidance',+ });+ });+});+describe('nextInpaintMaskName', () => {it('returns the first free "Inpaint Mask N"', () => {expect(nextInpaintMaskName([])).toBe('Inpaint Mask 1');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex a7ae0548b5..4b22bf3686 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -13,11 +13,13 @@ import type {CanvasControlAdapterContract,CanvasControlLayerContract,CanvasDocumentContractV2,+ CanvasImageRef,CanvasInpaintMaskLayerContract,CanvasLayerBaseContract,CanvasLayerContract,CanvasLayerSourceContract,CanvasMaskContract,+ CanvasMaskFillContract,CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,} from '@workbench/types';@@ -199,6 +201,34 @@ export const createRegionalGuidanceLayer = (type: 'regional_guidance',});+export interface CreateMaskLayerFromImageInput {+ image: CanvasImageRef;+ rect: Rect;+ id: string;+ name: string;+ fill: CanvasMaskFillContract;+}++export const createInpaintMaskFromImage = (input: CreateMaskLayerFromImageInput): CanvasInpaintMaskLayerContract => ({+ ...createInpaintMaskLayer(input.name, input.id),+ mask: {+ bitmap: { ...input.image },+ fill: { ...input.fill },+ offset: { x: input.rect.x, y: input.rect.y },+ },+});++export const createRegionalGuidanceFromImage = (+ input: CreateMaskLayerFromImageInput+): CanvasRegionalGuidanceLayerContract => ({+ ...createRegionalGuidanceLayer(input.name, 0, input.id),+ mask: {+ bitmap: { ...input.image },+ fill: { ...input.fill },+ offset: { x: input.rect.x, y: input.rect.y },+ },+});+/** Mints a fresh regional-guidance reference-image id. */export const createReferenceImageId = (): string =>`rgref-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;