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
refactor(webv2): extract the Select Object bridge from the engine
joshistoast581ca7daadfc
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex fbab1dd3d4..38c5f53dd0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -94,7 +94,7 @@ export type {CommitRasterFilterOptions,CommitRasterFilterResult,} from '@workbench/canvas-engine/controllers/filterResultController';-import type { CanvasApplicationHost, SelectObjectStartContext } from '@workbench/canvas-engine/applicationHost';+import type { CanvasApplicationHost } from '@workbench/canvas-engine/applicationHost';import type {CanvasImageRef,CanvasDocumentContractV2,@@ -146,8 +146,8 @@ import {import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';-import { applyToPoint, fromTRS } from '@workbench/canvas-engine/math/mat2d';-import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';+import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';+import { isEmpty, union } from '@workbench/canvas-engine/math/rect';import {type CompositeOptions,compositeDocument,@@ -197,6 +197,7 @@ import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';import { createBitmapStore, type BitmapStore } from './document/bitmapStore';import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';+import { createSelectObjectBridge } from './selectObjectBridge';import { createStrokeCommit } from './strokeCommit';import { createViewTool } from './tools/viewTool';@@ -2291,47 +2292,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}};- const decodeSelectObjectPreview = async (- result: { image: CanvasImageRef; rect: Rect },- signal: AbortSignal- ): Promise<RasterSurface> => {- const validateDecoded = (width: number, height: number): void => {- const valid =- Number.isInteger(width) &&- width > 0 &&- Number.isInteger(height) &&- height > 0 &&- width === result.image.width &&- height === result.image.height &&- width === result.rect.width &&- height === result.rect.height;- if (!valid) {- throw Object.assign(- new Error(- `Decoded Select Object preview dimensions ${String(width)}x${String(height)} do not match SAM output ${result.image.width}x${result.image.height} and preview rect ${result.rect.width}x${result.rect.height}.`- ),- { samErrorCode: 'output-dimension' as const }- );- }- };- const decoded = await rasterController.decodeImage(result.image, {- scaleToImage: false,- signal,- validateDecoded,- });- if (decoded.status !== 'ok') {- throw new DOMException('Select Object preview decode was aborted.', 'AbortError');- }- const surface = decoded.surface;- surface.ctx.globalCompositeOperation = 'source-in';- surface.ctx.fillStyle = '#38bdf8';- surface.ctx.fillRect(0, 0, surface.width, surface.height);- surface.ctx.globalCompositeOperation = 'source-over';- if (signal.aborted) {- throw new DOMException('Select Object preview decode was aborted.', 'AbortError');- }- return surface;- };+ const { decodeSelectObjectPreview, prepareSelectObjectStart } = createSelectObjectBridge({+ captureGuard: (layerId) => captureCurrentLayerExportGuard(layerId),+ decodeImage: (image, options) => rasterController.decodeImage(image, options),+ getDocument: () => mirror.getDocument(),+ layerCache,+ });// ---- Public API ---------------------------------------------------------@@ -3411,43 +3377,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreClogDebugInfo,};- const prepareSelectObjectStart = (layerId: string): SelectObjectStartContext => {- const document = mirror.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);- if (!document || !layer) {- return { status: 'missing' };- }- if (layer.type !== 'raster' && layer.type !== 'control') {- return { status: 'unsupported' };- }- if (!layer.isEnabled) {- return { status: 'disabled' };- }- if (layer.isLocked) {- return { status: 'locked' };- }- const guard = captureCurrentLayerExportGuard(layer.id);- const entry = layerCache.get(layer.id);- if (!guard || !entry) {- return { status: 'not-ready' };- }- const sourceRect = roundOut(- transformBounds(- fromTRS(- { x: layer.transform.x, y: layer.transform.y },- layer.transform.rotation,- layer.transform.scaleX,- layer.transform.scaleY- ),- entry.rect- )- );- if (isEmpty(sourceRect)) {- return { status: 'not-ready' };- }- return { guard, layerId, layerName: layer.name, layerType: layer.type, sourceRect, status: 'ready' };- };-const applicationHost: CanvasApplicationHost = {captureGuard: captureCurrentLayerExportGuard,clearFilterPreview,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.test.tsnew file mode 100644index 0000000000..8274946993--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.test.ts@@ -0,0 +1,132 @@+import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';+import type { Rect } from '@workbench/canvas-engine/types';++import { describe, expect, it, vi } from 'vitest';++import { createSelectObjectBridge, type CreateSelectObjectBridgeDeps } from './selectObjectBridge';++const layer = (overrides: Record<string, unknown> = {}) =>+ ({+ id: 'layer-1',+ isEnabled: true,+ isLocked: false,+ name: 'Layer 1',+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 20 },+ type: 'raster',+ ...overrides,+ }) as never;++const documentOf = (layers: unknown[]): CanvasDocumentContractV2 => ({ layers }) as CanvasDocumentContractV2;++const surface = () => {+ const ctx = { fillRect: vi.fn(), fillStyle: '', globalCompositeOperation: '' };+ return { ctx, height: 8, width: 8 } as never;+};++const makeDeps = (overrides: Partial<CreateSelectObjectBridgeDeps> = {}): CreateSelectObjectBridgeDeps => ({+ captureGuard: vi.fn(() => ({ layerId: 'layer-1' }) as never),+ decodeImage: vi.fn(() => Promise.resolve({ status: 'ok', surface: surface() } as never)),+ getDocument: () => documentOf([layer()]),+ layerCache: { get: vi.fn(() => ({ rect: { height: 4, width: 4, x: 0, y: 0 } })) } as never,+ ...overrides,+});++const samResult = (image: Partial<CanvasImageRef> = {}, rect: Partial<Rect> = {}) => ({+ image: { height: 8, imageName: 'sam.png', width: 8, ...image } as CanvasImageRef,+ rect: { height: 8, width: 8, x: 0, y: 0, ...rect } as Rect,+});++describe('prepareSelectObjectStart', () => {+ it('reports ready with the layer identity and its document-space bounds', () => {+ const result = createSelectObjectBridge(makeDeps()).prepareSelectObjectStart('layer-1');+ expect(result).toMatchObject({+ layerId: 'layer-1',+ layerName: 'Layer 1',+ layerType: 'raster',+ sourceRect: { height: 4, width: 4, x: 10, y: 20 },+ status: 'ready',+ });+ });++ it.each([+ ['missing', { getDocument: () => documentOf([]) }],+ ['unsupported', { getDocument: () => documentOf([layer({ type: 'inpaint_mask' })]) }],+ ['disabled', { getDocument: () => documentOf([layer({ isEnabled: false })]) }],+ ['locked', { getDocument: () => documentOf([layer({ isLocked: true })]) }],+ ['not-ready', { captureGuard: vi.fn(() => null) }],+ ['not-ready', { layerCache: { get: vi.fn(() => undefined) } as never }],+ ])('refuses with %s', (status, overrides) => {+ const result = createSelectObjectBridge(makeDeps(overrides)).prepareSelectObjectStart('layer-1');+ expect(result.status).toBe(status);+ });++ it('refuses a layer whose cached content transforms to an empty rect', () => {+ const deps = makeDeps({+ layerCache: { get: vi.fn(() => ({ rect: { height: 0, width: 0, x: 0, y: 0 } })) } as never,+ });+ expect(createSelectObjectBridge(deps).prepareSelectObjectStart('layer-1').status).toBe('not-ready');+ });++ it('accepts control layers as well as rasters', () => {+ const deps = makeDeps({ getDocument: () => documentOf([layer({ type: 'control' })]) });+ expect(createSelectObjectBridge(deps).prepareSelectObjectStart('layer-1')).toMatchObject({+ layerType: 'control',+ status: 'ready',+ });+ });+});++describe('decodeSelectObjectPreview', () => {+ const signal = () => new AbortController().signal;++ it('tints the decoded mask through source-in and restores the composite mode', async () => {+ const deps = makeDeps();+ const result = await createSelectObjectBridge(deps).decodeSelectObjectPreview(samResult(), signal());+ expect(result.ctx.fillRect).toHaveBeenCalledWith(0, 0, 8, 8);+ expect(result.ctx.globalCompositeOperation).toBe('source-over');+ });++ it('rejects a decode whose dimensions disagree with the SAM output', async () => {+ const deps = makeDeps({+ decodeImage: vi.fn((_image, options) => {+ options.validateDecoded?.(4, 4);+ return Promise.resolve({ status: 'ok', surface: surface() } as never);+ }),+ });+ await expect(createSelectObjectBridge(deps).decodeSelectObjectPreview(samResult(), signal())).rejects.toMatchObject(+ { samErrorCode: 'output-dimension' }+ );+ });++ it('rejects a decode whose dimensions disagree with the preview rect', async () => {+ const deps = makeDeps({+ decodeImage: vi.fn((_image, options) => {+ options.validateDecoded?.(8, 8);+ return Promise.resolve({ status: 'ok', surface: surface() } as never);+ }),+ });+ await expect(+ createSelectObjectBridge(deps).decodeSelectObjectPreview(samResult({}, { width: 16 }), signal())+ ).rejects.toMatchObject({ samErrorCode: 'output-dimension' });+ });++ it('aborts when the decode does not complete', async () => {+ const deps = makeDeps({ decodeImage: vi.fn(() => Promise.resolve({ status: 'aborted' } as never)) });+ await expect(createSelectObjectBridge(deps).decodeSelectObjectPreview(samResult(), signal())).rejects.toThrow(+ /aborted/i+ );+ });++ it('aborts when the signal fires after a successful decode', async () => {+ const controller = new AbortController();+ const deps = makeDeps({+ decodeImage: vi.fn(() => {+ controller.abort();+ return Promise.resolve({ status: 'ok', surface: surface() } as never);+ }),+ });+ await expect(+ createSelectObjectBridge(deps).decodeSelectObjectPreview(samResult(), controller.signal)+ ).rejects.toThrow(/aborted/i);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.tsnew file mode 100644index 0000000000..b76d6381db--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selectObjectBridge.ts@@ -0,0 +1,115 @@+import type { SelectObjectStartContext } from '@workbench/canvas-engine/applicationHost';+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';+import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';+import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Rect } from '@workbench/canvas-engine/types';++import { fromTRS } from '@workbench/canvas-engine/math/mat2d';+import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';++/** The Select Object preview tint, composited over the mask's alpha coverage. */+const SELECT_OBJECT_PREVIEW_TINT = '#38bdf8';++export interface CreateSelectObjectBridgeDeps {+ readonly layerCache: LayerCacheStore;+ readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly captureGuard: (layerId: string) => LayerExportGuard | null;+ readonly decodeImage: (+ image: CanvasImageRef,+ options: { scaleToImage?: boolean; signal?: AbortSignal; validateDecoded?: (w: number, h: number) => void }+ ) => Promise<DecodeImageResult>;+}++export interface SelectObjectBridge {+ /** Decodes a SAM result into a tinted preview surface, or throws on abort/dimension mismatch. */+ decodeSelectObjectPreview(result: { image: CanvasImageRef; rect: Rect }, signal: AbortSignal): Promise<RasterSurface>;+ /** Gates a Select Object run on the layer being present, supported, editable and rasterized. */+ prepareSelectObjectStart(layerId: string): SelectObjectStartContext;+}++/**+ * The engine's half of the Select Object (SAM) flow.+ *+ * Both halves are policy rather than wiring. The decode validates that what+ * came back actually matches the mask it was asked for — a SAM output whose+ * dimensions disagree with the preview rect would silently paint the wrong+ * region, so it fails loudly with a tagged error the application layer can+ * report. The start gate mirrors the refusal reasons the UI shows, and computes+ * the layer's document-space bounds so the caller does not have to re-derive+ * them from the transform.+ */+export const createSelectObjectBridge = (deps: CreateSelectObjectBridgeDeps): SelectObjectBridge => ({+ decodeSelectObjectPreview: async (result, signal) => {+ const validateDecoded = (width: number, height: number): void => {+ const valid =+ Number.isInteger(width) &&+ width > 0 &&+ Number.isInteger(height) &&+ height > 0 &&+ width === result.image.width &&+ height === result.image.height &&+ width === result.rect.width &&+ height === result.rect.height;+ if (!valid) {+ throw Object.assign(+ new Error(+ `Decoded Select Object preview dimensions ${String(width)}x${String(height)} do not match SAM output ${result.image.width}x${result.image.height} and preview rect ${result.rect.width}x${result.rect.height}.`+ ),+ { samErrorCode: 'output-dimension' as const }+ );+ }+ };+ const decoded = await deps.decodeImage(result.image, { scaleToImage: false, signal, validateDecoded });+ if (decoded.status !== 'ok') {+ throw new DOMException('Select Object preview decode was aborted.', 'AbortError');+ }+ const surface = decoded.surface;+ surface.ctx.globalCompositeOperation = 'source-in';+ surface.ctx.fillStyle = SELECT_OBJECT_PREVIEW_TINT;+ surface.ctx.fillRect(0, 0, surface.width, surface.height);+ surface.ctx.globalCompositeOperation = 'source-over';+ if (signal.aborted) {+ throw new DOMException('Select Object preview decode was aborted.', 'AbortError');+ }+ return surface;+ },++ prepareSelectObjectStart: (layerId) => {+ const document = deps.getDocument();+ const layer = document?.layers.find((candidate) => candidate.id === layerId);+ if (!document || !layer) {+ return { status: 'missing' };+ }+ if (layer.type !== 'raster' && layer.type !== 'control') {+ return { status: 'unsupported' };+ }+ if (!layer.isEnabled) {+ return { status: 'disabled' };+ }+ if (layer.isLocked) {+ return { status: 'locked' };+ }+ const guard = deps.captureGuard(layer.id);+ const entry = deps.layerCache.get(layer.id);+ if (!guard || !entry) {+ return { status: 'not-ready' };+ }+ const sourceRect = roundOut(+ transformBounds(+ fromTRS(+ { x: layer.transform.x, y: layer.transform.y },+ layer.transform.rotation,+ layer.transform.scaleX,+ layer.transform.scaleY+ ),+ entry.rect+ )+ );+ if (isEmpty(sourceRect)) {+ return { status: 'not-ready' };+ }+ return { guard, layerId, layerName: layer.name, layerType: layer.type, sourceRect, status: 'ready' };+ },+});