Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): undo pixel selections and reach undo from the Layers widget
Josh Corbettddf9495cd919
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.tsindex 472ec700da..c5d60bcbd7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts@@ -2,6 +2,7 @@ import type { SelectionState, SelectionStateDeps } from '@workbench/canvas-enginimport { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createTestEditConcurrency } from '@workbench/canvas-engine/editConcurrency.testStub';+import { createHistory } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';import { EditingController } from './editingController';@@ -17,7 +18,9 @@ const createSelection = (): SelectionState => ({invert: vi.fn(),mask: () => null,replaceMask: vi.fn(),+ restore: vi.fn(),selectAll: vi.fn(),+ snapshot: vi.fn(() => ({ alpha: null, bounds: null, commits: [], rect: null, selected: false })),});const createTextOptions = () => ({@@ -96,6 +99,7 @@ describe('EditingController', () => {const controller = new EditingController({floatingSelection: createFloatingSelectionOptions(),getDocument: () => null,+ history: createHistory(),selection: {} as SelectionStateDeps,selectionPixels: createSelectionPixelOptions(),selectionImage: createSelectionImageOptions(),@@ -104,7 +108,13 @@ describe('EditingController', () => {transform: createTransformOptions(),});- expect(controller.selection).toBe(selection);+ // The exposed selection records history over the created state; the+ // float and a document swap reach the state itself.+ controller.selection.clear();+ expect(selection.clear).toHaveBeenCalledTimes(1);+ controller.discardSelection();+ expect(selection.clear).toHaveBeenCalledTimes(2);+ expect(controller.floatingSelection).toBeDefined();const lease = controller.edits.tryAcquire({ kind: 'filter', layerId: 'layer-1' });expect(lease?.isCurrent()).toBe(true);@@ -119,6 +129,7 @@ describe('EditingController', () => {const controller = new EditingController({floatingSelection: createFloatingSelectionOptions(),getDocument: () => null,+ history: createHistory(),selection: {} as SelectionStateDeps,selectionPixels: createSelectionPixelOptions(),selectionImage: createSelectionImageOptions(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.tsindex b5a80d2c62..6715c84434 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts@@ -1,5 +1,6 @@import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { CanvasEditGate, CanvasEditGateController } from '@workbench/canvas-engine/editGate';+import type { History } from '@workbench/canvas-engine/history/history';import type { SelectionState, SelectionStateDeps } from '@workbench/canvas-engine/selection/selectionState';import type { Rect } from '@workbench/canvas-engine/types';@@ -7,6 +8,7 @@ import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/dimport { getSourceBounds, isRenderableLayer } from '@workbench/canvas-engine/document/sources';import { createCanvasEditGate } from '@workbench/canvas-engine/editGate';import { roundOut, union } from '@workbench/canvas-engine/math/rect';+import { withSelectionHistory } from '@workbench/canvas-engine/selection/selectionHistory';import { createSelectionState } from '@workbench/canvas-engine/selection/selectionState';import { FloatingSelectionController, type FloatingSelectionControllerOptions } from './floatingSelectionController';@@ -17,6 +19,8 @@ import { TransformEditingController, type TransformEditingControllerOptions } frexport interface EditingControllerOptions {readonly selection: SelectionStateDeps;+ /** Records selection changes; the float folds its own mask move into its entry instead. */+ readonly history: History;readonly getDocument: () => CanvasDocumentContractV3 | null;readonly createSelectionState?: (deps: SelectionStateDeps) => SelectionState;readonly createEditGate?: () => CanvasEditGateController;@@ -29,7 +33,9 @@ export interface EditingControllerOptions {/** Owns transient editing state whose lifetime follows one engine instance. */export class EditingController {+ /** The recording selection: every change through it is an undo step. */readonly selection: SelectionState;+ private readonly rawSelection: SelectionState;readonly edits: CanvasEditGate;readonly text: TextEditingController;readonly transform: TransformEditingController;@@ -41,7 +47,8 @@ export class EditingController {private disposed = false;constructor(options: EditingControllerOptions) {- this.selection = (options.createSelectionState ?? createSelectionState)(options.selection);+ this.rawSelection = (options.createSelectionState ?? createSelectionState)(options.selection);+ this.selection = withSelectionHistory(this.rawSelection, options.history);this.getDocument = options.getDocument;this.editGate = (options.createEditGate ?? createCanvasEditGate)();this.edits = this.editGate;@@ -54,7 +61,7 @@ export class EditingController {});this.floatingSelection = new FloatingSelectionController({...options.floatingSelection,- selection: this.selection,+ selection: this.rawSelection,});}@@ -89,6 +96,11 @@ export class EditingController {this.selection.clear();}+ /** Drops the selection without a history step: the document it belonged to is going away. */+ discardSelection(): void {+ this.rawSelection.clear();+ }+invertSelection(): void {const domain = this.selectionDomain();if (domain) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.tsindex b0cf487784..ba99c76473 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts@@ -56,7 +56,9 @@ const createHarness = (options: { layer?: CanvasLayerContract; maskRect?: Rect;invert: vi.fn(),mask: () => maskSurface,replaceMask,+ restore: vi.fn(),selectAll: vi.fn(),+ snapshot: vi.fn(() => ({ alpha: null, bounds: null, commits: [], rect: null, selected: false })),} as SelectionState;// Seed a cache so there is something to lift out of.@@ -94,6 +96,7 @@ const createHarness = (options: { layer?: CanvasLayerContract; maskRect?: Rect;layer,layers,replaceMask,+ selection,removeLayer: () => {document = makeDoc([]);},@@ -253,6 +256,23 @@ describe('FloatingSelectionController: commit', () => {expect(rect.x + rect.width).toBe(90);});+ it('moves the ants inside the same step as the pixels, so one undo puts both back', () => {+ const h = createHarness();+ const before = { alpha: null, bounds: null, commits: [], rect: null, selected: false };+ const after = { ...before, selected: true };+ (h.selection.snapshot as ReturnType<typeof vi.fn>).mockReturnValueOnce(before).mockReturnValueOnce(after);+ h.controller.lift('a');+ move(h.controller, 40, 0);+ h.controller.commit();++ expect(h.history.entries()).toEqual({ future: [], past: ['Move selection'] });+ h.history.undo();+ expect(h.calls.applyImagePatch).toHaveBeenCalledTimes(1);+ expect(h.selection.restore).toHaveBeenLastCalledWith(before);+ h.history.redo();+ expect(h.selection.restore).toHaveBeenLastCalledWith(after);+ });+it('marks the layer dirty so the baked pixels persist', () => {const h = createHarness();h.controller.lift('a');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.tsindex 4c56fb4303..8037c31537 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts@@ -228,20 +228,34 @@ export class FloatingSelectionController {this.deps.markDirty(float.layerId);this.deps.invalidateLayer(float.layerId);+ // The ants travel with the pixels inside the same step, so one undo puts+ // both back; the raw selection records nothing of its own here.+ const selectionBefore = this.deps.selection.snapshot();+ this.moveSelectionWithFloat(layer, matrix, float);+ const selectionAfter = this.deps.selection.snapshot();+if (!this.deps.history.isApplying()) {- this.deps.history.push(- createImagePatchEntry({- after,- apply: this.deps.applyImagePatch,- before,- label: 'Move selection',- layerId: float.layerId,- rect: patchRect,- })- );+ const patch = createImagePatchEntry({+ after,+ apply: this.deps.applyImagePatch,+ before,+ label: 'Move selection',+ layerId: float.layerId,+ rect: patchRect,+ });+ this.deps.history.push({+ bytes: patch.bytes + (selectionBefore.alpha?.byteLength ?? 0) + (selectionAfter.alpha?.byteLength ?? 0),+ label: patch.label,+ redo: () => {+ patch.redo();+ this.deps.selection.restore(selectionAfter);+ },+ undo: () => {+ patch.undo();+ this.deps.selection.restore(selectionBefore);+ },+ });}-- this.moveSelectionWithFloat(layer, matrix, float);}/**diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 120faadaa3..3ad51e3b61 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -7311,6 +7311,8 @@ describe('mergeVisibleRasterLayers', () => {engine.history.undo();const restored = await engine.exports.exportLayerPixels(result.duplicateIds[0]!);expect(restored.status).toBe('ok');+ // Past the selection's own step, then the duplicate itself.+ engine.history.undo();engine.history.undo();engine.history.redo();const redone = await engine.exports.exportLayerPixels(result.duplicateIds[0]!);@@ -9614,11 +9616,12 @@ describe('commitRasterFilterResult', () => {await drainUntil(() => uploadImage.mock.calls.length === 1);expect(uploadImage).toHaveBeenCalledOnce();- // Undo the paint edit, then undo the copy itself. Redo reuses the exact- // layer id while the pre-undo upload is still unresolved.+ // Undo the paint edit and the selection, then undo the copy itself. Redo+ // reuses the exact layer id while the pre-undo upload is still unresolved.harness.engine.history.undo();await harness.refreshPlacement(copied.layerId);harness.engine.history.undo();+ harness.engine.history.undo();expect((await harness.engine.exports.exportLayerPixels(copied.layerId)).status).toBe('missing');harness.engine.history.redo();expect(@@ -15583,9 +15586,46 @@ describe('engine selection: select all / deselect / invert + hasSelection store'expect(engine.stores.hasSelection.get()).toBe(true);engine.lifecycle.dispose();});++ it('selection changes are their own history steps, undone and redone through the engine', () => {+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );+ const { store } = createFakeStore(paintDoc());+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ engine.selection.selectAll();+ engine.selection.deselect();+ expect(engine.history.getEntries().past).toEqual(['Select all', 'Deselect']);++ engine.history.undo();+ expect(engine.stores.hasSelection.get()).toBe(true);+ engine.history.undo();+ expect(engine.stores.hasSelection.get()).toBe(false);+ engine.history.redo();+ expect(engine.stores.hasSelection.get()).toBe(true);+ expect(engine.history.getEntries()).toEqual({ future: ['Deselect'], past: ['Select all'] });+ engine.lifecycle.dispose();+ });});describe('engine selection: fill / erase', () => {+ // The selection's own history steps are not pixel edits; a fill/erase that+ // changed nothing must leave only those behind.+ const SELECTION_STEPS = new Set(['Select', 'Select all']);+ const editSteps = (engine: CanvasEngine): string[] =>+ engine.history.getEntries().past.filter((label) => !SELECTION_STEPS.has(label));const makeEngine = (doc: CanvasDocumentContractV3) => {vi.stubGlobal('Path2D',@@ -15668,7 +15708,7 @@ describe('engine selection: fill / erase', () => {h.overlay.fire('pointerup', pointerAt(0, 0, { buttons: 0 }));h.engine.selection.eraseSelection();expect(h.engine.document.getDocument()).toEqual(before);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.suspendLayer).not.toHaveBeenCalled();h.engine.lifecycle.dispose();});@@ -15682,7 +15722,7 @@ describe('engine selection: fill / erase', () => {h.engine.selection.selectAll();h.engine.selection.fillSelection();expect(h.engine.document.getDocument()).toEqual(before);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();h.engine.lifecycle.dispose();});@@ -15695,7 +15735,7 @@ describe('engine selection: fill / erase', () => {h.engine.selection.selectAll();h.engine.selection.fillSelection();expect(h.engine.document.getDocument()).toEqual(before);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();h.engine.lifecycle.dispose();});@@ -15723,7 +15763,7 @@ describe('engine selection: fill / erase', () => {}expect(h.engine.document.getDocument()).toEqual(beforeDocument);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(h.bitmapStore.suspendLayer).toHaveBeenCalledOnce();expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();@@ -15757,7 +15797,7 @@ describe('engine selection: fill / erase', () => {h.engine.selection.fillSelection();expect(h.engine.document.getDocument()).toEqual(beforeDocument);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(h.bitmapStore.suspendLayer).toHaveBeenCalledOnce();expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();@@ -15786,7 +15826,7 @@ describe('engine selection: fill / erase', () => {h.engine.selection.fillSelection();expect(h.engine.document.getDocument()).toEqual(beforeDocument);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(h.bitmapStore.suspendLayer).toHaveBeenCalledOnce();expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();@@ -15837,7 +15877,7 @@ describe('engine selection: fill / erase', () => {expect(didThrow).toBe(true);expect(h.engine.document.getDocument()).toEqual(beforeDocument);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(h.bitmapStore.suspendLayer).toHaveBeenCalledOnce();expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();@@ -15898,7 +15938,7 @@ describe('engine selection: fill / erase', () => {expect(() => h.engine.selection.fillSelection()).toThrow('selection compositing failed');expect(h.engine.document.getDocument()).toEqual(beforeDocument);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(capturedReads[0]).toMatchObject({ height: 10, width: 10 });expect(capturedReads.at(-1)).toMatchObject({ height: 5, width: 5 });@@ -15947,7 +15987,7 @@ describe('engine selection: fill / erase', () => {expect(() => h.engine.selection.eraseSelection()).toThrow('selection compositing failed');expect(h.engine.document.getDocument()).toEqual(beforeDocument);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();const restored = await h.engine.exports.exportLayerPixels('control', { includeDisabled: true });@@ -15978,7 +16018,7 @@ describe('engine selection: fill / erase', () => {expect(() => h.engine.selection.fillSelection()).toThrow('layer snapshot preparation failed');expect(h.engine.document.getDocument()).toEqual(beforeDocument);- expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();const restored = await h.engine.exports.exportLayerPixels('control', { includeDisabled: true });@@ -15994,9 +16034,9 @@ describe('engine selection: fill / erase', () => {it('fillSelection on the selected paint layer records one undoable edit + persists', () => {const { bitmapStore, engine } = makeEngine(paintDoc());engine.selection.selectAll();- expect(engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(engine)).toEqual([]);engine.selection.fillSelection();- expect(engine.stores.canUndo.get()).toBe(true);+ expect(editSteps(engine)).toEqual(['Fill selection']);expect(bitmapStore.markLayerDirty).toHaveBeenCalledWith('paint1');// Undo restores (canRedo becomes available).engine.history.undo();@@ -16067,14 +16107,14 @@ describe('engine selection: fill / erase', () => {const { engine } = makeEngine(paintDoc());engine.selection.selectAll();engine.selection.eraseSelection();- expect(engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(engine)).toEqual([]);engine.lifecycle.dispose();});it('fillSelection is a no-op with no selection', () => {const { engine } = makeEngine(paintDoc());engine.selection.fillSelection();- expect(engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(engine)).toEqual([]);engine.lifecycle.dispose();});@@ -16082,7 +16122,7 @@ describe('engine selection: fill / erase', () => {const { engine } = makeEngine(imageSelectedDoc());engine.selection.selectAll();engine.selection.fillSelection();- expect(engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(engine)).toEqual([]);engine.lifecycle.dispose();});@@ -16097,7 +16137,7 @@ describe('engine selection: fill / erase', () => {engine.selection.fillSelection();// The layer has no existing pixels, so a transparency-locked (source-atop) fill// lands nothing — no undoable edit.- expect(engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(engine)).toEqual([]);engine.lifecycle.dispose();});@@ -16105,7 +16145,7 @@ describe('engine selection: fill / erase', () => {const { engine } = makeEngine(lockedPaintDoc());engine.selection.selectAll();engine.selection.fillSelection();- expect(engine.stores.canUndo.get()).toBe(false);+ expect(editSteps(engine)).toEqual([]);engine.lifecycle.dispose();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex ecd5007758..cd82eb848d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -920,6 +920,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreConChange: () => stores.hasFloatingSelection.set(floatingSelection.has()),},getDocument: () => mirror.getDocument(),+ history,selection: {backend,createPath2D: createPath2DImpl,@@ -1560,7 +1561,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// A float belongs to the outgoing document's layer. Cancel (not commit):// the layer it would bake into is about to be replaced.cleanup.run(() => floatingSelection.cancel());- cleanup.run(() => selection.clear());+ cleanup.run(() => editingController.discardSelection());cleanup.run(() => stores.lassoPreview.set(null));cleanup.run(() => stores.marqueePreview.set(null));const doc = mirror.getDocument();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.tsnew file mode 100644index 0000000000..14868bad99--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts@@ -0,0 +1,101 @@+import type { Rect } from '@workbench/canvas-engine/types';++import { createHistory } from '@workbench/canvas-engine/history/history';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { createSelectionState } from '@workbench/canvas-engine/selection/selectionState';+import { describe, expect, it, vi } from 'vitest';++import { withSelectionHistory } from './selectionHistory';++const DOC = { height: 100, width: 100 };+const rectBounds = (x: number, y: number, w: number, h: number): Rect => ({ height: h, width: w, x, y });+const fakePath = (id: string): Path2D => ({ id }) as unknown as Path2D;++const createHarness = () => {+ const history = createHistory();+ const onChange = vi.fn();+ const selection = withSelectionHistory(+ createSelectionState({+ backend: createTestStubRasterBackend(),+ createPath2D: (d) => ({ d }) as unknown as Path2D,+ getDocumentSize: () => DOC,+ onChange,+ }),+ history+ );+ return { history, onChange, selection };+};++describe('withSelectionHistory', () => {+ it('records each selection change as one labelled step', () => {+ const { history, selection } = createHarness();+ selection.selectAll(rectBounds(0, 0, 100, 100));+ selection.commit({ bounds: rectBounds(10, 10, 20, 20), op: 'subtract', path: fakePath('a') });+ selection.invert(rectBounds(0, 0, 100, 100));+ selection.clear();+ expect(history.entries().past).toEqual(['Select all', 'Subtract from selection', 'Invert selection', 'Deselect']);+ });++ it('undo and redo replay the captured selections without recording again', () => {+ const { history, selection } = createHarness();+ selection.commit({ bounds: rectBounds(10, 10, 20, 20), op: 'replace', path: fakePath('a') });+ selection.commit({ bounds: rectBounds(40, 40, 10, 10), op: 'add', path: fakePath('b') });+ expect(selection.bounds()).toEqual(rectBounds(10, 10, 40, 40));++ history.undo();+ expect(selection.bounds()).toEqual(rectBounds(10, 10, 20, 20));+ expect(selection.antsPaths()).toHaveLength(1);+ history.undo();+ expect(selection.hasSelection()).toBe(false);+ expect(selection.antsPaths()).toEqual([]);+ history.redo();+ history.redo();+ expect(selection.bounds()).toEqual(rectBounds(10, 10, 40, 40));+ expect(selection.antsPaths()).toHaveLength(2);+ expect(history.entries()).toEqual({ future: [], past: ['Select', 'Add to selection'] });+ });++ it('records nothing for a call that leaves the selection unchanged', () => {+ const { history, selection } = createHarness();+ selection.clear();+ selection.commit({ bounds: rectBounds(10, 10, 20, 20), op: 'intersect', path: fakePath('a') });+ expect(history.canUndo()).toBe(false);+ });++ it('records a pixel-mask replacement as Select object and undoes it to the prior selection', () => {+ const { history, selection } = createHarness();+ const backend = createTestStubRasterBackend();+ const surface = backend.createSurface(2, 2);+ const pixels = {+ colorSpace: 'srgb',+ data: new Uint8ClampedArray([0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),+ height: 2,+ width: 2,+ } as ImageData;+ Object.defineProperty(surface.ctx, 'getImageData', { value: () => pixels });++ selection.replaceMask({ rect: rectBounds(7, -3, 2, 2), surface });++ expect(history.entries().past).toEqual(['Select object']);+ expect(selection.bounds()).toEqual(rectBounds(7, -3, 2, 2));+ history.undo();+ expect(selection.hasSelection()).toBe(false);+ });++ it('labels a degenerate replace as the deselect it performs', () => {+ const { history, selection } = createHarness();+ selection.selectAll(rectBounds(0, 0, 100, 100));+ selection.commit({ bounds: rectBounds(5, 5, 0, 0), op: 'replace', path: fakePath('tiny') });+ expect(history.entries().past).toEqual(['Select all', 'Deselect']);+ expect(selection.hasSelection()).toBe(false);+ });++ it('charges a plane shared between consecutive steps once', () => {+ const { history, selection } = createHarness();+ selection.selectAll(rectBounds(0, 0, 100, 100));+ expect(history.byteSize()).toBe(100 * 100);+ selection.invert(rectBounds(0, 0, 100, 100));+ // The inverted plane is new; the select-all plane it started from was already charged.+ expect(history.byteSize()).toBe(2 * 100 * 100);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.tsnew file mode 100644index 0000000000..c73a081b9f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts@@ -0,0 +1,95 @@+/**+ * Makes a {@link SelectionState} undoable: every selection-changing call is+ * bracketed by snapshots and recorded on the engine history as one step, so a+ * marquee, lasso, select-all, invert, deselect, or Select Object result reverts+ * on its own instead of taking the previous pixel edit with it.+ *+ * Replay restores snapshots directly and never re-enters this wrapper's+ * recording path; a call that leaves the selection unchanged records nothing.+ *+ * Zero React, zero import-time side effects.+ */++import type { History } from '@workbench/canvas-engine/history/history';+import type { Rect, SelectionOp } from '@workbench/canvas-engine/types';++import { isEmpty } from '@workbench/canvas-engine/math/rect';++import type { SelectionCommit, SelectionSnapshot, SelectionState } from './selectionState';++const COMMIT_LABELS: Record<SelectionOp, string> = {+ add: 'Add to selection',+ intersect: 'Intersect selection',+ replace: 'Select',+ subtract: 'Subtract from selection',+};++const sameRect = (left: Rect | null, right: Rect | null): boolean =>+ left === right ||+ (left !== null &&+ right !== null &&+ left.x === right.x &&+ left.y === right.y &&+ left.width === right.width &&+ left.height === right.height);++const sameAlpha = (left: Uint8ClampedArray | null, right: Uint8ClampedArray | null): boolean => {+ if (left === null || right === null) {+ return left === right;+ }+ if (left.length !== right.length) {+ return false;+ }+ for (let index = 0; index < left.length; index += 1) {+ if (left[index] !== right[index]) {+ return false;+ }+ }+ return true;+};++const sameSnapshot = (left: SelectionSnapshot, right: SelectionSnapshot): boolean =>+ left.selected === right.selected &&+ left.commits.length === right.commits.length &&+ sameRect(left.rect, right.rect) &&+ sameRect(left.bounds, right.bounds) &&+ sameAlpha(left.alpha, right.alpha);++/** A degenerate replace (a lasso too small to close) deselects rather than selects. */+const commitLabel = (commit: SelectionCommit): string =>+ commit.op === 'replace' && isEmpty(commit.bounds) ? 'Deselect' : COMMIT_LABELS[commit.op];++/** Wraps `selection` so its mutations record on `history`; reads and replay pass through untouched. */+export const withSelectionHistory = (selection: SelectionState, history: History): SelectionState => {+ // Consecutive steps share their boundary capture; charge a plane once.+ let lastAfter: SelectionSnapshot | null = null;+ const record = (label: string, mutate: () => void): void => {+ if (history.isApplying()) {+ mutate();+ return;+ }+ const before = selection.snapshot();+ mutate();+ const after = selection.snapshot();+ if (sameSnapshot(before, after)) {+ return;+ }+ const beforeBytes = before === lastAfter ? 0 : (before.alpha?.byteLength ?? 0);+ lastAfter = after;+ history.push({+ bytes: beforeBytes + (after.alpha?.byteLength ?? 0),+ label,+ redo: () => selection.restore(after),+ undo: () => selection.restore(before),+ });+ };++ return {+ ...selection,+ clear: () => record('Deselect', () => selection.clear()),+ commit: (commit) => record(commitLabel(commit), () => selection.commit(commit)),+ invert: (domain) => record('Invert selection', () => selection.invert(domain)),+ replaceMask: (mask) => record('Select object', () => selection.replaceMask(mask)),+ selectAll: (domain) => record('Select all', () => selection.selectAll(domain)),+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.tsindex afd648fdb6..fb0b1d94a1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts@@ -155,6 +155,47 @@ describe('selectionState: selectAll / invert / clear', () => {});});+describe('selectionState: snapshot / restore', () => {+ it('restores a captured selection exactly, and an empty capture deselects', () => {+ const { selection, onChange } = createHarness();+ const path = fakePath('a');+ selection.commit({ bounds: rectBounds(10, 10, 20, 20), op: 'replace', path });+ const captured = selection.snapshot();+ selection.clear();+ const empty = selection.snapshot();+ onChange.mockClear();++ selection.restore(captured);++ expect(selection.hasSelection()).toBe(true);+ expect(selection.bounds()).toEqual(rectBounds(10, 10, 20, 20));+ expect(selection.mask()?.rect).toEqual(rectBounds(10, 10, 20, 20));+ expect(selection.antsPaths()).toEqual([path]);+ const put = maskLog(selection)+ .filter((entry) => entry.op === 'putImageData')+ .at(-1);+ const pixels = put?.args[0] as ImageData;+ expect(pixels.width).toBe(20);+ expect(pixels.data.filter((_, index) => index % 4 === 3)).toEqual(captured.alpha);+ expect(onChange).toHaveBeenCalledOnce();++ selection.restore(empty);++ expect(selection.hasSelection()).toBe(false);+ expect(selection.mask()).toBeNull();+ expect(selection.antsPaths()).toEqual([]);+ });++ it('captures are detached from later mutations', () => {+ const { selection } = createHarness();+ selection.commit({ bounds: rectBounds(10, 10, 20, 20), op: 'replace', path: fakePath('a') });+ const captured = selection.snapshot();+ selection.commit({ bounds: rectBounds(40, 40, 10, 10), op: 'add', path: fakePath('b') });+ expect(captured.commits).toHaveLength(1);+ expect(captured.bounds).toEqual(rectBounds(10, 10, 20, 20));+ });+});+describe('selectionState: replaceMask', () => {it('replaces prior pixels with an isolated, pixel-exact alpha mask at its world rect', () => {const { selection, onChange } = createHarness();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.tsindex 708833b08e..c33627adf2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts@@ -2,7 +2,9 @@* Engine-transient pixel selection.** Per the plan's state-tier table, a selection is *interaction* state: it lives- * on the engine, never in the reducer contract, and is not undoable. The source+ * on the engine, never in the reducer contract. It is undoable only through the+ * engine's own history, which {@link SelectionState.snapshot} / `restore` serve+ * (see `selectionHistory.ts`); persistence never sees it. The source* of truth is the set of closed `Path2D` polygons the lasso tool commits; the* derived artifact is a bounded **mask surface** (alpha 255 inside the* selection), sized to the selection extent and placed in document space (a@@ -52,6 +54,19 @@ export interface SelectionCommit {op: SelectionOp;}+/**+ * A restorable capture of the selection: the mask's alpha plane over `rect`+ * plus the bookkeeping the mask alone cannot recover. Alpha-only keeps a+ * full-document capture at one byte per pixel; the mask is white by contract.+ */+export interface SelectionSnapshot {+ readonly alpha: Uint8ClampedArray<ArrayBuffer> | null;+ readonly rect: Rect | null;+ readonly commits: readonly SelectionCommit[];+ readonly bounds: Rect | null;+ readonly selected: boolean;+}+/** The engine-facing selection handle. */export interface SelectionState {/** Whether a selection currently exists (drives clip/fill/ants gating). */@@ -83,6 +98,10 @@ export interface SelectionState {invert(domain: Rect): void;/** Clears the selection (deselect). */clear(): void;+ /** Captures the selection for a later {@link restore}; the capture is immutable and detached. */+ snapshot(): SelectionSnapshot;+ /** Reinstates a captured selection exactly, notifying like any other mutation. */+ restore(snapshot: SelectionSnapshot): void;/** Releases the mask surface reference. */dispose(): void;}@@ -99,6 +118,29 @@ export interface SelectionStateDeps {const MASK_FILL = '#ffffff';+/** `ImageData` is absent on the node raster stub; a structural stand-in carries the same fields. */+const createImageData = (data: Uint8ClampedArray<ArrayBuffer>, width: number, height: number): ImageData =>+ typeof ImageData === 'undefined'+ ? ({ colorSpace: 'srgb', data, height, width } as ImageData)+ : new ImageData(data, width, height);++const alphaOf = (pixels: ImageData): Uint8ClampedArray<ArrayBuffer> => {+ const alpha = new Uint8ClampedArray(pixels.width * pixels.height);+ for (let index = 0; index < alpha.length; index += 1) {+ alpha[index] = pixels.data[index * 4 + 3] ?? 0;+ }+ return alpha;+};++/** Expands an alpha plane back into the mask's white-with-coverage pixels. */+const pixelsOf = (alpha: Uint8ClampedArray<ArrayBuffer>, width: number, height: number): ImageData => {+ const data = new Uint8ClampedArray(alpha.length * 4).fill(255);+ for (let index = 0; index < alpha.length; index += 1) {+ data[index * 4 + 3] = alpha[index] ?? 0;+ }+ return createImageData(data, width, height);+};+/** Builds a closed rectangle `Path2D` (document space) via the injected factory. */const rectPath = (createPath2D: CreatePath2D, r: Rect): Path2D => createPath2D(rectPathData(r));@@ -127,6 +169,14 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =let commits: SelectionCommit[] = [];let selectionBounds: Rect | null = null;let selected = false;+ // The last capture stays valid until the next mutation, so a change recorded+ // as before/after reads the mask back once, not twice.+ let cachedSnapshot: SelectionSnapshot | null = null;++ const changed = (): void => {+ cachedSnapshot = null;+ onChange();+ };/*** Ensures the mask surface exists and covers `rect` (integer bounds),@@ -206,7 +256,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =if (mask) {clearSurface(mask);}- onChange();+ changed();};const replaceMask = (next: PlacedSurface): void => {@@ -221,7 +271,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =commits = [];selectionBounds = null;selected = false;- onChange();+ changed();};if (isEmpty(rect) || next.surface.width <= 0 || next.surface.height <= 0) {publishEmptyReplacement();@@ -242,10 +292,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =}const copiedData = new Uint8ClampedArray(source.data);- const copied =- typeof ImageData === 'undefined'- ? ({ colorSpace: source.colorSpace, data: copiedData, height: source.height, width: source.width } as ImageData)- : new ImageData(copiedData, source.width, source.height);+ const copied = createImageData(copiedData, source.width, source.height);// Prepare every fallible replacement artifact before publishing any state.// If allocation, pixel upload, or Path2D construction fails, the exact prior// selection remains authoritative and the engine may safely report failure.@@ -264,7 +311,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =commits = [{ bounds: rect, op: 'replace', path: nextPath }];selectionBounds = rect;selected = true;- onChange();+ changed();};const commit = (next: SelectionCommit): void => {@@ -284,7 +331,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =commits = [next];selectionBounds = bounds;selected = true;- onChange();+ changed();return;}@@ -317,7 +364,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =selected = selectionBounds !== null;break;}- onChange();+ changed();};const selectAll = (domain: Rect): void => {@@ -334,7 +381,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =commits = [{ bounds: rect, op: 'replace', path: rectPath(createPath2D, rect) }];selectionBounds = rect;selected = !isEmpty(rect);- onChange();+ changed();};const invert = (domain: Rect): void => {@@ -369,6 +416,35 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =commits = [{ bounds: rect, op: 'replace', path: rectPath(createPath2D, rect) }, ...commits];selectionBounds = rect;selected = true;+ changed();+ };++ const snapshot = (): SelectionSnapshot => {+ if (cachedSnapshot) {+ return cachedSnapshot;+ }+ const captured = selected && mask && maskRect && !isEmpty(maskRect) ? maskRect : null;+ cachedSnapshot = {+ alpha: captured ? alphaOf(mask!.ctx.getImageData(0, 0, captured.width, captured.height)) : null,+ bounds: selectionBounds,+ commits: [...commits],+ rect: captured,+ selected,+ };+ return cachedSnapshot;+ };++ const restore = (next: SelectionSnapshot): void => {+ if (next.alpha && next.rect) {+ const surface = resetMask(next.rect);+ surface.ctx.putImageData(pixelsOf(next.alpha, next.rect.width, next.rect.height), 0, 0);+ } else if (mask) {+ clearSurface(mask);+ }+ commits = [...next.commits];+ selectionBounds = next.bounds;+ selected = next.selected;+ cachedSnapshot = next;onChange();};@@ -392,6 +468,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =commit,containsPoint,dispose: () => {+ cachedSnapshot = null;mask = null;maskRect = null;commits = [];@@ -402,6 +479,8 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =invert,mask: () => (selected && mask && maskRect ? { rect: maskRect, surface: mask } : null),replaceMask,+ restore,selectAll,+ snapshot,};};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsxindex f683fda6a3..824ae965b6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx@@ -33,6 +33,7 @@ import {} from './panes/editorPaneLayout';import { HistoryPane } from './panes/HistoryPane';import { LayerColorPane, LayerEditorPanes } from './panes/LayerEditorPanes';+import { useCanvasHistoryHotkeys } from './useCanvasHistoryHotkeys';import { useLayerSelectionCommands } from './useLayerSelectionCommands';/**@@ -68,6 +69,7 @@ export const LayersWidgetView = ({ runtime }: WidgetViewProps) => {const degraded = nodeCount > LAYER_PANEL_DEGRADE_THRESHOLD;const selectionCommands = useLayerSelectionCommands(engine, projectId, panel.selectedIds, editingLocked);+ useCanvasHistoryHotkeys(runtime, engine);const handleFilter = useCallback((filter: string) => setLayerPanelFilter(projectId, selectedLayerId, filter),[projectId, selectedLayerId]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsxnew file mode 100644index 0000000000..8a082c8d0e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsx@@ -0,0 +1,98 @@+import type { WidgetCommandContribution, WidgetHotkeyContribution } from '@workbench/widgetContracts';+import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';++import { act, createElement, type ReactElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useCanvasHistoryHotkeys } from './useCanvasHistoryHotkeys';++const translation = { t: (key: string) => key };+vi.mock('react-i18next', () => ({ useTranslation: () => translation }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const createRuntime = () => {+ const commands = new Map<string, WidgetCommandContribution>();+ const hotkeys = new Map<string, WidgetHotkeyContribution>();+ return {+ commands: {+ register: vi.fn((command: WidgetCommandContribution) => {+ commands.set(command.id, command);+ return () => commands.delete(command.id);+ }),+ },+ hotkeys: {+ register: vi.fn((hotkey: WidgetHotkeyContribution) => {+ hotkeys.set(hotkey.id, hotkey);+ return () => hotkeys.delete(hotkey.id);+ }),+ },+ registered: { commands, hotkeys },+ };+};++const Host = ({+ engine,+ runtime,+}: {+ engine: Pick<CanvasEngineHandle, 'history'> | null;+ runtime: ReturnType<typeof createRuntime>;+}) => {+ useCanvasHistoryHotkeys(runtime, engine);+ return null;+};++let root: Root | null = null;+let host: HTMLDivElement | null = null;++afterEach(() => {+ act(() => root?.unmount());+ host?.remove();+ root = null;+ host = null;+});++const mount = (element: ReactElement): void => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ act(() => root!.render(element));+};++describe('useCanvasHistoryHotkeys', () => {+ it('registers undo/redo outside editable fields and drives the current engine', () => {+ const runtime = createRuntime();+ const first = { history: { redo: vi.fn(), undo: vi.fn() } } as unknown as CanvasEngineHandle;+ const second = { history: { redo: vi.fn(), undo: vi.fn() } } as unknown as CanvasEngineHandle;+ mount(createElement(Host, { engine: first, runtime }));++ expect([...runtime.registered.hotkeys.values()]).toEqual([+ expect.objectContaining({ allowInEditable: false, commandId: 'canvas.undo', defaultKeys: ['mod+z'] }),+ expect.objectContaining({+ allowInEditable: false,+ commandId: 'canvas.redo',+ defaultKeys: ['mod+shift+z', 'mod+y'],+ }),+ ]);+ void runtime.registered.commands.get('canvas.undo')!.handler();+ expect(first.history.undo).toHaveBeenCalledOnce();++ // A new engine identity re-renders the host without re-registering.+ act(() => root!.render(createElement(Host, { engine: second, runtime })));+ void runtime.registered.commands.get('canvas.redo')!.handler();+ expect(second.history.redo).toHaveBeenCalledOnce();+ expect(first.history.redo).not.toHaveBeenCalled();+ expect(runtime.commands.register).toHaveBeenCalledTimes(2);+ });++ it('withdraws both registrations on unmount and tolerates a missing engine', () => {+ const runtime = createRuntime();+ mount(createElement(Host, { engine: null, runtime }));+ expect(() => runtime.registered.commands.get('canvas.undo')!.handler()).not.toThrow();++ act(() => root!.unmount());+ expect(runtime.registered.commands.size).toBe(0);+ expect(runtime.registered.hotkeys.size).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.tsnew file mode 100644index 0000000000..d7ba0b7f1c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts@@ -0,0 +1,45 @@+import type { WidgetCommandApi, WidgetHotkeyApi } from '@workbench/widgetContracts';+import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';++import { useEffect, useEffectEvent } from 'react';+import { useTranslation } from 'react-i18next';++// The canvas history's undo/redo, reachable while a companion widget owns+// focus: selecting a layer or editing its properties must not strand mod+Z.+const HISTORY_HOTKEYS = [+ ['canvas.undo', 'widgets.canvas.commands.undo', ['mod+z']],+ ['canvas.redo', 'widgets.canvas.commands.redo', ['mod+shift+z', 'mod+y']],+] as const;++type HistoryCommandId = (typeof HISTORY_HOTKEYS)[number][0];++/** Registers canvas undo/redo on `runtime` for as long as the caller is mounted. */+export const useCanvasHistoryHotkeys = (+ runtime: { commands: Pick<WidgetCommandApi, 'register'>; hotkeys: WidgetHotkeyApi },+ engine: Pick<CanvasEngineHandle, 'history'> | null+): void => {+ const { t } = useTranslation();+ const run = useEffectEvent((commandId: HistoryCommandId) => {+ if (commandId === 'canvas.undo') {+ engine?.history.undo();+ } else {+ engine?.history.redo();+ }+ });+ useEffect(() => {+ const disposers = HISTORY_HOTKEYS.flatMap(([id, titleKey, defaultKeys]) => [+ runtime.commands.register({ handler: () => run(id), id, title: t(titleKey) }),+ runtime.hotkeys.register({+ allowInEditable: false,+ commandId: id,+ defaultKeys: [...defaultKeys],+ id,+ title: t(titleKey),+ }),+ ]);++ return () => {+ disposers.forEach((dispose) => dispose());+ };+ }, [runtime.commands, runtime.hotkeys, t]);+};