Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(canvas): add select object canvas tool

joshistoastbd0a5b3a80d1
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 414ede5a2c..a662f2864f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -2014,7 +2014,11 @@ const createSpyBitmapStore = (): BitmapStore & {
const createInputCanvas = (
width = 100,
height = 100
-): { element: HTMLCanvasElement; fire: (type: string, event: Partial<PointerEvent>) => void } => {
+): {
+ element: HTMLCanvasElement;
+ fire: (type: string, event: Partial<PointerEvent>) => void;
+ surface: StubRasterSurface;
+} => {
const surface = createTestStubRasterBackend().createSurface(width, height);
const listeners = new Map<string, Set<(event: Event) => void>>();
const element = {
@@ -2038,7 +2042,7 @@ const createInputCanvas = (
handler({ preventDefault: () => {}, ...event } as unknown as Event);
}
};
- return { element, fire };
+ return { element, fire, surface };
};
const pointerAt = (x: number, y: number, opts: { button?: number; buttons?: number } = {}): Partial<PointerEvent> => ({
@@ -11828,3 +11832,208 @@ describe('contextMenuLayerIdAt (canvas right-click target)', () => {
engine.dispose();
});
});
+
+describe('Select Object canvas engine integration', () => {
+ const samLayer = (id: string, x = 0): CanvasRasterLayerContractV2 => ({
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: { fill: '#fff', height: 20, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 20 },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y: 0 },
+ type: 'raster',
+ });
+
+ const samDocument = (layers: CanvasLayerContract[] = [samLayer('source')]): CanvasDocumentContractV2 => ({
+ background: 'transparent',
+ bbox: { height: 100, width: 100, x: 0, y: 0 },
+ height: 100,
+ layers,
+ selectedLayerId: layers[0]?.id ?? null,
+ version: 2,
+ width: 100,
+ });
+
+ const createSamHarness = async (
+ options: {
+ backend?: StubRasterBackend;
+ imageResolver?: (imageName: string, signal?: AbortSignal) => Promise<Blob>;
+ layers?: CanvasLayerContract[];
+ runGraph?: () => Promise<{ imageName: string; origin: string }>;
+ } = {}
+ ) => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ const reactive = createReactiveStore(samDocument(options.layers));
+ const engine = createCanvasEngine({
+ backend: options.backend ?? createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: options.imageResolver ?? (() => Promise.resolve(new Blob())),
+ projectId: 'p1',
+ selectObjectDeps: {
+ runGraph: options.runGraph ?? (() => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' })),
+ uploadIntermediate: () => Promise.resolve({ imageName: 'sam-source.png' }),
+ },
+ store: reactive.store,
+ });
+ const screen = createInputCanvas();
+ const overlay = createInputCanvas();
+ engine.attach(screen.element, overlay.element);
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+ return { ...reactive, engine, overlay, raf, screen };
+ };
+
+ it('starts on the selected supported source, activates the real sam tool, and edits overlay-only', async () => {
+ const h = await createSamHarness();
+
+ expect(h.engine.startSelectObjectSession()).toBe('started');
+ expect(h.engine.stores.activeTool.get()).toBe('sam');
+ expect(h.engine.stores.samSession.get()).toMatchObject({
+ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },
+ layerId: 'source',
+ sourceRect: { height: 20, width: 20, x: 0, y: 0 },
+ });
+ h.raf.flush();
+ h.screen.surface.callLog.length = 0;
+ h.overlay.surface.callLog.length = 0;
+
+ h.overlay.fire('pointerdown', pointerAt(5, 5));
+ h.overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));
+ h.raf.flush();
+
+ expect(h.engine.stores.samSession.get()?.input.includePoints).toEqual([{ x: 5, y: 5 }]);
+ expect(h.overlay.surface.callLog.some((entry) => entry.op === 'arc')).toBe(true);
+ expect(h.screen.surface.callLog.some((entry) => entry.op === 'clearRect' || entry.op === 'drawImage')).toBe(false);
+ h.engine.dispose();
+ });
+
+ it('rejects missing and unsupported selections without activating sam', async () => {
+ const mask: CanvasInpaintMaskLayerContract = {
+ ...samLayer('mask'),
+ mask: { bitmap: null, fill: { color: '#fff', style: 'solid' } },
+ type: 'inpaint_mask',
+ };
+ const unsupported = await createSamHarness({ layers: [mask] });
+ expect(unsupported.engine.startSelectObjectSession()).toBe('unsupported');
+ expect(unsupported.engine.stores.activeTool.get()).toBe('view');
+ unsupported.engine.dispose();
+
+ const missing = await createSamHarness({ layers: [] });
+ expect(missing.engine.startSelectObjectSession()).toBe('missing');
+ expect(missing.engine.stores.samSession.get()).toBeNull();
+ missing.engine.dispose();
+ });
+
+ it('cancels the owned session and decoded preview on a real tool switch', async () => {
+ const h = await createSamHarness();
+ expect(h.engine.startSelectObjectSession()).toBe('started');
+ h.engine.updateSelectObjectSession({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },
+ });
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');
+ expect(h.engine.stores.samSession.get()?.hasPreview).toBe(true);
+
+ h.engine.setTool('view');
+
+ expect(h.engine.stores.samSession.get()).toBeNull();
+ h.engine.dispose();
+ });
+
+ it('suppresses a late preview decode after cancellation and closes its bitmap', async () => {
+ const image = createDeferred<Blob>();
+ const bitmap = createDeferred<ImageBitmap>();
+ const close = vi.fn();
+ const base = createTestStubRasterBackend();
+ const backend = { ...base, createImageBitmap: vi.fn(() => bitmap.promise) };
+ const h = await createSamHarness({ backend, imageResolver: () => image.promise });
+ h.engine.startSelectObjectSession();
+ h.engine.updateSelectObjectSession({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },
+ });
+ const pending = h.engine.processSelectObjectSession();
+ await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('processing'));
+ image.resolve(new Blob());
+ await vi.waitFor(() => expect(backend.createImageBitmap).toHaveBeenCalledOnce());
+
+ h.engine.cancelSelectObjectSession();
+ bitmap.resolve({ close, height: 20, width: 20 } as unknown as ImageBitmap);
+
+ await expect(pending).resolves.toBe('stale');
+ expect(close).toHaveBeenCalledOnce();
+ expect(h.engine.stores.samSession.get()).toBeNull();
+ h.engine.dispose();
+ });
+
+ it('isolates only the source layer in the compositor while an isolated preview is published', async () => {
+ const backend = createRecordingRasterBackend();
+ backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('sam-mask')));
+ const h = await createSamHarness({ backend, layers: [samLayer('source'), samLayer('other', 30)] });
+ h.engine.stores.checkerboard.set(false);
+ h.engine.startSelectObjectSession();
+ h.engine.updateSelectObjectSession({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },
+ });
+ await h.engine.processSelectObjectSession();
+ h.screen.surface.callLog.length = 0;
+ h.raf.flush();
+
+ expect(h.screen.surface.callLog.filter((entry) => entry.op === 'drawImage')).toHaveLength(1);
+ expect(h.engine.getDocument()!.layers.every((layer) => layer.isEnabled)).toBe(true);
+ h.engine.dispose();
+ });
+
+ it('tears down the session when its captured source contract changes', async () => {
+ const h = await createSamHarness();
+ h.engine.startSelectObjectSession();
+
+ h.setDocument({
+ ...h.engine.getDocument()!,
+ layers: [{ ...h.engine.getDocument()!.layers[0]!, opacity: 0.5 }],
+ });
+
+ expect(h.engine.stores.samSession.get()).toBeNull();
+ expect(h.engine.stores.activeTool.get()).toBe('view');
+ h.engine.dispose();
+ });
+
+ it('owns only the latest session and suppresses in-flight work from the replaced session', async () => {
+ const output = createDeferred<{ imageName: string; origin: string }>();
+ const layers = [samLayer('first'), samLayer('second', 30)];
+ const h = await createSamHarness({ layers, runGraph: () => output.promise });
+ h.engine.startSelectObjectSession();
+ h.engine.updateSelectObjectSession({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },
+ });
+ const pending = h.engine.processSelectObjectSession();
+ await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('processing'));
+
+ h.setDocument({ ...h.engine.getDocument()!, selectedLayerId: 'second' });
+ expect(h.engine.startSelectObjectSession()).toBe('started');
+ expect(h.engine.stores.samSession.get()?.layerId).toBe('second');
+ output.resolve({ imageName: 'late.png', origin: 'late' });
+
+ await expect(pending).resolves.toBe('stale');
+ expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: false, layerId: 'second' });
+ h.engine.dispose();
+ });
+
+ it('lets Escape cancel a gesture before a later Escape cancels the operation', async () => {
+ const h = await createSamHarness();
+ h.engine.startSelectObjectSession();
+ h.overlay.fire('pointerdown', pointerAt(5, 5));
+ h.overlay.fire('pointermove', pointerAt(15, 15));
+ h.overlay.fire('pointercancel', pointerAt(15, 15));
+
+ h.engine.handleEscapePriority({ gestureWasActive: true });
+ expect(h.engine.stores.samSession.get()).not.toBeNull();
+
+ h.engine.handleEscapePriority({ gestureWasActive: false });
+ expect(h.engine.stores.samSession.get()).toBeNull();
+ h.engine.dispose();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 13419e5718..c5fcd23666 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -32,6 +32,7 @@ import type { FontLoadApi } from '@workbench/canvas-engine/render/fontLoader';
import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';
import type { RenderScheduler } from '@workbench/canvas-engine/render/scheduler';
import type { Rect, RenderFlags, ToolId, Vec2 } from '@workbench/canvas-engine/types';
+import type { SamModel } from '@workbench/generation/canvas/samGraph';
import type {
CanvasImageRef,
CanvasDocumentContractV2,
@@ -39,9 +40,22 @@ import type {
CanvasLayerSourceContract,
WorkbenchState,
} from '@workbench/types';
+import type {
+ SelectObjectSession,
+ SelectObjectSessionPreview,
+ SelectObjectSessionProcessResult,
+} from '@workbench/widgets/layers/selectObjectSession';
import type { WorkbenchAction } from '@workbench/workbenchState';
-import { createEngineStores, type EngineStores, type TextToolOptions } from '@workbench/canvas-engine/engineStores';
+import { socketHub } from '@workbench/backend/socketHub';
+import { runUtilityGraph, type UtilityGraphResult } from '@workbench/canvas-engine/backend/utilityQueue';
+import {
+ createEngineStores,
+ type EngineStores,
+ type SamPointLabel,
+ type SamVisualInput,
+ type TextToolOptions,
+} from '@workbench/canvas-engine/engineStores';
import { executePsdExport, planPsdExport } from '@workbench/canvas-engine/export/psdExport';
import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';
import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';
@@ -86,6 +100,7 @@ import {
} from '@workbench/canvas-engine/tools/moveHitTest';
import { createMoveTool } from '@workbench/canvas-engine/tools/moveTool';
import { stepBrushSize } from '@workbench/canvas-engine/tools/paintConstants';
+import { createSamTool } from '@workbench/canvas-engine/tools/samTool';
import { createShapeTool } from '@workbench/canvas-engine/tools/shapeTool';
import { createTextTool } from '@workbench/canvas-engine/tools/textTool';
import { createTransformTool } from '@workbench/canvas-engine/tools/transformTool';
@@ -103,6 +118,7 @@ import {
nextRegionalGuidanceFillColor,
nextRegionalGuidanceName,
} from '@workbench/widgets/layers/layerOps';
+import { createSelectObjectSession } from '@workbench/widgets/layers/selectObjectSession';
import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';
@@ -300,6 +316,15 @@ export interface CanvasEngineOptions {
backend?: RasterBackend;
/** Resolves persisted image assets to blobs for decoding. */
imageResolver: ImageResolver;
+ /** Injectable Select Object queue/upload seams; production defaults use the utility queue. */
+ selectObjectDeps?: {
+ uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;
+ runGraph(options: {
+ graph: Parameters<typeof runUtilityGraph>[0]['graph'];
+ outputNodeId?: string;
+ signal?: AbortSignal;
+ }): Promise<UtilityGraphResult>;
+ };
/**
* Overrides the paint-persistence store. Defaults to a real {@link createBitmapStore}
* wired to the layer cache and the upload backend. Tests inject a fake to
@@ -314,6 +339,18 @@ export interface CanvasEngineOptions {
fonts?: FontLoadApi | null;
}
+export type StartSelectObjectSessionResult = 'started' | 'missing' | 'unsupported' | 'not-ready';
+
+export interface SelectObjectSessionUpdate {
+ input?: SamVisualInput;
+ pointLabel?: SamPointLabel;
+ model?: SamModel;
+ invert?: boolean;
+ applyPolygonRefinement?: boolean;
+ autoProcess?: boolean;
+ isolatedPreview?: boolean;
+}
+
/** The public engine handle. */
export interface CanvasEngine {
readonly projectId: string;
@@ -331,6 +368,13 @@ export interface CanvasEngine {
resize(cssWidth: number, cssHeight: number, dpr: number): void;
/** Activates a tool (deactivating the previous one). */
setTool(toolId: ToolId, opts?: { temporary?: boolean }): void;
+ /** Starts one Select Object session on the selected raster/control layer and activates the SAM tool. */
+ startSelectObjectSession(): StartSelectObjectSessionResult;
+ updateSelectObjectSession(changes: SelectObjectSessionUpdate): void;
+ processSelectObjectSession(): Promise<SelectObjectSessionProcessResult>;
+ resetSelectObjectSession(): void;
+ cancelSelectObjectSession(): void;
+ disposeSelectObjectSession(): void;
/** Locks interaction to the view tool; used while staged canvas results await a decision. */
setInteractionLocked(locked: boolean): void;
/**
@@ -752,6 +796,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
['shape', createShapeTool()],
['gradient', createGradientTool()],
['text', createTextTool()],
+ ['sam', createSamTool()],
]);
let activeToolId: ToolId = 'view';
let interactionLocked = false;
@@ -797,6 +842,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
let inputEl: HTMLCanvasElement | null = null;
let disposed = false;
+ let selectObjectSession: SelectObjectSession<RasterSurface> | null = null;
+ let selectObjectUnsubscribe: (() => void) | null = null;
+ let selectObjectGuard: LayerExportGuard | null = null;
+ let selectObjectSourceRect: Rect | null = null;
+ let selectObjectPointLabel: SamPointLabel = 'include';
+ let samPreview: SelectObjectSessionPreview<RasterSurface> | null = null;
+
// The brush/eraser cursor ring, drawn on the overlay (set by the active tool).
let overlayCursor: OverlayCursor | null = null;
@@ -1167,6 +1219,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
},
stores,
updateCursor: () => updateCursor(),
+ updateSamInput: (input) => updateSelectObjectSession({ input }),
updateTransformSession: (transform) => updateTransformSession(transform),
viewport,
};
@@ -2175,6 +2228,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
filterPreviews.size > 0
? new Map(Array.from(filterPreviews, ([id, decoded]) => [id, decoded.surface]))
: null,
+ onlyLayerId: samPreview?.isolated ? samPreview.guard.layerId : null,
// Feed the cached checkerboard tile only while the toggle is ON; passing
// `null` renders transparent documents without a checkerboard.
checkerboardTile: stores.checkerboard.get() ? getCheckerboardTile() : null,
@@ -2236,6 +2290,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
gradientPreview: stores.gradientPreview.get(),
lassoPreview: stores.lassoPreview.get(),
marchingAnts: selection.hasSelection() ? { paths: selection.antsPaths(), phase: antsPhase } : null,
+ samInput: stores.samSession.get()?.input ?? null,
+ samPreview: samPreview ? { opacity: 0.45, rect: samPreview.rect, surface: samPreview.data } : null,
bboxOverlay: stores.bboxOverlay.get(),
ruleOfThirds: stores.ruleOfThirds.get(),
shapePreview: stores.shapePreview.get(),
@@ -2264,6 +2320,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
scheduler.invalidate(stagedPreview && !stagedPreview.placement ? { all: true } : { overlay: true }),
onDocumentReplaced: () => {
canvasOperations.invalidateDocument(projectId);
+ cancelSelectObjectSession();
const previousImageNames = [...mirroredLayerImageNames.values()];
rasterDocumentGeneration += 1;
cancelAllLayerRasterizations();
@@ -2345,6 +2402,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
for (const id of ids) {
canvasOperations.invalidateLayer(projectId, id);
}
+ if (selectObjectGuard && !isLayerExportGuardCurrent(selectObjectGuard)) {
+ cancelSelectObjectSession();
+ }
const doc = mirror.getDocument();
const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);
const sourceChanged = new Set(sourceChangedIds);
@@ -2463,6 +2523,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
const activeProjectId = store.getState().activeProjectId;
if (lastActiveProjectId === projectId && activeProjectId !== projectId) {
canvasOperations.invalidateProject(projectId);
+ cancelSelectObjectSession();
rasterDocumentGeneration += 1;
cancelAllLayerRasterizations();
stores.thumbnailStatus.clear();
@@ -2580,6 +2641,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
cancelTransform();
return;
}
+ if (!gestureWasActive && selectObjectSession) {
+ cancelSelectObjectSession();
+ return;
+ }
if (!gestureWasActive && selection.hasSelection()) {
selection.clear();
}
@@ -2632,6 +2697,192 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
pipeline.reset();
};
+ const clearSamPreview = (): void => {
+ const previous = samPreview;
+ samPreview = null;
+ if (previous) {
+ scheduler.invalidate(previous.isolated ? { all: true } : { overlay: true });
+ }
+ };
+
+ const syncSelectObjectStore = (): void => {
+ const session = selectObjectSession;
+ const sourceRect = selectObjectSourceRect;
+ if (!session || !sourceRect) {
+ stores.samSession.set(null);
+ return;
+ }
+ const state = session.getSnapshot();
+ if (state.input.type !== 'visual') {
+ return;
+ }
+ stores.samSession.set({
+ error: state.error,
+ hasPreview: state.preview !== null,
+ input: {
+ bbox: state.input.bbox ? { ...state.input.bbox } : null,
+ excludePoints: state.input.excludePoints.map((point) => ({ ...point })),
+ includePoints: state.input.includePoints.map((point) => ({ ...point })),
+ type: 'visual',
+ },
+ isolatedPreview: state.isolatedPreview,
+ layerId: selectObjectGuard?.layerId ?? '',
+ pointLabel: selectObjectPointLabel,
+ sourceRect,
+ status: state.status,
+ });
+ scheduler.invalidate({ overlay: true });
+ };
+
+ const decodeSelectObjectPreview = async (
+ result: { image: CanvasImageRef; rect: Rect },
+ signal: AbortSignal
+ ): Promise<RasterSurface> => {
+ const blob = await imageResolver(result.image.imageName, signal);
+ if (signal.aborted) {
+ throw new DOMException('Select Object preview decode was aborted.', 'AbortError');
+ }
+ const bitmap = await backend.createImageBitmap(blob);
+ try {
+ if (signal.aborted) {
+ throw new DOMException('Select Object preview decode was aborted.', 'AbortError');
+ }
+ const surface = backend.createSurface(result.rect.width, result.rect.height);
+ const ctx = surface.ctx;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.clearRect(0, 0, surface.width, surface.height);
+ ctx.drawImage(bitmap, 0, 0, surface.width, surface.height);
+ ctx.globalCompositeOperation = 'source-in';
+ ctx.fillStyle = '#38bdf8';
+ ctx.fillRect(0, 0, surface.width, surface.height);
+ ctx.globalCompositeOperation = 'source-over';
+ if (signal.aborted) {
+ throw new DOMException('Select Object preview decode was aborted.', 'AbortError');
+ }
+ return surface;
+ } finally {
+ bitmap.close();
+ }
+ };
+
+ const clearOwnedSelectObjectSession = (): void => {
+ const session = selectObjectSession;
+ selectObjectSession = null;
+ selectObjectUnsubscribe?.();
+ selectObjectUnsubscribe = null;
+ session?.dispose();
+ clearSamPreview();
+ selectObjectGuard = null;
+ selectObjectSourceRect = null;
+ selectObjectPointLabel = 'include';
+ stores.samSession.set(null);
+ scheduler.invalidate({ overlay: true });
+ };
+
+ const startSelectObjectSession = (): StartSelectObjectSessionResult => {
+ const doc = mirror.getDocument();
+ const layer = doc?.layers.find((candidate) => candidate.id === doc.selectedLayerId);
+ if (!layer) {
+ return 'missing';
+ }
+ if (layer.type !== 'raster' && layer.type !== 'control') {
+ return 'unsupported';
+ }
+ const entry = layerCache.get(layer.id);
+ const guard = captureCurrentLayerExportGuard(layer.id);
+ if (!entry || !guard) {
+ return 'not-ready';
+ }
+ const matrix = fromTRS(
+ { x: layer.transform.x, y: layer.transform.y },
+ layer.transform.rotation,
+ layer.transform.scaleX,
+ layer.transform.scaleY
+ );
+ const sourceRect = roundOut(transformBounds(matrix, entry.rect));
+ if (isEmpty(sourceRect)) {
+ return 'not-ready';
+ }
+
+ clearOwnedSelectObjectSession();
+ selectObjectGuard = guard;
+ selectObjectSourceRect = sourceRect;
+ const queueDeps = opts.selectObjectDeps;
+ selectObjectSession = createSelectObjectSession({
+ deps: {
+ captureGuard: () =>
+ selectObjectGuard && isLayerExportGuardCurrent(selectObjectGuard) ? selectObjectGuard : null,
+ cleanupPreview: clearSamPreview,
+ controller: canvasOperations,
+ decodePreview: decodeSelectObjectPreview,
+ exportLayer: (layerId) => exportBakedLayerBlob(layerId, { includeDisabled: true }),
+ isGuardCurrent: isLayerExportGuardCurrent,
+ publishPreview: (preview) => {
+ const isolationChanged = samPreview?.isolated !== preview.isolated;
+ samPreview = preview;
+ scheduler.invalidate(preview.isolated || isolationChanged ? { all: true } : { overlay: true });
+ return undefined;
+ },
+ runGraph: (options) => queueDeps?.runGraph(options) ?? runUtilityGraph({ ...options, hub: socketHub }),
+ uploadIntermediate: async (blob, signal) => {
+ if (queueDeps) {
+ return queueDeps.uploadIntermediate(blob, signal);
+ }
+ if (signal?.aborted) {
+ throw new DOMException('Select Object upload was aborted.', 'AbortError');
+ }
+ const uploaded = await uploadCanvasImage(blob, { isIntermediate: true });
+ if (signal?.aborted) {
+ throw new DOMException('Select Object upload was aborted.', 'AbortError');
+ }
+ return { imageName: uploaded.imageName };
+ },
+ },
+ layerId: layer.id,
+ projectId,
+ });
+ selectObjectUnsubscribe = selectObjectSession.subscribe(syncSelectObjectStore);
+ selectObjectSession.update({
+ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },
+ });
+ syncSelectObjectStore();
+ setTool('sam');
+ return 'started';
+ };
+
+ const updateSelectObjectSession = (changes: SelectObjectSessionUpdate): void => {
+ const session = selectObjectSession;
+ if (!session) {
+ return;
+ }
+ const { pointLabel, ...sessionChanges } = changes;
+ if (pointLabel) {
+ selectObjectPointLabel = pointLabel;
+ }
+ session.update(sessionChanges);
+ syncSelectObjectStore();
+ };
+
+ const processSelectObjectSession = (): Promise<SelectObjectSessionProcessResult> =>
+ selectObjectSession?.process() ?? Promise.resolve('stale');
+
+ const resetSelectObjectSession = (): void => {
+ if (!selectObjectSession) {
+ return;
+ }
+ selectObjectPointLabel = 'include';
+ selectObjectSession.reset();
+ selectObjectSession.update({ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' } });
+ syncSelectObjectStore();
+ };
+
+ const cancelSelectObjectSession = (): void => {
+ clearOwnedSelectObjectSession();
+ if (activeToolId === 'sam') {
+ setTool('view');
+ }
+ };
+
// ---- Public API ---------------------------------------------------------
function setTool(toolId: ToolId, opts?: { temporary?: boolean }): void {
@@ -2641,6 +2892,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (toolId === activeToolId) {
return;
}
+ if (activeToolId === 'sam' && toolId !== 'sam' && !opts?.temporary) {
+ clearOwnedSelectObjectSession();
+ }
tools.get(activeToolId)?.onDeactivate?.(toolContext, opts);
activeToolId = toolId;
tools.get(toolId)?.onActivate?.(toolContext, opts);
@@ -5237,6 +5491,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return;
}
disposed = true;
+ clearOwnedSelectObjectSession();
canvasOperations.dispose();
cancelAllLayerRasterizations();
detach();
@@ -5359,6 +5614,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
contextMenuLayerIdAt,
logDebugInfo,
attach,
+ cancelSelectObjectSession,
cancelTextEdit,
cancelTransform,
commitGeneratedImageResult,
@@ -5374,6 +5630,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
deselect,
detach,
dispose,
+ disposeSelectObjectSession: cancelSelectObjectSession,
drawLayerThumbnail,
eraseSelection,
extractMaskedArea,
@@ -5397,6 +5654,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
isLayerExportGuardCurrent,
mergeLayerDown,
mergeVisibleRasterLayers,
+ processSelectObjectSession,
+ resetSelectObjectSession,
+ startSelectObjectSession,
+ updateSelectObjectSession,
openTextCreate,
openTextEdit,
rasterizeLayer,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index 530184eb3e..bb4c81d616 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -222,6 +222,27 @@ export interface TextEditSession {
transform: LayerTransform;
}
+export type SamPointLabel = 'include' | 'exclude';
+
+export interface SamVisualInput {
+ type: 'visual';
+ includePoints: Vec2[];
+ excludePoints: Vec2[];
+ bbox: Rect | null;
+}
+
+/** Narrow engine-owned Select Object state for canvas tools and future UI subscribers. */
+export interface SamSessionSnapshot {
+ layerId: string;
+ sourceRect: Rect;
+ input: SamVisualInput;
+ pointLabel: SamPointLabel;
+ isolatedPreview: boolean;
+ status: 'ready' | 'scheduled' | 'processing' | 'error';
+ error: string | null;
+ hasPreview: boolean;
+}
+
/** A single-value store, `useSyncExternalStore`-compatible. */
export interface ScalarStore<T> {
get(): T;
@@ -499,6 +520,8 @@ export interface EngineStores {
* Purely an interaction preference — no render effect.
*/
snapToGrid: ScalarStore<boolean>;
+ /** Active Select Object session state, or `null`; intentionally React-free and narrowly shaped. */
+ samSession: ScalarStore<SamSessionSnapshot | null>;
}
const brushOptionsEqual = (a: BrushOptions, b: BrushOptions): boolean =>
@@ -624,6 +647,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
lassoOptions: createScalarStore<LassoToolOptions>({ ...DEFAULT_LASSO_OPTIONS }, lassoOptionsEqual),
lassoPreview: createScalarStore<readonly Vec2[] | null>(null),
ruleOfThirds: createScalarStore<boolean>(false),
+ samSession: createScalarStore<SamSessionSnapshot | null>(null),
shapeOptions: createScalarStore<ShapeToolOptions>({ ...DEFAULT_SHAPE_OPTIONS }, shapeOptionsEqual),
shapePreview: createScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>(null, shapePreviewEqual),
showBbox: createScalarStore<boolean>(true),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
index ca1a34acc9..d96ad61323 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -136,6 +136,8 @@ export interface CompositeOptions {
* `null`/absent ⇒ no previews.
*/
layerPreviews?: ReadonlyMap<string, RasterSurface> | null;
+ /** When set, transiently composites only this layer without mutating document visibility. */
+ onlyLayerId?: string | null;
/**
* Returns a raster layer's ADJUSTED cache surface (brightness/contrast/
* saturation/curves applied), or `null` when the layer has identity (or no)
@@ -338,7 +340,13 @@ export const compositeDocument = (
const drawGroup = (rank: number): void => {
for (let i = doc.layers.length - 1; i >= 0; i--) {
const layer = doc.layers[i];
- if (!layer || !layer.isEnabled || layer.id === opts.skipLayerId || layerGroupRank(layer) !== rank) {
+ if (
+ !layer ||
+ !layer.isEnabled ||
+ layer.id === opts.skipLayerId ||
+ (opts.onlyLayerId && layer.id !== opts.onlyLayerId) ||
+ layerGroupRank(layer) !== rank
+ ) {
continue;
}
const entry = caches.get(layer.id);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
index 4379261434..06a3f9eac0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
@@ -124,4 +124,63 @@ describe('renderOverlay', () => {
const moveTos = target.callLog.filter((e) => e.op === 'moveTo');
expect(moveTos).toHaveLength(4);
});
+
+ it('draws the dedicated SAM mask preview before its bbox, handles, and colored points', () => {
+ const backend = createTestStubRasterBackend();
+ const target = backend.createSurface(200, 200);
+ const mask = backend.createSurface(20, 10);
+ renderOverlay(
+ target,
+ baseState({
+ samInput: {
+ bbox: { height: 30, width: 40, x: 20, y: 30 },
+ excludePoints: [{ x: 50, y: 60 }],
+ includePoints: [{ x: 30, y: 40 }],
+ },
+ samPreview: { opacity: 0.45, rect: { height: 10, width: 20, x: 20, y: 30 }, surface: mask },
+ showBbox: false,
+ })
+ );
+
+ const ops = target.callLog.map((entry) => entry.op);
+ const previewIndex = ops.indexOf('drawImage');
+ const bboxIndex = ops.indexOf('strokeRect');
+ const firstPointIndex = ops.indexOf('arc');
+ expect(previewIndex).toBeGreaterThan(-1);
+ expect(bboxIndex).toBeGreaterThan(previewIndex);
+ expect(firstPointIndex).toBeGreaterThan(bboxIndex);
+ expect(findSet(target.callLog, 'fillStyle')).toEqual(expect.arrayContaining(['#22c55e', '#ef4444']));
+ });
+
+ it.each([1, 4])('keeps SAM point and handle drawing screen-constant at %sx zoom', (zoom) => {
+ const backend = createTestStubRasterBackend();
+ const target = backend.createSurface(500, 500);
+ renderOverlay(
+ target,
+ baseState({
+ samInput: {
+ bbox: { height: 30, width: 40, x: 20, y: 30 },
+ excludePoints: [],
+ includePoints: [{ x: 30, y: 40 }],
+ },
+ showBbox: false,
+ view: scale(identity(), zoom),
+ })
+ );
+
+ const point = target.callLog.find((entry) => entry.op === 'arc');
+ const handles = target.callLog.filter((entry) => entry.op === 'fillRect');
+ expect(point?.args[2]).toBe(5);
+ expect(handles).toHaveLength(8);
+ expect(handles.every((entry) => entry.args[2] === 8 && entry.args[3] === 8)).toBe(true);
+ });
+
+ it('draws no SAM preview or geometry after cleanup', () => {
+ const backend = createTestStubRasterBackend();
+ const target = backend.createSurface(200, 200);
+ renderOverlay(target, baseState({ samInput: null, samPreview: null, showBbox: false }));
+
+ expect(target.callLog.some((entry) => entry.op === 'drawImage' || entry.op === 'arc')).toBe(false);
+ expect(target.callLog.filter((entry) => entry.op === 'strokeRect')).toHaveLength(0);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
index b30cfa6af4..a83e8232cf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
@@ -103,6 +103,10 @@ export interface OverlayState {
* drawn as a direction indicator. Absent/`null` when idle.
*/
gradientPreview?: { start: Vec2; end: Vec2 } | null;
+ /** Dedicated Select Object mask preview, already colorized by the engine. */
+ samPreview?: { surface: RasterSurface; rect: Rect; opacity: number } | null;
+ /** Select Object visual prompt geometry in document space. */
+ samInput?: { includePoints: readonly Vec2[]; excludePoints: readonly Vec2[]; bbox: Rect | null } | null;
}
/** Document-space geometry the overlay draws for an active transform session. */
@@ -367,6 +371,64 @@ const drawGradientPreview = (ctx: Ctx, state: OverlayState): void => {
ctx.restore();
};
+const SAM_BBOX_COLOR = '#f59e0b';
+const SAM_INCLUDE_COLOR = '#22c55e';
+const SAM_EXCLUDE_COLOR = '#ef4444';
+const SAM_POINT_RADIUS_PX = 5;
+const SAM_HANDLE_DRAW_PX = 8;
+
+const drawSamPreview = (ctx: Ctx, state: OverlayState): void => {
+ const preview = state.samPreview;
+ if (!preview) {
+ return;
+ }
+ const { view } = state;
+ ctx.save();
+ ctx.setTransform(view.a, view.b, view.c, view.d, view.e, view.f);
+ ctx.globalAlpha = preview.opacity;
+ ctx.drawImage(preview.surface.canvas, preview.rect.x, preview.rect.y, preview.rect.width, preview.rect.height);
+ ctx.restore();
+};
+
+const drawSamGeometry = (ctx: Ctx, state: OverlayState): void => {
+ const input = state.samInput;
+ if (!input) {
+ return;
+ }
+ ctx.save();
+ ctx.lineWidth = 1;
+ ctx.strokeStyle = SAM_BBOX_COLOR;
+ ctx.setLineDash([...BBOX_DASH]);
+ if (input.bbox) {
+ const screenRect = transformBounds(state.view, input.bbox);
+ ctx.strokeRect(screenRect.x, screenRect.y, screenRect.width, screenRect.height);
+ ctx.setLineDash([]);
+ ctx.fillStyle = BBOX_HANDLE_FILL;
+ const half = SAM_HANDLE_DRAW_PX / 2;
+ for (const handle of BBOX_HANDLES) {
+ const center = bboxHandlePoint(screenRect, handle);
+ ctx.fillRect(center.x - half, center.y - half, SAM_HANDLE_DRAW_PX, SAM_HANDLE_DRAW_PX);
+ ctx.strokeRect(center.x - half, center.y - half, SAM_HANDLE_DRAW_PX, SAM_HANDLE_DRAW_PX);
+ }
+ }
+ ctx.setLineDash([]);
+ for (const [points, color] of [
+ [input.includePoints, SAM_INCLUDE_COLOR],
+ [input.excludePoints, SAM_EXCLUDE_COLOR],
+ ] as const) {
+ ctx.fillStyle = color;
+ ctx.strokeStyle = '#ffffff';
+ for (const point of points) {
+ const screen = applyToPoint(state.view, point);
+ ctx.beginPath();
+ ctx.arc(screen.x, screen.y, SAM_POINT_RADIUS_PX, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.stroke();
+ }
+ }
+ ctx.restore();
+};
+
/**
* Draws the bbox overlay shade: a translucent dark fill over the ENTIRE viewport
* with the bbox region punched out (even-odd fill rule — the two nested rect paths
@@ -467,6 +529,8 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): void
ctx.setLineDash([]);
}
+ drawSamPreview(ctx, state);
+ drawSamGeometry(ctx, state);
drawLayerOutline(ctx, state);
drawBboxHandles(ctx, state);
drawTransformFrame(ctx, state);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.test.ts
new file mode 100644
index 0000000000..6c2d7c8995
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.test.ts
@@ -0,0 +1,93 @@
+import { identity, scale } from '@workbench/canvas-engine/math/mat2d';
+import { describe, expect, it } from 'vitest';
+
+import { clipPointToRect, clipRectToRect, moveSamBbox, rectFromPoints, resizeSamBbox, samHitTest } from './samHitTest';
+
+const source = { height: 80, width: 100, x: 10, y: 20 };
+
+describe('samHitTest', () => {
+ it.each([1, 4])('keeps point and bbox handle hit regions screen-constant at %sx zoom', (zoom) => {
+ const view = scale(identity(), zoom);
+ const point = { x: 30, y: 40 };
+ const bbox = { height: 30, width: 40, x: 40, y: 30 };
+
+ expect(
+ samHitTest({
+ bbox,
+ excludePoints: [],
+ includePoints: [point],
+ screenPoint: { x: point.x * zoom + 5, y: point.y * zoom },
+ view,
+ })
+ ).toEqual({ index: 0, kind: 'point', label: 'include' });
+ expect(
+ samHitTest({
+ bbox,
+ excludePoints: [],
+ includePoints: [],
+ screenPoint: { x: bbox.x * zoom + 5, y: bbox.y * zoom },
+ view,
+ })
+ ).toEqual({ handle: 'nw', kind: 'bbox-handle' });
+ });
+
+ it('prioritizes points, then handles, then the bbox body', () => {
+ const bbox = { height: 30, width: 40, x: 40, y: 30 };
+ const common = { bbox, excludePoints: [{ x: 40, y: 30 }], includePoints: [], view: identity() };
+
+ expect(samHitTest({ ...common, screenPoint: { x: 40, y: 30 } })).toEqual({
+ index: 0,
+ kind: 'point',
+ label: 'exclude',
+ });
+ expect(samHitTest({ ...common, excludePoints: [], screenPoint: { x: 80, y: 45 } })).toEqual({
+ handle: 'e',
+ kind: 'bbox-handle',
+ });
+ expect(samHitTest({ ...common, excludePoints: [], screenPoint: { x: 60, y: 45 } })).toEqual({
+ kind: 'bbox-body',
+ });
+ expect(samHitTest({ ...common, excludePoints: [], screenPoint: { x: 95, y: 70 } })).toBeNull();
+ });
+});
+
+describe('SAM bbox geometry', () => {
+ it('normalizes dragged corners and clips to the source export bounds', () => {
+ expect(rectFromPoints({ x: 120, y: 120 }, { x: 0, y: 0 }, source)).toEqual(source);
+ expect(clipRectToRect({ height: 30, width: 30, x: 100, y: 80 }, source)).toEqual({
+ height: 20,
+ width: 10,
+ x: 100,
+ y: 80,
+ });
+ });
+
+ it('clips points and bbox moves without changing bbox size', () => {
+ expect(clipPointToRect({ x: -5, y: 200 }, source)).toEqual({ x: 10, y: 100 });
+ expect(moveSamBbox({ height: 20, width: 30, x: 20, y: 30 }, 500, -500, source)).toEqual({
+ height: 20,
+ width: 30,
+ x: 80,
+ y: 20,
+ });
+ });
+
+ it('resizes from screen-constant handles and clamps to source bounds and one document pixel', () => {
+ expect(
+ resizeSamBbox({
+ bounds: source,
+ delta: { x: 100, y: 100 },
+ handle: 'nw',
+ start: { height: 30, width: 40, x: 40, y: 30 },
+ })
+ ).toEqual({ height: 1, width: 1, x: 79, y: 59 });
+ expect(
+ resizeSamBbox({
+ bounds: source,
+ delta: { x: 100, y: 100 },
+ handle: 'se',
+ start: { height: 30, width: 40, x: 40, y: 30 },
+ })
+ ).toEqual({ height: 70, width: 70, x: 40, y: 30 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.ts
new file mode 100644
index 0000000000..122faef6cb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.ts
@@ -0,0 +1,110 @@
+import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
+
+import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';
+import { transformBounds } from '@workbench/canvas-engine/math/rect';
+
+import { BBOX_HANDLES, bboxHandleAt, type BboxHandle, isInsideRect } from './bboxHitTest';
+
+export const SAM_POINT_HIT_RADIUS_PX = 8;
+export const SAM_BBOX_HANDLE_HIT_PX = 14;
+
+export type SamPointLabel = 'include' | 'exclude';
+
+export type SamHitTarget =
+ | { kind: 'point'; label: SamPointLabel; index: number }
+ | { kind: 'bbox-handle'; handle: BboxHandle }
+ | { kind: 'bbox-body' };
+
+export interface SamHitTestOptions {
+ view: Mat2d;
+ screenPoint: Vec2;
+ includePoints: readonly Vec2[];
+ excludePoints: readonly Vec2[];
+ bbox: Rect | null;
+}
+
+export const samHitTest = (options: SamHitTestOptions): SamHitTarget | null => {
+ for (const label of ['include', 'exclude'] as const) {
+ const points = label === 'include' ? options.includePoints : options.excludePoints;
+ for (let index = points.length - 1; index >= 0; index -= 1) {
+ const point = points[index];
+ if (!point) {
+ continue;
+ }
+ const screen = applyToPoint(options.view, point);
+ if (Math.hypot(options.screenPoint.x - screen.x, options.screenPoint.y - screen.y) <= SAM_POINT_HIT_RADIUS_PX) {
+ return { index, kind: 'point', label };
+ }
+ }
+ }
+
+ if (!options.bbox) {
+ return null;
+ }
+ const screenRect = transformBounds(options.view, options.bbox);
+ const handle = bboxHandleAt(screenRect, options.screenPoint, SAM_BBOX_HANDLE_HIT_PX);
+ if (handle) {
+ return { handle, kind: 'bbox-handle' };
+ }
+ return isInsideRect(screenRect, options.screenPoint) ? { kind: 'bbox-body' } : null;
+};
+
+const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));
+
+export const clipPointToRect = (point: Vec2, bounds: Rect): Vec2 => ({
+ x: clamp(point.x, bounds.x, bounds.x + bounds.width),
+ y: clamp(point.y, bounds.y, bounds.y + bounds.height),
+});
+
+export const clipRectToRect = (rect: Rect, bounds: Rect): Rect => {
+ const left = clamp(rect.x, bounds.x, bounds.x + bounds.width);
+ const top = clamp(rect.y, bounds.y, bounds.y + bounds.height);
+ const right = clamp(rect.x + rect.width, left, bounds.x + bounds.width);
+ const bottom = clamp(rect.y + rect.height, top, bounds.y + bounds.height);
+ return { height: bottom - top, width: right - left, x: left, y: top };
+};
+
+export const rectFromPoints = (start: Vec2, end: Vec2, bounds: Rect): Rect =>
+ clipRectToRect(
+ {
+ height: Math.abs(end.y - start.y),
+ width: Math.abs(end.x - start.x),
+ x: Math.min(start.x, end.x),
+ y: Math.min(start.y, end.y),
+ },
+ bounds
+ );
+
+export const moveSamBbox = (start: Rect, dx: number, dy: number, bounds: Rect): Rect => ({
+ height: start.height,
+ width: start.width,
+ x: clamp(start.x + dx, bounds.x, bounds.x + bounds.width - start.width),
+ y: clamp(start.y + dy, bounds.y, bounds.y + bounds.height - start.height),
+});
+
+const hasWest = (handle: BboxHandle): boolean => BBOX_HANDLES.includes(handle) && handle.includes('w');
+const hasEast = (handle: BboxHandle): boolean => handle.includes('e');
+const hasNorth = (handle: BboxHandle): boolean => handle.includes('n');
+const hasSouth = (handle: BboxHandle): boolean => handle.includes('s');
+
+export const resizeSamBbox = (options: { start: Rect; handle: BboxHandle; delta: Vec2; bounds: Rect }): Rect => {
+ const { bounds, delta, handle, start } = options;
+ let left = start.x;
+ let top = start.y;
+ let right = start.x + start.width;
+ let bottom = start.y + start.height;
+
+ if (hasWest(handle)) {
+ left = clamp(start.x + delta.x, bounds.x, right - 1);
+ }
+ if (hasEast(handle)) {
+ right = clamp(start.x + start.width + delta.x, left + 1, bounds.x + bounds.width);
+ }
+ if (hasNorth(handle)) {
+ top = clamp(start.y + delta.y, bounds.y, bottom - 1);
+ }
+ if (hasSouth(handle)) {
+ bottom = clamp(start.y + start.height + delta.y, top + 1, bounds.y + bounds.height);
+ }
+ return { height: bottom - top, width: right - left, x: left, y: top };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts
new file mode 100644
index 0000000000..5229a40d3e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts
@@ -0,0 +1,158 @@
+import type { SamSessionSnapshot } from '@workbench/canvas-engine/engineStores';
+import type { PointerInput } from '@workbench/canvas-engine/types';
+
+import { createEngineStores } from '@workbench/canvas-engine/engineStores';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ToolContext } from './tool';
+
+import { createSamTool } from './samTool';
+
+const sourceRect = { height: 100, width: 100, x: 0, y: 0 };
+
+const visualSnapshot = (overrides: Partial<SamSessionSnapshot> = {}): SamSessionSnapshot => ({
+ error: null,
+ hasPreview: false,
+ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },
+ isolatedPreview: true,
+ layerId: 'source',
+ pointLabel: 'include',
+ sourceRect,
+ status: 'ready',
+ ...overrides,
+});
+
+const pointer = (x: number, y: number, options: { buttons?: number; shift?: boolean } = {}): PointerInput => ({
+ buttons: options.buttons ?? 1,
+ documentPoint: { x, y },
+ modifiers: { alt: false, ctrl: false, meta: false, shift: options.shift ?? false },
+ pointerType: 'mouse',
+ pressure: 0.5,
+ screenPoint: { x, y },
+ timeStamp: 0,
+});
+
+const createHarness = (snapshot = visualSnapshot()) => {
+ const stores = createEngineStores();
+ stores.samSession.set(snapshot);
+ const invalidate = vi.fn();
+ const updateSamInput = vi.fn((input: SamSessionSnapshot['input']) => {
+ const current = stores.samSession.get();
+ if (current) {
+ stores.samSession.set({ ...current, input });
+ }
+ });
+ const ctx = {
+ invalidate,
+ stores,
+ updateCursor: vi.fn(),
+ updateSamInput,
+ viewport: {
+ documentToScreen: (point: { x: number; y: number }) => point,
+ viewMatrix: () => ({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }),
+ },
+ } as unknown as ToolContext;
+ return { ctx, invalidate, stores, tool: createSamTool(), updateSamInput };
+};
+
+const down = (h: ReturnType<typeof createHarness>, input: PointerInput): void => h.tool.onPointerDown?.(h.ctx, input);
+const move = (h: ReturnType<typeof createHarness>, input: PointerInput): void =>
+ h.tool.onPointerMove?.(h.ctx, input, [input]);
+const up = (h: ReturnType<typeof createHarness>, input: PointerInput): void => h.tool.onPointerUp?.(h.ctx, input);
+
+describe('createSamTool', () => {
+ it('adds configured points on click and temporarily flips their label with Shift', () => {
+ const h = createHarness();
+
+ down(h, pointer(20, 30));
+ up(h, pointer(20, 30, { buttons: 0 }));
+ down(h, pointer(50, 60, { shift: true }));
+ up(h, pointer(50, 60, { buttons: 0, shift: true }));
+
+ expect(h.stores.samSession.get()?.input).toEqual({
+ bbox: null,
+ excludePoints: [{ x: 50, y: 60 }],
+ includePoints: [{ x: 20, y: 30 }],
+ type: 'visual',
+ });
+ expect(h.invalidate.mock.calls.every(([payload]) => payload.overlay === true && !payload.all)).toBe(true);
+ });
+
+ it('removes an existing point on click but drags it after the screen threshold', () => {
+ const h = createHarness(
+ visualSnapshot({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 20, y: 20 }], type: 'visual' },
+ })
+ );
+
+ down(h, pointer(20, 20));
+ up(h, pointer(20, 20, { buttons: 0 }));
+ expect(h.stores.samSession.get()?.input.includePoints).toEqual([]);
+
+ h.stores.samSession.set(
+ visualSnapshot({ input: { bbox: null, excludePoints: [], includePoints: [{ x: 20, y: 20 }], type: 'visual' } })
+ );
+ down(h, pointer(20, 20));
+ move(h, pointer(21, 21));
+ expect(h.stores.samSession.get()?.input.includePoints).toEqual([{ x: 20, y: 20 }]);
+ move(h, pointer(35, 40));
+ up(h, pointer(35, 40, { buttons: 0 }));
+ expect(h.stores.samSession.get()?.input.includePoints).toEqual([{ x: 35, y: 40 }]);
+ });
+
+ it('creates a clipped bbox from an empty drag and treats a sub-threshold drag as a click', () => {
+ const h = createHarness();
+
+ down(h, pointer(80, 80));
+ move(h, pointer(120, 130));
+ up(h, pointer(120, 130, { buttons: 0 }));
+ expect(h.stores.samSession.get()?.input.bbox).toEqual({ height: 20, width: 20, x: 80, y: 80 });
+
+ down(h, pointer(10, 10));
+ move(h, pointer(12, 12));
+ up(h, pointer(12, 12, { buttons: 0 }));
+ expect(h.stores.samSession.get()?.input.includePoints).toEqual([{ x: 12, y: 12 }]);
+ });
+
+ it('does not publish a degenerate bbox when a boundary drag clips to zero area', () => {
+ const h = createHarness();
+
+ down(h, pointer(100, 100));
+ move(h, pointer(120, 130));
+ up(h, pointer(120, 130, { buttons: 0 }));
+
+ expect(h.stores.samSession.get()?.input.bbox).toBeNull();
+ });
+
+ it('moves the bbox body and resizes a handle while clipping to source bounds', () => {
+ const h = createHarness(
+ visualSnapshot({
+ input: { bbox: { height: 30, width: 40, x: 20, y: 20 }, excludePoints: [], includePoints: [], type: 'visual' },
+ })
+ );
+
+ down(h, pointer(40, 35));
+ move(h, pointer(90, 90));
+ up(h, pointer(90, 90, { buttons: 0 }));
+ expect(h.stores.samSession.get()?.input.bbox).toEqual({ height: 30, width: 40, x: 60, y: 70 });
+
+ down(h, pointer(100, 100));
+ move(h, pointer(150, 150));
+ up(h, pointer(150, 150, { buttons: 0 }));
+ expect(h.stores.samSession.get()?.input.bbox).toEqual({ height: 30, width: 40, x: 60, y: 70 });
+ });
+
+ it('restores the exact pre-gesture input on pointercancel', () => {
+ const initial = visualSnapshot({
+ input: { bbox: null, excludePoints: [{ x: 10, y: 10 }], includePoints: [], type: 'visual' },
+ });
+ const h = createHarness(initial);
+
+ down(h, pointer(10, 10));
+ move(h, pointer(50, 50));
+ expect(h.stores.samSession.get()?.input.excludePoints).toEqual([{ x: 50, y: 50 }]);
+ h.tool.onPointerCancel?.(h.ctx);
+
+ expect(h.stores.samSession.get()?.input).toEqual(initial.input);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.ts
new file mode 100644
index 0000000000..5417b1e3f7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.ts
@@ -0,0 +1,144 @@
+import type { SamVisualInput } from '@workbench/canvas-engine/engineStores';
+import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
+
+import type { SamHitTarget } from './samHitTest';
+import type { Tool, ToolContext } from './tool';
+
+import { clipPointToRect, moveSamBbox, rectFromPoints, resizeSamBbox, samHitTest } from './samHitTest';
+
+const PRIMARY_BUTTON = 1;
+export const SAM_DRAG_THRESHOLD_PX = 3;
+
+interface GestureState {
+ startDoc: Vec2;
+ startScreen: Vec2;
+ startInput: SamVisualInput;
+ target: SamHitTarget | null;
+ moved: boolean;
+}
+
+const cloneInput = (input: SamVisualInput): SamVisualInput => ({
+ bbox: input.bbox ? { ...input.bbox } : null,
+ excludePoints: input.excludePoints.map((point) => ({ ...point })),
+ includePoints: input.includePoints.map((point) => ({ ...point })),
+ type: 'visual',
+});
+
+const isInside = (point: Vec2, rect: { x: number; y: number; width: number; height: number }): boolean =>
+ point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
+
+const flippedLabel = (label: 'include' | 'exclude'): 'include' | 'exclude' =>
+ label === 'include' ? 'exclude' : 'include';
+
+export const createSamTool = (): Tool => {
+ let gesture: GestureState | null = null;
+
+ const publish = (ctx: ToolContext, input: SamVisualInput): void => {
+ ctx.updateSamInput?.(input);
+ ctx.invalidate({ overlay: true });
+ };
+
+ const updateGesture = (ctx: ToolContext, input: PointerInput, state: GestureState): void => {
+ const snapshot = ctx.stores.samSession.get();
+ if (!snapshot) {
+ return;
+ }
+ const next = cloneInput(state.startInput);
+ const delta = {
+ x: input.documentPoint.x - state.startDoc.x,
+ y: input.documentPoint.y - state.startDoc.y,
+ };
+
+ if (state.target?.kind === 'point') {
+ const points = state.target.label === 'include' ? next.includePoints : next.excludePoints;
+ points[state.target.index] = clipPointToRect(input.documentPoint, snapshot.sourceRect);
+ } else if (state.target?.kind === 'bbox-body' && next.bbox) {
+ next.bbox = moveSamBbox(next.bbox, delta.x, delta.y, snapshot.sourceRect);
+ } else if (state.target?.kind === 'bbox-handle' && next.bbox) {
+ next.bbox = resizeSamBbox({ bounds: snapshot.sourceRect, delta, handle: state.target.handle, start: next.bbox });
+ } else {
+ const created = rectFromPoints(state.startDoc, input.documentPoint, snapshot.sourceRect);
+ next.bbox = created.width >= 1 && created.height >= 1 ? created : state.startInput.bbox;
+ }
+ publish(ctx, next);
+ };
+
+ const cancelGesture = (ctx: ToolContext): void => {
+ const current = gesture;
+ gesture = null;
+ if (current?.moved) {
+ publish(ctx, cloneInput(current.startInput));
+ }
+ };
+
+ return {
+ cursor: () => 'crosshair',
+ id: 'sam',
+ onDeactivate: (ctx) => cancelGesture(ctx),
+ onPointerCancel: (ctx) => cancelGesture(ctx),
+ onPointerDown: (ctx, input) => {
+ const snapshot = ctx.stores.samSession.get();
+ if (
+ gesture ||
+ !snapshot ||
+ (input.buttons & PRIMARY_BUTTON) === 0 ||
+ !isInside(input.documentPoint, snapshot.sourceRect)
+ ) {
+ return;
+ }
+ gesture = {
+ moved: false,
+ startDoc: input.documentPoint,
+ startInput: cloneInput(snapshot.input),
+ startScreen: input.screenPoint,
+ target: samHitTest({
+ bbox: snapshot.input.bbox,
+ excludePoints: snapshot.input.excludePoints,
+ includePoints: snapshot.input.includePoints,
+ screenPoint: input.screenPoint,
+ view: ctx.viewport.viewMatrix(1),
+ }),
+ };
+ },
+ onPointerMove: (ctx, input) => {
+ if (!gesture) {
+ return;
+ }
+ if (!gesture.moved) {
+ const dx = input.screenPoint.x - gesture.startScreen.x;
+ const dy = input.screenPoint.y - gesture.startScreen.y;
+ if (Math.hypot(dx, dy) < SAM_DRAG_THRESHOLD_PX) {
+ return;
+ }
+ gesture.moved = true;
+ }
+ updateGesture(ctx, input, gesture);
+ },
+ onPointerUp: (ctx, input) => {
+ const current = gesture;
+ gesture = null;
+ if (!current) {
+ return;
+ }
+ if (current.moved) {
+ updateGesture(ctx, input, current);
+ return;
+ }
+
+ const snapshot = ctx.stores.samSession.get();
+ if (!snapshot) {
+ return;
+ }
+ const next = cloneInput(current.startInput);
+ if (current.target?.kind === 'point') {
+ const points = current.target.label === 'include' ? next.includePoints : next.excludePoints;
+ points.splice(current.target.index, 1);
+ } else {
+ const label = input.modifiers.shift ? flippedLabel(snapshot.pointLabel) : snapshot.pointLabel;
+ const points = label === 'include' ? next.includePoints : next.excludePoints;
+ points.push(clipPointToRect(input.documentPoint, snapshot.sourceRect));
+ }
+ publish(ctx, next);
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index 5de9cb7844..accc0983fd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -13,7 +13,7 @@
* Zero React, zero import-time side effects.
*/
-import type { EngineStores } from '@workbench/canvas-engine/engineStores';
+import type { EngineStores, SamVisualInput } from '@workbench/canvas-engine/engineStores';
import type { CreatePath2D } from '@workbench/canvas-engine/freehand';
import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';
@@ -156,6 +156,8 @@ export interface ToolContext {
* hot path. Absent in minimal test harnesses.
*/
getSelectionMask?(): PlacedSurface | null;
+ /** Updates visual SAM input for the active engine-owned Select Object session. */
+ updateSamInput?(input: SamVisualInput): void;
}
/**