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): segment canvas bbox composite
joshistoast04dad82db640
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.tsindex e511cb7756..ec009ef991 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.test.ts@@ -37,9 +37,34 @@ const createDeferred = <T>() => {};const filterIdentity = { kind: 'filter' as const, layerId: layer.id, projectId: 'project-1' };-const selectObjectIdentity = { kind: 'select-object' 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 },+ documentFingerprint: 'document-1',+ documentGeneration: 1,+ participants: [{ cacheVersion: 1, layer, layerId: layer.id }],+ projectId: 'project-1',+};+const documentSelectObjectIdentity = { kind: 'select-object' as const, projectId: 'project-1' };describe('createCanvasOperationController', () => {+ it('uses document-composite identity and guards for Select Object without a layer sentinel', () => {+ const controller = createCanvasOperationController({ isGuardCurrent: () => true });++ const session = controller.start({+ cleanupPreview: vi.fn(),+ guard: compositeGuard,+ identity: documentSelectObjectIdentity,+ });++ 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();+ // @ts-expect-error Filter cannot accept a document-composite guard.+ expect(controller.start({ cleanupPreview: vi.fn(), guard: compositeGuard, identity: filterIdentity })).toBeNull();+ });it('replaces the active operation and prevents its stale session from affecting the replacement', async () => {const firstWork = createDeferred<string>();const firstCleanup = vi.fn();@@ -50,7 +75,11 @@ describe('createCanvasOperationController', () => {const pending = first.run(() => firstWork.promise, publishFirst);firstCleanup.mockClear();- const second = controller.start({ cleanupPreview: secondCleanup, guard, identity: selectObjectIdentity })!;+ const second = controller.start({+ cleanupPreview: secondCleanup,+ guard: compositeGuard,+ identity: selectObjectIdentity,+ })!;expect(firstCleanup).toHaveBeenCalledOnce();expect(controller.getSnapshot()).toMatchObject({ identity: selectObjectIdentity, status: 'active' });@@ -180,7 +209,7 @@ describe('createCanvasOperationController', () => {const result = await session.run(() => Promise.resolve('prepared'),() => {- controller.start({ cleanupPreview: replacementCleanup, guard, identity: selectObjectIdentity });+ controller.start({ cleanupPreview: replacementCleanup, guard: compositeGuard, identity: selectObjectIdentity });return undefined;});@@ -235,7 +264,7 @@ describe('createCanvasOperationController', () => {const controller = createCanvasOperationController({ isGuardCurrent: () => true });const replacementCleanup = vi.fn();const cleanupPreview = vi.fn(() => {- controller.start({ cleanupPreview: replacementCleanup, guard, identity: selectObjectIdentity });+ controller.start({ cleanupPreview: replacementCleanup, guard: compositeGuard, identity: selectObjectIdentity });});const session = controller.start({ cleanupPreview, guard, identity: filterIdentity })!;@@ -257,7 +286,7 @@ describe('createCanvasOperationController', () => {const controller = createCanvasOperationController({ isGuardCurrent: () => true });const replacementCleanup = vi.fn();const cleanupPreview = vi.fn(() => {- controller.start({ cleanupPreview: replacementCleanup, guard, identity: selectObjectIdentity });+ controller.start({ cleanupPreview: replacementCleanup, guard: compositeGuard, identity: selectObjectIdentity });});const session = controller.start({ cleanupPreview, guard, identity: filterIdentity })!;const work = vi.fn(() => Promise.resolve('prepared'));@@ -393,7 +422,11 @@ describe('createCanvasOperationController', () => {const work = createDeferred<string>();const publish = vi.fn((_result: string): undefined => undefined);const controller = createCanvasOperationController({ isGuardCurrent: () => true });- const session = controller.start({ cleanupPreview: vi.fn(), guard, identity: selectObjectIdentity })!;+ const session = controller.start({+ cleanupPreview: vi.fn(),+ guard: compositeGuard,+ identity: selectObjectIdentity,+ })!;const pending = session.run(() => work.promise, publish);controller.cancel();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.tsindex 695a2529e6..3e78a778c8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts@@ -1,9 +1,11 @@-import type { LayerExportGuard } from './engine';+import type { CanvasCompositeExportGuard, LayerExportGuard } from './engine';export type CanvasOperationIdentity =- | { kind: 'select-object'; projectId: string; layerId: string }+ | { kind: 'select-object'; projectId: string }| { kind: 'filter'; projectId: string; layerId: string };+export type CanvasOperationGuard = CanvasCompositeExportGuard | LayerExportGuard;+export type CanvasOperationState =| { status: 'idle' }| {@@ -32,11 +34,17 @@ export interface CanvasOperationSession {cancel(): void;}-export interface StartCanvasOperationOptions {- identity: CanvasOperationIdentity;- guard: LayerExportGuard;- cleanupPreview(): void;-}+export type StartCanvasOperationOptions =+ | {+ identity: Extract<CanvasOperationIdentity, { kind: 'select-object' }>;+ guard: CanvasCompositeExportGuard;+ cleanupPreview(): void;+ }+ | {+ identity: Extract<CanvasOperationIdentity, { kind: 'filter' }>;+ guard: LayerExportGuard;+ cleanupPreview(): void;+ };export interface CanvasOperationController {getSnapshot(): CanvasOperationState;@@ -46,19 +54,20 @@ 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;}export interface CanvasOperationControllerDeps {- isGuardCurrent(guard: LayerExportGuard): boolean;+ isGuardCurrent(guard: CanvasOperationGuard): boolean;}-interface ActiveOperation extends StartCanvasOperationOptions {+type ActiveOperation = StartCanvasOperationOptions & {requestController: AbortController | null;requestToken: number;-}+};const errorMessage = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));@@ -207,10 +216,15 @@ 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' && 'participants' in options.guard;if (disposed ||options.identity.projectId !== options.guard.projectId ||- options.identity.layerId !== options.guard.layerId+ (!layerIdentityMatches && !compositeIdentityMatches)) {return null;}@@ -246,7 +260,14 @@ export const createCanvasOperationController = (deps: CanvasOperationControllerD};const invalidateTarget = (projectId: string, layerId?: string): void => {- if (active?.identity.projectId === projectId && (layerId === undefined || active.identity.layerId === layerId)) {+ if (+ active?.identity.projectId === projectId &&+ (layerId === undefined ||+ (active.identity.kind === 'select-object'+ ? 'participants' in active.guard &&+ active.guard.participants.some((participant) => participant.layerId === layerId)+ : active.identity.layerId === layerId))+ ) {close(active);}};@@ -271,6 +292,11 @@ 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) => invalidateTarget(projectId, layerId),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 1321af6379..f84373a117 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -964,7 +964,7 @@ describe('createCanvasEngine', () => {engine.canvasOperations.start({cleanupPreview,guard: exported.guard,- identity: { kind: 'select-object', layerId: 'a', projectId: 'p1' },+ identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },});setDocument({ ...document, layers: nextLayers });@@ -993,7 +993,7 @@ describe('createCanvasEngine', () => {engine.canvasOperations.start({cleanupPreview,guard: exported.guard,- identity: { kind: 'select-object', layerId: 'a', projectId: 'p1' },+ identity: { kind: 'filter', layerId: 'a', projectId: 'p1' },});setDocument({ ...document, layers: document.layers }, 1);@@ -6847,7 +6847,7 @@ describe('commitRasterFilterResult', () => {harness.engine.canvasOperations.start({cleanupPreview,guard: harness.guard,- identity: { kind: 'select-object', layerId: harness.layer.id, projectId: 'p1' },+ identity: { kind: 'filter', layerId: harness.layer.id, projectId: 'p1' },});harness.decoded.resolve(new Blob());@@ -6858,7 +6858,7 @@ describe('commitRasterFilterResult', () => {expect(harness.engine.stores.canUndo.get()).toBe(false);expect(cleanupPreview).not.toHaveBeenCalled();expect(harness.engine.canvasOperations.getSnapshot()).toMatchObject({- identity: { kind: 'select-object' },+ identity: { kind: 'filter' },status: 'active',});harness.engine.dispose();@@ -9219,7 +9219,7 @@ describe('guarded filter previews', () => {engine.setInteractionLocked(true);expect(engine.startFilterOperation(layer.id)).toBe('locked');- expect(engine.startSelectObject(layer.id)).toBe('locked');+ expect(engine.startSelectObject()).toBe('locked');expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });expect(engine.stores.filterSession.get()).toBeNull();expect(engine.stores.samSession.get()).toBeNull();@@ -9236,12 +9236,12 @@ describe('guarded filter previews', () => {store,});expect((await engine.exportLayerPixels(layer.id)).status).toBe('ok');- expect(engine.startSelectObject(layer.id)).toBe('started');+ expect(engine.startSelectObject()).toBe('started');engine.setInteractionLocked(true);expect(engine.canvasOperations.getSnapshot()).toMatchObject({- identity: { kind: 'select-object', layerId: layer.id },+ identity: { kind: 'select-object' },status: 'active',});expect(engine.stores.samSession.get()).not.toBeNull();@@ -9428,13 +9428,13 @@ describe('guarded filter previews', () => {store,});expect((await engine.exportLayerPixels('first')).status).toBe('ok');- expect(engine.startSelectObject('first')).toBe('started');+ expect((await engine.exportLayerPixels('second')).status).toBe('ok');+ expect(engine.startSelectObject()).toBe('started');const operation = engine.canvasOperations.getSnapshot();- expect((await engine.exportLayerPixels('second')).status).toBe('ok');expect(engine.startFilterOperation('second', 'normal_map')).toBe('not-ready');expect(engine.canvasOperations.getSnapshot()).toEqual(operation);- expect(engine.stores.samSession.get()?.layerId).toBe('first');+ expect(engine.stores.samSession.get()?.sourceRect).toEqual(document.bbox);engine.dispose();});@@ -9721,7 +9721,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(source.id)).toBe('started');+ expect(engine.startSelectObject()).toBe('started');resolvePromotion();await pending;@@ -9796,7 +9796,7 @@ describe('guarded filter previews', () => {expect((await engine.exportLayerPixels('L')).status).toBe('ok');expect(engine.startFilterOperation('L')).toBe('started');- expect(engine.startSelectObject('L')).toBe('started');+ expect(engine.startSelectObject()).toBe('started');expect(engine.stores.filterSession.get()).toBeNull();expect(engine.stores.samSession.get()).not.toBeNull();@@ -9855,11 +9855,17 @@ describe('guarded filter previews', () => {if (!guard) {throw new Error('expected a current operation guard');}- const operation = engine.canvasOperations.start({- cleanupPreview: vi.fn(),- guard,- identity: { kind, layerId: 'L', projectId },- });+ const operation =+ kind === 'filter'+ ? engine.canvasOperations.start({+ cleanupPreview: vi.fn(),+ guard,+ identity: { kind, layerId: 'L', projectId },+ })+ : null;+ if (kind === 'select-object') {+ expect(engine.startSelectObject()).toBe('started');+ }expect(engine.stores.documentEditingLocked.get()).toBe(true);engine.undo();@@ -9884,7 +9890,11 @@ describe('guarded filter previews', () => {expect(engine.getDocument()!.layers[0]).toMatchObject({ name: 'Renamed', transform: { x: 0 } });expect(engine.canvasOperations.getSnapshot()).toMatchObject({ identity: { kind }, status: 'active' });- operation?.cancel();+ if (kind === 'select-object') {+ engine.cancelSelectObjectSession();+ } else {+ operation?.cancel();+ }expect(engine.stores.documentEditingLocked.get()).toBe(false);engine.undo();expect(engine.getDocument()!.layers[0]?.name).toBe('L');@@ -11962,14 +11972,14 @@ describe('engine selection: fill / erase', () => {engine.canvasOperations.start({cleanupPreview,guard: exported.guard,- identity: { kind: 'select-object', layerId: 'paint1', projectId: 'p1' },+ identity: { kind: 'filter', layerId: 'paint1', projectId: 'p1' },});engine.fillSelection();expect(cleanupPreview).not.toHaveBeenCalled();expect(engine.canvasOperations.getSnapshot()).toMatchObject({- identity: { kind: 'select-object' },+ identity: { kind: 'filter' },status: 'active',});engine.dispose();@@ -11987,7 +11997,7 @@ describe('engine selection: fill / erase', () => {engine.canvasOperations.start({cleanupPreview,guard: exported.guard,- identity: { kind: 'select-object', layerId: 'paint1', projectId: 'p1' },+ identity: { kind: 'filter', layerId: 'paint1', projectId: 'p1' },});await engine.clearCaches();@@ -12667,9 +12677,10 @@ describe('Select Object canvas engine integration', () => {const createCommittingSamHarness = async (imageResolver: (imageName: string, signal?: AbortSignal) => Promise<Blob> = () => Promise.resolve(new Blob()),- backend: StubRasterBackend = createTestStubRasterBackend()+ backend: StubRasterBackend = createTestStubRasterBackend(),+ bbox: CanvasDocumentContractV2['bbox'] = { height: 100, width: 100, x: 0, y: 0 }) => {- const document = samDocument([samLayer('source', -5)]);+ const document = { ...samDocument([samLayer('source', -5)]), bbox };const reactive = createReducerBackedStore(document);const engine = createCanvasEngine({backend,@@ -12683,9 +12694,14 @@ describe('Select Object canvas engine integration', () => {store: reactive.store,});await engine.exportLayerPixels('source');- engine.startSelectObject('source');+ engine.startSelectObject();engine.updateSelectObjectSession({- input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },+ input: {+ bbox: null,+ excludePoints: [],+ includePoints: [{ x: bbox.x + 5, y: bbox.y + 5 }],+ type: 'visual',+ },});await engine.processSelectObjectSession();return { ...reactive, document, engine };@@ -12707,16 +12723,15 @@ 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('source')).toBe('started');+ expect(h.engine.startSelectObject()).toBe('started');expect(h.engine.stores.activeTool.get()).toBe('sam');expect(h.engine.canvasOperations.getSnapshot()).toMatchObject({- identity: { kind: 'select-object', layerId: 'source', projectId: 'p1' },+ identity: { kind: 'select-object', projectId: 'p1' },status: 'active',});expect(h.engine.stores.samSession.get()).toMatchObject({input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },- layerId: 'source',- sourceRect: { height: 20, width: 20, x: 0, y: 0 },+ sourceRect: { height: 100, width: 100, x: 0, y: 0 },});h.raf.flush();h.screen.surface.callLog.length = 0;@@ -12732,13 +12747,13 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('selects an explicit context-action source before starting', async () => {+ it('starts from every visible participant without changing the selected layer', async () => {const h = await createSamHarness({ layers: [samLayer('first'), samLayer('second', 30)] });- expect(h.engine.startSelectObject('second')).toBe('started');+ expect(h.engine.startSelectObject()).toBe('started');- expect(h.store.dispatch).toHaveBeenCalledWith({ id: 'second', type: 'setCanvasSelectedLayer' });- expect(h.engine.stores.samSession.get()?.layerId).toBe('second');+ expect(h.store.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'setCanvasSelectedLayer' }));+ expect(h.engine.getDocument()?.selectedLayerId).toBe('first');h.engine.dispose();});@@ -12832,7 +12847,7 @@ describe('Select Object canvas engine integration', () => {const graph = createDeferred<{ imageName: string; origin: string }>();const runGraph = vi.fn(() => graph.promise);const h = await createSamHarness({ runGraph });- expect(h.engine.startSelectObject('source')).toBe('started');+ expect(h.engine.startSelectObject()).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();@@ -12865,7 +12880,7 @@ describe('Select Object canvas engine integration', () => {await expect(pending).resolves.not.toEqual({ status: 'selected' });expect(h.engine.getDocument()).toEqual(h.document);- expect(h.engine.stores.samSession.get()).toMatchObject({ layerId: 'source' });+ expect(h.engine.stores.samSession.get()).not.toBeNull();h.engine.dispose();});@@ -12901,7 +12916,7 @@ describe('Select Object canvas engine integration', () => {});it.each(['raster', 'control', 'inpaint_mask', 'regional_guidance'] as const)(- 'promotes then atomically saves the guarded preview as %s above its source',+ 'promotes then atomically saves the guarded bbox preview as %s at the top of its group',async (target) => {const calls: string[] = [];const h = await createCommittingSamHarness();@@ -12920,9 +12935,9 @@ describe('Select Object canvas engine integration', () => {throw new Error('expected a saved object layer');}if (created.type === 'raster' || created.type === 'control') {- expect(created.source).toMatchObject({ offset: { x: -5, y: 0 }, type: 'paint' });+ expect(created.source).toMatchObject({ offset: { x: 0, y: 0 }, type: 'paint' });} else {- expect(created.mask).toMatchObject({ offset: { x: -5, y: 0 } });+ expect(created.mask).toMatchObject({ offset: { x: 0, y: 0 } });}expect(created.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });expect(h.engine.stores.canUndo.get()).toBe(true);@@ -12935,6 +12950,24 @@ 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);++ const result = await h.engine.saveSelectObjectSession('raster', () => Promise.resolve());++ expect(result.status).toBe('committed');+ const created = h.engine.getDocument()?.layers[0];+ 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 },+ });+ }+ h.engine.dispose();+ });+it('publishes a committing phase and mutually excludes Apply and Save', async () => {const h = await createCommittingSamHarness();const durable = createDeferred<void>();@@ -12962,7 +12995,7 @@ describe('Select Object canvas engine integration', () => {await expect(pending).resolves.not.toMatchObject({ status: 'committed' });expect(h.engine.getDocument()).toEqual(h.document);- expect(h.engine.stores.samSession.get()).toMatchObject({ layerId: 'source' });+ expect(h.engine.stores.samSession.get()).not.toBeNull();h.engine.dispose();});@@ -12989,7 +13022,7 @@ describe('Select Object canvas engine integration', () => {await expect(pending).resolves.not.toMatchObject({ status: 'committed' });expect(h.engine.getDocument()).toEqual(h.document);- expect(h.engine.stores.samSession.get()).toMatchObject({ layerId: 'source' });+ expect(h.engine.stores.samSession.get()).not.toBeNull();h.engine.dispose();});@@ -13009,7 +13042,7 @@ describe('Select Object canvas engine integration', () => {});await engine.exportLayerPixels('first');await engine.exportLayerPixels('second');- engine.startSelectObject('first');+ engine.startSelectObject();engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13020,11 +13053,11 @@ describe('Select Object canvas engine integration', () => {});const oldSave = engine.saveSelectObjectSession('raster', () => durability);- expect(engine.startSelectObject('second')).toBe('started');+ expect(engine.startSelectObject()).toBe('started');rejectDurability(new Error('old failure'));await expect(oldSave).resolves.toMatchObject({ status: 'failed' });- expect(engine.stores.samSession.get()).toMatchObject({ error: null, layerId: 'second' });+ expect(engine.stores.samSession.get()).toMatchObject({ error: null });engine.dispose();});@@ -13045,7 +13078,7 @@ describe('Select Object canvas engine integration', () => {});await engine.exportLayerPixels('first');await engine.exportLayerPixels('second');- engine.startSelectObject('first');+ engine.startSelectObject();engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13054,13 +13087,13 @@ describe('Select Object canvas engine integration', () => {const unsubscribe = engine.stores.hasSelection.subscribe(() => {if (!replaced && engine.stores.hasSelection.get()) {replaced = true;- engine.startSelectObject('second');+ engine.startSelectObject();}});await expect(engine.applySelectObjectSession()).resolves.toEqual({ status: 'selected' });- expect(engine.stores.samSession.get()).toMatchObject({ error: null, layerId: 'second' });+ expect(engine.stores.samSession.get()).toMatchObject({ error: null });unsubscribe();engine.dispose();});@@ -13084,7 +13117,7 @@ describe('Select Object canvas engine integration', () => {});await engine.exportLayerPixels('first');await engine.exportLayerPixels('second');- engine.startSelectObject('first');+ engine.startSelectObject();engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13097,7 +13130,7 @@ describe('Select Object canvas engine integration', () => {sawCommitting = true;} else if (sawCommitting && !replaced) {replaced = true;- expect(engine.startSelectObject('second')).toBe('started');+ expect(engine.startSelectObject()).toBe('started');}});@@ -13108,7 +13141,7 @@ describe('Select Object canvas engine integration', () => {expect(result.status).toBe(kind === 'apply' ? 'selected' : 'committed');expect(replaced).toBe(true);- expect(engine.stores.samSession.get()).toMatchObject({ error: null, layerId: 'second' });+ expect(engine.stores.samSession.get()).toMatchObject({ error: null });expect(engine.stores.activeTool.get()).toBe('sam');unsubscribe();engine.dispose();@@ -13165,7 +13198,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('source');+ h.engine.startSelectObject();h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13222,45 +13255,108 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('processes a sole near-edge point after canonicalizing it to the last source pixel', async () => {+ it('processes a sole bbox near-edge point after canonicalizing it to the last bbox pixel', async () => {const runGraph = vi.fn(() => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }));const h = await createSamHarness({ runGraph });- h.engine.startSelectObject('source');+ h.engine.startSelectObject();- h.overlay.fire('pointerdown', pointerAt(19.8, 19.7));- h.overlay.fire('pointerup', pointerAt(19.8, 19.7, { buttons: 0 }));+ h.overlay.fire('pointerdown', pointerAt(99.8, 99.7));+ h.overlay.fire('pointerup', pointerAt(99.8, 99.7, { buttons: 0 }));- expect(h.engine.stores.samSession.get()?.input.includePoints).toEqual([{ x: 19, y: 19 }]);+ expect(h.engine.stores.samSession.get()?.input.includePoints).toEqual([{ x: 99, y: 99 }]);await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');expect(runGraph).toHaveBeenCalledOnce();h.engine.dispose();});- it('rejects missing, disabled, and unsupported selections without activating sam', async () => {+ it('uses the half-open generation bbox as the only point domain', async () => {+ const h = await createSamHarness();+ expect(h.engine.startSelectObject()).toBe('started');++ h.overlay.fire('pointerdown', pointerAt(100, 50));+ h.overlay.fire('pointerup', pointerAt(100, 50, { buttons: 0 }));+ h.overlay.fire('pointerdown', pointerAt(-0.01, 50));+ h.overlay.fire('pointerup', pointerAt(-0.01, 50, { buttons: 0 }));+ expect(h.engine.stores.samSession.get()?.input.includePoints).toEqual([]);++ h.overlay.fire('pointerdown', pointerAt(99.99, 99.99));+ h.overlay.fire('pointerup', pointerAt(99.99, 99.99, { buttons: 0 }));+ expect(h.engine.stores.samSession.get()?.input.includePoints).toEqual([{ x: 99, y: 99 }]);+ h.engine.dispose();+ });++ it('keeps viewport changes current but invalidates on bbox and cache changes', async () => {+ const h = await createSamHarness();+ expect(h.engine.startSelectObject()).toBe('started');++ h.engine.getViewport().panBy({ x: 20, y: -10 });+ h.engine.getViewport().zoomAtPoint(2, { x: 50, y: 50 });+ expect(h.engine.canvasOperations.getSnapshot()).toMatchObject({+ identity: { kind: 'select-object' },+ 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()!;++ h.setDocument({ ...document, layers: [...document.layers].reverse() });++ expect(h.engine.stores.samSession.get()).toBeNull();+ expect(h.engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });+ h.engine.dispose();+ });++ 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' },+ });++ await expect(h.engine.processSelectObjectSession()).resolves.toBe('error');+ expect(h.engine.stores.samSession.get()).toMatchObject({+ error: 'Select Object source is empty.',+ status: 'error',+ });+ h.engine.dispose();+ });++ it('opens independently of selected layer type, visibility, or document content', 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('mask')).toBe('unsupported');- expect(unsupported.engine.stores.activeTool.get()).toBe('view');+ expect(unsupported.engine.startSelectObject()).toBe('started');+ expect(unsupported.engine.stores.activeTool.get()).toBe('sam');unsupported.engine.dispose();const disabled = await createSamHarness({ layers: [{ ...samLayer('disabled'), isEnabled: false }] });- expect(disabled.engine.startSelectObject('disabled')).toBe('disabled');- expect(disabled.engine.stores.activeTool.get()).toBe('view');+ expect(disabled.engine.startSelectObject()).toBe('started');+ expect(disabled.engine.stores.activeTool.get()).toBe('sam');disabled.engine.dispose();const missing = await createSamHarness({ layers: [] });- expect(missing.engine.startSelectObject('missing')).toBe('missing');- expect(missing.engine.stores.samSession.get()).toBeNull();+ expect(missing.engine.startSelectObject()).toBe('started');+ expect(missing.engine.stores.samSession.get()).not.toBeNull();missing.engine.dispose();});it('cancels the owned session and decoded preview on a real tool switch', async () => {const h = await createSamHarness();- expect(h.engine.startSelectObject('source')).toBe('started');+ expect(h.engine.startSelectObject()).toBe('started');h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13280,7 +13376,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('source');+ h.engine.startSelectObject();h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13298,12 +13394,12 @@ describe('Select Object canvas engine integration', () => {h.engine.dispose();});- it('isolates only the source layer in the compositor while an isolated preview is published', async () => {+ it('isolates the same flattened bbox participants in the compositor while a preview is published', async () => {const backend = createRecordingRasterBackend();backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('sam-mask')));const h = await createSamHarness({ backend, layers: [samLayer('source'), samLayer('other', 30)] });h.engine.stores.checkerboard.set(false);- h.engine.startSelectObject('source');+ h.engine.startSelectObject();h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13311,14 +13407,78 @@ 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(1);+ expect(h.screen.surface.callLog.filter((entry) => entry.op === 'drawImage')).toHaveLength(2);+ expect(h.screen.surface.callLog).toEqual(+ expect.arrayContaining([+ { args: [0, 0, 100, 100], op: 'rect' },+ { args: [], op: 'clip' },+ ])+ );expect(h.engine.getDocument()!.layers.every((layer) => layer.isEnabled)).toBe(true);h.engine.dispose();});+ it('flattens transformed raster and control participants with display semantics while excluding masks', async () => {+ const backend = createRecordingRasterBackend();+ backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('decoded')));+ const raster: CanvasLayerContract = {+ ...samLayer('adjusted-raster'),+ adjustments: { brightness: 0.2, contrast: -0.1, saturation: 0.3 },+ blendMode: 'multiply',+ opacity: 0.4,+ source: {+ bitmap: { height: 10, imageName: 'sparse.png', width: 10 },+ offset: { x: -4, y: 6 },+ type: 'paint',+ },+ transform: { rotation: 0, scaleX: 2, scaleY: 1.5, x: 12, y: 8 },+ };+ const control: CanvasLayerContract = {+ adapter: { beginEndStepPct: [0, 0.75], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ blendMode: 'screen',+ id: 'control',+ isEnabled: true,+ isLocked: false,+ name: 'Control',+ opacity: 0.65,+ source: { image: { height: 12, imageName: 'control.png', width: 14 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 30, y: 20 },+ type: 'control',+ withTransparencyEffect: true,+ };+ const mask: CanvasInpaintMaskLayerContract = {+ ...samLayer('mask'),+ 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] });+ h.engine.stores.checkerboard.set(false);+ expect(h.engine.startSelectObject()).toBe('started');+ h.engine.updateSelectObjectSession({+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 35, y: 25 }], 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(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' },+ ])+ );+ expect(adjustedSurfaceCacheGets).toContain('adjusted-raster');+ h.engine.dispose();+ });+it('tears down the session when its captured source contract changes', async () => {const h = await createSamHarness();- h.engine.startSelectObject('source');+ h.engine.startSelectObject();h.setDocument({...h.engine.getDocument()!,@@ -13334,7 +13494,7 @@ describe('Select Object canvas engine integration', () => {const output = createDeferred<{ imageName: string; origin: string }>();const layers = [samLayer('first'), samLayer('second', 30)];const h = await createSamHarness({ layers, runGraph: () => output.promise });- h.engine.startSelectObject('first');+ h.engine.startSelectObject();h.engine.updateSelectObjectSession({input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },});@@ -13342,18 +13502,18 @@ describe('Select Object canvas engine integration', () => {await vi.waitFor(() => expect(h.engine.stores.samSession.get()?.status).toBe('processing'));h.setDocument({ ...h.engine.getDocument()!, selectedLayerId: 'second' });- expect(h.engine.startSelectObject('second')).toBe('started');- expect(h.engine.stores.samSession.get()?.layerId).toBe('second');+ expect(h.engine.startSelectObject()).toBe('started');+ expect(h.engine.stores.samSession.get()).not.toBeNull();output.resolve({ imageName: 'late.png', origin: 'late' });await expect(pending).resolves.toBe('stale');- expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: false, layerId: 'second' });+ expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: false });h.engine.dispose();});it('lets Escape cancel a gesture before a later Escape cancels the operation', async () => {const h = await createSamHarness();- h.engine.startSelectObject('source');+ h.engine.startSelectObject();h.overlay.fire('pointerdown', pointerAt(5, 5));h.overlay.fire('pointermove', pointerAt(15, 15));h.overlay.fire('pointercancel', pointerAt(15, 15));@@ -13368,7 +13528,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('source');+ h.engine.startSelectObject();h.overlay.fire('pointerenter', {});h.fireKey('keydown', 'Space', ' ');@@ -13382,7 +13542,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('source');+ h.engine.startSelectObject();h.overlay.fire('pointerenter', {});h.fireKey('keydown', 'Space', ' ');expect(h.engine.stores.activeTool.get()).toBe('view');@@ -13397,7 +13557,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('source');+ h.engine.startSelectObject();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 5760ca3ea6..9664900d12 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -219,7 +219,7 @@ export type CommitGeneratedImageResult =| { status: 'failed'; message: string };export interface CommitGeneratedImageOptions {- guard: LayerExportGuard;+ guard: LayerExportGuard | CanvasCompositeExportGuard;image: CanvasImageRef;origin: Vec2;target: GeneratedImageTarget;@@ -234,7 +234,7 @@ export type ReplaceSelectionFromImageResult =export type MaskImageResultTarget = 'inpaint_mask' | 'regional_guidance';export interface CommitMaskImageResultOptions {- guard: LayerExportGuard;+ guard: LayerExportGuard | CanvasCompositeExportGuard;image: CanvasImageRef;rect: Rect;target: MaskImageResultTarget;@@ -269,6 +269,22 @@ export interface LayerExportGuard {readonly documentGeneration: number;}+export interface CanvasCompositeExportGuard {+ readonly projectId: string;+ readonly bbox: Rect;+ readonly documentGeneration: number;+ readonly documentFingerprint: string;+ readonly participants: readonly {+ readonly layerId: string;+ readonly layer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }>;+ readonly cacheVersion: 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' };@@ -397,7 +413,7 @@ export interface SelectObjectSessionUpdate {interface SelectObjectCommitOwner {controller: AbortController;- guard: LayerExportGuard;+ guard: CanvasCompositeExportGuard;inputHash: string;preview: SelectObjectSessionPreview<RasterSurface>;previewId: number;@@ -422,8 +438,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;- /** Selects the requested raster/control layer, starts Select Object, and activates the SAM tool. */- startSelectObject(layerId: string): StartSelectObjectSessionResult;+ /** Starts document-level Select Object over the current generation bbox. */+ startSelectObject(): 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;@@ -905,11 +921,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {let selectObjectSession: SelectObjectSession<RasterSurface> | null = null;let selectObjectUnsubscribe: (() => void) | null = null;- let selectObjectGuard: LayerExportGuard | null = null;+ let selectObjectGuard: CanvasCompositeExportGuard | null = null;let selectObjectSourceRect: Rect | null = null;let selectObjectPointLabel: SamPointLabel = 'include';let selectObjectCommitOwner: SelectObjectCommitOwner | null = null;let selectObjectCommitToken = 0;+ let selectObjectOwnMutation = false;let samPreview: SelectObjectSessionPreview<RasterSurface> | null = null;let filterSession: FilterOperationSession | null = null;let filterUnsubscribe: (() => void) | null = null;@@ -1108,6 +1125,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {/** Bumps a layer's cache version after a direct paint (pixels stay fresh) and recomposites. */const notifyLayerPainted = (layerId: string): void => {const entry = layerCache.publishPixels(layerId);+ canvasOperations.invalidateLayer(projectId, layerId);if (entry) {stores.thumbnailVersion.set(layerId, entry.version);stores.thumbnailStatus.set(layerId, 'ready');@@ -1571,7 +1589,153 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return isLayerExportGuardCurrent(guard) ? guard : null;};- canvasOperations = createCanvasOperationController({ isGuardCurrent: isLayerExportGuardCurrent });+ const compositeParticipants = (document: CanvasDocumentContractV2) =>+ document.layers.flatMap((layer) => {+ const source = renderableSourceOf(layer);+ if (!layer.isEnabled || (layer.type !== 'raster' && layer.type !== 'control') || !source) {+ return [];+ }+ const entry = layerCache.get(layer.id);+ const rect = entry && !isEmpty(entry.rect) ? entry.rect : getSourceContentRect(layer, document);+ if (+ !rect ||+ 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+ ) {+ return [];+ }+ return [{ cacheVersion: layerCache.version(layer.id), layer, layerId: layer.id }];+ });++ const compositeFingerprint = (bbox: Rect, participants: CanvasCompositeExportGuard['participants']): string =>+ JSON.stringify([+ bbox.x,+ bbox.y,+ bbox.width,+ bbox.height,+ ...participants.map(({ cacheVersion, layer }) => [layer, cacheVersion]),+ ]);++ 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 participants = compositeParticipants(document);+ return {+ bbox,+ documentFingerprint: compositeFingerprint(bbox, 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 participants = compositeParticipants(document);+ return (+ participants.length === guard.participants.length &&+ participants.every(+ (participant, index) =>+ participant.layer === guard.participants[index]?.layer &&+ participant.cacheVersion === guard.participants[index]?.cacheVersion+ ) &&+ compositeFingerprint(guard.bbox, participants) === guard.documentFingerprint+ );+ };++ 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' };+ }+ 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) =>+ 'participants' in guard ? isCanvasCompositeExportGuardCurrent(guard) : isLayerExportGuardCurrent(guard),+ });const documentEditOwner = Symbol('canvas-operation-document-edit-owner');type DocumentEditPermit = { epoch: number; owner?: symbol };let documentEditEpoch = 0;@@ -2303,8 +2467,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (needsComposite) {ensureLayerCaches(doc);const stagedPlacement = stagedPreview?.placement;- const isolatedLayerId = samPreview?.isolated ? samPreview.guard.layerId : null;- compositeDocument(screen, doc, layerCache, view, {+ const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;+ const isolatedIds = isolatedGuard+ ? new Set(isolatedGuard.participants.map((participant) => participant.layerId))+ : null;+ const compositeDoc = isolatedIds+ ? { ...doc, layers: doc.layers.filter((layer) => isolatedIds.has(layer.id)) }+ : doc;+ compositeDocument(screen, compositeDoc, layerCache, view, {// Memoized adjusted surfaces for raster layers with brightness/contrast/// saturation/curves (not recomputed per frame — see adjustedSurfaceCache).adjustedSurface: getAdjustedSurface,@@ -2315,8 +2485,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// Non-destructive control-filter previews (drawn in place of the layer's// committed pixels). Only allocated when a preview is actually active.layerPreviews:- filterPreviews.size > 0 ? new Map(Array.from(filterPreviews, ([id, preview]) => [id, preview])) : null,- onlyLayerId: isolatedLayerId,+ !isolatedGuard && filterPreviews.size > 0+ ? new Map(Array.from(filterPreviews, ([id, preview]) => [id, preview]))+ : null,+ clipRect: isolatedGuard?.bbox ?? 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,@@ -2325,28 +2497,29 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {imageSmoothing: shouldSmoothAtZoom(viewport.getZoom()),// Candidate-specific placement wins for final images. Progress frames// and legacy image inputs continue to follow the CURRENT bbox origin.- stagedPreview: stagedPreview- ? {- opacity: stagedPlacement?.opacity ?? 1,- rect: stagedPlacement- ? {- height: stagedPlacement.height,- width: stagedPlacement.width,- x: stagedPlacement.x,- y: stagedPlacement.y,- }- : { height: stagedPreview.height, width: stagedPreview.width, x: doc.bbox.x, y: doc.bbox.y },- surface: stagedPreview.surface,- }- : null,+ stagedPreview:+ !isolatedGuard && stagedPreview+ ? {+ opacity: stagedPlacement?.opacity ?? 1,+ rect: stagedPlacement+ ? {+ height: stagedPlacement.height,+ width: stagedPlacement.width,+ x: stagedPlacement.x,+ y: stagedPlacement.y,+ }+ : { height: stagedPreview.height, width: stagedPreview.width, x: doc.bbox.x, y: doc.bbox.y },+ surface: stagedPreview.surface,+ }+ : null,// While a text-edit session is open on a layer, skip it in the composite —// the contenteditable portal shows its live text instead (avoids double-draw).skipLayerId: stores.textEditSession.get()?.layerId ?? null,- transformOverrides: transformOverrides.size > 0 ? transformOverrides : null,+ transformOverrides: !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null,});const visibleIds = doc.layers- .filter((layer) => layer.id === isolatedLayerId || isRenderableLayer(layer))+ .filter((layer) => isolatedIds?.has(layer.id) || isRenderableLayer(layer)).map((layer) => layer.id);const evicted = layerCache.evictHidden(visibleIds);// Prune version-keyed dependents for every evicted id (mirrors dropLayer):@@ -2407,8 +2580,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// overlay-only (no recomposite). The one exception: a legacy/progress staged// 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: () =>- scheduler.invalidate(stagedPreview && !stagedPreview.placement ? { all: true } : { overlay: true }),+ onBboxChanged: () => {+ canvasOperations.invalidateComposite(projectId);+ cancelSelectObjectSession();+ scheduler.invalidate(stagedPreview && !stagedPreview.placement ? { all: true } : { overlay: true });+ },onDocumentReplaced: () => {canvasOperations.invalidateDocument(projectId);cancelSelectObjectSession();@@ -2485,18 +2661,39 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {bitmapStore.reset();scheduler.invalidate({ all: true });},- onLayerOrderChanged: () => scheduler.invalidate({ all: true }),+ onLayerOrderChanged: () => {+ canvasOperations.invalidateComposite(projectId);+ cancelSelectObjectSession();+ scheduler.invalidate({ all: true });+ },onLayersChanged: (ids, sourceChangedIds) => {- for (const id of sourceChangedIds) {- canvasOperations.invalidateSource(projectId, id);- }- for (const id of ids) {- canvasOperations.invalidateLayer(projectId, id);+ if (!selectObjectOwnMutation) {+ for (const id of sourceChangedIds) {+ canvasOperations.invalidateSource(projectId, id);+ }+ for (const id of ids) {+ canvasOperations.invalidateLayer(projectId, id);+ }}- if (selectObjectGuard && !isLayerExportGuardCurrent(selectObjectGuard)) {+ if (!selectObjectOwnMutation && selectObjectGuard && !isCanvasCompositeExportGuardCurrent(selectObjectGuard)) {cancelSelectObjectSession();}const doc = mirror.getDocument();+ if (+ !selectObjectOwnMutation &&+ selectObjectGuard &&+ ids.some((id) => {+ const layer = doc?.layers.find((candidate) => candidate.id === id);+ return (+ !!layer &&+ (layer.type === 'raster' || layer.type === 'control') &&+ !selectObjectGuard?.participants.some((participant) => participant.layerId === id)+ );+ })+ ) {+ canvasOperations.invalidateComposite(projectId);+ cancelSelectObjectSession();+ }const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);const sourceChanged = new Set(sourceChangedIds);const previousImageNames = new Map(ids.map((id) => [id, mirroredLayerImageNames.get(id)]));@@ -2821,7 +3018,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {: { prompt: state.input.prompt, type: 'prompt' },invert: state.invert,isolatedPreview: state.isolatedPreview,- layerId: selectObjectGuard?.layerId ?? '',model: state.model,pointLabel: selectObjectPointLabel,sourceRect,@@ -2834,6 +3030,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {selectObjectCommitToken += 1;const owner = selectObjectCommitOwner;selectObjectCommitOwner = null;+ selectObjectOwnMutation = false;owner?.controller.abort();};@@ -2852,7 +3049,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {state.preview?.previewId === owner.previewId &&state.preview.inputHash === owner.inputHash &&owner.preview.inputHash === owner.inputHash &&- isLayerExportGuardCurrent(owner.guard) &&+ (selectObjectOwnMutation || isCanvasCompositeExportGuardCurrent(owner.guard)) &&!owner.controller.signal.aborted);};@@ -2873,6 +3070,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {session,token: ++selectObjectCommitToken,};+ selectObjectOwnMutation = false;selectObjectCommitOwner = owner;syncSelectObjectStore();return owner;@@ -2944,7 +3142,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return true;};- const startSelectObject = (layerId: string): StartSelectObjectSessionResult => {+ const startSelectObject = (): StartSelectObjectSessionResult => {if (interactionLocked) {return 'locked';}@@ -2952,44 +3150,19 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (!doc) {return 'missing';}- const layer = doc?.layers.find((candidate) => candidate.id === layerId);- if (!layer) {- return 'missing';- }- if (layer.type !== 'raster' && layer.type !== 'control') {- return 'unsupported';- }- if (!layer.isEnabled) {- return 'disabled';- }- const entry = layerCache.get(layer.id);- const guard = captureCurrentLayerExportGuard(layer.id);- if (!entry || !guard) {- return 'not-ready';- }- const matrix = fromTRS(- { x: layer.transform.x, y: layer.transform.y },- layer.transform.rotation,- layer.transform.scaleX,- layer.transform.scaleY- );- const sourceRect = roundOut(transformBounds(matrix, entry.rect));- if (isEmpty(sourceRect)) {+ const guard = captureCanvasCompositeExportGuard();+ if (!guard) {return 'not-ready';}- if (doc.selectedLayerId !== layer.id) {- store.dispatch({ id: layer.id, type: 'setCanvasSelectedLayer' });- }-clearOwnedFilterSession();clearOwnedSelectObjectSession();selectObjectGuard = guard;- selectObjectSourceRect = sourceRect;+ selectObjectSourceRect = { ...guard.bbox };const operation = canvasOperations.start({cleanupPreview: clearSamPreview,guard,- identity: { kind: 'select-object', layerId: layer.id, projectId },+ identity: { kind: 'select-object', projectId },});if (!operation) {selectObjectGuard = null;@@ -3000,12 +3173,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {selectObjectSession = createSelectObjectSession({deps: {captureGuard: () =>- selectObjectGuard && isLayerExportGuardCurrent(selectObjectGuard) ? selectObjectGuard : null,+ selectObjectGuard && isCanvasCompositeExportGuardCurrent(selectObjectGuard) ? selectObjectGuard : null,cleanupPreview: clearSamPreview,controller: canvasOperations,decodePreview: decodeSelectObjectPreview,- exportLayer: (layerId) => exportBakedLayerBlob(layerId, { includeDisabled: true }),- isGuardCurrent: isLayerExportGuardCurrent,+ exportComposite: exportCanvasCompositeBlob,+ isGuardCurrent: isCanvasCompositeExportGuardCurrent,publishPreview: (preview) => {const isolationChanged = samPreview?.isolated !== preview.isolated;samPreview = preview;@@ -3027,7 +3200,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return { imageName: uploaded.imageName };},},- layerId: layer.id,projectId,});const installedSession = selectObjectSession;@@ -3096,7 +3268,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {) {return null;}- return isLayerExportGuardCurrent(preview.guard) ? preview : null;+ return isCanvasCompositeExportGuardCurrent(preview.guard) ? preview : null;};const applySelectObjectSession = async (): Promise<ReplaceSelectionFromImageResult> => {@@ -3256,7 +3428,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {canvasOperations.start({cleanupPreview: clearSamPreview,guard,- identity: { kind: 'select-object', layerId: guard.layerId, projectId },+ identity: { kind: 'select-object', projectId },});syncSelectObjectStore();return 'updated';@@ -3987,7 +4159,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {};const replaceSelectionFromImage = async (- guard: LayerExportGuard,+ guard: LayerExportGuard | CanvasCompositeExportGuard,image: CanvasImageRef,rect: Rect,signal?: AbortSignal,@@ -4033,20 +4205,25 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {}const document = mirror.getDocument();- const liveLayer = document?.layers.find((candidate) => candidate.id === guard.layerId);- if (!document || !liveLayer) {+ if (!document) {return { status: 'missing' };}- if (liveLayer.isLocked) {- return { status: 'locked' };- }- if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {- return { status: 'unsupported' };+ 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' };+ }}if (!isDocumentEditPermitCurrent(permit) || pipeline.isGestureActive()) {return { status: 'busy' };}- if (!isLayerExportGuardCurrent(guard)) {+ if (!('participants' in guard ? isCanvasCompositeExportGuardCurrent(guard) : isLayerExportGuardCurrent(guard))) {return { status: 'stale' };}if (signal?.aborted) {@@ -4077,27 +4254,38 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return Promise.resolve({ status: 'aborted' });}const document = mirror.getDocument();- const liveLayer = document?.layers.find((candidate) => candidate.id === options.guard.layerId);- if (!document || !liveLayer) {+ if (!document) {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' });+ 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);}if (pipeline.isGestureActive()) {return Promise.resolve({ status: 'busy' });}- if (!isLayerExportGuardCurrent(options.guard)) {+ if (+ !('participants' in options.guard+ ? isCanvasCompositeExportGuardCurrent(options.guard)+ : isLayerExportGuardCurrent(options.guard))+ ) {return Promise.resolve({ status: 'stale' });}if (options.signal?.aborted) {return Promise.resolve({ status: 'aborted' });}- const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);if (sourceIndex < 0) {return Promise.resolve({ status: 'missing' });}@@ -4133,6 +4321,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {);endNudgeBurst();+ if (owner === documentEditOwner && selectObjectCommitOwner) {+ selectObjectOwnMutation = true;+ }apply();history.push({bytes: 256,@@ -4395,27 +4586,39 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const validateGuard = ():| {document: CanvasDocumentContractV2;- liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }>;+ liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }> | null;}| { result: CommitGeneratedImageResult } => {if (!isDocumentEditPermitCurrent(permit)) {return { result: { status: 'busy' } };}const document = mirror.getDocument();- const liveLayer = document?.layers.find((candidate) => candidate.id === options.guard.layerId);- if (!document || !liveLayer) {+ if (!document) {return { result: { status: 'missing' } };}- if (liveLayer.isLocked) {- return { result: { status: 'locked' } };- }- if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {- return { result: { status: 'unsupported' } };+ 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;}if (pipeline.isGestureActive()) {return { result: { status: 'busy' } };}- if (!isLayerExportGuardCurrent(options.guard)) {+ if (+ !('participants' in options.guard+ ? isCanvasCompositeExportGuardCurrent(options.guard)+ : isLayerExportGuardCurrent(options.guard))+ ) {return { result: { status: 'stale' } };}return { document, liveLayer };@@ -4463,27 +4666,31 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const rect = { height: image.height, width: image.width, ...origin };const source = { bitmap: image, offset: origin, type: 'paint' } as const;const identityTransform: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };+ const replacementLayer = liveLayer;const publishSnapshot = (contract: CanvasLayerContract,prepared: ReturnType<LayerCacheStore['prepareReplacement']>,publishOptions: { discardPersistence: boolean; persist: boolean }): void => {+ if (!replacementLayer) {+ throw new Error('A replacement target is required.');+ }dispatchPreparedMutation(- { layer: contract, layerId: liveLayer.id, type: 'replaceCanvasLayer' },- () => getReducerDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract,- () => mirror.getDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract+ { layer: contract, layerId: replacementLayer.id, type: 'replaceCanvasLayer' },+ () => getReducerDocument()?.layers.find((candidate) => candidate.id === replacementLayer.id) === contract,+ () => mirror.getDocument()?.layers.find((candidate) => candidate.id === replacementLayer.id) === contract);if (publishOptions.discardPersistence) {try {- bitmapStore.discardLayer(liveLayer.id);+ bitmapStore.discardLayer(replacementLayer.id);} catch {// Persistence generation cancellation is ancillary once the durable// contract has been accepted by the reducer.}}try {- clearFilterPreview(liveLayer.id);+ clearFilterPreview(replacementLayer.id);} catch {// A transient preview is ancillary to the committed document/cache.}@@ -4495,11 +4702,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {snapshot: { pixels: RasterSurface; rect: Rect },publishOptions: { discardPersistence: boolean; persist: boolean }): void => {- const prepared = prepareGeneratedPaintCache(liveLayer.id, snapshot.rect, snapshot.pixels);+ if (!replacementLayer) {+ throw new Error('A replacement target is required.');+ }+ const prepared = prepareGeneratedPaintCache(replacementLayer.id, snapshot.rect, snapshot.pixels);publishSnapshot(contract, prepared, publishOptions);};if (options.target === 'replace') {+ if (!liveLayer) {+ return { status: 'unsupported' };+ }const beforePixels = captureLayerCache(liveLayer, document);if (!beforePixels || beforePixels === 'not-ready') {return { status: 'stale' };@@ -4546,7 +4759,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return { layerId: liveLayer.id, status: 'committed' };}- const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);+ const sourceIndex = liveLayer ? document.layers.findIndex((candidate) => candidate.id === liveLayer.id) : 0;if (sourceIndex < 0) {return { status: 'missing' };}@@ -4556,7 +4769,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {options.target === 'copy-control'? {...createControlLayer(- nextControlLayerName(document.layers.map((layer) => layer.name)),+ liveLayer+ ? nextControlLayerName(document.layers.map((layer) => layer.name))+ : 'Segmented Object Control',layerId,getMainModelBase()),@@ -4568,7 +4783,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {id: layerId,isEnabled: true,isLocked: false,- name: `${liveLayer.name} workflow result`,+ name: liveLayer ? `${liveLayer.name} workflow result` : 'Segmented Object',opacity: 1,source,transform: identityTransform,@@ -4597,6 +4812,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {}endNudgeBurst();+ if (owner === documentEditOwner && selectObjectCommitOwner && 'participants' in options.guard) {+ selectObjectOwnMutation = true;+ }publishCopy(preparedCopy);history.push({bytes: rect.width * rect.height * 4 + 256,@@ -6262,6 +6480,8 @@ 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 we// invalidated the cache before flushing, that in-flight stroke would bediff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 5ef871a30c..26b6cc31f5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -240,7 +240,6 @@ export type SamSessionInput =/** Narrow engine-owned Select Object state for canvas tools and future UI subscribers. */export interface SamSessionSnapshot {- layerId: string;sourceRect: Rect;input: SamSessionInput;pointLabel: SamPointLabel;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 4c03d0743f..0cd1385439 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -80,6 +80,8 @@ const STAGED_PREVIEW_OUTLINE_DASH = 6;/** Optional inputs to {@link compositeDocument}. */export interface CompositeOptions {+ /** Clips document layers to this document-space rect without clipping the background or staged preview. */+ clipRect?: Rect | null;/** A staged generation candidate to draw at its placement (document space). */stagedPreview?: { surface: RasterSurface; rect: Rect; opacity?: number } | null;/**@@ -335,6 +337,14 @@ export const compositeDocument = (ctx.clearRect(0, 0, target.width, target.height);drawBackground(ctx, target, opts.checkerboardTile ?? null);+ if (opts.clipRect) {+ ctx.save();+ setTransformFromMat(ctx, view);+ ctx.beginPath();+ ctx.rect(opts.clipRect.x, opts.clipRect.y, opts.clipRect.width, opts.clipRect.height);+ ctx.clip();+ }+// Composite in STRICT GROUP ORDER (legacy `arrangeEntities` / `CanvasEntityRendererModule`):// raster (bottom) < control < regional guidance < inpaint mask (top). This// matches the layers panel, which renders these as fixed grouped sections, and@@ -367,6 +377,10 @@ export const compositeDocument = (drawGroup(rank);}+ if (opts.clipRect) {+ ctx.restore();+ }+// Staged generation preview over its bbox (document space), with a subtle// dashed outline so the pending result reads distinctly from committed pixels.const staged = opts.onlyLayerId ? null : opts.stagedPreview;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 ecb9d9ccdd..0733cdc144 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,7 +18,6 @@ const visualSnapshot = (overrides: Partial<SamSessionSnapshot> = {}): SamSessioninput: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },invert: false,isolatedPreview: true,- layerId: 'source',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 c874aed17d..7c4161c85c 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@@ -12,7 +12,6 @@ const snapshot = (overrides: Partial<SamSessionSnapshot> = {}): SamSessionSnapshinput: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },invert: false,isolatedPreview: true,- layerId: 'source',model: 'segment-anything-2-large',pointLabel: 'include',sourceRect: { height: 20, width: 20, x: 0, y: 0 },diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 334fdb5a12..efa6fca570 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -383,7 +383,8 @@ const LayerMenu = ({if (!engine) {throw makeStatusError('not-ready');}- const result = engine.startSelectObject(layerId);+ void layerId;+ const result = engine.startSelectObject();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 949d5cf6ca..99520e410a 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', false],- ['regional_guidance', false],- ] as const)('exposes Select Object only for exportable %s content', (type, expected) => {+ ['inpaint_mask', true],+ ['regional_guidance', true],+ ] as const)('exposes document-level Select Object from every %s layer context', (type, expected) => {const action = getLayerContextActions(makeState(makeLayer(type))).find((item) => item.id === 'select-object');expect(Boolean(action)).toBe(expected);});- it('hides Select Object without supported source content', () => {+ it('keeps Select Object visible without source content', () => {expect(getLayerContextActions(makeState(rasterLayer, { hasSupportedContent: false })).some((action) => action.id === 'select-object')- ).toBe(false);+ ).toBe(true);});it.each([@@ -370,12 +370,14 @@ describe('getLayerContextActions', () => {it.each([['missing engine', { hasEngine: false }],- ['disabled layer', { layer: { ...rasterLayer, isEnabled: false } }],- ['locked layer', { layer: { ...rasterLayer, isLocked: true } }],['locked interaction', { interactionLocked: true }],] as const)('disables Select Object for %s', (_label, overrides) => {- const layer = 'layer' in overrides ? overrides.layer : rasterLayer;- expect(byId(getLayerContextActions(makeState(layer, overrides)), 'select-object').isDisabled).toBe(true);+ 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 transform for a hidden layer', () => {@@ -484,7 +486,6 @@ describe('getLayerContextActions', () => {'fit-to-bbox','adjustments','filter',- 'select-object','run-workflow','crop-to-bbox','convert-to-control',@@ -495,6 +496,7 @@ 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 b05af07daa..62299c5b55 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -428,12 +428,16 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinihandler: ({ effects, layer }) => effects.startSelectObject(layer.id),icon: ScanSearchIcon,id: 'select-object',- isEnabled: hasTransformablePixels,- isVisible: (context) => context.hasSupportedContent,+ isEnabled: (context) =>+ context.hasEngine &&+ !context.interactionLocked &&+ context.document.bbox.width > 0 &&+ context.document.bbox.height > 0,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.selectObject',order: 41,section: 'primary',- supportedLayerTypes: RASTER_AND_CONTROL,+ supportedLayerTypes: ALL_LAYER_TYPES,},{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 807dc531c8..35b2e6b3fb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -92,7 +92,13 @@ describe('getLayerContextMenuLayout', () => {expect(summarize(inpaint)[1]).toEqual({id: 'primary',- items: ['add-modifiers(inpaint-noise,inpaint-denoise-limit)', 'rename', 'fit-to-bbox', 'extract-masked-area'],+ items: [+ 'add-modifiers(inpaint-noise,inpaint-denoise-limit)',+ 'rename',+ 'fit-to-bbox',+ 'select-object',+ 'extract-masked-area',+ ],presentation: 'list',});expect(summarize(regional)[1]).toEqual({@@ -101,6 +107,7 @@ 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.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerImageResult.tsindex d5008264a9..8b80a233ed 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 { ExportBakedLayerBlobResult, LayerExportGuard } from '@workbench/canvas-engine/engine';+import type { CanvasCompositeExportGuard, ExportCanvasCompositeBlobResult } from '@workbench/canvas-engine/engine';import type { Rect } from '@workbench/canvas-engine/types';import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';import type { CanvasImageRef } from '@workbench/types';@@ -10,7 +10,7 @@ export interface SelectObjectReadyResult {status: 'ready';image: CanvasImageRef;rect: Rect;- guard: LayerExportGuard;+ guard: CanvasCompositeExportGuard;}export type SelectObjectRunResult =@@ -19,7 +19,7 @@ export type SelectObjectRunResult =| { status: 'failed'; message: string };export interface SelectObjectRunnerDeps {- exportLayer(layerId: string): Promise<ExportBakedLayerBlobResult>;+ exportComposite(): Promise<ExportCanvasCompositeBlobResult>;uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>@@ -30,7 +30,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: LayerExportGuard;+ guard: CanvasCompositeExportGuard;imageName: string;rect: Rect;}@@ -40,15 +40,14 @@ export type PrepareSelectObjectSourceResult =| Exclude<SelectObjectRunResult, SelectObjectReadyResult>;export const prepareSelectObjectSource = async (- layerId: string,- deps: Pick<SelectObjectRunnerDeps, 'exportLayer' | 'uploadIntermediate'>,+ deps: Pick<SelectObjectRunnerDeps, 'exportComposite' | 'uploadIntermediate'>,signal?: AbortSignal): Promise<PrepareSelectObjectSourceResult> => {if (signal?.aborted) {return { status: 'aborted' };}try {- const exported = await deps.exportLayer(layerId);+ const exported = await deps.exportComposite();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 85b637d7b2..1ff5428e5a 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 { LayerExportGuard } from '@workbench/canvas-engine/engine';+import type { CanvasCompositeExportGuard } from '@workbench/canvas-engine/engine';import type { CanvasRasterLayerContractV2 } from '@workbench/types';import { createCanvasOperationController } from '@workbench/canvas-engine/canvasOperationController';@@ -19,14 +19,18 @@ const layer: CanvasRasterLayerContractV2 = {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: -5, y: 7 },type: 'raster',};-const guard: LayerExportGuard = {- cacheVersion: 3,+const guard: CanvasCompositeExportGuard = {+ bbox: { height: 12, width: 16, x: -5, y: 7 },+ documentFingerprint: 'document:3',documentGeneration: 4,- layer,- layerId: layer.id,+ participants: [{ cacheVersion: 3, layer, layerId: layer.id }],projectId: 'p1',};-const replacementGuard: LayerExportGuard = { ...guard, cacheVersion: 4 };+const replacementGuard: CanvasCompositeExportGuard = {+ ...guard,+ documentFingerprint: 'document:4',+ participants: [{ cacheVersion: 4, layer, layerId: layer.id }],+};const rect = { height: 12, width: 16, x: -5, y: 7 };const blob = new Blob(['source'], { type: 'image/png' });@@ -39,7 +43,7 @@ const deferred = <T>() => {};const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {}) => {- let currentGuard: LayerExportGuard | null = guard;+ let currentGuard: CanvasCompositeExportGuard | null = guard;let controllerSubscriber: (() => void) | null = null;const unsubscribe = vi.fn();const baseController = createCanvasOperationController({ isGuardCurrent: (candidate) => candidate === currentGuard });@@ -58,7 +62,7 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})captureGuard: vi.fn(() => currentGuard),controller,decodePreview: vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),- exportLayer: vi.fn(() => Promise.resolve({ blob, guard: currentGuard ?? guard, rect, status: 'ok' as const })),+ exportComposite: 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(),@@ -66,7 +70,7 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})uploadIntermediate: vi.fn(() => Promise.resolve({ imageName: 'input.png' })),...overrides,};- const session = createSelectObjectSession({ deps, layerId: layer.id, projectId: 'p1' });+ const session = createSelectObjectSession({ deps, projectId: 'p1' });session.update({ input: { prompt: 'cat', type: 'prompt' } });return {controller,@@ -75,7 +79,7 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})controllerSubscriber?.();},session,- setCurrentGuard(next: LayerExportGuard | null) {+ setCurrentGuard(next: CanvasCompositeExportGuard | null) {currentGuard = next;},unsubscribe,@@ -178,13 +182,13 @@ describe('createSelectObjectSession', () => {harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });await expect(harness.session.process()).resolves.toBe('published');- expect(harness.deps.exportLayer).toHaveBeenCalledTimes(1);+ expect(harness.deps.exportComposite).toHaveBeenCalledTimes(1);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(1);expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);expect(harness.session.getSnapshot().sourceGuard).toBe(guard);harness.setCurrentGuard(replacementGuard);- vi.mocked(harness.deps.exportLayer).mockResolvedValue({+ vi.mocked(harness.deps.exportComposite).mockResolvedValue({blob,guard: replacementGuard,rect,@@ -193,7 +197,7 @@ describe('createSelectObjectSession', () => {harness.session.update({ input: { prompt: 'bird', type: 'prompt' } });await expect(harness.session.process()).resolves.toBe('published');- expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);expect(harness.session.getSnapshot().sourceGuard).toBe(replacementGuard);});@@ -237,7 +241,7 @@ describe('createSelectObjectSession', () => {expect(newPending).not.toBe(oldPending);await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledTimes(2));- expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);older.resolve({ imageName: 'old.png', origin: 'old' });await expect(oldPending).resolves.toBe('stale');expect(harness.session.process()).toBe(newPending);@@ -250,22 +254,22 @@ 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>['exportLayer']>>>();+ const oldExport = deferred<Awaited<ReturnType<SelectObjectSessionDeps<string>['exportComposite']>>>();const harness = createHarness({- exportLayer: vi+ exportComposite: vi.fn().mockImplementationOnce(() => oldExport.promise).mockImplementationOnce(() => Promise.resolve({ blob, guard, rect, status: 'ok' as const })),});const oldPending = harness.session.process();- await vi.waitFor(() => expect(harness.deps.exportLayer).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(harness.deps.exportComposite).toHaveBeenCalledOnce());harness.controller.invalidateSource('p1', layer.id);const newPending = harness.session.process();expect(newPending).not.toBe(oldPending);await expect(newPending).resolves.toBe('published');- expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledOnce();expect(harness.deps.runGraph).toHaveBeenCalledOnce();oldExport.resolve({ blob, guard, rect, status: 'ok' });@@ -290,7 +294,7 @@ describe('createSelectObjectSession', () => {expect(newPending).not.toBe(oldPending);await expect(newPending).resolves.toBe('published');- expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);expect(harness.deps.runGraph).toHaveBeenCalledOnce();oldUpload.resolve({ imageName: 'old-input.png' });@@ -350,10 +354,10 @@ describe('createSelectObjectSession', () => {await expect(harness.session.process()).resolves.toBe('published');harness.setCurrentGuard(replacementGuard);- vi.mocked(harness.deps.exportLayer).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });+ vi.mocked(harness.deps.exportComposite).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });await expect(harness.session.process()).resolves.toBe('published');- expect(harness.deps.exportLayer).toHaveBeenCalledTimes(2);+ expect(harness.deps.exportComposite).toHaveBeenCalledTimes(2);expect(harness.deps.uploadIntermediate).toHaveBeenCalledTimes(2);expect(harness.deps.runGraph).toHaveBeenCalledTimes(2);expect(harness.session.getSnapshot().sourceGuard).toBe(replacementGuard);@@ -367,7 +371,7 @@ describe('createSelectObjectSession', () => {await vi.advanceTimersByTimeAsync(500);harness.session.update({ input: { prompt: 'second', type: 'prompt' } });await vi.advanceTimersByTimeAsync(999);- expect(harness.deps.exportLayer).not.toHaveBeenCalled();+ expect(harness.deps.exportComposite).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(1);await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());@@ -487,7 +491,7 @@ describe('createSelectObjectSession', () => {await expect(harness.session.process()).resolves.toBe('invalid');await vi.runAllTimersAsync();- expect(harness.deps.exportLayer).not.toHaveBeenCalled();+ expect(harness.deps.exportComposite).not.toHaveBeenCalled();expect(harness.deps.runGraph).not.toHaveBeenCalled();});@@ -524,9 +528,9 @@ describe('createSelectObjectSession', () => {boundary === 'decode'? vi.fn(() => wait.promise as Promise<string>): vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),- exportLayer:+ exportComposite:boundary === 'export'- ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportLayer']>)+ ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportComposite']>): vi.fn(() => Promise.resolve({ blob, guard, rect, status: 'ok' as const })),runGraph:boundary === 'queue'@@ -541,7 +545,7 @@ describe('createSelectObjectSession', () => {await vi.waitFor(() => {const fn =boundary === 'export'- ? harness.deps.exportLayer+ ? harness.deps.exportComposite: boundary === 'upload'? harness.deps.uploadIntermediate: boundary === 'queue'@@ -580,9 +584,9 @@ describe('createSelectObjectSession', () => {boundary === 'decode'? vi.fn(() => wait.promise as Promise<string>): vi.fn(({ image }) => Promise.resolve(`decoded:${image.imageName}`)),- exportLayer:+ exportComposite:boundary === 'export'- ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportLayer']>)+ ? vi.fn(() => wait.promise as ReturnType<SelectObjectSessionDeps<string>['exportComposite']>): vi.fn(() => Promise.resolve({ blob, guard, rect, status: 'ok' as const })),runGraph:boundary === 'queue'@@ -598,7 +602,7 @@ describe('createSelectObjectSession', () => {await vi.waitFor(() => {const fn =boundary === 'export'- ? harness.deps.exportLayer+ ? harness.deps.exportComposite: 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 e46de77980..f3e83ae59b 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 { ExportBakedLayerBlobResult, LayerExportGuard } from '@workbench/canvas-engine/engine';+import type { CanvasCompositeExportGuard, ExportCanvasCompositeBlobResult } from '@workbench/canvas-engine/engine';import type { Rect } from '@workbench/canvas-engine/types';import type { SamInput, SamModel } from '@workbench/generation/canvas/samGraph';@@ -18,7 +18,7 @@ export type SelectObjectSessionStatus = 'ready' | 'scheduled' | 'processing' | 'export interface SelectObjectSessionPreview<T> {data: T;- guard: LayerExportGuard;+ guard: CanvasCompositeExportGuard;image: SelectObjectReadyResult['image'];inputHash: string;previewId: number;@@ -37,13 +37,13 @@ export interface SelectObjectSessionState<T> {status: SelectObjectSessionStatus;error: string | null;preview: SelectObjectSessionPreview<T> | null;- sourceGuard: LayerExportGuard | null;+ sourceGuard: CanvasCompositeExportGuard | null;}export interface SelectObjectSessionDeps<T> {- captureGuard(layerId: string): LayerExportGuard | null;+ captureGuard(): CanvasCompositeExportGuard | null;controller: CanvasOperationController;- exportLayer(layerId: string): Promise<ExportBakedLayerBlobResult>;+ exportComposite(): Promise<ExportCanvasCompositeBlobResult>;uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;runGraph(options: Pick<RunUtilityGraphOptions, 'graph' | 'outputNodeId' | 'signal'>@@ -51,12 +51,11 @@ export interface SelectObjectSessionDeps<T> {decodePreview(result: SelectObjectReadyResult, signal: AbortSignal): Promise<T>;publishPreview(preview: SelectObjectSessionPreview<T>): undefined;cleanupPreview(): void;- isGuardCurrent(guard: LayerExportGuard): boolean;+ isGuardCurrent(guard: CanvasCompositeExportGuard): boolean;}export interface CreateSelectObjectSessionOptions<T> {projectId: string;- layerId: string;deps: SelectObjectSessionDeps<T>;}@@ -113,11 +112,11 @@ const resultError = (result: Exclude<Awaited<ReturnType<typeof prepareSelectObjeresult.status === 'failed' ? result.message : `Select Object source is ${result.status}.`;export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOptions<T>): SelectObjectSession<T> => {- const { deps, layerId, projectId } = options;+ const { deps, projectId } = options;let state = defaultState<T>();let source: SelectObjectPreparedSource | null = null;let operation: CanvasOperationSession | null = null;- let operationGuard: LayerExportGuard | null = null;+ let operationGuard: CanvasCompositeExportGuard | null = null;let requestToken = 0;let lastPublishedHash: string | null = null;let pendingHash: string | null = null;@@ -161,7 +160,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOpublishState({ ...state, preview: null, sourceGuard: null, status: 'ready' });};- const isGuardCurrent = (guard: LayerExportGuard): boolean => {+ const isGuardCurrent = (guard: CanvasCompositeExportGuard): boolean => {try {return deps.isGuardCurrent(guard);} catch {@@ -169,11 +168,9 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO}};- const isSameGuard = (left: LayerExportGuard, right: LayerExportGuard): boolean =>+ const isSameGuard = (left: CanvasCompositeExportGuard, right: CanvasCompositeExportGuard): boolean =>left.projectId === right.projectId &&- left.layerId === right.layerId &&- left.layer === right.layer &&- left.cacheVersion === right.cacheVersion &&+ left.documentFingerprint === right.documentFingerprint &&left.documentGeneration === right.documentGeneration;unsubscribeController = deps.controller.subscribe(() => {@@ -210,12 +207,15 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionO}, 1_000);};- const ensureSource = async (guard: LayerExportGuard, signal: AbortSignal): Promise<SelectObjectPreparedSource> => {+ const ensureSource = async (+ guard: CanvasCompositeExportGuard,+ signal: AbortSignal+ ): Promise<SelectObjectPreparedSource> => {if (source?.guard === guard && isGuardCurrent(guard)) {return source;}source = null;- const prepared = await prepareSelectObjectSource(layerId, deps, signal);+ const prepared = await prepareSelectObjectSource(deps, signal);if (prepared.status !== 'ready') {throw new Error(resultError(prepared));}@@ -230,7 +230,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOtoken: number,hash: string,requestState: SelectObjectSessionState<T>,- guard: LayerExportGuard+ guard: CanvasCompositeExportGuard): Promise<SelectObjectSessionProcessResult> => {try {if (operationGuard !== guard || !operation) {@@ -240,7 +240,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOnextOperation = deps.controller.start({cleanupPreview,guard,- identity: { kind: 'select-object', layerId, projectId },+ identity: { kind: 'select-object', projectId },});} finally {startingOperation = false;@@ -372,7 +372,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOrequestToken += 1;const token = requestToken;- const guard = operationGuard && isGuardCurrent(operationGuard) ? operationGuard : deps.captureGuard(layerId);+ const guard = operationGuard && isGuardCurrent(operationGuard) ? operationGuard : deps.captureGuard();if (!guard || !isGuardCurrent(guard)) {publishState({ ...state, error: 'Select Object source is not ready.', status: 'error' });return Promise.resolve('error');