Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(canvas): SAM behavior matches legacy
joshistoast44a58792832f
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex c1c38dafa0..43f8c920b8 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1331,16 +1331,16 @@"bboxActive": "Bounding box active","bboxInactive": "No bounding box","errorDecode": "The object preview could not be decoded.",- "errorEmpty": "The canvas area has no visible content to select.",+ "errorEmpty": "The layer has no visible content to select.","errorInvalid": "Add an object prompt, point, or bounding box before processing.","errorLocked": "Select Object cannot finish while canvas editing is locked.","errorNoOutput": "Select Object finished without producing an image.",- "errorNotReady": "The canvas source is not ready. Try again when it finishes loading.",- "errorOutputDimension": "The Select Object result dimensions do not match the canvas area.",+ "errorNotReady": "The layer source is not ready. Try again when it finishes loading.",+ "errorOutputDimension": "The Select Object result dimensions do not match the layer source.","errorQueue": "Select Object processing failed on the backend.","errorReconcile": "The completed Select Object result could not be retrieved.","errorUnknown": "Select Object could not finish.",- "errorUpload": "The canvas composite could not be uploaded for Select Object.",+ "errorUpload": "The layer source could not be uploaded for Select Object.","exclude": "Exclude","excludeCount": "Exclude {{count}}","include": "Include",@@ -1363,17 +1363,17 @@"saveAs_inpaint_mask": "Inpaint mask","saveAs_raster": "Raster layer","saveAs_regional_guidance": "Regional guidance",+ "saveAs_selection": "Selection","settings": "Select Object settings",- "sourceDimensions": "{{width}} × {{height}}",- "sourceDimensionsLabel": "Generation area: {{width}} × {{height}}",+ "sourceLayerLabel": "{{name}} · {{type}} · {{width}} × {{height}}","statusCommitting": "Applying object result…","statusError": "Select Object needs attention.",- "statusPreparingComposite": "Preparing canvas composite…",+ "statusPreparingSource": "Preparing layer source…","statusProcessingSam": "Finding object…","statusReady": "Ready","statusRenderingPreview": "Rendering object preview…","statusScheduled": "Waiting to process object…",- "statusUploading": "Uploading canvas composite…",+ "statusUploading": "Uploading layer source…","technicalDetails": "Technical details","title": "Select Object","visual": "Visual",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.tsindex 42e874812e..0923212047 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.ts@@ -2,7 +2,7 @@ import type { CanvasRasterLayerContractV2 } from '@workbench/types';import { describe, expect, it, vi } from 'vitest';-import type { LayerExportGuard, SelectObjectLifecycleGuard } from './engine';+import type { LayerExportGuard } from './engine';import { createCanvasOperationController } from './canvasOperationController';@@ -37,48 +37,27 @@ const createDeferred = <T>() => {};const filterIdentity = { kind: 'filter' as const, layerId: layer.id, projectId: 'project-1' };-const selectObjectIdentity = { kind: 'select-object' as const, projectId: 'project-1' };--const compositeGuard = {- bbox: { height: 10, width: 10, x: 0, y: 0 },- candidates: [{ cacheVersion: 1, layer, layerId: layer.id }],- documentFingerprint: 'document-1',- documentGeneration: 1,- participants: [{ cacheVersion: 1, layer, layerId: layer.id }],- projectId: 'project-1',-};-const selectObjectLifecycleGuard: SelectObjectLifecycleGuard = {- bbox: compositeGuard.bbox,- documentGeneration: 1,- kind: 'select-object-lifecycle',- projectId: 'project-1',-};-const documentSelectObjectIdentity = { kind: 'select-object' as const, projectId: 'project-1' };+const selectObjectIdentity = { kind: 'select-object' as const, layerId: layer.id, projectId: 'project-1' };describe('createCanvasOperationController', () => {- it('uses document-composite identity and guards for Select Object without a layer sentinel', () => {+ it('requires the identity to name the guarded layer for both operation kinds', () => {const controller = createCanvasOperationController({ isGuardCurrent: () => true });const session = controller.start({cleanupPreview: vi.fn(),- guard: selectObjectLifecycleGuard,- identity: documentSelectObjectIdentity,+ guard,+ identity: selectObjectIdentity,});expect(session).not.toBeNull();- expect(controller.getSnapshot()).toMatchObject({ identity: documentSelectObjectIdentity, status: 'active' });- // @ts-expect-error Select Object cannot accept a layer guard.- expect(controller.start({ cleanupPreview: vi.fn(), guard, identity: documentSelectObjectIdentity })).toBeNull();- const invalidFilterOptions = {- cleanupPreview: vi.fn(),- guard: selectObjectLifecycleGuard,- identity: filterIdentity,- };- if (Date.now() < 0) {- // @ts-expect-error Filter cannot accept a Select Object lifecycle guard.- controller.start(invalidFilterOptions);- }- expect(controller.start(invalidFilterOptions as never)).toBeNull();+ expect(controller.getSnapshot()).toMatchObject({ identity: selectObjectIdentity, status: 'active' });+ expect(+ controller.start({ cleanupPreview: vi.fn(), guard, identity: { ...selectObjectIdentity, layerId: 'other' } })+ ).toBeNull();+ expect(+ controller.start({ cleanupPreview: vi.fn(), guard, identity: { ...filterIdentity, layerId: 'other' } })+ ).toBeNull();+ expect(controller.getSnapshot()).toMatchObject({ identity: selectObjectIdentity, status: 'active' });});it('replaces the active operation and prevents its stale session from affecting the replacement', async () => {const firstWork = createDeferred<string>();@@ -92,7 +71,7 @@ describe('createCanvasOperationController', () => {const second = controller.start({cleanupPreview: secondCleanup,- guard: selectObjectLifecycleGuard,+ guard,identity: selectObjectIdentity,})!;@@ -226,7 +205,7 @@ describe('createCanvasOperationController', () => {() => {controller.start({cleanupPreview: replacementCleanup,- guard: selectObjectLifecycleGuard,+ guard,identity: selectObjectIdentity,});return undefined;@@ -285,7 +264,7 @@ describe('createCanvasOperationController', () => {const cleanupPreview = vi.fn(() => {controller.start({cleanupPreview: replacementCleanup,- guard: selectObjectLifecycleGuard,+ guard,identity: selectObjectIdentity,});});@@ -311,7 +290,7 @@ describe('createCanvasOperationController', () => {const cleanupPreview = vi.fn(() => {controller.start({cleanupPreview: replacementCleanup,- guard: selectObjectLifecycleGuard,+ guard,identity: selectObjectIdentity,});});@@ -445,21 +424,22 @@ describe('createCanvasOperationController', () => {expect(controller.getSnapshot()).toMatchObject({ identity: filterIdentity, status: 'active' });});- it('does not close Select Object for participant cache invalidation but closes it for document lifetime invalidation', () => {+ it('keeps Select Object open across other-layer invalidation but closes it for its own source layer', () => {const cleanupPreview = vi.fn();const controller = createCanvasOperationController({ isGuardCurrent: () => true });controller.start({cleanupPreview,- guard: selectObjectLifecycleGuard,+ guard,identity: selectObjectIdentity,});- controller.invalidateSource('project-1', layer.id);+ controller.invalidateSource('project-1', 'other-layer');+ controller.invalidateLayer('project-1', 'other-layer');expect(cleanupPreview).not.toHaveBeenCalled();expect(controller.getSnapshot()).toMatchObject({ identity: selectObjectIdentity, status: 'active' });- controller.invalidateDocument('project-1');+ controller.invalidateSource('project-1', layer.id);expect(cleanupPreview).toHaveBeenCalledOnce();expect(controller.getSnapshot()).toEqual({ status: 'idle' });});@@ -470,7 +450,7 @@ describe('createCanvasOperationController', () => {const controller = createCanvasOperationController({ isGuardCurrent: () => true });const session = controller.start({cleanupPreview: vi.fn(),- guard: selectObjectLifecycleGuard,+ guard,identity: selectObjectIdentity,})!;const pending = session.run(() => work.promise, publish);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.tsindex d2def88014..4b75e5a6c0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts@@ -1,10 +1,10 @@-import type { LayerExportGuard, SelectObjectLifecycleGuard } from './engine';+import type { LayerExportGuard } from './engine';export type CanvasOperationIdentity =- | { kind: 'select-object'; projectId: string }+ | { kind: 'select-object'; projectId: string; layerId: string }| { kind: 'filter'; projectId: string; layerId: string };-export type CanvasOperationGuard = LayerExportGuard | SelectObjectLifecycleGuard;+export type CanvasOperationGuard = LayerExportGuard;export type CanvasOperationState =| { status: 'idle' }@@ -34,17 +34,11 @@ export interface CanvasOperationSession {cancel(): void;}-export type StartCanvasOperationOptions =- | {- identity: Extract<CanvasOperationIdentity, { kind: 'select-object' }>;- guard: SelectObjectLifecycleGuard;- cleanupPreview(): void;- }- | {- identity: Extract<CanvasOperationIdentity, { kind: 'filter' }>;- guard: LayerExportGuard;- cleanupPreview(): void;- };+export interface StartCanvasOperationOptions {+ identity: CanvasOperationIdentity;+ guard: LayerExportGuard;+ cleanupPreview(): void;+}export interface CanvasOperationController {getSnapshot(): CanvasOperationState;@@ -54,7 +48,6 @@ export interface CanvasOperationController {cancel(): void;invalidateSource(projectId: string, layerId: string): void;invalidateLayer(projectId: string, layerId: string): void;- invalidateComposite(projectId: string): void;invalidateProject(projectId: string): void;invalidateDocument(projectId: string): void;dispose(): void;@@ -216,18 +209,10 @@ export const createCanvasOperationController = (deps: CanvasOperationControllerD};const start = (options: StartCanvasOperationOptions): CanvasOperationSession | null => {- const layerIdentityMatches =- options.identity.kind === 'filter' &&- 'layerId' in options.guard &&- options.identity.layerId === options.guard.layerId;- const compositeIdentityMatches =- options.identity.kind === 'select-object' &&- 'kind' in options.guard &&- options.guard.kind === 'select-object-lifecycle';if (disposed ||options.identity.projectId !== options.guard.projectId ||- (!layerIdentityMatches && !compositeIdentityMatches)+ options.identity.layerId !== options.guard.layerId) {return null;}@@ -263,10 +248,7 @@ export const createCanvasOperationController = (deps: CanvasOperationControllerD};const invalidateTarget = (projectId: string, layerId?: string): void => {- if (- active?.identity.projectId === projectId &&- (layerId === undefined || (active.identity.kind === 'select-object' ? true : active.identity.layerId === layerId))- ) {+ if (active?.identity.projectId === projectId && (layerId === undefined || active.identity.layerId === layerId)) {close(active);}};@@ -291,22 +273,9 @@ export const createCanvasOperationController = (deps: CanvasOperationControllerD},getSnapshot: () => state,invalidateDocument: (projectId) => invalidateTarget(projectId),- invalidateComposite: (projectId) => {- if (active?.identity.projectId === projectId && active.identity.kind === 'select-object') {- close(active);- }- },invalidateLayer: (projectId, layerId) => invalidateTarget(projectId, layerId),invalidateProject: (projectId) => invalidateTarget(projectId),- invalidateSource: (projectId, layerId) => {- if (- active?.identity.kind === 'filter' &&- active.identity.projectId === projectId &&- active.identity.layerId === layerId- ) {- close(active);- }- },+ invalidateSource: (projectId, layerId) => invalidateTarget(projectId, layerId),reset: () => {if (active) {interruptProcessing(active);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex aa3850c40d..a7fc78d147 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -9302,7 +9302,7 @@ describe('guarded filter previews', () => {engine.setInteractionLocked(true);expect(engine.startFilterOperation(layer.id)).toBe('locked');- expect(engine.startSelectObject()).toBe('locked');+ expect(engine.startSelectObject(layer.id)).toBe('locked');expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });expect(engine.stores.filterSession.get()).toBeNull();expect(engine.stores.samSession.get()).toBeNull();@@ -9319,7 +9319,7 @@ describe('guarded filter previews', () => {store,});expect((await engine.exportLayerPixels(layer.id)).status).toBe('ok');- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject(layer.id)).toBe('started');engine.setInteractionLocked(true);@@ -9513,12 +9513,12 @@ describe('guarded filter previews', () => {});expect((await engine.exportLayerPixels('first')).status).toBe('ok');expect((await engine.exportLayerPixels('second')).status).toBe('ok');- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject('first')).toBe('started');const operation = engine.canvasOperations.getSnapshot();expect(engine.startFilterOperation('second', 'normal_map')).toBe('not-ready');expect(engine.canvasOperations.getSnapshot()).toEqual(operation);- expect(engine.stores.samSession.get()?.sourceRect).toEqual(document.bbox);+ expect(engine.stores.samSession.get()?.sourceRect).toEqual({ height: 10, width: 10, x: 0, y: 0 });engine.dispose();});@@ -9805,7 +9805,7 @@ describe('guarded filter previews', () => {const pending = engine.commitFilterOperation('apply', () => promotion);await vi.waitFor(() => expect(engine.stores.filterSession.get()?.status).toBe('committing'));- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject(source.id)).toBe('started');resolvePromotion();await pending;@@ -9880,7 +9880,7 @@ describe('guarded filter previews', () => {expect((await engine.exportLayerPixels('L')).status).toBe('ok');expect(engine.startFilterOperation('L')).toBe('started');- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject('L')).toBe('started');expect(engine.stores.filterSession.get()).toBeNull();expect(engine.stores.samSession.get()).not.toBeNull();@@ -9948,7 +9948,7 @@ describe('guarded filter previews', () => {}): null;if (kind === 'select-object') {- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject('L')).toBe('started');}expect(engine.stores.documentEditingLocked.get()).toBe(true);@@ -12671,11 +12671,26 @@ describe('Select Object canvas engine integration', () => {isLocked: false,name: id,opacity: 1,- source: { fill: '#fff', height: 20, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 20 },+ source: { fill: '#fff', height: 100, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 100 },transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y: 0 },type: 'raster',});+ /** A raster layer whose baked world rect exactly covers `rect`. */+ const samRectLayer = (id: string, rect: CanvasDocumentContractV2['bbox']): CanvasRasterLayerContractV2 => ({+ ...samLayer(id),+ source: {+ fill: '#fff',+ height: rect.height,+ kind: 'rect',+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: rect.width,+ },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: rect.x, y: rect.y },+ });+const samDocument = (layers: CanvasLayerContract[] = [samLayer('source')]): CanvasDocumentContractV2 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },@@ -12783,12 +12798,16 @@ describe('Select Object canvas engine integration', () => {return { ...reactive, engine, fireKey, overlay, raf, screen };};- it('keeps Select Object visible and inputs intact when first Process rasterizes a missing candidate, then retries', async () => {+ it('keeps Select Object visible and inputs intact when the first Process fails to upload, then retries', async () => {const bbox = { height: 100, width: 100, x: 0, y: 0 };const reactive = createReactiveStore(samDocument());const runGraph = vi.fn(() =>Promise.resolve({ height: bbox.height, imageName: 'sam-mask.png', origin: 'test', width: bbox.width }));+ const uploadIntermediate = vi+ .fn<NonNullable<CanvasEngineOptions['selectObjectDeps']>['uploadIntermediate']>()+ .mockRejectedValueOnce(new Error('upload failed'))+ .mockResolvedValueOnce({ height: bbox.height, imageName: 'sam-source.png', width: bbox.width });const engine = createCanvasEngine({backend: {...createTestStubRasterBackend(),@@ -12800,13 +12819,13 @@ describe('Select Object canvas engine integration', () => {projectId: 'p1',selectObjectDeps: {runGraph,- uploadIntermediate: () =>- Promise.resolve({ height: bbox.height, imageName: 'sam-source.png', width: bbox.width }),+ uploadIntermediate,},store: reactive.store,});+ await engine.exportLayerPixels('source');const input = { prompt: 'keep this', type: 'prompt' as const };- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject('source')).toBe('started');engine.updateSelectObjectSession({ input, invert: true });await expect(engine.processSelectObjectSession()).resolves.toBe('error');@@ -12821,16 +12840,14 @@ describe('Select Object canvas engine integration', () => {engine.dispose();});- it.each(['bbox', 'document', 'project'] as const)(+ it.each(['document', 'project'] as const)('fully clears Select Object session, store, operation, and tool on %s invalidation',async (kind) => {const h = await createSamHarness();- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('source')).toBe('started');const document = h.engine.getDocument()!;- if (kind === 'bbox') {- h.setDocument({ ...document, bbox: { ...document.bbox, x: document.bbox.x + 1 } });- } else if (kind === 'document') {+ if (kind === 'document') {h.setDocument({ ...document }, 1);} else {h.setActiveProjectId('p2');@@ -12848,7 +12865,7 @@ describe('Select Object canvas engine integration', () => {backend: StubRasterBackend = createTestStubRasterBackend(),bbox: CanvasDocumentContractV2['bbox'] = { height: 100, width: 100, x: 0, y: 0 }) => {- const document = { ...samDocument([samLayer('source', -5)]), bbox };+ const document = { ...samDocument([samRectLayer('source', bbox)]), bbox };const reactive = createReducerBackedStore(document);const engine = createCanvasEngine({backend: {@@ -12868,7 +12885,7 @@ describe('Select Object canvas engine integration', () => {store: reactive.store,});await engine.exportLayerPixels('source');- engine.startSelectObject();+ engine.startSelectObject('source');engine.updateSelectObjectSession({input: {bbox: null,@@ -12897,14 +12914,16 @@ describe('Select Object canvas engine integration', () => {it('starts on the selected supported source, activates the real sam tool, and edits overlay-only', async () => {const h = await createSamHarness();- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('source')).toBe('started');expect(h.engine.stores.activeTool.get()).toBe('sam');expect(h.engine.canvasOperations.getSnapshot()).toMatchObject({- identity: { kind: 'select-object', projectId: 'p1' },+ identity: { kind: 'select-object', layerId: 'source', projectId: 'p1' },status: 'active',});expect(h.engine.stores.samSession.get()).toMatchObject({input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },+ layerName: 'source',+ layerType: 'raster',sourceRect: { height: 100, width: 100, x: 0, y: 0 },});h.raf.flush();@@ -12923,7 +12942,7 @@ describe('Select Object canvas engine integration', () => {it('resets edited inputs and point mode immediately after launch without requiring a preview guard', async () => {const h = await createSamHarness();- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('source')).toBe('started');h.engine.updateSelectObjectSession({input: {bbox: { height: 10, width: 10, x: 1, y: 2 },@@ -12949,7 +12968,7 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('resets after a first not-ready Process while preserving lifecycle ownership', async () => {+ it('resets after a first failed Process while preserving lifecycle ownership', async () => {const bbox = { height: 100, width: 100, x: 0, y: 0 };const reactive = createReactiveStore(samDocument());const engine = createCanvasEngine({@@ -12958,15 +12977,16 @@ describe('Select Object canvas engine integration', () => {imageResolver: () => Promise.resolve(new Blob()),projectId: 'p1',selectObjectDeps: {- runGraph: () => Promise.resolve({ height: 100, imageName: 'mask.png', origin: 'test', width: 100 }),+ runGraph: () => Promise.reject(new Error('queue failed')),uploadIntermediate: () => Promise.resolve({ height: 100, imageName: 'source.png', width: 100 }),},store: reactive.store,});- expect(engine.startSelectObject()).toBe('started');+ await engine.exportLayerPixels('source');+ expect(engine.startSelectObject('source')).toBe('started');engine.updateSelectObjectSession({ input: { prompt: 'cat', type: 'prompt' }, invert: true });await expect(engine.processSelectObjectSession()).resolves.toBe('error');- expect(engine.stores.samSession.get()).toMatchObject({ error: { code: 'not-ready' }, status: 'error' });+ expect(engine.stores.samSession.get()).toMatchObject({ error: { code: 'queue' }, status: 'error' });expect(engine.resetSelectObjectSession()).toBe('updated');@@ -12983,11 +13003,11 @@ describe('Select Object canvas engine integration', () => {engine.dispose();});- it('reuses one uploaded composite across fresh engine guards for point, invert, and refinement changes', async () => {+ it('reuses one uploaded source image across fresh engine guards for point, invert, and refinement changes', async () => {const uploadIntermediate = vi.fn(() => Promise.resolve({ height: 100, imageName: 'source.png', width: 100 }));const runGraph = vi.fn(() => Promise.resolve({ height: 100, imageName: 'mask.png', origin: 'test', width: 100 }));const h = await createSamHarness({ runGraph, uploadIntermediate });- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('source')).toBe('started');h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 2, y: 2 }], type: 'visual' },});@@ -13007,24 +13027,24 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('starts from every visible participant without changing the selected layer', async () => {+ it('keeps the selection when starting on the selected layer and selects a non-selected source', async () => {const h = await createSamHarness({ layers: [samLayer('first'), samLayer('second', 30)] });- expect(h.engine.startSelectObject()).toBe('started');-+ expect(h.engine.startSelectObject('first')).toBe('started');expect(h.store.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'setCanvasSelectedLayer' }));- expect(h.engine.getDocument()?.selectedLayerId).toBe('first');++ expect(h.engine.startSelectObject('second')).toBe('started');+ expect(h.store.dispatch).toHaveBeenCalledWith({ id: 'second', type: 'setCanvasSelectedLayer' });h.engine.dispose();});- it('runs transformed multilayer bbox composite through upload, local visual graph, metadata, and decoded rect', async () => {- const bbox = { height: 30, width: 40, x: -11, y: 7 };+ it('runs a transformed layer rect through upload, local visual graph, metadata, and decoded rect', async () => {const base = createTestStubRasterBackend();const surfaces: StubRasterSurface[] = [];const backend: StubRasterBackend = {...base,createImageBitmap: () =>- Promise.resolve({ close: () => undefined, height: bbox.height, width: bbox.width } as unknown as ImageBitmap),+ Promise.resolve({ close: () => undefined, height: 20, width: 30 } as unknown as ImageBitmap),createSurface: (width, height) => {const surface = base.createSurface(width, height);surfaces.push(surface);@@ -13032,28 +13052,32 @@ describe('Select Object canvas engine integration', () => {},};const uploadIntermediate = vi.fn(async (source: Blob) => {- expect(await source.text()).toBe('stub-surface-40x30');- return { height: 30, imageName: 'composite.png', width: 40 };+ expect(await source.text()).toBe('stub-surface-30x20');+ return { height: 20, imageName: 'layer-source.png', width: 30 };});const runGraph = vi.fn<NonNullable<CanvasEngineOptions['selectObjectDeps']>['runGraph']>((options) => {expect(options.graph.nodes['sam-segment']).toMatchObject({- bounding_boxes: [{ x_max: 25, x_min: 5, y_max: 20, y_min: 5 }],- point_lists: [{ points: [{ label: 1, x: 10, y: 10 }] }],+ bounding_boxes: [{ x_max: 20, x_min: 0, y_max: 18, y_min: 3 }],+ point_lists: [{ points: [{ label: 1, x: 5, y: 8 }] }],});- return Promise.resolve({ height: 30, imageName: 'mask.png', origin: 'test', width: 40 });+ return Promise.resolve({ height: 20, imageName: 'mask.png', origin: 'test', width: 30 });});const imageResolver = vi.fn(() => Promise.resolve(new Blob(['mask'])));- const lower = { ...samLayer('lower', -6), transform: { rotation: 0, scaleX: 1.5, scaleY: 1, x: -6, y: 9 } };- const upper = { ...samLayer('upper', 4), transform: { rotation: 15, scaleX: 1, scaleY: 0.75, x: 4, y: 11 } };+ // A 20x20 shape scaled 1.5x horizontally and translated: baked world rect {-6, 9, 30, 20}.+ const scaled: CanvasRasterLayerContractV2 = {+ ...samLayer('scaled'),+ source: { fill: '#fff', height: 20, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 20 },+ transform: { rotation: 0, scaleX: 1.5, scaleY: 1, x: -6, y: 9 },+ };const h = await createSamHarness({backend,- bbox,imageResolver,- layers: [upper, lower],+ layers: [scaled, samLayer('other', 40)],runGraph,uploadIntermediate,});- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('scaled')).toBe('started');+ expect(h.engine.stores.samSession.get()?.sourceRect).toEqual({ height: 20, width: 30, x: -6, y: 9 });h.engine.updateSelectObjectSession({input: {bbox: { height: 15, width: 20, x: -6, y: 12 },@@ -13069,9 +13093,9 @@ describe('Select Object canvas engine integration', () => {expect(uploadIntermediate).toHaveBeenCalledOnce();expect(runGraph).toHaveBeenCalledOnce();expect(imageResolver).toHaveBeenCalledWith('mask.png', expect.any(AbortSignal));- expect(surfaces.some((surface) => surface.width === 40 && surface.height === 30)).toBe(true);+ expect(surfaces.some((surface) => surface.width === 30 && surface.height === 20)).toBe(true);expect(h.overlay.surface.callLog).toContainEqual({- args: [expect.anything(), -11, 7, 40, 30],+ args: [expect.anything(), -6, 9, 30, 20],op: 'drawImage',});h.engine.dispose();@@ -13083,7 +13107,7 @@ describe('Select Object canvas engine integration', () => {return Promise.resolve({ height: 100, imageName: 'prompt-mask.png', origin: 'test', width: 100 });});const h = await createSamHarness({ runGraph });- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.engine.updateSelectObjectSession({ input: { prompt: ' red car ', type: 'prompt' } });await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');@@ -13096,7 +13120,7 @@ describe('Select Object canvas engine integration', () => {const h = await createSamHarness({runGraph: () => Promise.resolve({ height: 99, imageName: 'bad-mask.png', origin: 'test', width: 100 }),});- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.engine.updateSelectObjectSession({ input: { prompt: 'cat', type: 'prompt' } });await expect(h.engine.processSelectObjectSession()).resolves.toBe('error');@@ -13111,7 +13135,7 @@ describe('Select Object canvas engine integration', () => {it('reports preview decode failures without publishing a stale surface', async () => {const h = await createSamHarness({ imageResolver: () => Promise.reject(new Error('preview decode failed')) });- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.engine.updateSelectObjectSession({ input: { prompt: 'cat', type: 'prompt' } });await expect(h.engine.processSelectObjectSession()).resolves.toBe('error');@@ -13148,7 +13172,7 @@ describe('Select Object canvas engine integration', () => {},};const h = await createSamHarness({ backend });- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.engine.updateSelectObjectSession({ input: { prompt: 'cat', type: 'prompt' } });await expect(h.engine.processSelectObjectSession()).resolves.toBe('error');@@ -13165,9 +13189,10 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('applies the guarded preview to selection and exits only after success', async () => {+ it('saves the guarded preview to the selection mask and exits only after success', async () => {const { backend, surfaces } = createOpaqueSamBackend();const h = await createCommittingSamHarness(() => Promise.resolve(new Blob()), backend);+ const makeDurable = vi.fn(() => Promise.resolve());const previewCalls = surfaces.find((surface) =>surface.callLog.some(@@ -13181,13 +13206,50 @@ describe('Select Object canvas engine integration', () => {]));- await expect(h.engine.applySelectObjectSession()).resolves.toEqual({ status: 'selected' });+ await expect(h.engine.saveSelectObjectSession('selection', makeDurable)).resolves.toEqual({ status: 'selected' });+ expect(makeDurable).not.toHaveBeenCalled();expect(h.engine.getDocument()).toEqual(h.document);expect(h.engine.stores.hasSelection.get()).toBe(true);expect(h.engine.getSelectionBounds()).toEqual(h.document.bbox);expect(h.engine.getSelectionMaskRect()).toEqual(h.document.bbox);expect(h.engine.stores.samSession.get()).toBeNull();+ expect(h.engine.stores.activeTool.get()).toBe('view');+ h.engine.dispose();+ });++ it('Apply replaces the source layer content in place with one undoable history entry', async () => {+ const h = await createCommittingSamHarness();+ const makeDurable = vi.fn(() => Promise.resolve());++ await expect(h.engine.applySelectObjectSession(makeDurable)).resolves.toEqual({+ layerId: 'source',+ status: 'committed',+ });++ expect(makeDurable).toHaveBeenCalledOnce();+ expect(makeDurable).toHaveBeenCalledWith('sam-mask.png');+ const replaced = h.engine.getDocument()!.layers.find((layer) => layer.id === 'source')!;+ expect(replaced).toMatchObject({+ source: {+ bitmap: { height: 100, imageName: 'sam-mask.png', width: 100 },+ offset: { x: 0, y: 0 },+ type: 'paint',+ },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ });+ expect(h.engine.getDocument()!.layers).toHaveLength(1);+ expect(h.engine.stores.samSession.get()).toBeNull();+ expect(h.engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });+ expect(h.engine.stores.activeTool.get()).toBe('view');++ expect(h.engine.stores.canUndo.get()).toBe(true);+ h.engine.undo();+ expect(h.engine.getDocument()).toEqual(h.document);+ expect(h.engine.stores.canUndo.get()).toBe(false);+ h.engine.redo();+ expect(h.engine.getDocument()!.layers.find((layer) => layer.id === 'source')).toEqual(replaced);h.engine.dispose();});@@ -13201,7 +13263,7 @@ describe('Select Object canvas engine integration', () => {expect(h.engine.updateSelectObjectSession({ input: { prompt: 'changed', type: 'prompt' } })).toBe('blocked');expect(h.engine.resetSelectObjectSession()).toBe('blocked');await expect(h.engine.processSelectObjectSession()).resolves.toBe('blocked');- await expect(h.engine.applySelectObjectSession()).resolves.toEqual({ status: 'locked' });+ await expect(h.engine.applySelectObjectSession(makeDurable)).resolves.toEqual({ status: 'locked' });await expect(h.engine.saveSelectObjectSession('raster', makeDurable)).resolves.toEqual({ status: 'locked' });expect(makeDurable).not.toHaveBeenCalled();expect(h.engine.getDocument()).toEqual(h.document);@@ -13240,13 +13302,13 @@ describe('Select Object canvas engine integration', () => {resolutions += 1;return resolutions === 1 ? Promise.resolve(new Blob()) : finalDecode.promise;});- const pending = h.engine.applySelectObjectSession();+ const pending = h.engine.applySelectObjectSession(() => Promise.resolve());await vi.waitFor(() => expect(resolutions).toBe(2));h.engine.setInteractionLocked(true);finalDecode.resolve(new Blob());- await expect(pending).resolves.not.toEqual({ status: 'selected' });+ await expect(pending).resolves.not.toMatchObject({ status: 'committed' });expect(h.engine.getDocument()).toEqual(h.document);expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: true, status: 'ready' });h.engine.cancelSelectObjectSession();@@ -13257,10 +13319,11 @@ describe('Select Object canvas engine integration', () => {const graph = createDeferred<{ height: number; imageName: string; origin: string; width: number }>();const runGraph = vi.fn(() => graph.promise);const h = await createSamHarness({ runGraph });- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('source')).toBe('started');const input = { prompt: 'keep this prompt', type: 'prompt' as const };expect(h.engine.updateSelectObjectSession({ input, invert: true })).toBe('updated');const pending = h.engine.processSelectObjectSession();+ expect(h.engine.stores.samSession.get()?.status).toBe('preparing-source');await vi.waitFor(() => expect(runGraph).toHaveBeenCalledOnce());h.engine.setInteractionLocked(true);@@ -13282,13 +13345,13 @@ describe('Select Object canvas engine integration', () => {resolutions += 1;return resolutions === 1 ? Promise.resolve(new Blob()) : finalDecode.promise;});- const pending = h.engine.applySelectObjectSession();+ const pending = h.engine.applySelectObjectSession(() => Promise.resolve());await vi.waitFor(() => expect(resolutions).toBe(2));await invalidateSelectObjectCommit(h.engine, kind);finalDecode.resolve(new Blob());- await expect(pending).resolves.not.toEqual({ status: 'selected' });+ await expect(pending).resolves.not.toMatchObject({ status: 'committed' });expect(h.engine.getDocument()).toEqual(h.document);expect(h.engine.stores.samSession.get()).not.toBeNull();h.engine.dispose();@@ -13325,9 +13388,14 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it.each(['raster', 'control', 'inpaint_mask', 'regional_guidance'] as const)(- 'promotes then atomically saves the guarded bbox preview as %s at the top of its group',- async (target) => {+ it.each([+ ['raster', 'Segmented Object'],+ ['control', 'Segmented Object Control'],+ ['inpaint_mask', null],+ ['regional_guidance', null],+ ] as const)(+ 'promotes then atomically saves the guarded preview as %s at the top of its group, keeping the session',+ async (target, copyName) => {const calls: string[] = [];const h = await createCommittingSamHarness();@@ -13345,13 +13413,20 @@ describe('Select Object canvas engine integration', () => {throw new Error('expected a saved object layer');}if (created.type === 'raster' || created.type === 'control') {+ expect(created.name).toBe(copyName);expect(created.source).toMatchObject({ offset: { x: 0, y: 0 }, type: 'paint' });} else {expect(created.mask).toMatchObject({ offset: { x: 0, y: 0 } });}expect(created.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });++ // Save As keeps the session and its preview open; only Apply, the+ // Selection target, and Cancel end it.+ expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: true, status: 'ready' });+ expect(h.engine.stores.activeTool.get()).toBe('sam');+ h.engine.cancelSelectObjectSession();+expect(h.engine.stores.canUndo.get()).toBe(true);- expect(h.engine.stores.samSession.get()).toBeNull();h.engine.undo();expect(h.engine.getDocument()?.layers.map((layer) => layer.id)).toEqual(['source']);h.engine.redo();@@ -13360,9 +13435,32 @@ describe('Select Object canvas engine integration', () => {});- it('saves the exact non-zero bbox origin and dimensions independently of source placement', async () => {- const bbox = { height: 30, width: 40, x: -11, y: 7 };- const h = await createCommittingSamHarness(undefined, undefined, bbox);+ it('keeps the session open across saves so a second save also succeeds without touching the source', async () => {+ const h = await createCommittingSamHarness();++ await expect(h.engine.saveSelectObjectSession('raster', () => Promise.resolve())).resolves.toMatchObject({+ status: 'committed',+ });+ expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: true, status: 'ready' });++ await expect(h.engine.saveSelectObjectSession('raster', () => Promise.resolve())).resolves.toMatchObject({+ status: 'committed',+ });++ expect(h.engine.getDocument()?.layers.map((layer) => layer.name)).toEqual([+ 'Segmented Object',+ 'Segmented Object',+ 'source',+ ]);+ expect(h.engine.getDocument()?.layers[2]).toEqual(h.document.layers[0]);+ expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: true, status: 'ready' });+ expect(h.engine.stores.activeTool.get()).toBe('sam');+ h.engine.dispose();+ });++ it('saves the exact non-zero source rect origin and dimensions', async () => {+ const rect = { height: 30, width: 40, x: -11, y: 7 };+ const h = await createCommittingSamHarness(undefined, undefined, rect);const result = await h.engine.saveSelectObjectSession('raster', () => Promise.resolve());@@ -13371,8 +13469,8 @@ describe('Select Object canvas engine integration', () => {expect(created?.type).toBe('raster');if (created?.type === 'raster') {expect(created.source).toMatchObject({- bitmap: { height: bbox.height, width: bbox.width },- offset: { x: bbox.x, y: bbox.y },+ bitmap: { height: rect.height, width: rect.width },+ offset: { x: rect.x, y: rect.y },});}h.engine.dispose();@@ -13384,7 +13482,7 @@ describe('Select Object canvas engine integration', () => {const pending = h.engine.saveSelectObjectSession('raster', () => durable.promise);expect(h.engine.stores.samSession.get()?.status).toBe('committing');- await expect(h.engine.applySelectObjectSession()).resolves.toEqual({ status: 'busy' });+ await expect(h.engine.applySelectObjectSession(() => Promise.resolve())).resolves.toEqual({ status: 'busy' });await expect(h.engine.saveSelectObjectSession('control', () => Promise.resolve())).resolves.toEqual({status: 'busy',});@@ -13452,7 +13550,7 @@ describe('Select Object canvas engine integration', () => {});await engine.exportLayerPixels('first');await engine.exportLayerPixels('second');- engine.startSelectObject();+ engine.startSelectObject('first');engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13463,7 +13561,7 @@ describe('Select Object canvas engine integration', () => {});const oldSave = engine.saveSelectObjectSession('raster', () => durability);- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject('second')).toBe('started');rejectDurability(new Error('old failure'));await expect(oldSave).resolves.toMatchObject({ status: 'failed' });@@ -13471,7 +13569,7 @@ describe('Select Object canvas engine integration', () => {engine.dispose();});- it('does not close a replacement session when the old Apply finishes authoritatively', async () => {+ it('does not close a replacement session when the old selection save finishes authoritatively', async () => {const document = samDocument([samLayer('first'), samLayer('second', 30)]);const reactive = createReducerBackedStore(document);const { backend } = createOpaqueSamBackend();@@ -13488,7 +13586,7 @@ describe('Select Object canvas engine integration', () => {});await engine.exportLayerPixels('first');await engine.exportLayerPixels('second');- engine.startSelectObject();+ engine.startSelectObject('first');engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13497,11 +13595,13 @@ describe('Select Object canvas engine integration', () => {const unsubscribe = engine.stores.hasSelection.subscribe(() => {if (!replaced && engine.stores.hasSelection.get()) {replaced = true;- engine.startSelectObject();+ engine.startSelectObject('second');}});- await expect(engine.applySelectObjectSession()).resolves.toEqual({ status: 'selected' });+ await expect(engine.saveSelectObjectSession('selection', () => Promise.resolve())).resolves.toEqual({+ status: 'selected',+ });expect(engine.stores.samSession.get()).toMatchObject({ error: null });unsubscribe();@@ -13527,7 +13627,7 @@ describe('Select Object canvas engine integration', () => {});await engine.exportLayerPixels('first');await engine.exportLayerPixels('second');- engine.startSelectObject();+ engine.startSelectObject('first');engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13540,16 +13640,16 @@ describe('Select Object canvas engine integration', () => {sawCommitting = true;} else if (sawCommitting && !replaced) {replaced = true;- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject('second')).toBe('started');}});const result =kind === 'apply'- ? await engine.applySelectObjectSession()+ ? await engine.applySelectObjectSession(() => Promise.resolve()): await engine.saveSelectObjectSession('inpaint_mask', () => Promise.resolve());- expect(result.status).toBe(kind === 'apply' ? 'selected' : 'committed');+ expect(result.status).toBe('committed');expect(replaced).toBe(true);expect(engine.stores.samSession.get()).toMatchObject({ error: null });expect(engine.stores.activeTool.get()).toBe('sam');@@ -13638,7 +13738,7 @@ describe('Select Object canvas engine integration', () => {store: reducer.store,});await engine.exportLayerPixels('source');- expect(engine.startSelectObject()).toBe('started');+ expect(engine.startSelectObject('source')).toBe('started');engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13657,7 +13757,7 @@ describe('Select Object canvas engine integration', () => {it.each(['source', 'project', 'document'] as const)('aborts a pending save on %s invalidation', async (kind) => {const h = await createSamHarness();- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13719,7 +13819,7 @@ describe('Select Object canvas engine integration', () => {Promise.resolve({ height: 100, imageName: 'sam-mask.png', origin: 'test', width: 100 }));const h = await createSamHarness({ runGraph });- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.overlay.fire('pointerdown', pointerAt(99.8, 99.7));h.overlay.fire('pointerup', pointerAt(99.8, 99.7, { buttons: 0 }));@@ -13732,7 +13832,7 @@ describe('Select Object canvas engine integration', () => {it('uses the half-open generation bbox as the only point domain', async () => {const h = await createSamHarness();- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('source')).toBe('started');h.overlay.fire('pointerdown', pointerAt(100, 50));h.overlay.fire('pointerup', pointerAt(100, 50, { buttons: 0 }));@@ -13746,9 +13846,9 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('keeps viewport changes current but invalidates on bbox and cache changes', async () => {+ it('keeps viewport changes current but invalidates on cache clears', async () => {const h = await createSamHarness();- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('source')).toBe('started');h.engine.getViewport().panBy({ x: 20, y: -10 });h.engine.getViewport().zoomAtPoint(2, { x: 50, y: 50 });@@ -13757,48 +13857,47 @@ describe('Select Object canvas engine integration', () => {status: 'active',});- h.setDocument({ ...h.engine.getDocument()!, bbox: { height: 80, width: 90, x: 3, y: 4 } });- expect(h.engine.stores.samSession.get()).toBeNull();-- expect(h.engine.startSelectObject()).toBe('started');await h.engine.clearCaches();expect(h.engine.stores.samSession.get()).toBeNull();h.engine.dispose();});- it('invalidates the composite operation when participant z-order changes', async () => {- const h = await createSamHarness({ layers: [samLayer('top'), samLayer('bottom', 30)] });- expect(h.engine.startSelectObject()).toBe('started');- const document = h.engine.getDocument()!;+ it('survives bbox moves, layer reorders, and other-layer edits but cancels on a source-layer edit', async () => {+ const h = await createSamHarness({ layers: [samLayer('source'), samLayer('other', 30)] });+ expect(h.engine.startSelectObject('source')).toBe('started');- h.setDocument({ ...document, layers: [...document.layers].reverse() });+ const document = h.engine.getDocument()!;+ h.setDocument({ ...document, bbox: { height: 80, width: 90, x: 3, y: 4 } });+ expect(h.engine.stores.samSession.get()).not.toBeNull();- expect(h.engine.stores.samSession.get()).toBeNull();- expect(h.engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });- h.engine.dispose();- });+ const reordered = h.engine.getDocument()!;+ h.setDocument({ ...reordered, layers: [...reordered.layers].reverse() });+ expect(h.engine.stores.samSession.get()).not.toBeNull();- it('opens on an empty document and reports a clear process-time composite error', async () => {- const h = await createSamHarness({ layers: [] });- expect(h.engine.startSelectObject()).toBe('started');- h.engine.updateSelectObjectSession({- input: { bbox: null, excludePoints: [], includePoints: [{ x: 10, y: 10 }], type: 'visual' },+ const withOtherEdited = h.engine.getDocument()!;+ h.setDocument({+ ...withOtherEdited,+ layers: withOtherEdited.layers.map((layer) => (layer.id === 'other' ? { ...layer, opacity: 0.5 } : layer)),+ });+ expect(h.engine.stores.samSession.get()).not.toBeNull();+ expect(h.engine.canvasOperations.getSnapshot()).toMatchObject({+ identity: { kind: 'select-object', layerId: 'source' },+ status: 'active',});- await expect(h.engine.processSelectObjectSession()).resolves.toBe('error');- expect(h.engine.stores.samSession.get()).toMatchObject({- error: { code: 'empty' },- status: 'error',+ const withSourceEdited = h.engine.getDocument()!;+ h.setDocument({+ ...withSourceEdited,+ layers: withSourceEdited.layers.map((layer) => (layer.id === 'source' ? { ...layer, opacity: 0.25 } : layer)),});+ expect(h.engine.stores.samSession.get()).toBeNull();+ expect(h.engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });+ expect(h.engine.stores.activeTool.get()).toBe('view');h.engine.dispose();});- it('does not omit a stale outside cache when its new source may enter the bbox', async () => {+ it('does not start from a stale cache whose replacement source is still decoding', async () => {const nextImage = createDeferred<Blob>();- const uploadIntermediate = vi.fn(() => Promise.resolve({ height: 100, imageName: 'sam-source.png', width: 100 }));- const runGraph = vi.fn(() =>- Promise.resolve({ height: 100, imageName: 'sam-mask.png', origin: 'test', width: 100 })- );const outside = {...samLayer('moving-source'),source: {@@ -13812,8 +13911,6 @@ describe('Select Object canvas engine integration', () => {imageResolver: (imageName) =>imageName === 'inside.png' ? nextImage.promise : Promise.resolve(new Blob(['outside'])),layers: [outside],- runGraph,- uploadIntermediate,});const document = h.engine.getDocument()!;h.setDocument({@@ -13825,29 +13922,18 @@ describe('Select Object canvas engine integration', () => {},],});- expect(h.engine.startSelectObject()).toBe('started');- h.engine.updateSelectObjectSession({- input: { bbox: null, excludePoints: [], includePoints: [{ x: 2, y: 2 }], type: 'visual' },- });- const firstProcess = h.engine.processSelectObjectSession();- await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('preparing-composite'));- expect(runGraph).not.toHaveBeenCalled();- expect(uploadIntermediate).not.toHaveBeenCalled();- nextImage.resolve(new Blob(['inside']));- await expect(firstProcess).resolves.not.toBe('published');- expect(h.engine.canvasOperations.getSnapshot()).toMatchObject({ phase: 'error', status: 'active' });- expect(h.engine.stores.samSession.get()).toMatchObject({- input: { bbox: null, excludePoints: [], includePoints: [{ x: 2, y: 2 }], type: 'visual' },- });+ expect(h.engine.startSelectObject('moving-source')).toBe('not-ready');+ expect(h.engine.stores.samSession.get()).toBeNull();+ expect(h.engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });- await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');- expect(uploadIntermediate).toHaveBeenCalledOnce();- expect(runGraph).toHaveBeenCalledOnce();+ nextImage.resolve(new Blob(['inside']));+ await expect(h.engine.exportLayerPixels('moving-source')).resolves.toMatchObject({ status: 'ok' });+ expect(h.engine.startSelectObject('moving-source')).toBe('started');h.engine.dispose();});- it('excludes disabled and authoritatively empty layers from composite readiness', async () => {+ it('refuses disabled and authoritatively empty source layers without rasterizing', async () => {const imageResolver = vi.fn(() => Promise.reject(new Error('disabled layer must not rasterize')));const empty = {...samLayer('empty'),@@ -13859,42 +13945,48 @@ describe('Select Object canvas engine integration', () => {source: { image: { height: 10, imageName: 'disabled.png', width: 10 }, type: 'image' as const },};const h = await createSamHarness({ imageResolver, layers: [disabled, empty] });- expect(h.engine.startSelectObject()).toBe('started');- h.engine.updateSelectObjectSession({- input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },- });- await expect(h.engine.processSelectObjectSession()).resolves.toBe('error');- expect(h.engine.stores.samSession.get()?.error).toEqual({ code: 'empty' });+ expect(h.engine.startSelectObject('disabled')).toBe('disabled');+ expect(h.engine.startSelectObject('empty')).toBe('not-ready');++ expect(h.engine.stores.samSession.get()).toBeNull();+ expect(h.engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });expect(imageResolver).not.toHaveBeenCalled();h.engine.dispose();});- it('opens independently of selected layer type, visibility, or document content', async () => {+ it('validates the source layer on start: missing, unsupported, disabled, and locked', 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.startSelectObject()).toBe('started');- expect(unsupported.engine.stores.activeTool.get()).toBe('sam');- unsupported.engine.dispose();+ const h = await createSamHarness({+ layers: [+ mask,+ { ...samLayer('disabled'), isEnabled: false },+ { ...samLayer('locked'), isLocked: true },+ samLayer('ready'),+ ],+ });++ expect(h.engine.startSelectObject('missing')).toBe('missing');+ expect(h.engine.startSelectObject('mask')).toBe('unsupported');+ expect(h.engine.startSelectObject('disabled')).toBe('disabled');+ expect(h.engine.startSelectObject('locked')).toBe('locked');- const disabled = await createSamHarness({ layers: [{ ...samLayer('disabled'), isEnabled: false }] });- expect(disabled.engine.startSelectObject()).toBe('started');- expect(disabled.engine.stores.activeTool.get()).toBe('sam');- disabled.engine.dispose();+ expect(h.engine.stores.samSession.get()).toBeNull();+ expect(h.engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });+ expect(h.engine.stores.activeTool.get()).toBe('view');- const missing = await createSamHarness({ layers: [] });- expect(missing.engine.startSelectObject()).toBe('started');- expect(missing.engine.stores.samSession.get()).not.toBeNull();- missing.engine.dispose();+ expect(h.engine.startSelectObject('ready')).toBe('started');+ expect(h.engine.stores.activeTool.get()).toBe('sam');+ h.engine.dispose();});it('cancels the owned session and decoded preview on a real tool switch', async () => {const h = await createSamHarness();- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('source')).toBe('started');h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13914,7 +14006,7 @@ describe('Select Object canvas engine integration', () => {const base = createTestStubRasterBackend();const backend = { ...base, createImageBitmap: vi.fn(() => bitmap.promise) };const h = await createSamHarness({ backend, imageResolver: () => image.promise });- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13932,12 +14024,12 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('isolates the same flattened bbox participants in the compositor while a preview is published', async () => {+ it('isolates only the source layer in the compositor while a preview is published', async () => {const backend = createRecordingRasterBackend();backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('sam-mask', 100, 100)));const h = await createSamHarness({ backend, layers: [samLayer('source'), samLayer('other', 30)] });h.engine.stores.checkerboard.set(false);- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13945,7 +14037,7 @@ describe('Select Object canvas engine integration', () => {h.screen.surface.callLog.length = 0;h.raf.flush();- expect(h.screen.surface.callLog.filter((entry) => entry.op === 'drawImage')).toHaveLength(2);+ expect(h.screen.surface.callLog.filter((entry) => entry.op === 'drawImage')).toHaveLength(1);expect(h.screen.surface.callLog).toEqual(expect.arrayContaining([{ args: [0, 0, 100, 100], op: 'rect' },@@ -13956,9 +14048,11 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('flattens transformed raster and control participants with display semantics while excluding masks', async () => {+ it('isolates the transformed source layer with display semantics while excluding other layers', async () => {const backend = createRecordingRasterBackend();- backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('decoded', 100, 100)));+ backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('decoded', 20, 15)));+ // Paint bitmap 10x10 at offset (-4, 6), scaled 2x1.5 and translated (12, 8):+ // baked world rect {4, 17, 20, 15}.const raster: CanvasLayerContract = {...samLayer('adjusted-raster'),adjustments: { brightness: 0.2, contrast: -0.1, saturation: 0.3 },@@ -13989,39 +14083,47 @@ describe('Select Object canvas engine integration', () => {mask: { bitmap: { height: 20, imageName: 'mask.png', width: 20 }, fill: { color: '#fff', style: 'solid' } },type: 'inpaint_mask',};- const h = await createSamHarness({ backend, layers: [mask, control, raster] });+ const h = await createSamHarness({+ backend,+ layers: [mask, control, raster],+ runGraph: () => Promise.resolve({ height: 15, imageName: 'sam-mask.png', origin: 'test', width: 20 }),+ uploadIntermediate: () => Promise.resolve({ height: 15, imageName: 'sam-source.png', width: 20 }),+ });h.engine.stores.checkerboard.set(false);- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('adjusted-raster')).toBe('started');+ expect(h.engine.stores.samSession.get()?.sourceRect).toEqual({ height: 15, width: 20, x: 4, y: 17 });h.engine.updateSelectObjectSession({- input: { bbox: null, excludePoints: [], includePoints: [{ x: 35, y: 25 }], type: 'visual' },+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 18 }], type: 'visual' },});await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');h.screen.surface.callLog.length = 0;h.raf.flush();const draws = h.screen.surface.callLog.filter((entry) => entry.op === 'drawImage');- expect(draws).toHaveLength(2);+ expect(draws).toHaveLength(1);expect(h.screen.surface.callLog).toEqual(expect.arrayContaining([{ args: ['globalAlpha', 0.4], op: 'set' },{ args: ['globalCompositeOperation', 'multiply'], op: 'set' },- { args: ['globalAlpha', 0.65], op: 'set' },- { args: ['globalCompositeOperation', 'screen'], op: 'set' },- { args: [0, 0, 100, 100], op: 'rect' },+ { args: [4, 17, 20, 15], op: 'rect' },]));+ expect(h.screen.surface.callLog).not.toContainEqual({ args: ['globalAlpha', 0.65], op: 'set' });+ expect(h.screen.surface.callLog).not.toContainEqual({ args: ['globalCompositeOperation', 'screen'], op: 'set' });expect(adjustedSurfaceCacheGets).toContain('adjusted-raster');h.engine.dispose();});- it('encodes the exact bbox composite surface with participant order and transforms', async () => {+ it('encodes exactly the baked source layer surface, excluding other layers and previews', async () => {const backend = createRecordingRasterBackend();const encoded: StubRasterSurface[] = [];backend.encodeSurface = vi.fn((surface) => {encoded.push(surface as StubRasterSurface);- return Promise.resolve(new Blob(['composite'], { type: 'image/png' }));+ return Promise.resolve(new Blob(['baked-layer'], { type: 'image/png' }));});- backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('decoded', 80, 70)));+ backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('decoded', 12, 24)));+ // Paint bitmap 6x8 at offset (-4, 6), scaled 2x3 and translated (20, 30):+ // baked world rect {12, 48, 12, 24}.const raster: CanvasLayerContract = {...samLayer('raster'),source: {@@ -14052,14 +14154,14 @@ describe('Select Object canvas engine integration', () => {const h = await createSamHarness({backend,layers: [mask, control, raster],- runGraph: () => Promise.resolve({ height: 70, imageName: 'sam-mask.png', origin: 'test', width: 80 }),- uploadIntermediate: () => Promise.resolve({ height: 70, imageName: 'sam-source.png', width: 80 }),+ runGraph: () => Promise.resolve({ height: 24, imageName: 'sam-mask.png', origin: 'test', width: 12 }),+ uploadIntermediate: () => Promise.resolve({ height: 24, imageName: 'sam-source.png', width: 12 }),});h.setDocument({ ...h.engine.getDocument()!, bbox: { height: 70, width: 80, x: 10, y: 15 } });const rasterExport = await h.engine.exportLayerPixels('raster');const controlExport = await h.engine.exportLayerPixels('control');if (rasterExport.status !== 'ok' || controlExport.status !== 'ok') {- throw new Error('expected authoritative participant caches');+ throw new Error('expected authoritative layer caches');}await expect(h.engine.setGuardedFilterPreview(@@ -14070,38 +14172,29 @@ describe('Select Object canvas engine integration', () => {).resolves.toBe('shown');h.engine.setStagedPreview({ imageName: 'staged.png' });await flushMicrotasks();- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('raster')).toBe('started');h.engine.updateSelectObjectSession({- input: { bbox: null, excludePoints: [], includePoints: [{ x: 45, y: 55 }], type: 'visual' },+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 15, y: 50 }], type: 'visual' },});await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');- const composite = encoded.find((surface) => surface.width === 80 && surface.height === 70);- expect(composite).toBeDefined();- const log = composite!.callLog;+ const baked = encoded.find((surface) => surface.width === 12 && surface.height === 24);+ expect(baked).toBeDefined();+ const log = baked!.callLog;const draws = log.filter((entry) => entry.op === 'drawImage');- expect(draws).toHaveLength(2);- expect(backend.drawSourcesFor(composite!)).toEqual([- backend.surfaceId(rasterExport.surface as StubRasterSurface),- backend.surfaceId(controlExport.surface as StubRasterSurface),- ]);- expect(draws.map((entry) => entry.args.slice(1))).toEqual([- [-4, 6],- [0, 0],- ]);+ expect(draws).toHaveLength(1);+ expect(backend.drawSourcesFor(baked!)).toEqual([backend.surfaceId(rasterExport.surface as StubRasterSurface)]);+ expect(draws.map((entry) => entry.args.slice(1))).toEqual([[-4, 6]]);expect(log.filter((entry) => entry.op === 'setTransform').map((entry) => entry.args)).toEqual(- expect.arrayContaining([- [2, 0, 0, 3, 10, 15],- [1, 0, 0, 1, 30, 35],- ])+ expect.arrayContaining([[2, 0, 0, 3, 8, -18]]));h.engine.dispose();});it('tears down the session when its captured source contract changes', async () => {const h = await createSamHarness();- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.setDocument({...h.engine.getDocument()!,@@ -14117,15 +14210,14 @@ describe('Select Object canvas engine integration', () => {const output = createDeferred<{ height: number; imageName: string; origin: string; width: number }>();const layers = [samLayer('first'), samLayer('second', 30)];const h = await createSamHarness({ layers, runGraph: () => output.promise });- h.engine.startSelectObject();+ h.engine.startSelectObject('first');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-sam'));- h.setDocument({ ...h.engine.getDocument()!, selectedLayerId: 'second' });- expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.startSelectObject('second')).toBe('started');expect(h.engine.stores.samSession.get()).not.toBeNull();output.resolve({ height: 100, imageName: 'late.png', origin: 'late', width: 100 });@@ -14136,7 +14228,7 @@ describe('Select Object canvas engine integration', () => {it('lets Escape cancel a gesture before a later Escape cancels the operation', async () => {const h = await createSamHarness();- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.overlay.fire('pointerdown', pointerAt(5, 5));h.overlay.fire('pointermove', pointerAt(15, 15));h.overlay.fire('pointercancel', pointerAt(15, 15));@@ -14151,7 +14243,7 @@ describe('Select Object canvas engine integration', () => {it('keeps the Select Object operation active while Space temporarily switches to view', async () => {const h = await createSamHarness();- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.overlay.fire('pointerenter', {});h.fireKey('keydown', 'Space', ' ');@@ -14165,7 +14257,7 @@ describe('Select Object canvas engine integration', () => {it('does not restore sessionless sam when Escape closes the session during a Space hold', async () => {const h = await createSamHarness();- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.overlay.fire('pointerenter', {});h.fireKey('keydown', 'Space', ' ');expect(h.engine.stores.activeTool.get()).toBe('view');@@ -14180,7 +14272,7 @@ describe('Select Object canvas engine integration', () => {it('does not restore sessionless sam when source invalidation closes the session during a Space hold', async () => {const h = await createSamHarness();- h.engine.startSelectObject();+ h.engine.startSelectObject('source');h.overlay.fire('pointerenter', {});h.fireKey('keydown', 'Space', ' ');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex e950eee60f..f8d5b1c573 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -221,10 +221,14 @@ export type CommitGeneratedImageResult =| { status: 'failed'; message: string };export interface CommitGeneratedImageOptions {- guard: LayerExportGuard | CanvasCompositeExportGuard;+ guard: LayerExportGuard;image: CanvasImageRef;origin: Vec2;target: GeneratedImageTarget;+ /** Overrides the undo-history label of the `replace` target. */+ historyLabel?: string;+ /** Overrides the new layer's name for the copy targets. */+ copyLayerName?: string;signal?: AbortSignal;}@@ -236,7 +240,7 @@ export type ReplaceSelectionFromImageResult =export type MaskImageResultTarget = 'inpaint_mask' | 'regional_guidance';export interface CommitMaskImageResultOptions {- guard: LayerExportGuard | CanvasCompositeExportGuard;+ guard: LayerExportGuard;image: CanvasImageRef;rect: Rect;target: MaskImageResultTarget;@@ -271,31 +275,6 @@ export interface LayerExportGuard {readonly documentGeneration: number;}-export interface CanvasCompositeExportGuard {- readonly projectId: string;- readonly bbox: Rect;- readonly documentGeneration: number;- readonly documentFingerprint: string;- readonly candidates: readonly {- readonly layerId: string;- readonly layer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }>;- readonly cacheVersion: number;- }[];- readonly participants: readonly CanvasCompositeExportGuard['candidates'][number][];-}--/** Stable Select Object chrome lifetime, independent of mutable raster-cache versions. */-export interface SelectObjectLifecycleGuard {- readonly kind: 'select-object-lifecycle';- readonly projectId: string;- readonly bbox: Rect;- readonly documentGeneration: number;-}--export type ExportCanvasCompositeBlobResult =- | { status: 'ok'; blob: Blob; rect: Rect; guard: CanvasCompositeExportGuard }- | { status: 'empty' | 'not-ready' };-export type ExportLayerPixelsResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' };@@ -409,8 +388,11 @@ export type CanvasOperationActionResult = 'completed' | 'blocked' | 'stale';export type FilterCommitOperationResult = 'committed' | 'blocked' | 'stale';export type CanvasOperationMutationResult = 'updated' | 'blocked' | 'stale';-export type SelectObjectSaveTarget = 'raster' | 'control' | MaskImageResultTarget;-export type SaveSelectObjectSessionResult = CommitGeneratedImageResult | CommitMaskImageResult;+export type SelectObjectSaveTarget = 'selection' | 'raster' | 'control' | MaskImageResultTarget;+export type SaveSelectObjectSessionResult =+ | CommitGeneratedImageResult+ | CommitMaskImageResult+ | ReplaceSelectionFromImageResult;export interface SelectObjectSessionUpdate {input?: SamInput;@@ -424,7 +406,7 @@ export interface SelectObjectSessionUpdate {interface SelectObjectCommitOwner {controller: AbortController;- guard: CanvasCompositeExportGuard;+ guard: LayerExportGuard;inputHash: string;preview: SelectObjectSessionPreview<RasterSurface>;previewId: number;@@ -432,13 +414,6 @@ interface SelectObjectCommitOwner {token: number;}-interface SelectObjectExpectedMutation {- actionType: 'addCanvasLayer';- layer: CanvasLayerContract;- layerId: string;- owner: SelectObjectCommitOwner;-}-/** The public engine handle. */export interface CanvasEngine {readonly projectId: string;@@ -456,8 +431,8 @@ 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 document-level Select Object over the current generation bbox. */- startSelectObject(): StartSelectObjectSessionResult;+ /** Starts one engine-owned guarded Select Object session for a raster or control layer. */+ startSelectObject(layerId: string): StartSelectObjectSessionResult;/** Starts one engine-owned guarded filter operation for a raster or control layer. */startFilterOperation(layerId: string, recommendedFilterType?: string | null): StartFilterOperationResult;updateFilterOperation(draft: LayerFilterSettings): CanvasOperationMutationResult;@@ -470,7 +445,7 @@ export interface CanvasEngine {cancelFilterOperation(): void;updateSelectObjectSession(changes: SelectObjectSessionUpdate): CanvasOperationMutationResult;processSelectObjectSession(): Promise<SelectObjectSessionProcessResult>;- applySelectObjectSession(): Promise<ReplaceSelectionFromImageResult>;+ applySelectObjectSession(makeImageDurable: (imageName: string) => Promise<void>): Promise<CommitGeneratedImageResult>;saveSelectObjectSession(target: SelectObjectSaveTarget,makeImageDurable: (imageName: string) => Promise<void>@@ -944,13 +919,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {let selectObjectSession: SelectObjectSession<RasterSurface> | null = null;let selectObjectUnsubscribe: (() => void) | null = null;let selectObjectControllerUnsubscribe: (() => void) | null = null;- let selectObjectLifecycleGuard: SelectObjectLifecycleGuard | null = null;- let selectObjectGuard: CanvasCompositeExportGuard | null = null;+ let selectObjectStartGuard: LayerExportGuard | null = null;+ let selectObjectGuard: LayerExportGuard | null = null;let selectObjectSourceRect: Rect | null = null;let selectObjectPointLabel: SamPointLabel = 'include';let selectObjectCommitOwner: SelectObjectCommitOwner | null = null;let selectObjectCommitToken = 0;- let selectObjectExpectedMutation: SelectObjectExpectedMutation | null = null;let samPreview: SelectObjectSessionPreview<RasterSurface> | null = null;let filterSession: FilterOperationSession | null = null;let filterUnsubscribe: (() => void) | null = null;@@ -1613,211 +1587,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return isLayerExportGuardCurrent(guard) ? guard : null;};- const planCanvasComposite = (document: CanvasDocumentContractV2) => {- const candidates: CanvasCompositeExportGuard['candidates'][number][] = [];- const participants: CanvasCompositeExportGuard['participants'][number][] = [];- const pending: Extract<CanvasLayerContract, { type: 'raster' | 'control' }>[] = [];- for (const layer of document.layers) {- const source = renderableSourceOf(layer);- if (!layer.isEnabled || (layer.type !== 'raster' && layer.type !== 'control') || !source) {- continue;- }- const entry = layerCache.get(layer.id);- const candidate = { cacheVersion: layerCache.version(layer.id), layer, layerId: layer.id };- candidates.push(candidate);- if (!entry || entry.stale || layerRasterizationJobs.has(layer.id)) {- pending.push(layer);- continue;- }- const rect = entry.rect;- if (- isEmpty(rect) ||- intersect(- document.bbox,- roundOut(- transformBounds(- fromTRS(- { x: layer.transform.x, y: layer.transform.y },- layer.transform.rotation,- layer.transform.scaleX,- layer.transform.scaleY- ),- rect- )- )- ) === null- ) {- continue;- }- participants.push(candidate);- }- return { candidates, participants, pending };- };-- const compositeFingerprint = (- bbox: Rect,- candidates: CanvasCompositeExportGuard['candidates'],- participants: CanvasCompositeExportGuard['participants']- ): string =>- JSON.stringify([- bbox.x,- bbox.y,- bbox.width,- bbox.height,- candidates.map(({ cacheVersion, layer }) => [layer, cacheVersion]),- participants.map(({ layerId }) => layerId),- ]);-- const captureCanvasCompositeExportGuard = (): CanvasCompositeExportGuard | null => {- const document = mirror.getDocument();- if (!document || document.bbox.width <= 0 || document.bbox.height <= 0) {- return null;- }- const bbox = { ...document.bbox };- const { candidates, participants } = planCanvasComposite(document);- return {- bbox,- candidates,- documentFingerprint: compositeFingerprint(bbox, candidates, participants),- documentGeneration: rasterDocumentGeneration,- participants,- projectId,- };- };-- const isCanvasCompositeExportGuardCurrent = (guard: CanvasCompositeExportGuard): boolean => {- if (- disposed ||- guard.projectId !== projectId ||- store.getState().activeProjectId !== projectId ||- guard.documentGeneration !== rasterDocumentGeneration- ) {- return false;- }- const document = mirror.getDocument();- if (- !document ||- document.bbox.x !== guard.bbox.x ||- document.bbox.y !== guard.bbox.y ||- document.bbox.width !== guard.bbox.width ||- document.bbox.height !== guard.bbox.height- ) {- return false;- }- const { candidates, participants } = planCanvasComposite(document);- return (- candidates.length === guard.candidates.length &&- candidates.every(- (candidate, index) =>- candidate.layer === guard.candidates[index]?.layer &&- candidate.cacheVersion === guard.candidates[index]?.cacheVersion- ) &&- participants.length === guard.participants.length &&- participants.every(- (participant, index) =>- participant.layer === guard.participants[index]?.layer &&- participant.cacheVersion === guard.participants[index]?.cacheVersion- ) &&- compositeFingerprint(guard.bbox, candidates, participants) === guard.documentFingerprint- );- };-- const captureSelectObjectLifecycleGuard = (): SelectObjectLifecycleGuard | null => {- const document = mirror.getDocument();- if (!document || document.bbox.width <= 0 || document.bbox.height <= 0) {- return null;- }- return {- bbox: { ...document.bbox },- documentGeneration: rasterDocumentGeneration,- kind: 'select-object-lifecycle',- projectId,- };- };-- const isSelectObjectLifecycleGuardCurrent = (guard: SelectObjectLifecycleGuard): boolean => {- const document = mirror.getDocument();- return (- !disposed &&- guard.projectId === projectId &&- store.getState().activeProjectId === projectId &&- guard.documentGeneration === rasterDocumentGeneration &&- document !== null &&- document.bbox.x === guard.bbox.x &&- document.bbox.y === guard.bbox.y &&- document.bbox.width === guard.bbox.width &&- document.bbox.height === guard.bbox.height- );- };-- const exportCanvasCompositeBlob = async (): Promise<ExportCanvasCompositeBlobResult> => {- const guard = captureCanvasCompositeExportGuard();- if (!guard || !isCanvasCompositeExportGuardCurrent(guard)) {- return { status: 'not-ready' };- }- const document = mirror.getDocument();- if (!document) {- return { status: 'not-ready' };- }- const { pending } = planCanvasComposite(document);- if (pending.length > 0) {- await Promise.all(pending.map((layer) => getOrStartLayerRasterization(layer, document)));- return { status: 'not-ready' };- }- let hasContent = false;- for (const participant of guard.participants) {- const entry = layerCache.get(participant.layerId);- if (!entry || entry.stale || isCurrentRasterizationJob(participant.layer)) {- return { status: 'not-ready' };- }- if (- !isEmpty(entry.rect) &&- intersect(- guard.bbox,- roundOut(- transformBounds(- fromTRS(- { x: participant.layer.transform.x, y: participant.layer.transform.y },- participant.layer.transform.rotation,- participant.layer.transform.scaleX,- participant.layer.transform.scaleY- ),- entry.rect- )- )- ) !== null- ) {- hasContent = true;- }- }- if (!hasContent) {- return { status: 'empty' };- }- const surface = backend.createSurface(guard.bbox.width, guard.bbox.height);- const participantIds = new Set(guard.participants.map((participant) => participant.layerId));- compositeDocument(- surface,- { ...document, layers: document.layers.filter((layer) => participantIds.has(layer.id)) },- layerCache,- { a: 1, b: 0, c: 0, d: 1, e: -guard.bbox.x, f: -guard.bbox.y },- { adjustedSurface: getAdjustedSurface, backend, checkerboardTile: null }- );- if (!isCanvasCompositeExportGuardCurrent(guard)) {- return { status: 'not-ready' };- }- const blob = await backend.encodeSurface(surface, 'image/png');- return isCanvasCompositeExportGuardCurrent(guard)- ? { blob, guard, rect: { ...guard.bbox }, status: 'ok' }- : { status: 'not-ready' };- };-canvasOperations = createCanvasOperationController({- isGuardCurrent: (guard) => {- if ('kind' in guard) {- return isSelectObjectLifecycleGuardCurrent(guard);- }- return isLayerExportGuardCurrent(guard);- },+ isGuardCurrent: isLayerExportGuardCurrent,});const documentEditOwner = Symbol('canvas-operation-document-edit-owner');type DocumentEditPermit = { epoch: number; owner?: symbol };@@ -2561,9 +2332,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {ensureLayerCaches(doc);const stagedPlacement = stagedPreview?.placement;const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;- const isolatedIds = isolatedGuard- ? new Set(isolatedGuard.participants.map((participant) => participant.layerId))- : null;+ const isolatedIds = isolatedGuard ? new Set([isolatedGuard.layerId]) : null;const compositeDoc = isolatedIds? { ...doc, layers: doc.layers.filter((layer) => isolatedIds.has(layer.id)) }: doc;@@ -2581,7 +2350,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {!isolatedGuard && filterPreviews.size > 0? new Map(Array.from(filterPreviews, ([id, preview]) => [id, preview])): null,- clipRect: isolatedGuard?.bbox ?? null,+ clipRect: isolatedGuard && samPreview ? samPreview.rect : 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,@@ -2674,8 +2443,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// preview is drawn in the COMPOSITE at the current bbox origin, so it must// recomposite to follow the bbox. Explicitly placed candidates do not.onBboxChanged: () => {- canvasOperations.invalidateComposite(projectId);- cancelSelectObjectSession();scheduler.invalidate(stagedPreview && !stagedPreview.placement ? { all: true } : { overlay: true });},onDocumentReplaced: () => {@@ -2755,51 +2522,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {scheduler.invalidate({ all: true });},onLayerOrderChanged: () => {- canvasOperations.invalidateComposite(projectId);- cancelSelectObjectSession();scheduler.invalidate({ all: true });},onLayersChanged: (ids, sourceChangedIds) => {const doc = mirror.getDocument();- const expected = selectObjectExpectedMutation;- const isExactExpectedMutation =- expected !== null &&- expected.actionType === 'addCanvasLayer' &&- selectObjectCommitOwner === expected.owner &&- ids.length === 1 &&- ids[0] === expected.layerId &&- sourceChangedIds.length === 1 &&- sourceChangedIds[0] === expected.layerId &&- doc?.layers.find((layer) => layer.id === expected.layerId) === expected.layer;- if (expected && !isExactExpectedMutation) {- canvasOperations.invalidateComposite(projectId);- cancelSelectObjectSession();- }- if (!isExactExpectedMutation) {- for (const id of sourceChangedIds) {- canvasOperations.invalidateSource(projectId, id);- }- for (const id of ids) {- canvasOperations.invalidateLayer(projectId, id);- }- }- if (!isExactExpectedMutation && selectObjectGuard && !isCanvasCompositeExportGuardCurrent(selectObjectGuard)) {- cancelSelectObjectSession();+ for (const id of sourceChangedIds) {+ canvasOperations.invalidateSource(projectId, id);}- if (- !isExactExpectedMutation &&- selectObjectGuard &&- ids.some((id) => {- const layer = doc?.layers.find((candidate) => candidate.id === id);- return (- !!layer &&- (layer.type === 'raster' || layer.type === 'control') &&- !selectObjectGuard?.candidates.some((candidate) => candidate.layerId === id)- );- })- ) {- canvasOperations.invalidateComposite(projectId);- cancelSelectObjectSession();+ for (const id of ids) {+ canvasOperations.invalidateLayer(projectId, id);}const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);const sourceChanged = new Set(sourceChangedIds);@@ -3104,7 +2835,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const syncSelectObjectStore = (): void => {const session = selectObjectSession;const sourceRect = selectObjectSourceRect;- if (!session || !sourceRect) {+ const startGuard = selectObjectStartGuard;+ if (!session || !sourceRect || !startGuard) {stores.samSession.set(null);return;}@@ -3114,6 +2846,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {autoProcess: state.autoProcess,error: state.error,hasPreview: state.preview !== null,+ layerName: startGuard.layer.name,+ layerType: startGuard.layer.type === 'control' ? 'control' : 'raster',input:state.input.type === 'visual'? {@@ -3137,7 +2871,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {selectObjectCommitToken += 1;const owner = selectObjectCommitOwner;selectObjectCommitOwner = null;- selectObjectExpectedMutation = null;owner?.controller.abort();};@@ -3148,10 +2881,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const isSelectObjectCommitOwnerCurrent = (owner: SelectObjectCommitOwner): boolean => {const state = owner.session.getSnapshot();- const expected = selectObjectExpectedMutation;- const expectedMutationApplied =- expected?.owner === owner &&- mirror.getDocument()?.layers.find((layer) => layer.id === expected.layerId) === expected.layer;return (selectObjectCommitOwner === owner &&selectObjectCommitToken === owner.token &&@@ -3160,7 +2889,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {state.preview?.previewId === owner.previewId &&state.preview.inputHash === owner.inputHash &&owner.preview.inputHash === owner.inputHash &&- (expectedMutationApplied || isCanvasCompositeExportGuardCurrent(owner.guard)) &&+ isLayerExportGuardCurrent(owner.guard) &&!owner.controller.signal.aborted);};@@ -3181,7 +2910,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {session,token: ++selectObjectCommitToken,};- selectObjectExpectedMutation = null;selectObjectCommitOwner = owner;syncSelectObjectStore();return owner;@@ -3192,9 +2920,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return false;}selectObjectCommitOwner = null;- if (selectObjectExpectedMutation?.owner === owner) {- selectObjectExpectedMutation = null;- }syncSelectObjectStore();return true;};@@ -3263,7 +2988,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {selectObjectUnsubscribe = null;selectObjectControllerUnsubscribe?.();selectObjectControllerUnsubscribe = null;- selectObjectLifecycleGuard = null;+ selectObjectStartGuard = null;selectObjectGuard = null;selectObjectSourceRect = null;selectObjectPointLabel = 'include';@@ -3278,31 +3003,61 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return true;};- const startSelectObject = (): StartSelectObjectSessionResult => {+ const startSelectObject = (layerId: string): StartSelectObjectSessionResult => {if (interactionLocked) {return 'locked';}const doc = mirror.getDocument();- if (!doc) {+ const layer = doc?.layers.find((candidate) => candidate.id === layerId);+ if (!doc || !layer) {return 'missing';}- const lifecycleGuard = captureSelectObjectLifecycleGuard();- if (!lifecycleGuard) {+ if (layer.type !== 'raster' && layer.type !== 'control') {+ return 'unsupported';+ }+ if (!layer.isEnabled) {+ return 'disabled';+ }+ if (layer.isLocked) {+ return 'locked';+ }+ const guard = captureCurrentLayerExportGuard(layer.id);+ const entry = layerCache.get(layer.id);+ if (!guard || !entry) {+ return 'not-ready';+ }+ // The session works in the layer's baked world rect (transform applied), the+ // same space `exportBakedLayerBlob` renders the SAM source image into.+ 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 'not-ready';}clearOwnedFilterSession();clearOwnedSelectObjectSession();- selectObjectLifecycleGuard = lifecycleGuard;+ selectObjectStartGuard = guard;selectObjectGuard = null;- selectObjectSourceRect = { ...lifecycleGuard.bbox };+ selectObjectSourceRect = sourceRect;+ if (doc.selectedLayerId !== layer.id) {+ store.dispatch({ id: layer.id, type: 'setCanvasSelectedLayer' });+ }const operation = canvasOperations.start({cleanupPreview: clearSamPreview,- guard: lifecycleGuard,- identity: { kind: 'select-object', projectId },+ guard,+ identity: { kind: 'select-object', layerId: layer.id, projectId },});if (!operation) {- selectObjectLifecycleGuard = null;+ selectObjectStartGuard = null;selectObjectGuard = null;selectObjectSourceRect = null;return 'not-ready';@@ -3310,12 +3065,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const queueDeps = opts.selectObjectDeps;selectObjectSession = createSelectObjectSession({deps: {- captureGuard: captureCanvasCompositeExportGuard,+ captureGuard: () => captureCurrentLayerExportGuard(layer.id),cleanupPreview: clearSamPreview,controller: canvasOperations,decodePreview: decodeSelectObjectPreview,- exportComposite: exportCanvasCompositeBlob,- isGuardCurrent: isCanvasCompositeExportGuardCurrent,+ exportSource: () => exportBakedLayerBlob(layer.id, { includeDisabled: true }),+ isGuardCurrent: isLayerExportGuardCurrent,publishPreview: (preview) => {selectObjectGuard = preview.guard;const isolationChanged = samPreview?.isolated !== preview.isolated;@@ -3413,10 +3168,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {) {return null;}- return isCanvasCompositeExportGuardCurrent(preview.guard) ? preview : null;+ return isLayerExportGuardCurrent(preview.guard) ? preview : null;};- const applySelectObjectSession = async (): Promise<ReplaceSelectionFromImageResult> => {+ const applySelectObjectSession = async (+ makeImageDurable: (imageName: string) => Promise<void>+ ): Promise<CommitGeneratedImageResult> => {if (interactionLocked) {return { status: 'locked' };}@@ -3437,17 +3194,46 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {invalidateSelectObjectCommit();return { status: 'locked' };}- const result = await replaceSelectionFromImage(- preview.guard,- preview.image,- preview.rect,- owner.controller.signal,- documentEditOwner- );+ try {+ await makeImageDurable(preview.image.imageName);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (finishSelectObjectCommit(owner)) {+ owner.session.reportError({ code: 'unknown', detail: message });+ }+ return { message, status: 'failed' };+ }+ if (!isSelectObjectCommitOwnerCurrent(owner)) {+ return interactionLocked ? { status: 'locked' } : { status: 'stale' };+ }+ if (interactionLocked) {+ invalidateSelectObjectCommit();+ return { status: 'locked' };+ }+ let result: CommitGeneratedImageResult;+ try {+ result = await commitGeneratedImageResult(+ {+ guard: preview.guard,+ historyLabel: 'Replace layer with selected object',+ image: preview.image,+ origin: { x: preview.rect.x, y: preview.rect.y },+ signal: owner.controller.signal,+ target: 'replace',+ },+ documentEditOwner+ );+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (finishSelectObjectCommit(owner)) {+ owner.session.reportError({ code: 'unknown', detail: message });+ }+ return { message, status: 'failed' };+ }if (!isSelectObjectCommitOwnerCurrent(owner)) {return result;}- if (result.status === 'selected') {+ if (result.status === 'committed') {if (!clearOwnedSelectObjectSession(owner)) {return result;}@@ -3494,6 +3280,41 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {invalidateSelectObjectCommit();return { status: 'locked' };}+ if (target === 'selection') {+ // The mask pixels are copied out of the intermediate image synchronously,+ // so this is the one target that does not need a durable image.+ const result = await replaceSelectionFromImage(+ preview.guard,+ preview.image,+ preview.rect,+ owner.controller.signal,+ documentEditOwner+ );+ if (!isSelectObjectCommitOwnerCurrent(owner)) {+ return result;+ }+ if (result.status === 'selected') {+ if (!clearOwnedSelectObjectSession(owner)) {+ return result;+ }+ if (selectObjectSession === null && activeToolId === 'sam') {+ setTool('view');+ }+ } else {+ if (!finishSelectObjectCommit(owner)) {+ return result;+ }+ owner.session.reportError(+ result.status === 'locked'+ ? { code: 'locked' }+ : {+ code: 'unknown',+ detail: result.status === 'failed' ? result.message : `Select Object save is ${result.status}.`,+ }+ );+ }+ return result;+ }try {await makeImageDurable(preview.image.imageName);} catch (error) {@@ -3516,6 +3337,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {target === 'raster' || target === 'control'? await commitGeneratedImageResult({+ copyLayerName: target === 'raster' ? 'Segmented Object' : 'Segmented Object Control',guard: preview.guard,image: preview.image,origin: { x: preview.rect.x, y: preview.rect.y },@@ -3545,12 +3367,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return result;}if (result.status === 'committed') {- if (!clearOwnedSelectObjectSession(owner)) {- return result;- }- if (selectObjectSession === null && activeToolId === 'sam') {- setTool('view');- }+ // Save As keeps the session open (legacy parity) — only Apply, the+ // Selection target, and Cancel end it. The preview and inputs survive so+ // the same selection can be saved to multiple targets.+ finishSelectObjectCommit(owner);} else {if (!finishSelectObjectCommit(owner)) {return result;@@ -3572,15 +3392,16 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return 'blocked';}const session = selectObjectSession;- const lifecycleGuard = selectObjectLifecycleGuard;+ const startGuard = selectObjectStartGuard;const operation = canvasOperations.getSnapshot();if (!session ||- !lifecycleGuard ||- !isSelectObjectLifecycleGuardCurrent(lifecycleGuard) ||+ !startGuard ||+ !isLayerExportGuardCurrent(startGuard) ||operation.status !== 'active' ||operation.identity.kind !== 'select-object' ||- operation.identity.projectId !== projectId+ operation.identity.projectId !== projectId ||+ operation.identity.layerId !== startGuard.layerId) {return 'stale';}@@ -4320,7 +4141,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {};const replaceSelectionFromImage = async (- guard: LayerExportGuard | CanvasCompositeExportGuard,+ guard: LayerExportGuard,image: CanvasImageRef,rect: Rect,signal?: AbortSignal,@@ -4369,22 +4190,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (!document) {return { status: 'missing' };}- if ('layerId' in guard) {- const liveLayer = document.layers.find((candidate) => candidate.id === guard.layerId);- if (!liveLayer) {- return { status: 'missing' };- }- if (liveLayer.isLocked) {- return { status: 'locked' };- }- if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {- return { status: 'unsupported' };- }+ const liveLayer = document.layers.find((candidate) => candidate.id === guard.layerId);+ if (!liveLayer) {+ return { status: 'missing' };+ }+ if (liveLayer.isLocked) {+ return { status: 'locked' };+ }+ if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {+ return { status: 'unsupported' };}if (!isDocumentEditPermitCurrent(permit) || pipeline.isGestureActive()) {return { status: 'busy' };}- if (!('participants' in guard ? isCanvasCompositeExportGuardCurrent(guard) : isLayerExportGuardCurrent(guard))) {+ if (!isLayerExportGuardCurrent(guard)) {return { status: 'stale' };}if (signal?.aborted) {@@ -4418,29 +4237,21 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (!document) {return Promise.resolve({ status: 'missing' });}- let sourceIndex = 0;- if ('layerId' in options.guard) {- const layerId = options.guard.layerId;- const liveLayer = document.layers.find((candidate) => candidate.id === layerId);- if (!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' });- }- sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);+ const liveLayer = document.layers.find((candidate) => candidate.id === options.guard.layerId);+ if (!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' });+ }+ const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);if (pipeline.isGestureActive()) {return Promise.resolve({ status: 'busy' });}- if (- !('participants' in options.guard- ? isCanvasCompositeExportGuardCurrent(options.guard)- : isLayerExportGuardCurrent(options.guard))- ) {+ if (!isLayerExportGuardCurrent(options.guard)) {return Promise.resolve({ status: 'stale' });}if (options.signal?.aborted) {@@ -4482,14 +4293,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {);endNudgeBurst();- if (owner === documentEditOwner && selectObjectCommitOwner) {- selectObjectExpectedMutation = {- actionType: 'addCanvasLayer',- layer,- layerId,- owner: selectObjectCommitOwner,- };- }apply();history.push({bytes: 256,@@ -4764,7 +4567,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const validateGuard = ():| {document: CanvasDocumentContractV2;- liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }> | null;+ liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }>;}| { result: CommitGeneratedImageResult } => {if (!isDocumentEditPermitCurrent(permit)) {@@ -4774,29 +4577,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (!document) {return { result: { status: 'missing' } };}- let liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }> | null = null;- if ('layerId' in options.guard) {- const layerId = options.guard.layerId;- const candidate = document.layers.find((layer) => layer.id === layerId);- if (!candidate) {- return { result: { status: 'missing' } };- }- if (candidate.isLocked) {- return { result: { status: 'locked' } };- }- if (candidate.type !== 'raster' && candidate.type !== 'control') {- return { result: { status: 'unsupported' } };- }- liveLayer = candidate;+ const liveLayer = document.layers.find((layer) => layer.id === options.guard.layerId);+ if (!liveLayer) {+ return { result: { status: 'missing' } };+ }+ if (liveLayer.isLocked) {+ return { result: { status: 'locked' } };+ }+ if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {+ return { result: { status: 'unsupported' } };}if (pipeline.isGestureActive()) {return { result: { status: 'busy' } };}- if (- !('participants' in options.guard- ? isCanvasCompositeExportGuardCurrent(options.guard)- : isLayerExportGuardCurrent(options.guard))- ) {+ if (!isLayerExportGuardCurrent(options.guard)) {return { result: { status: 'stale' } };}return { document, liveLayer };@@ -4888,9 +4682,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {};if (options.target === 'replace') {- if (!liveLayer) {- return { status: 'unsupported' };- }const beforePixels = captureLayerCache(liveLayer, document);if (!beforePixels || beforePixels === 'not-ready') {return { status: 'stale' };@@ -4925,7 +4716,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {beforePixels.rect.width * beforePixels.rect.height * 4 +afterPixels.rect.width * afterPixels.rect.height * 4 +256,- label: 'Replace layer with workflow result',+ label: options.historyLabel ?? 'Replace layer with workflow result',redo: () => applySnapshot(after, afterPixels, { discardPersistence: true, persist: false }),replayFailureAtomic: true,undo: () =>@@ -4937,7 +4728,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return { layerId: liveLayer.id, status: 'committed' };}- const sourceIndex = liveLayer ? document.layers.findIndex((candidate) => candidate.id === liveLayer.id) : 0;+ const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);if (sourceIndex < 0) {return { status: 'missing' };}@@ -4947,9 +4738,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {options.target === 'copy-control'? {...createControlLayer(- liveLayer- ? nextControlLayerName(document.layers.map((layer) => layer.name))- : 'Segmented Object Control',+ options.copyLayerName ?? nextControlLayerName(document.layers.map((layer) => layer.name)),layerId,getMainModelBase()),@@ -4961,7 +4750,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {id: layerId,isEnabled: true,isLocked: false,- name: liveLayer ? `${liveLayer.name} workflow result` : 'Segmented Object',+ name: options.copyLayerName ?? `${liveLayer.name} workflow result`,opacity: 1,source,transform: identityTransform,@@ -4990,14 +4779,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {}endNudgeBurst();- if (owner === documentEditOwner && selectObjectCommitOwner && 'participants' in options.guard) {- selectObjectExpectedMutation = {- actionType: 'addCanvasLayer',- layer: copy,- layerId,- owner: selectObjectCommitOwner,- };- }publishCopy(preparedCopy);history.push({bytes: rect.width * rect.height * 4 + 256,@@ -6663,7 +6444,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {};const clearCaches = async (): Promise<void> => {- canvasOperations.invalidateComposite(projectId);cancelSelectObjectSession();// Flush pending paint-bitmap uploads FIRST: an unflushed stroke lives only in// the live `layerCache` until the debounced (1500ms) flush persists it. If wediff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 9d9a21f062..45e9f07b0c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -259,6 +259,8 @@ export type SamSessionInput =/** Narrow engine-owned Select Object state for canvas tools and future UI subscribers. */export interface SamSessionSnapshot {sourceRect: Rect;+ layerName: string;+ layerType: 'raster' | 'control';input: SamSessionInput;pointLabel: SamPointLabel;model: SamModel;@@ -269,7 +271,7 @@ export interface SamSessionSnapshot {status:| 'ready'| 'scheduled'- | 'preparing-composite'+ | 'preparing-source'| 'uploading'| 'processing-sam'| 'rendering-preview'diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.test.tsnew file mode 100644index 0000000000..229df87c77--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.test.ts@@ -0,0 +1,104 @@+import { describe, expect, it } from 'vitest';++import { traceMaskOutlinePath } from './maskOutline';++/** Builds RGBA data from a row-major alpha grid. */+const alphaGrid = (+ rows: readonly (readonly number[])[]+): { data: Uint8ClampedArray; height: number; width: number } => {+ const height = rows.length;+ const width = rows[0]?.length ?? 0;+ const data = new Uint8ClampedArray(width * height * 4);+ rows.forEach((row, y) =>+ row.forEach((alpha, x) => {+ data[(y * width + x) * 4 + 3] = alpha;+ })+ );+ return { data, height, width };+};++const ORIGIN = { x: 0, y: 0 };++describe('traceMaskOutlinePath', () => {+ it('returns an empty path for an empty or sub-threshold mask', () => {+ expect(traceMaskOutlinePath(alphaGrid([]), ORIGIN)).toBe('');+ expect(+ traceMaskOutlinePath(+ alphaGrid([+ [0, 0],+ [0, 0],+ ]),+ ORIGIN+ )+ ).toBe('');+ expect(+ traceMaskOutlinePath(+ alphaGrid([+ [64, 64],+ [64, 64],+ ]),+ ORIGIN+ )+ ).toBe('');+ });++ it('honors a lower threshold for faint coverage', () => {+ const grid = alphaGrid([[64]]);+ expect(traceMaskOutlinePath(grid, ORIGIN)).toBe('');+ expect(traceMaskOutlinePath(grid, ORIGIN, 1)).toBe('M 0 0 L 1 0 L 1 1 L 0 1 Z');+ });++ it('traces a full mask as its bounding rectangle with merged collinear runs', () => {+ const grid = alphaGrid([+ [255, 255, 255],+ [255, 255, 255],+ ]);+ expect(traceMaskOutlinePath(grid, { x: 10, y: 20 })).toBe('M 10 20 L 13 20 L 13 22 L 10 22 Z');+ });++ it('traces a single interior pixel offset by the document-space origin', () => {+ const grid = alphaGrid([+ [0, 0, 0],+ [0, 255, 0],+ [0, 0, 0],+ ]);+ expect(traceMaskOutlinePath(grid, { x: 7, y: -3 })).toBe('M 8 -2 L 9 -2 L 9 -1 L 8 -1 Z');+ });++ it('emits a counter-clockwise inner loop for a hole', () => {+ const grid = alphaGrid([+ [255, 255, 255],+ [255, 0, 255],+ [255, 255, 255],+ ]);+ const path = traceMaskOutlinePath(grid, ORIGIN);+ const loops = path.split(' Z').filter((segment) => segment.trim().length > 0);+ expect(loops).toHaveLength(2);+ expect(path).toContain('M 0 0 L 3 0 L 3 3 L 0 3 Z');+ // The hole loop winds opposite to the outer loop (counter-clockwise), so+ // nonzero fill keeps the hole.+ expect(path).toContain('M 2 1 L 1 1 L 1 2 L 2 2 Z');+ });++ it('keeps diagonally touching regions as two separate loops', () => {+ const grid = alphaGrid([+ [255, 0],+ [0, 255],+ ]);+ const path = traceMaskOutlinePath(grid, ORIGIN);+ const loops = path.split(' Z').filter((segment) => segment.trim().length > 0);+ expect(loops).toHaveLength(2);+ expect(path).toContain('M 0 0 L 1 0 L 1 1 L 0 1 Z');+ expect(path).toContain('M 1 1 L 2 1 L 2 2 L 1 2 Z');+ });++ it('traces disjoint regions as independent closed loops', () => {+ const grid = alphaGrid([+ [255, 0, 255],+ [255, 0, 255],+ ]);+ const path = traceMaskOutlinePath(grid, ORIGIN);+ expect(path).toContain('M 0 0 L 1 0 L 1 2 L 0 2 Z');+ expect(path).toContain('M 2 0 L 3 0 L 3 2 L 2 2 Z');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.tsnew file mode 100644index 0000000000..0bc0338db2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/maskOutline.ts@@ -0,0 +1,143 @@+/**+ * Rectilinear boundary tracing for alpha masks.+ *+ * Converts a mask's alpha channel into closed pixel-edge contours so the+ * marching ants can stroke the mask's true outline instead of its bounding+ * rect. Outer boundaries wind clockwise (screen coordinates) and holes wind+ * counter-clockwise, so the emitted path also nonzero-fills to the same shape+ * it outlines.+ */++interface MaskAlphaSource {+ /** RGBA pixel data (only the alpha channel is read). */+ data: Uint8ClampedArray;+ width: number;+ height: number;+}++// Directions: 0 = right, 1 = down, 2 = left, 3 = up (screen coordinates).+const DIRECTION_X = [1, 0, -1, 0] as const;+const DIRECTION_Y = [0, 1, 0, -1] as const;++/**+ * Traces the outline of every alpha region as an SVG path in document space+ * (`origin` offsets the mask-local pixel grid). Pixels count as inside at+ * `alpha >= threshold`. Returns an empty string for an empty mask.+ */+export const traceMaskOutlinePath = (+ source: MaskAlphaSource,+ origin: { x: number; y: number },+ threshold = 128+): string => {+ const { data, height, width } = source;+ if (width <= 0 || height <= 0) {+ return '';+ }+ const inside = (x: number, y: number): boolean =>+ x >= 0 && y >= 0 && x < width && y < height && data[(y * width + x) * 4 + 3]! >= threshold;++ // Directed boundary edges bucketed by start vertex on the (width+1)×(height+1)+ // pixel-corner grid. Travelling each edge keeps the inside on the right, which+ // makes outer loops clockwise and holes counter-clockwise.+ const stride = width + 1;+ const outgoing = new Map<number, number[]>();+ const addEdge = (x: number, y: number, direction: number): void => {+ const key = y * stride + x;+ const bucket = outgoing.get(key);+ if (bucket) {+ bucket.push(direction);+ } else {+ outgoing.set(key, [direction]);+ }+ };+ for (let y = 0; y < height; y += 1) {+ for (let x = 0; x < width; x += 1) {+ if (!inside(x, y)) {+ continue;+ }+ if (!inside(x, y - 1)) {+ addEdge(x, y, 0);+ }+ if (!inside(x + 1, y)) {+ addEdge(x + 1, y, 1);+ }+ if (!inside(x, y + 1)) {+ addEdge(x + 1, y + 1, 2);+ }+ if (!inside(x - 1, y)) {+ addEdge(x, y + 1, 3);+ }+ }+ }+ if (outgoing.size === 0) {+ return '';+ }++ // At a pinch vertex (two regions touching diagonally) two edges leave the+ // same corner; preferring the tightest right turn keeps each loop around its+ // own region instead of crossing over to the neighbour.+ const takeEdge = (vertex: number, incoming: number): number | null => {+ const bucket = outgoing.get(vertex);+ if (!bucket || bucket.length === 0) {+ return null;+ }+ for (const direction of [(incoming + 1) % 4, incoming, (incoming + 3) % 4]) {+ const index = bucket.indexOf(direction);+ if (index !== -1) {+ bucket.splice(index, 1);+ if (bucket.length === 0) {+ outgoing.delete(vertex);+ }+ return direction;+ }+ }+ return null;+ };++ const segments: string[] = [];+ for (const [startVertex, bucket] of outgoing) {+ while (bucket.length > 0) {+ let direction = bucket[0]!;+ bucket.splice(0, 1);+ if (bucket.length === 0) {+ outgoing.delete(startVertex);+ }+ let vertex = startVertex;+ const startX = vertex % stride;+ const startY = (vertex - startX) / stride;+ const points: number[] = [startX, startY];+ let lastDirection = direction;+ for (;;) {+ vertex += DIRECTION_Y[direction]! * stride + DIRECTION_X[direction]!;+ const x = vertex % stride;+ const y = (vertex - x) / stride;+ if (direction === lastDirection && points.length >= 4) {+ points[points.length - 2] = x;+ points[points.length - 1] = y;+ } else {+ points.push(x, y);+ }+ lastDirection = direction;+ if (vertex === startVertex) {+ break;+ }+ const next = takeEdge(vertex, direction);+ if (next === null) {+ // Unreachable for well-formed edge sets; bail rather than loop forever.+ break;+ }+ direction = next;+ }+ // The walk re-appends the start vertex before closing; `Z` already closes.+ if (points.length >= 4 && points[points.length - 2] === startX && points[points.length - 1] === startY) {+ points.length -= 2;+ }+ let d = `M ${origin.x + points[0]!} ${origin.y + points[1]!}`;+ for (let index = 2; index < points.length; index += 2) {+ d += ` L ${origin.x + points[index]!} ${origin.y + points[index + 1]!}`;+ }+ segments.push(`${d} Z`);+ }+ }+ return segments.join(' ');+};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 9393d41e02..afd648fdb6 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@@ -170,7 +170,9 @@ describe('selectionState: replaceMask', () => {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]);+ // The ants trace the mask's true edge — here only the solid (0,1) pixel —+ // rather than the replacement's bounding rect.+ expect(selection.antsPaths()).toEqual([{ d: 'M 7 -2 L 8 -2 L 8 -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;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.tsindex 679180198e..9862a9298e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts@@ -21,7 +21,10 @@* approximation for `intersect` and for heavily overlapping compositions, where* the true selection outline is the boolean result rather than the union of the* source outlines — the ants may show interior source edges that the mask does- * not. Mask-edge tracing is deferred; the mask itself is always exact.+ * not. The exception is {@link SelectionState.replaceMask} (pixel-mask+ * replacement, e.g. a Select Object result), whose ants ARE traced from the+ * mask's true edge via {@link traceMaskOutlinePath}. The mask itself is always+ * exact.** ## Emptiness*@@ -38,6 +41,7 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rendimport type { PlacedSurface, Rect, SelectionOp, Vec2 } from '@workbench/canvas-engine/types';import { intersect, isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';+import { traceMaskOutlinePath } from '@workbench/canvas-engine/selection/maskOutline';/** A committed selection contribution: the closed path and the op it applied. */export interface SelectionCommit {@@ -94,11 +98,12 @@ export interface SelectionStateDeps {const MASK_FILL = '#ffffff';+/** SVG path data for a closed rectangle in document space. */+const rectToPathData = (r: Rect): string =>+ `M ${r.x} ${r.y} L ${r.x + r.width} ${r.y} L ${r.x + r.width} ${r.y + r.height} L ${r.x} ${r.y + r.height} Z`;+/** Builds a closed rectangle `Path2D` (document space) via the injected factory. */-const rectPath = (createPath2D: CreatePath2D, r: Rect): Path2D =>- createPath2D(- `M ${r.x} ${r.y} L ${r.x + r.width} ${r.y} L ${r.x + r.width} ${r.y + r.height} L ${r.x} ${r.y + r.height} Z`- );+const rectPath = (createPath2D: CreatePath2D, r: Rect): Path2D => createPath2D(rectToPathData(r));/** The canvas composite op that realizes each boolean selection op on the mask. */const compositeForOp = (op: SelectionOp): GlobalCompositeOperation => {@@ -249,7 +254,13 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =// 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);+ // Trace the mask's true edge for the ants; a mask whose alpha never reaches+ // the solid threshold still selected something (hasAlpha above), so fall+ // back to tracing any non-zero coverage rather than showing no outline.+ const alphaSource = { data: copiedData, height: source.height, width: source.width };+ const outline =+ traceMaskOutlinePath(alphaSource, rect) || traceMaskOutlinePath(alphaSource, rect, 1) || rectToPathData(rect);+ const nextPath = createPath2D(outline);mask = nextMask;maskRect = rect;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.tsindex 0733cdc144..1b8ad16063 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts@@ -18,6 +18,8 @@ const visualSnapshot = (overrides: Partial<SamSessionSnapshot> = {}): SamSessioninput: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },invert: false,isolatedPreview: true,+ layerName: 'Layer 1',+ layerType: 'raster',model: 'segment-anything-2-large',pointLabel: 'include',sourceRect,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.tsindex 3067464d18..eb7c545fde 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts@@ -47,6 +47,8 @@ const snapshot = (overrides: Partial<SamSessionSnapshot> = {}): SamSessionSnapshinput: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },invert: false,isolatedPreview: true,+ layerName: 'Layer 1',+ layerType: 'raster',model: 'segment-anything-2-large',pointLabel: 'include',sourceRect: { height: 20, width: 20, x: 0, y: 0 },@@ -125,7 +127,7 @@ describe('getSamActionEligibility', () => {});describe('getSamPanelViewModel', () => {- it('derives visual counts, bbox state, and a localized generation-area source summary', () => {+ it('derives visual counts, bbox state, and a localized layer source label', () => {expect(getSamPanelViewModel(snapshot({@@ -138,17 +140,16 @@ describe('getSamPanelViewModel', () => {],type: 'visual',},+ layerName: 'Subject',sourceRect: { height: 768, width: 1024, x: 64, y: 32 },}),- (width, height) => `Área de generación ${width} por ${height}`,- (width, height) => `Generation area ${width} by ${height}`+ (layerName, width, height) => `${layerName} at ${width} by ${height}`)).toEqual({bboxActive: true,excludeCount: 1,includeCount: 2,- sourceLabel: 'Generation area 1024 by 768',- sourceSummary: 'Área de generación 1024 por 768',+ sourceLabel: 'Subject at 1024 by 768',});});@@ -156,15 +157,13 @@ describe('getSamPanelViewModel', () => {expect(getSamPanelViewModel(snapshot({ input: { prompt: 'cat', type: 'prompt' } }),- (w, h) => `${w} × ${h}`,- (w, h) => `Generation area ${w} × ${h}`+ (layerName, w, h) => `${layerName} ${w} × ${h}`)).toEqual({bboxActive: false,excludeCount: 0,includeCount: 0,- sourceLabel: 'Generation area 20 × 20',- sourceSummary: '20 × 20',+ sourceLabel: 'Layer 1 20 × 20',});});});@@ -198,7 +197,7 @@ describe('SamStatusSlot', () => {it.each(['ready','scheduled',- 'preparing-composite',+ 'preparing-source','uploading','processing-sam','rendering-preview',@@ -348,8 +347,9 @@ describe('single-row SAM inputs', () => {expect(en.widgets.layers.selectObject.settings).toBe('Select Object settings');expect(en.widgets.layers.selectObject.bbox).toBe('BBox');expect(en.widgets.layers.selectObject.technicalDetails).toBe('Technical details');- expect(en.widgets.layers.selectObject.sourceDimensions).toBe('{{width}} × {{height}}');- expect(en.widgets.layers.selectObject.sourceDimensionsLabel).toContain('{{width}}');+ expect(en.widgets.layers.selectObject.sourceLayerLabel).toContain('{{name}}');+ expect(en.widgets.layers.selectObject.sourceLayerLabel).toContain('{{width}}');+ expect(en.widgets.layers.selectObject.saveAs_selection).toBe('Selection');expect(en.widgets.layers.selectObject.includeCount).toBe('Include {{count}}');expect(en.widgets.layers.selectObject.excludeCount).toBe('Exclude {{count}}');expect(en.widgets.layers.selectObject).not.toHaveProperty('autoProcessCompact');@@ -394,11 +394,7 @@ describe('single-row SAM inputs', () => {onExclude: () => undefined,onInclude: () => undefined,pointLabel: session.pointLabel,- viewModel: getSamPanelViewModel(- session,- (width, height) => `${width} × ${height}`,- (width, height) => `Generation area ${width} × ${height}`- ),+ viewModel: getSamPanelViewModel(session, (layerName, width, height) => `${layerName} ${width} × ${height}`),})))@@ -431,11 +427,13 @@ describe('getSamActionHandlers', () => {actions.reset();actions.apply();actions.save('control');+ actions.save('selection');actions.cancel();expect(engine.processSelectObjectSession).toHaveBeenCalledOnce();expect(engine.resetSelectObjectSession).toHaveBeenCalledOnce();expect(engine.applySelectObjectSession).toHaveBeenCalledOnce();+ expect(engine.applySelectObjectSession).toHaveBeenCalledWith(expect.any(Function));expect(engine.processSelectObjectSession.mock.invocationCallOrder[0]).toBeLessThan(engine.resetSelectObjectSession.mock.invocationCallOrder[0] as number);@@ -443,6 +441,7 @@ describe('getSamActionHandlers', () => {engine.applySelectObjectSession.mock.invocationCallOrder[0] as number);expect(engine.saveSelectObjectSession).toHaveBeenCalledWith('control', expect.any(Function));+ expect(engine.saveSelectObjectSession).toHaveBeenCalledWith('selection', expect.any(Function));expect(engine.cancelSelectObjectSession).toHaveBeenCalledOnce();});});@@ -480,7 +479,7 @@ describe('SamOptionsBar', () => {expect(markup).not.toContain('data-slot="body"');expect(markup).not.toContain('data-slot="footer"');expect(markup).not.toContain('data-operation=');- expect(markup).toContain('Generation area: 1024 × 768');+ expect(markup).toContain('Layer 1 · Raster layer · 1024 × 768');expect(markup).toContain('aria-label="Select Object settings"');expect(markup).toContain('aria-label="Save As"');expect(markup.indexOf('>Visual<')).toBeLessThan(markup.indexOf('Include 1'));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsxindex fd2a30196e..77193c3575 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx@@ -44,7 +44,6 @@ export interface SamPanelViewModel {excludeCount: number;includeCount: number;sourceLabel: string;- sourceSummary: string;}const SAM_PROMPT_GUIDANCE_ID = 'sam-prompt-guidance';@@ -62,7 +61,7 @@ const SAM_ERROR_CLAMP_STYLE: CSSProperties = {const SAM_STATUS_TRANSLATION_KEYS: Record<SamSessionSnapshot['status'], string> = {committing: 'widgets.layers.selectObject.statusCommitting',error: 'widgets.layers.selectObject.statusError',- 'preparing-composite': 'widgets.layers.selectObject.statusPreparingComposite',+ 'preparing-source': 'widgets.layers.selectObject.statusPreparingSource','processing-sam': 'widgets.layers.selectObject.statusProcessingSam',ready: 'widgets.layers.selectObject.statusReady','rendering-preview': 'widgets.layers.selectObject.statusRenderingPreview',@@ -84,10 +83,16 @@ const SAM_ERROR_TRANSLATION_KEYS: Record<SamSessionErrorCode, string> = {upload: 'widgets.layers.selectObject.errorUpload',};-const SAVE_TARGETS: readonly SelectObjectSaveTarget[] = ['raster', 'control', 'inpaint_mask', 'regional_guidance'];+const SAVE_TARGETS: readonly SelectObjectSaveTarget[] = [+ 'selection',+ 'raster',+ 'control',+ 'inpaint_mask',+ 'regional_guidance',+];const isSamProcessingStatus = (status: SamSessionSnapshot['status']): boolean =>- status === 'preparing-composite' ||+ status === 'preparing-source' ||status === 'uploading' ||status === 'processing-sam' ||status === 'rendering-preview';@@ -99,14 +104,12 @@ export const getSamErrorTranslationKey = (code: SamSessionErrorCode): string =>export const getSamPanelViewModel = (session: SamSessionSnapshot,- formatSourceSummary: (width: number, height: number) => string,- formatSourceLabel: (width: number, height: number) => string+ formatSourceLabel: (layerName: string, width: number, height: number) => string): SamPanelViewModel => ({bboxActive: session.input.type === 'visual' && session.input.bbox !== null,excludeCount: session.input.type === 'visual' ? session.input.excludePoints.length : 0,includeCount: session.input.type === 'visual' ? session.input.includePoints.length : 0,- sourceLabel: formatSourceLabel(session.sourceRect.width, session.sourceRect.height),- sourceSummary: formatSourceSummary(session.sourceRect.width, session.sourceRect.height),+ sourceLabel: formatSourceLabel(session.layerName, session.sourceRect.width, session.sourceRect.height),});/**@@ -166,7 +169,7 @@ export const SamStatusSlot = ({};export const getSamActionHandlers = (engine: ToolOptionsComponentProps['engine']) => ({- apply: () => void engine.applySelectObjectSession(),+ apply: () => void engine.applySelectObjectSession(makeImageDurable),cancel: () => engine.cancelSelectObjectSession(),process: () => void engine.processSelectObjectSession(),reset: () => engine.resetSelectObjectSession(),@@ -455,10 +458,13 @@ export const SamOptionsBar = ({}) => {const { t } = useTranslation();const eligibility = getSamActionEligibility(session, isExternalInteractionLocked);- const viewModel = getSamPanelViewModel(- session,- (width, height) => t('widgets.layers.selectObject.sourceDimensions', { height, width }),- (width, height) => t('widgets.layers.selectObject.sourceDimensionsLabel', { height, width })+ const viewModel = getSamPanelViewModel(session, (layerName, width, height) =>+ t('widgets.layers.selectObject.sourceLayerLabel', {+ height,+ name: layerName,+ type: t(`widgets.layers.selectObject.saveAs_${session.layerType}`),+ width,+ }));const actions = getSamActionHandlers(engine);const isProcessing = isSamProcessingStatus(session.status);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex efa6fca570..334fdb5a12 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -383,8 +383,7 @@ const LayerMenu = ({if (!engine) {throw makeStatusError('not-ready');}- void layerId;- const result = engine.startSelectObject();+ const result = engine.startSelectObject(layerId);if (result !== 'started') {throw makeStatusError(result);}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex 99520e410a..b64a5f73b2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -325,19 +325,19 @@ describe('getLayerContextActions', () => {it.each([['raster', true],['control', true],- ['inpaint_mask', true],- ['regional_guidance', true],- ] as const)('exposes document-level Select Object from every %s layer context', (type, expected) => {+ ['inpaint_mask', false],+ ['regional_guidance', false],+ ] as const)('exposes layer-scoped Select Object only for pixel %s layers', (type, expected) => {const action = getLayerContextActions(makeState(makeLayer(type))).find((item) => item.id === 'select-object');expect(Boolean(action)).toBe(expected);});- it('keeps Select Object visible without source content', () => {+ it('hides Select Object without source content', () => {expect(getLayerContextActions(makeState(rasterLayer, { hasSupportedContent: false })).some((action) => action.id === 'select-object')- ).toBe(true);+ ).toBe(false);});it.each([@@ -375,9 +375,9 @@ describe('getLayerContextActions', () => {expect(byId(getLayerContextActions(makeState(rasterLayer, overrides)), 'select-object').isDisabled).toBe(true);});- it('disables Select Object for an invalid generation bbox', () => {- const document = { ...makeDocument([rasterLayer]), bbox: { height: 100, width: 0, x: 0, y: 0 } };- expect(byId(getLayerContextActions(makeState(rasterLayer, { document })), 'select-object').isDisabled).toBe(true);+ it('disables Select Object for a locked layer', () => {+ const locked = { ...rasterLayer, isLocked: true };+ expect(byId(getLayerContextActions(makeState(locked)), 'select-object').isDisabled).toBe(true);});it('disables transform for a hidden layer', () => {@@ -486,6 +486,7 @@ describe('getLayerContextActions', () => {'fit-to-bbox','adjustments','filter',+ 'select-object','run-workflow','crop-to-bbox','convert-to-control',@@ -496,7 +497,6 @@ describe('getLayerContextActions', () => {expect(byId(actions, id).isDisabled, id).toBe(true);}expect(byId(actions, 'toggle-lock').isDisabled).toBe(false);- expect(byId(actions, 'select-object').isDisabled).toBe(false);const lockedControl = { ...nonEmptyControlLayer, isLocked: true };const controlActions = getLayerContextActions(makeState(lockedControl));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex 62299c5b55..9b42b7d527 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -428,16 +428,12 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinihandler: ({ effects, layer }) => effects.startSelectObject(layer.id),icon: ScanSearchIcon,id: 'select-object',- isEnabled: (context) =>- context.hasEngine &&- !context.interactionLocked &&- context.document.bbox.width > 0 &&- context.document.bbox.height > 0,- isVisible: alwaysVisible,+ isEnabled: hasMutablePixels,+ isVisible: hasFilterableLayerContent,labelKey: 'widgets.layers.actions.selectObject',order: 41,section: 'primary',- supportedLayerTypes: ALL_LAYER_TYPES,+ supportedLayerTypes: RASTER_AND_CONTROL,},{defaultLabel: 'Run workflow',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex 35b2e6b3fb..807dc531c8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -92,13 +92,7 @@ describe('getLayerContextMenuLayout', () => {expect(summarize(inpaint)[1]).toEqual({id: 'primary',- items: [- 'add-modifiers(inpaint-noise,inpaint-denoise-limit)',- 'rename',- 'fit-to-bbox',- 'select-object',- 'extract-masked-area',- ],+ items: ['add-modifiers(inpaint-noise,inpaint-denoise-limit)', 'rename', 'fit-to-bbox', 'extract-masked-area'],presentation: 'list',});expect(summarize(regional)[1]).toEqual({@@ -107,7 +101,6 @@ describe('getLayerContextMenuLayout', () => {'add-regional(regional-positive-prompt,regional-negative-prompt,regional-reference-image)','rename','fit-to-bbox',- 'select-object','regional-auto-negative',],presentation: 'list',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.tsindex 9bbf75ee47..3ab9ceb8aa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.test.ts@@ -1,24 +1,35 @@-import type { CanvasCompositeExportGuard } from '@workbench/canvas-engine/engine';+import type { LayerExportGuard } from '@workbench/canvas-engine/engine';+import type { CanvasRasterLayerContractV2 } from '@workbench/types';import { describe, expect, it, vi } from 'vitest';import { prepareSelectObjectSource, processSelectObjectSource } from './layerImageResult';const rect = { height: 12, width: 16, x: -5, y: 7 };+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 = {- bbox: rect,- candidates: [],- documentFingerprint: 'document:1',+ cacheVersion: 1,documentGeneration: 1,- participants: [],+ layer,+ layerId: layer.id,projectId: 'p1',-} satisfies CanvasCompositeExportGuard;+} satisfies LayerExportGuard;describe('Select Object image processing', () => {it('carries exact upload dimensions into the prepared source', async () => {await expect(prepareSelectObjectSource({- exportComposite: () => Promise.resolve({ blob: new Blob(), guard, rect, status: 'ok' }),+ exportSource: () => Promise.resolve({ blob: new Blob(), guard, rect, status: 'ok' }),uploadIntermediate: () => Promise.resolve({ height: 12, imageName: 'source.png', width: 16 }),})).resolves.toEqual({@@ -35,7 +46,7 @@ describe('Select Object image processing', () => {])('rejects upload dimensions that do not exactly match the bbox: $width x $height', async (dimensions) => {await expect(prepareSelectObjectSource({- exportComposite: () => Promise.resolve({ blob: new Blob(), guard, rect, status: 'ok' }),+ exportSource: () => Promise.resolve({ blob: new Blob(), guard, rect, status: 'ok' }),uploadIntermediate: () => Promise.resolve({ ...dimensions, imageName: 'source.png' }),})).resolves.toMatchObject({ status: 'dimension-mismatch' });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.tsindex e4acedc732..3c7d65d143 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.ts@@ -1,5 +1,5 @@import type { RunUtilityGraphOptions, UtilityGraphResult } from '@workbench/canvas-engine/backend/utilityQueue';-import type { CanvasCompositeExportGuard, ExportCanvasCompositeBlobResult } from '@workbench/canvas-engine/engine';+import type { ExportBakedLayerBlobResult, LayerExportGuard } from '@workbench/canvas-engine/engine';import type { SamSessionErrorCode } from '@workbench/canvas-engine/engineStores';import type { Rect } from '@workbench/canvas-engine/types';import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';@@ -12,7 +12,7 @@ export interface SelectObjectReadyResult {status: 'ready';image: CanvasImageRef;rect: Rect;- guard: CanvasCompositeExportGuard;+ guard: LayerExportGuard;}export type SelectObjectRunResult =@@ -23,7 +23,7 @@ export type SelectObjectRunResult =| { status: 'failed'; message: string; code: SamSessionErrorCode };export interface SelectObjectRunnerDeps {- exportComposite(): Promise<ExportCanvasCompositeBlobResult>;+ exportSource(): Promise<ExportBakedLayerBlobResult>;uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ height: number; imageName: string; width: number }>;runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>): Promise<UtilityGraphResult>;}@@ -32,7 +32,7 @@ const isAbortError = (error: unknown): boolean => error instanceof Error && erroconst errorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));export interface SelectObjectPreparedSource {- guard: CanvasCompositeExportGuard;+ guard: LayerExportGuard;imageName: string;height: number;rect: Rect;@@ -44,16 +44,16 @@ export type PrepareSelectObjectSourceResult =| Exclude<SelectObjectRunResult, SelectObjectReadyResult>;export const prepareSelectObjectSource = async (- deps: Pick<SelectObjectRunnerDeps, 'exportComposite' | 'uploadIntermediate'>,+ deps: Pick<SelectObjectRunnerDeps, 'exportSource' | 'uploadIntermediate'>,signal?: AbortSignal,onPhase?: (phase: 'uploading') => void): Promise<PrepareSelectObjectSourceResult> => {if (signal?.aborted) {return { status: 'aborted' };}- let exported: ExportCanvasCompositeBlobResult;+ let exported: ExportBakedLayerBlobResult;try {- exported = await deps.exportComposite();+ exported = await deps.exportSource();if (signal?.aborted) {return { status: 'aborted' };}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.tsindex c455990a20..745df192cb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.test.ts@@ -1,4 +1,4 @@-import type { CanvasCompositeExportGuard, SelectObjectLifecycleGuard } from '@workbench/canvas-engine/engine';+import type { LayerExportGuard } from '@workbench/canvas-engine/engine';import type { SamSessionError } from '@workbench/canvas-engine/engineStores';import type { CanvasRasterLayerContractV2 } from '@workbench/types';@@ -21,32 +21,18 @@ const layer: CanvasRasterLayerContractV2 = {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: -5, y: 7 },type: 'raster',};-const guard: CanvasCompositeExportGuard = {- bbox: { height: 12, width: 16, x: -5, y: 7 },- candidates: [{ cacheVersion: 3, layer, layerId: layer.id }],- documentFingerprint: 'document:3',+const guard: LayerExportGuard = {+ cacheVersion: 3,documentGeneration: 4,- participants: [{ cacheVersion: 3, layer, layerId: layer.id }],+ layer,+ layerId: layer.id,projectId: 'p1',};-const replacementGuard: CanvasCompositeExportGuard = {+const replacementGuard: LayerExportGuard = {...guard,- candidates: [{ cacheVersion: 4, layer, layerId: layer.id }],- documentFingerprint: 'document:4',- participants: [{ cacheVersion: 4, layer, layerId: layer.id }],-};-const cloneGuard = (source: CanvasCompositeExportGuard = guard): CanvasCompositeExportGuard => ({- ...source,- bbox: { ...source.bbox },- candidates: source.candidates.map((candidate) => ({ ...candidate })),- participants: source.participants.map((participant) => ({ ...participant })),-});-const lifecycleGuard: SelectObjectLifecycleGuard = {- bbox: guard.bbox,- documentGeneration: guard.documentGeneration,- kind: 'select-object-lifecycle',- projectId: guard.projectId,+ cacheVersion: 4,};+const cloneGuard = (source: LayerExportGuard = guard): LayerExportGuard => ({ ...source });const rect = { height: 12, width: 16, x: -5, y: 7 };const blob = new Blob(['source'], { type: 'image/png' });@@ -59,11 +45,11 @@ const deferred = <T>() => {};const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {}) => {- let currentGuard: CanvasCompositeExportGuard | null = guard;+ let currentGuard: LayerExportGuard | null = guard;let controllerSubscriber: (() => void) | null = null;const unsubscribe = vi.fn();const baseController = createCanvasOperationController({- isGuardCurrent: (candidate) => candidate === lifecycleGuard,+ isGuardCurrent: (candidate) => candidate === guard,});const controller = {...baseController,@@ -80,7 +66,7 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})captureGuard: vi.fn(() => currentGuard),controller,decodePreview: vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),- exportComposite: vi.fn(() => Promise.resolve({ blob, guard: currentGuard ?? guard, rect, status: 'ok' as const })),+ exportSource: vi.fn(() => Promise.resolve({ blob, guard: currentGuard ?? guard, rect, status: 'ok' as const })),isGuardCurrent: (candidate) => candidate === currentGuard,publishPreview: vi.fn((): undefined => undefined),cleanupPreview: vi.fn(),@@ -92,8 +78,8 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})};const operation = controller.start({cleanupPreview: deps.cleanupPreview,- guard: lifecycleGuard,- identity: { kind: 'select-object', projectId: 'p1' },+ guard,+ identity: { kind: 'select-object', layerId: layer.id, projectId: 'p1' },});if (!operation) {throw new Error('expected Select Object operation');@@ -107,7 +93,7 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})controllerSubscriber?.();},session,- setCurrentGuard(next: CanvasCompositeExportGuard | null) {+ setCurrentGuard(next: LayerExportGuard | null) {currentGuard = next;},unsubscribe,@@ -136,14 +122,14 @@ describe('createSelectObjectSession', () => {});});- it('reports phases from the composite, upload, SAM, render, and ready boundaries', async () => {+ it('reports phases from the source export, upload, SAM, render, and ready boundaries', async () => {const harness = createHarness();const phases: string[] = [];harness.session.subscribe(() => phases.push(harness.session.getSnapshot().status));await expect(harness.session.process()).resolves.toBe('published');- expect(phases).toEqual(['preparing-composite', 'uploading', 'processing-sam', 'rendering-preview', 'ready']);+ expect(phases).toEqual(['preparing-source', 'uploading', 'processing-sam', 'rendering-preview', 'ready']);});it('does not publish a stale request phase after a replacement retry starts', async () => {@@ -160,7 +146,7 @@ describe('createSelectObjectSession', () => {await vi.waitFor(() => expect(harness.session.getSnapshot().status).toBe('uploading'));harness.setCurrentGuard(replacementGuard);- vi.mocked(harness.deps.exportComposite).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });+ vi.mocked(harness.deps.exportSource).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });const newPending = harness.session.process();await expect(newPending).resolves.toBe('published');const readyIndex = phases.lastIndexOf('ready');@@ -290,7 +276,7 @@ describe('createSelectObjectSession', () => {});it('maps empty and not-ready sources to typed errors', async () => {- const empty = createHarness({ exportComposite: vi.fn(() => Promise.resolve({ status: 'empty' as const })) });+ const empty = createHarness({ exportSource: vi.fn(() => Promise.resolve({ status: 'empty' as const })) });await expect(empty.session.process()).resolves.toBe('error');expect(empty.session.getSnapshot().error).toEqual({ code: 'empty' });@@ -328,14 +314,19 @@ describe('createSelectObjectSession', () => {expect(harness.session.getSnapshot().error).toEqual({ code: 'unknown', detail: 'legacy failure detail' });});- it('does not close or clear a failed process on cache-only source invalidation', async () => {+ it('survives source invalidation of other layers but closes when its own layer is invalidated', async () => {const harness = createHarness({ runGraph: vi.fn(() => Promise.reject(new Error('graph failed'))) });await expect(harness.session.process()).resolves.toBe('error');- harness.controller.invalidateSource('p1', layer.id);+ harness.controller.invalidateSource('p1', 'other-layer');expect(harness.session.getSnapshot()).toMatchObject({ error: { code: 'queue' }, status: 'error' });expect(harness.controller.getSnapshot()).toMatchObject({ status: 'active' });++ harness.controller.invalidateSource('p1', layer.id);++ expect(harness.controller.getSnapshot()).toMatchObject({ status: 'idle' });+ expect(harness.session.getSnapshot()).toMatchObject({ preview: null, sourceGuard: null, status: 'ready' });});it('reuses an uploaded export only while its exact guard remains current', async () => {@@ -345,13 +336,13 @@ describe('createSelectObjectSession', () => {harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });await expect(harness.session.process()).resolves.toBe('published');- expect(harness.deps.exportComposite).toHaveBeenCalledTimes(1);+ expect(harness.deps.exportSource).toHaveBeenCalledTimes(1);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(1);expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);expect(harness.session.getSnapshot().sourceGuard).toBe(guard);harness.setCurrentGuard(replacementGuard);- vi.mocked(harness.deps.exportComposite).mockResolvedValue({+ vi.mocked(harness.deps.exportSource).mockResolvedValue({blob,guard: replacementGuard,rect,@@ -360,7 +351,7 @@ describe('createSelectObjectSession', () => {harness.session.update({ input: { prompt: 'bird', type: 'prompt' } });await expect(harness.session.process()).resolves.toBe('published');- expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportSource).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);expect(harness.session.getSnapshot().sourceGuard).toBe(replacementGuard);});@@ -369,9 +360,9 @@ describe('createSelectObjectSession', () => {let currentGuard = cloneGuard();const harness = createHarness({captureGuard: () => currentGuard,- exportComposite: vi.fn(() => Promise.resolve({ blob, guard: currentGuard, rect, status: 'ok' as const })),+ exportSource: vi.fn(() => Promise.resolve({ blob, guard: currentGuard, rect, status: 'ok' as const })),isGuardCurrent: (candidate) =>- candidate.documentFingerprint === currentGuard.documentFingerprint &&+ candidate.cacheVersion === currentGuard.cacheVersion &&candidate.documentGeneration === currentGuard.documentGeneration,});harness.session.update({@@ -390,35 +381,26 @@ describe('createSelectObjectSession', () => {expect(harness.session.getSnapshot().sourceGuard).toBe(currentGuard);}- expect(harness.deps.exportComposite).toHaveBeenCalledOnce();+ expect(harness.deps.exportSource).toHaveBeenCalledOnce();expect(harness.deps.uploadIntermediate).toHaveBeenCalledOnce();expect(harness.deps.runGraph).toHaveBeenCalledTimes(4);});it.each([- ['bbox', { ...cloneGuard(), bbox: { ...guard.bbox, x: guard.bbox.x + 1 }, documentFingerprint: 'bbox:4' }],- [- 'cache participant',- {- ...cloneGuard(replacementGuard),- documentFingerprint: 'cache:4',- },- ],+ ['layer reference', { ...cloneGuard(), layer: { ...layer } }],+ ['cache version', cloneGuard(replacementGuard)],['document generation',{...cloneGuard(),- documentFingerprint: 'document:5',documentGeneration: guard.documentGeneration + 1,},],] as const)('does not reuse the prepared source after a changed %s guard', async (_label, nextGuard) => {- let currentGuard: CanvasCompositeExportGuard = guard;+ let currentGuard: LayerExportGuard = guard;const harness = createHarness({captureGuard: () => currentGuard,- exportComposite: vi.fn(() =>- Promise.resolve({ blob, guard: currentGuard, rect: currentGuard.bbox, status: 'ok' as const })- ),+ exportSource: vi.fn(() => Promise.resolve({ blob, guard: currentGuard, rect, status: 'ok' as const })),isGuardCurrent: (candidate) => candidate === currentGuard,});await expect(harness.session.process()).resolves.toBe('published');@@ -427,7 +409,7 @@ describe('createSelectObjectSession', () => {harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });await expect(harness.session.process()).resolves.toBe('published');- expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportSource).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);});@@ -464,12 +446,12 @@ describe('createSelectObjectSession', () => {await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());harness.setCurrentGuard(replacementGuard);- vi.mocked(harness.deps.exportComposite).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });+ vi.mocked(harness.deps.exportSource).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });const newPending = harness.session.process();expect(newPending).not.toBe(oldPending);await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledTimes(2));- expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportSource).toHaveBeenCalledTimes(2);older.resolve({ height: 12, imageName: 'old.png', origin: 'old', width: 16 });await expect(oldPending).resolves.toBe('stale');expect(harness.session.process()).toBe(newPending);@@ -482,23 +464,23 @@ describe('createSelectObjectSession', () => {});it('starts an immediate same-input retry when invalidation aborts an export that ignores its signal', async () => {- const oldExport = deferred<Awaited<ReturnType<SelectObjectSessionDeps<string>['exportComposite']>>>();+ const oldExport = deferred<Awaited<ReturnType<SelectObjectSessionDeps<string>['exportSource']>>>();const harness = createHarness({- exportComposite: vi+ exportSource: vi.fn().mockImplementationOnce(() => oldExport.promise).mockImplementationOnce(() => Promise.resolve({ blob, guard: replacementGuard, rect, status: 'ok' as const })),});const oldPending = harness.session.process();- await vi.waitFor(() => expect(harness.deps.exportComposite).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(harness.deps.exportSource).toHaveBeenCalledOnce());harness.setCurrentGuard(replacementGuard);- vi.mocked(harness.deps.exportComposite).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });+ vi.mocked(harness.deps.exportSource).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });const newPending = harness.session.process();expect(newPending).not.toBe(oldPending);await expect(newPending).resolves.toBe('published');- expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportSource).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledOnce();expect(harness.deps.runGraph).toHaveBeenCalledOnce();oldExport.resolve({ blob, guard, rect, status: 'ok' });@@ -519,12 +501,12 @@ describe('createSelectObjectSession', () => {await vi.waitFor(() => expect(harness.deps.uploadIntermediate).toHaveBeenCalledOnce());harness.setCurrentGuard(replacementGuard);- vi.mocked(harness.deps.exportComposite).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });+ vi.mocked(harness.deps.exportSource).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });const newPending = harness.session.process();expect(newPending).not.toBe(oldPending);await expect(newPending).resolves.toBe('published');- expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportSource).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);expect(harness.deps.runGraph).toHaveBeenCalledOnce();oldUpload.resolve({ height: 12, imageName: 'old-input.png', width: 16 });@@ -584,10 +566,10 @@ describe('createSelectObjectSession', () => {await expect(harness.session.process()).resolves.toBe('published');harness.setCurrentGuard(replacementGuard);- vi.mocked(harness.deps.exportComposite).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });+ vi.mocked(harness.deps.exportSource).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });await expect(harness.session.process()).resolves.toBe('published');- expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportSource).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);expect(harness.session.getSnapshot().sourceGuard).toBe(replacementGuard);@@ -601,7 +583,7 @@ describe('createSelectObjectSession', () => {await vi.advanceTimersByTimeAsync(500);harness.session.update({ input: { prompt: 'second', type: 'prompt' } });await vi.advanceTimersByTimeAsync(999);- expect(harness.deps.exportComposite).not.toHaveBeenCalled();+ expect(harness.deps.exportSource).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(1);await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());@@ -721,7 +703,7 @@ describe('createSelectObjectSession', () => {await expect(harness.session.process()).resolves.toBe('invalid');await vi.runAllTimersAsync();- expect(harness.deps.exportComposite).not.toHaveBeenCalled();+ expect(harness.deps.exportSource).not.toHaveBeenCalled();expect(harness.deps.runGraph).not.toHaveBeenCalled();});@@ -758,9 +740,9 @@ describe('createSelectObjectSession', () => {boundary === 'decode'? vi.fn(() => wait.promise as Promise<string>): vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),- exportComposite:+ exportSource:boundary === 'export'- ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportComposite']>)+ ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportSource']>): vi.fn(() => Promise.resolve({ blob, guard, rect, status: 'ok' as const })),runGraph:boundary === 'queue'@@ -775,7 +757,7 @@ describe('createSelectObjectSession', () => {await vi.waitFor(() => {const fn =boundary === 'export'- ? harness.deps.exportComposite+ ? harness.deps.exportSource: boundary === 'upload'? harness.deps.uploadIntermediate: boundary === 'queue'@@ -814,9 +796,9 @@ describe('createSelectObjectSession', () => {boundary === 'decode'? vi.fn(() => wait.promise as Promise<string>): vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),- exportComposite:+ exportSource:boundary === 'export'- ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportComposite']>)+ ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportSource']>): vi.fn(() => Promise.resolve({ blob, guard, rect, status: 'ok' as const })),runGraph:boundary === 'queue'@@ -832,7 +814,7 @@ describe('createSelectObjectSession', () => {await vi.waitFor(() => {const fn =boundary === 'export'- ? harness.deps.exportComposite+ ? harness.deps.exportSource: boundary === 'upload'? harness.deps.uploadIntermediate: boundary === 'queue'diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.tsindex 19f683e485..add03de465 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectObjectSession.ts@@ -4,7 +4,7 @@ import type {CanvasOperationRunResult,CanvasOperationSession,} from '@workbench/canvas-engine/canvasOperationController';-import type { CanvasCompositeExportGuard, ExportCanvasCompositeBlobResult } from '@workbench/canvas-engine/engine';+import type { ExportBakedLayerBlobResult, LayerExportGuard } from '@workbench/canvas-engine/engine';import type { SamSessionError, SamSessionErrorCode } from '@workbench/canvas-engine/engineStores';import type { Rect } from '@workbench/canvas-engine/types';import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';@@ -18,7 +18,7 @@ import { prepareSelectObjectSource, processSelectObjectSource } from './layerImaexport type SelectObjectSessionStatus =| 'ready'| 'scheduled'- | 'preparing-composite'+ | 'preparing-source'| 'uploading'| 'processing-sam'| 'rendering-preview'@@ -26,7 +26,7 @@ export type SelectObjectSessionStatus =export interface SelectObjectSessionPreview<T> {data: T;- guard: CanvasCompositeExportGuard;+ guard: LayerExportGuard;image: SelectObjectReadyResult['image'];inputHash: string;previewId: number;@@ -45,19 +45,19 @@ export interface SelectObjectSessionState<T> {status: SelectObjectSessionStatus;error: SamSessionError | null;preview: SelectObjectSessionPreview<T> | null;- sourceGuard: CanvasCompositeExportGuard | null;+ sourceGuard: LayerExportGuard | null;}export interface SelectObjectSessionDeps<T> {- captureGuard(): CanvasCompositeExportGuard | null;+ captureGuard(): LayerExportGuard | null;controller: CanvasOperationController;- exportComposite(): Promise<ExportCanvasCompositeBlobResult>;+ exportSource(): Promise<ExportBakedLayerBlobResult>;uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ height: number; imageName: string; width: number }>;runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>): Promise<UtilityGraphResult>;decodePreview(result: SelectObjectReadyResult, signal: AbortSignal): Promise<T>;publishPreview(preview: SelectObjectSessionPreview<T>): undefined;cleanupPreview(): void;- isGuardCurrent(guard: CanvasCompositeExportGuard): boolean;+ isGuardCurrent(guard: LayerExportGuard): boolean;}export interface CreateSelectObjectSessionOptions<T> {@@ -212,7 +212,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOpublishState({ ...state, preview: null, sourceGuard: null, status: 'ready' });};- const isGuardCurrent = (guard: CanvasCompositeExportGuard): boolean => {+ const isGuardCurrent = (guard: LayerExportGuard): boolean => {try {return deps.isGuardCurrent(guard);} catch {@@ -220,32 +220,12 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO}};- const isSameGuard = (left: CanvasCompositeExportGuard, right: CanvasCompositeExportGuard): boolean => {- const sameParticipants = (- leftParticipants: CanvasCompositeExportGuard['candidates'],- rightParticipants: CanvasCompositeExportGuard['candidates']- ): boolean =>- leftParticipants.length === rightParticipants.length &&- leftParticipants.every((participant, index) => {- const other = rightParticipants[index];- return (- participant.layerId === other?.layerId &&- participant.layer === other.layer &&- participant.cacheVersion === other.cacheVersion- );- });- return (- left.projectId === right.projectId &&- left.documentGeneration === right.documentGeneration &&- left.documentFingerprint === right.documentFingerprint &&- left.bbox.x === right.bbox.x &&- left.bbox.y === right.bbox.y &&- left.bbox.width === right.bbox.width &&- left.bbox.height === right.bbox.height &&- sameParticipants(left.candidates, right.candidates) &&- sameParticipants(left.participants, right.participants)- );- };+ const isSameGuard = (left: LayerExportGuard, right: LayerExportGuard): boolean =>+ left.projectId === right.projectId &&+ left.layerId === right.layerId &&+ left.layer === right.layer &&+ left.cacheVersion === right.cacheVersion &&+ left.documentGeneration === right.documentGeneration;unsubscribeController = deps.controller.subscribe(() => {if (!disposed && deps.controller.getSnapshot().status === 'idle') {@@ -272,7 +252,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO};const ensureSource = async (- guard: CanvasCompositeExportGuard,+ guard: LayerExportGuard,signal: AbortSignal,token: number): Promise<SelectObjectPreparedSource> => {@@ -296,12 +276,12 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOtoken: number,hash: string,requestState: SelectObjectSessionState<T>,- guard: CanvasCompositeExportGuard+ guard: LayerExportGuard): Promise<SelectObjectSessionProcessResult> => {let requestError: SamSessionError | null = null;try {- pendingPhase = 'preparing-composite';- publishState({ ...state, sourceGuard: guard, status: 'preparing-composite' });+ pendingPhase = 'preparing-source';+ publishState({ ...state, sourceGuard: guard, status: 'preparing-source' });const result = await operation.run(async (signal) => {try {@@ -326,7 +306,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOthrow new SamSessionFailure(getProcessedSourceError(processed));}if (!isGuardCurrent(guard) || !isSameGuard(processed.guard, guard)) {- throw new DOMException('Select Object composite became stale.', 'AbortError');+ throw new DOMException('Select Object layer source became stale.', 'AbortError');}publishPhase(token, 'rendering-preview');let data: T;@@ -433,7 +413,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO}const hash = stableInputHash(state);if (hash === pendingHash && pendingProcess) {- publishState({ ...state, error: null, status: pendingPhase ?? 'preparing-composite' });+ publishState({ ...state, error: null, status: pendingPhase ?? 'preparing-source' });return pendingProcess;}if (