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): make structural commits failure-atomic with typed results
Josh Corbett24967c5f0db0
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 059a7a195c..51e65abe45 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2289,6 +2289,16 @@"saved": "Saved to gallery","savedDescription": "{{name}} added to your gallery."},+ "structural": {+ "failed": "Canvas edit failed",+ "gestureActive": "Finish the current canvas gesture, then try again.",+ "notReady": "The canvas is not ready to record this edit.",+ "rejected": "The canvas did not accept this edit. Nothing changed.",+ "reverted": "The edit could not be verified and was reverted.",+ "stale": "The canvas changed before this edit landed. Try again.",+ "unmirrored": "The edit was reverted, but the canvas view may be out of date.",+ "unverified": "The edit could not be verified or reverted. Check the canvas before continuing."+ },"surface": "Canvas surface","toolOptions": {"applyTransform": "Apply",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex d0ea2c8306..305003956d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -47,6 +47,10 @@ export interface LayerExportGuard {* `busy` — another edit owns the document, or a gesture started mid-flight.* `stale` — the guarded pixels no longer match the live layer.* `aborted` — the caller's signal fired.+ *+ * This union still mixes runtime outcomes with document refusals (`missing`,+ * `locked`, `unsupported`); structural commits use the transaction-only+ * {@link StructuralCommitResult} instead.*/export type GuardedMutationRefusal = 'aborted' | 'busy' | 'locked' | 'missing' | 'stale' | 'unsupported';@@ -135,6 +139,13 @@ export interface CanvasSurfaceCapability {export interface CanvasDocumentCapability {captureSnapshot(): CanvasDocumentSnapshot | null;getDocument(): CanvasDocumentContractV2 | null;+ /**+ * Counts every reducer document identity change, whatever its origin (user edits, previews,+ * selection, system syncs). Unlike `documentGeneration` (raster invalidation) and the persisted+ * `documentRevision` (wholesale swaps), it moves on each edit, so an edit prepared against a+ * captured value can be refused as stale once anything else lands.+ */+ getEditRevision(): number;}/** Immutable reducer canvas state captured at one engine document generation. */@@ -244,12 +255,43 @@ export type ReplaceSelectionFromImageResult =| { status: GuardedMutationRefusal }| { status: 'failed'; message: string };+/**+ * The runtime outcome of a structural document commit. `busy`, `gesture-active`, `not-ready`, and+ * `stale` refuse before dispatch. `dispatch-rejected` means the reducer left the document unchanged,+ * which includes a forward that would not change anything. `postcondition-failed` means the reducer+ * accepted but the result could not be verified; `recovered` says how far the inverse got, and any+ * outcome short of `reverted` was reported. Exactly one history entry is recorded, and only for+ * `committed`.+ */+export type StructuralCommitResult =+ | { status: 'committed' }+ | { status: 'busy' | 'gesture-active' | 'not-ready' | 'dispatch-rejected' }+ | { status: 'stale'; expectedRevision: number; actualRevision: number }+ | { status: 'postcondition-failed'; recovered: 'reverted' | 'reverted-unmirrored' | 'unreverted' };++export interface StructuralCommitOptions {+ /** The edit revision the edit was prepared against; a mismatch refuses as `stale`. */+ expectedRevision?: number;+ /** An extra reducer postcondition beyond "the document changed". */+ verify?: (document: CanvasDocumentContractV2) => boolean;+}++/** The narrowest engine surface a structural edit needs. */+export interface CanvasStructuralEngine {+ readonly layers: CanvasLayerCapability;+}+export interface CanvasLayerCapability {applyStructuralPreview(action: CanvasProjectMutation): boolean;canCommitStructural(): boolean;commitGeneratedImageResult(options: CommitGeneratedImageOptions): Promise<CommitGeneratedImageResult>;commitStagedImage(options: CommitStagedImageOptions): CommitStagedImageResult;- commitStructural(label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation): boolean;+ commitStructural(+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation,+ options?: StructuralCommitOptions+ ): StructuralCommitResult;invertMask(layerId: string): boolean;}@@ -377,14 +419,16 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {commitMaskImageResult(options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult>;commitOpenTextSession(): boolean;commitRasterFilterResult(options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult>;- commitTextEdit(content: string, styleChanges?: Partial<TextToolOptions>): void;+ /** `null` when there was nothing to commit: an empty creation or an unchanged edit. */+ commitTextEdit(content: string, styleChanges?: Partial<TextToolOptions>): StructuralCommitResult | null;copyLayerToRaster(layerId: string): Promise<string | null>;cropLayerToBbox(layerId: string): Promise<CropLayerResult>;duplicateLayers(layerIds: readonly string[]): Promise<DuplicateLayersResult>;mergeLayerDown(upperLayerId: string): boolean;mergeSelectedRasterLayers(layerIds: readonly string[]): Promise<MergeVisibleResult>;mergeVisibleRasterLayers(): Promise<MergeVisibleResult>;- nudgeSelectedLayer(dx: number, dy: number): void;+ /** `dispatch-rejected` also covers a selection with nothing eligible to move. */+ nudgeSelectedLayer(dx: number, dy: number): StructuralCommitResult;openTextCreate(docPoint: Vec2): void;openTextEdit(layerId: string): void;rasterizeLayer(layerId: string): boolean;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.tsindex e7d3ff01bc..98ba59e362 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts@@ -37,11 +37,17 @@ describe('LayerController', () => {setStatus: vi.fn(),};const structural = new StructuralLayerController({- canEdit: () => true,- dispatch: vi.fn(),- getDocument: () => null,- history: { push: vi.fn() } as never,- isGestureActive: () => false,+ ctx: {+ canEdit: () => true,+ capturePermit: () => ({ epoch: 0 }),+ dispatch: vi.fn(() => true),+ dispatchPrepared: vi.fn(),+ getDocument: () => null,+ getEditRevision: () => 0,+ getReducerDocument: () => null,+ history: { push: vi.fn() } as never,+ isGestureActive: () => false,+ },});const rasterize = {backend: {} as never,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.tsindex 0cc5022fc4..5b2eeaa8b0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts@@ -62,7 +62,8 @@ export class LayerController<Permit> {canCommitStructural: () => this.structural.canCommit(),commitGeneratedImageResult: (options) =>this.disposed ? Promise.resolve({ status: 'aborted' }) : deps.commitGeneratedImageResult(options),- commitStructural: (label, forward, inverse) => this.structural.commit(label, forward, inverse),+ commitStructural: (label, forward, inverse, options) =>+ this.disposed ? { status: 'not-ready' } : this.structural.commit(label, forward, inverse, options),invertMask: (layerId) => (this.disposed ? false : this.mask.invert(layerId)),};this.previews = {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.tsindex 0fc4952265..a573a86bb9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts@@ -1,3 +1,4 @@+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -55,6 +56,7 @@ const createHarness = (overrides: Partial<CanvasMutationContextDeps> = {}) => {isGuardCurrent: () => true,preparePixels: (layerId, rect) => ({ layerId, rect, surface: {} }) as PreparedLayerCacheReplacement,refreshMirror: vi.fn(),+ subscribeReducer: () => () => undefined,...overrides,};const context = createCanvasMutationContext(deps);@@ -328,3 +330,28 @@ describe('createCanvasMutationContext', () => {});});});++describe('edit revision', () => {+ it('advances once per reducer document identity and never on notification alone', () => {+ let document = { layers: [] } as unknown as CanvasDocumentContractV2;+ const listeners: (() => void)[] = [];+ const { context } = createHarness({+ getReducerDocument: () => document,+ subscribeReducer: (listener) => {+ listeners.push(listener);+ return () => undefined;+ },+ });++ expect(context.getEditRevision()).toBe(0);+ listeners.forEach((listener) => listener());+ expect(context.getEditRevision()).toBe(0);++ document = { ...document };+ listeners.forEach((listener) => listener());+ expect(context.getEditRevision()).toBe(1);++ document = { ...document };+ expect(context.getEditRevision()).toBe(2);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.tsindex 6c1df357a2..47cd1cc5a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts@@ -29,6 +29,8 @@ export interface CanvasMutationContext {readonly history: History;getDocument(): CanvasDocumentContractV2 | null;getReducerDocument(): CanvasDocumentContractV2 | null;+ /** Counts reducer document identities; a captured value is stale once any edit lands. */+ getEditRevision(): number;canEdit(owner?: symbol): boolean;capturePermit(owner?: symbol): DocumentEditPermit | null;isPermitCurrent(permit: DocumentEditPermit): boolean;@@ -52,6 +54,7 @@ export interface CanvasMutationContextDeps {readonly history: History;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly subscribeReducer: (listener: () => void) => () => void;readonly dispatch: (action: CanvasProjectMutation, origin?: WorkbenchActionOrigin) => boolean;readonly commitEdit: (intent: CanvasEditIntent) => void;readonly refreshMirror: () => void;@@ -84,6 +87,16 @@ export const createCanvasMutationContext = (}};const unsubscribeDocumentEditingLock = deps.editingLocked.subscribe(syncDocumentEditingLock);+ let editRevision = 0;+ let observedDocument = deps.getReducerDocument();+ const syncEditRevision = (): void => {+ const document = deps.getReducerDocument();+ if (document !== observedDocument) {+ observedDocument = document;+ editRevision += 1;+ }+ };+ const unsubscribeReducer = deps.subscribeReducer(syncEditRevision);const canEdit = (owner?: symbol): boolean => owner === deps.editOwner || !deps.editingLocked.get();const capturePermit = (owner?: symbol): DocumentEditPermit | null =>canEdit(owner) ? { epoch: documentEditEpoch, owner } : null;@@ -164,9 +177,16 @@ export const createCanvasMutationContext = (createLayerId: () => deps.createLayerId(),dispatch: (action, origin) => deps.dispatch(action, origin),dispatchPrepared,- dispose: () => unsubscribeDocumentEditingLock(),+ dispose: () => {+ unsubscribeDocumentEditingLock();+ unsubscribeReducer();+ },endBurst: () => deps.endBurst(),getDocument: () => deps.getDocument(),+ getEditRevision: () => {+ syncEditRevision();+ return editRevision;+ },getReducerDocument: () => deps.getReducerDocument(),history: deps.history,installPrepared: (prepared, persist) => deps.installPrepared(prepared, persist),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.tsindex 1d41e7a8f6..45a3dd70b9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts@@ -1,112 +1,242 @@import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import type { Project } from '@workbench/projectContracts';import { createHistory } from '@workbench/canvas-engine/history/history';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';+import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';+import { createCanvasMutationContext } from './mutationContext';import { StructuralLayerController } from './structuralLayerController';+interface HarnessOptions {+ locked?: boolean;+ gestureActive?: boolean;+ /** Mirror refreshes only when asked, as when a store observer threw mid-notification. */+ mirrorLag?: boolean;+ /** Makes mirror refresh fail so an accepted mutation can never be mirrored. */+ mirrorBroken?: boolean;+}++const createHarness = (options: HarnessOptions & { now?: () => number } = {}) => {+ const base = createInitialWorkbenchState().projects[0]!;+ const layer = createEmptyPaintLayer('Layer', 'layer');+ let project: Project = applyCanvasProjectMutation(base, { index: 0, layer, type: 'addCanvasLayer' });+ let mirrorDocument = project.canvas.document;+ const listeners = new Set<() => void>();+ const dispatched: CanvasProjectMutation[] = [];+ const report = vi.fn();+ const refreshMirror = (): void => {+ if (options.mirrorBroken) {+ throw new Error('mirror broken');+ }+ mirrorDocument = project.canvas.document;+ };+ const dispatch = (action: CanvasProjectMutation): boolean => {+ dispatched.push(action);+ const next = applyCanvasProjectMutation(project, action);+ const changed = next.canvas !== project.canvas;+ project = next;+ if (!options.mirrorLag && !options.mirrorBroken) {+ mirrorDocument = project.canvas.document;+ }+ listeners.forEach((listener) => listener());+ return changed;+ };+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'new',+ dispatch,+ editOwner: Symbol('owner'),+ editingLocked: { get: () => options.locked ?? false, subscribe: () => () => undefined },+ endBurst: () => undefined,+ getDocument: () => mirrorDocument,+ getReducerDocument: () => project.canvas.document,+ history: createHistory(),+ installPrepared: () => undefined,+ isGestureActive: () => options.gestureActive ?? false,+ isGuardCurrent: () => true,+ preparePixels: () => ({}) as never,+ refreshMirror,+ subscribeReducer: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ });+ const controller = new StructuralLayerController({ ctx, now: options.now ?? (() => 0), report });+ return {+ controller,+ ctx,+ dispatched,+ document: () => project.canvas.document,+ history: ctx.history,+ layer,+ mirror: () => mirrorDocument,+ report,+ };+};++const rename = (id: string, name: string): CanvasProjectMutation => ({+ id,+ patch: { name },+ type: 'updateCanvasLayer',+});+const layerName = (document: CanvasDocumentContractV2, id = 'layer'): string | undefined =>+ document.layers.find((layer) => layer.id === id)?.name;+describe('StructuralLayerController', () => {- it('reports whether a structural commit is currently allowed and committed', () => {- const dispatch = vi.fn();- const history = createHistory();- const controller = new StructuralLayerController({- canEdit: () => true,- dispatch,- getDocument: () => null,- history,- isGestureActive: () => false,- });- const forward = { id: 'layer', type: 'setCanvasSelectedLayer' } as const;- const inverse = { id: null, type: 'setCanvasSelectedLayer' } as const;+ it('commits through the guarded dispatch and records one failure-atomic history entry', () => {+ const { controller, document, history, mirror } = createHarness();expect(controller.canCommit()).toBe(true);- expect(controller.commit('Select layer', forward, inverse)).toBe(true);- expect(dispatch).toHaveBeenCalledOnce();+ expect(controller.commit('Rename', rename('layer', 'Renamed'), rename('layer', 'Layer'))).toEqual({+ status: 'committed',+ });+ expect(layerName(document())).toBe('Renamed');+ expect(mirror()).toBe(document());expect(history.canUndo()).toBe(true);++ history.undo();+ expect(layerName(document())).toBe('Layer');+ history.redo();+ expect(layerName(document())).toBe('Renamed');});it.each([- { canEdit: false, gestureActive: false, reason: 'editing is disallowed' },- { canEdit: true, gestureActive: true, reason: 'a gesture is active' },- ])('reports and refuses a structural commit when $reason', ({ canEdit, gestureActive }) => {- const dispatch = vi.fn();- const history = createHistory();- const controller = new StructuralLayerController({- canEdit: () => canEdit,- dispatch,- getDocument: () => null,- history,- isGestureActive: () => gestureActive,+ { expected: 'busy', locked: true, reason: 'editing is locked' },+ { expected: 'gesture-active', gestureActive: true, reason: 'a gesture is active' },+ ])('refuses before dispatch when $reason', ({ expected, ...options }) => {+ const { controller, dispatched, history } = createHarness(options);++ expect(controller.commit('Rename', rename('layer', 'Renamed'), rename('layer', 'Layer'))).toEqual({+ status: expected,});+ expect(dispatched).toEqual([]);+ expect(history.canUndo()).toBe(false);+ });++ it('refuses after disposal', () => {+ const { controller, dispatched } = createHarness();++ controller.dispose();expect(controller.canCommit()).toBe(false);+ expect(controller.commit('Rename', rename('layer', 'Renamed'), rename('layer', 'Layer'))).toEqual({+ status: 'not-ready',+ });+ expect(dispatched).toEqual([]);+ });++ it('refuses an edit prepared against an older revision as stale', () => {+ const { controller, ctx, dispatched } = createHarness();+ const captured = ctx.getEditRevision();++ expect(controller.commit('First', rename('layer', 'A'), rename('layer', 'Layer'))).toEqual({ status: 'committed' });+ const actual = ctx.getEditRevision();++ expect(+ controller.commit('Second', rename('layer', 'B'), rename('layer', 'A'), { expectedRevision: captured })+ ).toEqual({ actualRevision: actual, expectedRevision: captured, status: 'stale' });+ expect(dispatched).toHaveLength(1);+ expect(+ controller.commit('Third', rename('layer', 'B'), rename('layer', 'A'), { expectedRevision: actual })+ ).toEqual({+ status: 'committed',+ });+ });++ it('reports a reducer rejection without recording history', () => {+ const { controller, document, history } = createHarness();+ const before = document();+expect(- controller.commit(- 'Select layer',- { id: 'layer', type: 'setCanvasSelectedLayer' },- { id: null, type: 'setCanvasSelectedLayer' }- )- ).toBe(false);- expect(dispatch).not.toHaveBeenCalled();+ controller.commit('Select', { id: 'missing', type: 'setCanvasSelectedLayer' }, rename('layer', 'Layer'))+ ).toEqual({ status: 'dispatch-rejected' });+ expect(document()).toBe(before);expect(history.canUndo()).toBe(false);});- it('reports and refuses structural commits after disposal', () => {- const dispatch = vi.fn();- const history = createHistory();- const controller = new StructuralLayerController({- canEdit: () => true,- dispatch,- getDocument: () => null,- history,- isGestureActive: () => false,- });+ it('applies the inverse when an accepted edit fails its postcondition', () => {+ const { controller, document, history, mirror } = createHarness();- controller.dispose();+ expect(+ controller.commit('Rename', rename('layer', 'Renamed'), rename('layer', 'Layer'), { verify: () => false })+ ).toEqual({ recovered: 'reverted', status: 'postcondition-failed' });+ expect(layerName(document())).toBe('Layer');+ expect(mirror()).toBe(document());+ expect(history.canUndo()).toBe(false);+ });++ it('reports when the inverse cannot be applied and leaves the edit unrecorded', () => {+ const { controller, document, history, report } = createHarness();- expect(controller.canCommit()).toBe(false);expect(- controller.commit(- 'Select layer',- { id: 'layer', type: 'setCanvasSelectedLayer' },- { id: null, type: 'setCanvasSelectedLayer' }- )- ).toBe(false);- expect(dispatch).not.toHaveBeenCalled();+ controller.commit('Rename', rename('layer', 'Renamed'), rename('missing', 'Layer'), { verify: () => false })+ ).toEqual({ recovered: 'unreverted', status: 'postcondition-failed' });+ expect(layerName(document())).toBe('Renamed');+ expect(history.canUndo()).toBe(false);+ expect(report).toHaveBeenCalledWith('Structural edit could not be reverted', 'Rename', expect.any(Error));});- it('owns guarded structural history and coalesces rapid nudges', () => {- let now = 0;- const dispatch = vi.fn();- const history = createHistory();- const document = {- layers: [- {- id: 'layer',- isEnabled: true,- isLocked: false,- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- },- ],- selectedLayerId: 'layer',- } as CanvasDocumentContractV2;- const controller = new StructuralLayerController({- canEdit: () => true,- dispatch,- getDocument: () => document,- history,- isGestureActive: () => false,- now: () => now,+ it('reconciles a lagging mirror before recording the entry', () => {+ const { controller, document, mirror } = createHarness({ mirrorLag: true });++ expect(controller.commit('Rename', rename('layer', 'Renamed'), rename('layer', 'Layer'))).toEqual({+ status: 'committed',});+ expect(mirror()).toBe(document());+ });++ it('reverts an accepted edit that can never be mirrored and says the view may lag', () => {+ const { controller, document, history, report } = createHarness({ mirrorBroken: true });- controller.nudge(1, 0);+ expect(controller.commit('Rename', rename('layer', 'Renamed'), rename('layer', 'Layer'))).toEqual({+ recovered: 'reverted-unmirrored',+ status: 'postcondition-failed',+ });+ expect(layerName(document())).toBe('Layer');+ expect(history.canUndo()).toBe(false);+ expect(report).toHaveBeenCalledWith('Structural edit could not be mirrored', 'Rename', expect.any(Error));+ });++ it('moves a replay the reducer refuses as a reported no-op instead of wedging history', () => {+ const { controller, ctx, document, history, report } = createHarness();+ const added = createEmptyPaintLayer('Added', 'added');++ controller.commit(+ 'Add',+ { index: 0, layer: added, type: 'addCanvasLayer' },+ { ids: ['added'], type: 'removeCanvasLayers' }+ );+ ctx.dispatch({ ids: ['added'], type: 'removeCanvasLayers' }, 'system');++ expect(() => history.undo()).not.toThrow();+ expect(report).toHaveBeenCalledWith('Structural history replay was refused', 'Add', expect.any(Error));+ expect(history.canUndo()).toBe(false);+ expect(history.canRedo()).toBe(true);+ expect(layerName(document(), 'added')).toBeUndefined();+ });++ it('coalesces rapid nudges into one entry and reports an ineligible nudge as rejected', () => {+ let now = 0;+ const { controller, document, history } = createHarness({ now: () => now });++ expect(controller.nudge(1, 0)).toEqual({ status: 'committed' });now = 100;- document.layers[0]!.transform.x = 1;- controller.nudge(1, 0);+ expect(controller.nudge(1, 0)).toEqual({ status: 'committed' });+ expect(document().layers[0]?.transform.x).toBe(2);- expect(dispatch).toHaveBeenCalledTimes(2);history.undo();- expect(dispatch).toHaveBeenLastCalledWith(expect.objectContaining({ patch: { transform: { x: 0, y: 0 } } }));+ expect(document().layers[0]?.transform.x).toBe(0);expect(history.canUndo()).toBe(false);++ controller.commit(+ 'Deselect',+ { id: null, type: 'setCanvasSelectedLayer' },+ { id: 'layer', type: 'setCanvasSelectedLayer' }+ );+ expect(controller.nudge(1, 0)).toEqual({ status: 'dispatch-rejected' });});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.tsindex 2a85e98250..7f6f91f8c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts@@ -1,16 +1,34 @@+import type { StructuralCommitOptions, StructuralCommitResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';-import type { History } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';+import type { CanvasMutationContext } from './mutationContext';++export type StructuralMutationContext = Pick<+ CanvasMutationContext,+ | 'canEdit'+ | 'capturePermit'+ | 'dispatch'+ | 'dispatchPrepared'+ | 'getDocument'+ | 'getEditRevision'+ | 'getReducerDocument'+ | 'history'+ | 'isGestureActive'+>;++export type StructuralFailureReport =+ | 'Structural edit could not be reverted'+ | 'Structural edit could not be mirrored'+ | 'Structural history replay was refused'+ | 'Structural history replay could not be mirrored';+export interface StructuralLayerControllerOptions {- readonly history: History;- readonly dispatch: (action: CanvasProjectMutation) => void;- readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly ctx: StructuralMutationContext;readonly getSelectedLayerIds?: (document: CanvasDocumentContractV2) => readonly string[];- readonly canEdit: () => boolean;- readonly isGestureActive: () => boolean;+ readonly report?: (message: StructuralFailureReport, label: string, error: unknown) => void;readonly now?: () => number;}@@ -22,7 +40,16 @@ interface NudgeBurst {const NUDGE_COALESCE_MS = 500;-/** Owns guarded structural document edits and nudge coalescing. */+const positionMutation = (positions: readonly { id: string; x: number; y: number }[]): CanvasProjectMutation =>+ positions.length === 1+ ? {+ id: positions[0]!.id,+ patch: { transform: { x: positions[0]!.x, y: positions[0]!.y } },+ type: 'updateCanvasLayer',+ }+ : { type: 'setCanvasLayerPositions', updates: [...positions] };++/** Owns guarded, failure-atomic structural document edits and nudge coalescing. */export class StructuralLayerController {private burst: NudgeBurst | null = null;private disposed = false;@@ -37,34 +64,45 @@ export class StructuralLayerController {}canCommit(): boolean {- return !this.disposed && this.deps.canEdit() && !this.deps.isGestureActive();+ const { ctx } = this.deps;+ return !this.disposed && ctx.canEdit() && !ctx.isGestureActive();}- commit(label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation): boolean {- if (!this.canCommit()) {- return false;+ commit(+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation,+ options: StructuralCommitOptions = {}+ ): StructuralCommitResult {+ const refusal = this.refuse(options);+ if (refusal) {+ return refusal;}this.endBurst();- this.deps.dispatch(forward);- this.deps.history.push(createDocumentPatchEntry({ dispatch: this.deps.dispatch, forward, inverse, label }));- return true;+ const applied = this.apply(label, forward, inverse, options.verify);+ if (applied.status === 'committed') {+ this.deps.ctx.history.push(this.entry(label, forward, inverse));+ }+ return applied;}preview(action: CanvasProjectMutation): boolean {- if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {+ if (!this.canCommit()) {return false;}- this.deps.dispatch(action);+ this.deps.ctx.dispatch(action);return true;}- nudge(dx: number, dy: number): void {- if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {- return;+ nudge(dx: number, dy: number): StructuralCommitResult {+ const { ctx } = this.deps;+ const refusal = this.refuse({});+ if (refusal) {+ return refusal;}- const document = this.deps.getDocument();+ const document = ctx.getDocument();if (!document?.selectedLayerId) {- return;+ return { status: 'dispatch-rejected' };}const requested = new Set(this.deps.getSelectedLayerIds?.(document) ?? [document.selectedLayerId]);const layers = document.layers.filter((layer) => requested.has(layer.id));@@ -74,7 +112,7 @@ export class StructuralLayerController {!requested.has(document.selectedLayerId) ||layers.some((layer) => layer.isLocked || !layer.isEnabled)) {- return;+ return { status: 'dispatch-rejected' };}const selectionKey = layers.map((layer) => layer.id).join('\0');const now = this.now();@@ -84,34 +122,126 @@ export class StructuralLayerController {? this.burst.origins: layers.map((layer) => ({ id: layer.id, x: layer.transform.x, y: layer.transform.y }));const next = layers.map((layer) => ({ id: layer.id, x: layer.transform.x + dx, y: layer.transform.y + dy }));- const forward: CanvasProjectMutation =- layers.length === 1- ? {- id: layers[0]!.id,- patch: { transform: { x: next[0]!.x, y: next[0]!.y } },- type: 'updateCanvasLayer',- }- : { type: 'setCanvasLayerPositions', updates: next };- const inverse: CanvasProjectMutation =- layers.length === 1- ? {- id: layers[0]!.id,- patch: { transform: { x: origins[0]!.x, y: origins[0]!.y } },- type: 'updateCanvasLayer',- }- : { type: 'setCanvasLayerPositions', updates: origins };- this.deps.dispatch(forward);- const entry = createDocumentPatchEntry({ dispatch: this.deps.dispatch, forward, inverse, label: 'Nudge layer' });+ const label = 'Nudge layer';+ const forward = positionMutation(next);+ const inverse = positionMutation(origins);+ const applied = this.apply(label, forward, inverse);+ if (applied.status !== 'committed') {+ this.burst = null;+ return applied;+ }+ const entry = this.entry(label, forward, inverse);if (coalesce) {- this.deps.history.amendLast(entry);+ ctx.history.amendLast(entry);} else {- this.deps.history.push(entry);+ ctx.history.push(entry);}this.burst = { expiresAt: now + NUDGE_COALESCE_MS, origins, selectionKey };+ return applied;}dispose(): void {this.disposed = true;this.endBurst();}++ private refuse(options: StructuralCommitOptions): StructuralCommitResult | null {+ const { ctx } = this.deps;+ if (this.disposed) {+ return { status: 'not-ready' };+ }+ if (!ctx.capturePermit()) {+ return { status: 'busy' };+ }+ if (ctx.isGestureActive()) {+ return { status: 'gesture-active' };+ }+ if (!ctx.getReducerDocument()) {+ return { status: 'not-ready' };+ }+ const actualRevision = ctx.getEditRevision();+ if (options.expectedRevision !== undefined && options.expectedRevision !== actualRevision) {+ return { actualRevision, expectedRevision: options.expectedRevision, status: 'stale' };+ }+ return null;+ }++ /** Dispatches `forward` once through the guarded context; a verified failure applies `inverse`. */+ private apply(+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation,+ verify: (document: CanvasDocumentContractV2) => boolean = () => true+ ): StructuralCommitResult {+ const { ctx } = this.deps;+ const before = ctx.getReducerDocument();+ const isMirrored = (): boolean => ctx.getDocument() === ctx.getReducerDocument();+ const isApplied = (): boolean => {+ const document = ctx.getReducerDocument();+ return document !== null && document !== before && verify(document);+ };+ try {+ ctx.dispatchPrepared(forward, isApplied, isMirrored);+ return { status: 'committed' };+ } catch (error) {+ const after = ctx.getReducerDocument();+ if (after === before) {+ return { status: 'dispatch-rejected' };+ }+ let recoveryError: unknown = error;+ try {+ ctx.dispatchPrepared(inverse, () => ctx.getReducerDocument() !== after, isMirrored, 'system');+ } catch (inverseError) {+ recoveryError = inverseError;+ }+ const recovered =+ ctx.getReducerDocument() === after ? 'unreverted' : isMirrored() ? 'reverted' : 'reverted-unmirrored';+ if (recovered === 'unreverted') {+ this.deps.report?.('Structural edit could not be reverted', label, recoveryError);+ } else if (recovered === 'reverted-unmirrored') {+ this.deps.report?.('Structural edit could not be mirrored', label, recoveryError);+ }+ return { recovered, status: 'postcondition-failed' };+ }+ }++ private entry(label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation) {+ return createDocumentPatchEntry({+ dispatch: (action) => this.replay(label, action, forward, inverse),+ forward,+ inverse,+ label,+ replayFailureAtomic: true,+ });+ }++ /**+ * A reducer that refuses a replay (its target changed since) is expected: the entry moves as a+ * no-op and the refusal is reported. A mirror that cannot follow an accepted replay is not: the+ * opposite action restores the reducer and the failure surfaces.+ */+ private replay(+ label: string,+ action: CanvasProjectMutation,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation+ ): void {+ const { ctx } = this.deps;+ const before = ctx.getReducerDocument();+ try {+ ctx.dispatchPrepared(+ action,+ () => ctx.getReducerDocument() !== before,+ () => ctx.getDocument() === ctx.getReducerDocument()+ );+ } catch (error) {+ if (ctx.getReducerDocument() === before) {+ this.deps.report?.('Structural history replay was refused', label, error);+ return;+ }+ this.deps.report?.('Structural history replay could not be mirrored', label, error);+ ctx.dispatch(action === forward ? inverse : forward, 'system');+ throw error;+ }+ }}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.tsindex 7d086a04c9..641b4249d1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts@@ -1,3 +1,4 @@+import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { TextEditSession } from '@workbench/canvas-engine/engineStores';@@ -8,7 +9,9 @@ import { TextEditingController } from './textEditingController';const createHarness = (document: CanvasDocumentContractV2) => {let session: TextEditSession | null = null;- const commitStructural = vi.fn();+ const commitStructural = vi.fn<(label: string, forward: unknown, inverse: unknown) => StructuralCommitResult>(() => ({+ status: 'committed',+ }));const invalidate = vi.fn();const controller = new TextEditingController({canEdit: () => true,@@ -49,3 +52,27 @@ describe('TextEditingController', () => {expect(h.invalidate).toHaveBeenCalledWith({ overlay: true });});});++describe('TextEditingController refusals', () => {+ it('keeps the session for a transient refusal and drops it when the target is gone', () => {+ const h = createHarness({ bbox: { height: 1, width: 1, x: 0, y: 0 }, height: 1, layers: [], width: 1 } as never);+ h.commitStructural.mockReturnValueOnce({ status: 'busy' as const });+ h.controller.openCreate({ x: 0, y: 0 });++ expect(h.controller.commit('hello')).toEqual({ status: 'busy' });+ expect(h.getSession()).not.toBeNull();++ h.commitStructural.mockReturnValueOnce({ status: 'dispatch-rejected' as const });+ expect(h.controller.commit('hello')).toEqual({ status: 'dispatch-rejected' });+ expect(h.getSession()).toBeNull();+ });++ it('reports nothing to commit for an empty creation', () => {+ const h = createHarness({ bbox: { height: 1, width: 1, x: 0, y: 0 }, height: 1, layers: [], width: 1 } as never);+ h.controller.openCreate({ x: 0, y: 0 });++ expect(h.controller.commit(' ')).toBeNull();+ expect(h.getSession()).toBeNull();+ expect(h.commitStructural).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.tsindex c0028f7fa7..112ff1212a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts@@ -1,3 +1,4 @@+import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { TextEditSession, TextSource, TextToolOptions } from '@workbench/canvas-engine/engineStores';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';@@ -13,7 +14,11 @@ export interface TextEditingControllerOptions {readonly canEdit: () => boolean;readonly isGestureActive: () => boolean;readonly createLayerId: () => string;- readonly commitStructural: (label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation) => void;+ readonly commitStructural: (+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation+ ) => StructuralCommitResult;readonly invalidate: (payload: { layers?: string[]; overlay?: true }) => void;}@@ -111,19 +116,25 @@ export class TextEditingController {this.deps.invalidate(session.layerId ? { layers: [session.layerId] } : { overlay: true });}- commit(content: string, styleChanges?: Partial<TextToolOptions>): void {- if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {- return;+ commit(content: string, styleChanges?: Partial<TextToolOptions>): StructuralCommitResult | null {+ if (this.disposed) {+ return { status: 'not-ready' };+ }+ if (!this.deps.canEdit()) {+ return { status: 'busy' };+ }+ if (this.deps.isGestureActive()) {+ return { status: 'gesture-active' };}const session = this.deps.session.get();if (!session) {- return;+ return null;}const finalSource: TextSource = { ...session.source, ...styleChanges, content };if (session.mode === 'create') {if (content.trim() === '') {this.cancel();- return;+ return null;}const layerId = this.deps.createLayerId();const layer: CanvasLayerContract = {@@ -137,30 +148,39 @@ export class TextEditingController {transform: session.transform,type: 'raster',};- this.deps.session.set(null);- this.deps.commitStructural(+ const added = this.deps.commitStructural('Add text',{ index: 0, layer, type: 'addCanvasLayer' },{ ids: [layerId], type: 'removeCanvasLayers' });+ this.settle(added);this.deps.invalidate({ overlay: true });- return;+ return added;}const { layerId, startSource } = session;if (!layerId || !startSource) {this.cancel();- return;+ return null;}- this.deps.session.set(null);if (sourcesEqual(startSource, finalSource)) {+ this.deps.session.set(null);this.deps.invalidate({ layers: [layerId] });- return;+ return null;}- this.deps.commitStructural(+ const edited = this.deps.commitStructural('Edit text',{ id: layerId, source: finalSource, type: 'updateCanvasLayerSource' },{ id: layerId, source: startSource, type: 'updateCanvasLayerSource' });+ this.settle(edited);+ return edited;+ }++ /** A landed edit or a target that is gone ends the session; a transient refusal keeps the text for retry. */+ private settle(result: StructuralCommitResult): void {+ if (result.status === 'committed' || result.status === 'dispatch-rejected' || result.status === 'not-ready') {+ this.deps.session.set(null);+ }}commitOpen(): boolean {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 238081ad1c..ee82822b9e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -4118,7 +4118,7 @@ describe('commitStructural', () => {});expect(engine.layers.canCommitStructural()).toBe(true);- expect(engine.layers.commitStructural('Select layer', forward, inverse)).toBe(true);+ expect(engine.layers.commitStructural('Select layer', forward, inverse)).toEqual({ status: 'committed' });// Forward dispatched once; the edit is now undoable but not redoable.expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenNthCalledWith(1, forward);@@ -4139,7 +4139,82 @@ describe('commitStructural', () => {engine.lifecycle.dispose();expect(engine.layers.canCommitStructural()).toBe(false);- expect(engine.layers.commitStructural('Select layer', forward, inverse)).toBe(false);+ expect(engine.layers.commitStructural('Select layer', forward, inverse)).toEqual({ status: 'not-ready' });+ });++ it('reports a reducer refusal as dispatch-rejected with no history entry', () => {+ const layer = rasterLayer('L');+ const { projectId, store } = createReducerBackedStore({ ...makeDoc(), layers: [layer], selectedLayerId: 'L' });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });++ expect(+ engine.layers.commitStructural('Select', { id: 'missing', type: 'setCanvasSelectedLayer' }, inverse)+ ).toEqual({ status: 'dispatch-rejected' });+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.lifecycle.dispose();+ });++ it('reverts an accepted edit that fails its postcondition and records nothing', () => {+ const layer = rasterLayer('L');+ const { projectId, store } = createReducerBackedStore({ ...makeDoc(), layers: [layer], selectedLayerId: 'L' });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });++ expect(+ engine.layers.commitStructural(+ 'Rename',+ { id: 'L', patch: { name: 'Renamed' }, type: 'updateCanvasLayer' },+ { id: 'L', patch: { name: 'L' }, type: 'updateCanvasLayer' },+ { verify: () => false }+ )+ ).toEqual({ recovered: 'reverted', status: 'postcondition-failed' });+ expect(engine.document.getDocument()?.layers[0]?.name).toBe('L');+ expect(engine.stores.canUndo.get()).toBe(false);+ engine.lifecycle.dispose();+ });++ it('moves a refused undo as a no-op instead of throwing out of history', () => {+ const layer = rasterLayer('L');+ const { dispatch, projectId, store } = createReducerBackedStore({+ ...makeDoc(),+ layers: [layer],+ selectedLayerId: 'L',+ });+ const reportError = vi.fn();+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ reportError,+ store,+ });+ const added = rasterLayer('added');++ expect(+ engine.layers.commitStructural(+ 'Add',+ { index: 0, layer: added, type: 'addCanvasLayer' },+ { ids: ['added'], type: 'removeCanvasLayers' }+ )+ ).toEqual({ status: 'committed' });+ dispatch({ ids: ['added'], type: 'removeCanvasLayers' });++ expect(() => engine.history.undo()).not.toThrow();+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);+ expect(reportError).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'Structural history replay was refused' })+ );+ engine.lifecycle.dispose();});});@@ -14005,20 +14080,20 @@ describe('gesture guard: nudge / commitStructural mid-stroke', () => {engine.lifecycle.dispose();});- it('no-ops commitStructural while a stroke gesture is open, then commits after it ends', () => {+ it('refuses commitStructural as gesture-active while a stroke gesture is open, then commits after it ends', () => {const { dispatch, engine, overlay } = startOpenStroke();- const forward: EngineTestAction = { id: 'x', type: 'setCanvasSelectedLayer' };- const inverse: EngineTestAction = { id: null, type: 'setCanvasSelectedLayer' };+ const forward: EngineTestAction = { id: null, type: 'setCanvasSelectedLayer' };+ const inverse: EngineTestAction = { id: 'paint1', type: 'setCanvasSelectedLayer' };expect(engine.layers.canCommitStructural()).toBe(false);- expect(engine.layers.commitStructural('Select', forward, inverse)).toBe(false);+ expect(engine.layers.commitStructural('Select', forward, inverse)).toEqual({ status: 'gesture-active' });// Nothing dispatched, nothing recorded on history mid-gesture.expect(dispatch.mock.calls.some((call) => call[0] === forward)).toBe(false);expect(engine.stores.canUndo.get()).toBe(false);overlay.fire('pointerup', pointerAt(30, 30, { buttons: 0 }));expect(engine.layers.canCommitStructural()).toBe(true);- expect(engine.layers.commitStructural('Select', forward, inverse)).toBe(true);+ expect(engine.layers.commitStructural('Select', forward, inverse)).toEqual({ status: 'committed' });expect(dispatch.mock.calls.some((call) => call[0] === forward)).toBe(true);expect(engine.stores.canUndo.get()).toBe(true);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 26abc2a775..af256f70d9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -23,6 +23,8 @@ import type {MergeVisibleResult,NewRasterLayerResult,PsdExportResult,+ StructuralCommitOptions,+ StructuralCommitResult,} from '@workbench/canvas-engine/capabilities';import type {CanvasCompositeExecutorDeps,@@ -209,7 +211,15 @@ const createCleanupAccumulator = (): { run: (step: () => void) => void; throwIfFexport interface CanvasEngineErrorReport {area: 'canvas-engine';context: { error: string; layerId: string };- message: 'Layer thumbnail rasterization failed' | 'Bitmap persistence failed' | 'Bitmap persistence suspended';+ message:+ | 'Layer thumbnail rasterization failed'+ | 'Bitmap persistence failed'+ | 'Bitmap persistence suspended'+ | 'Structural edit was refused'+ | 'Structural edit could not be reverted'+ | 'Structural edit could not be mirrored'+ | 'Structural history replay was refused'+ | 'Structural history replay could not be mirrored';namespace: 'canvas';projectId: string;}@@ -716,18 +726,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCpixelEditController?.cancel();};- const structuralController = new StructuralLayerController({- canEdit: () => canEditDocument(),- dispatch: (action) => dispatchCanvasMutation(action),- getDocument: () => mirror.getDocument(),- getSelectedLayerIds: resolveSelectedLayerIds,- history,- isGestureActive: () => pipeline.isGestureActive(),- });+ let structuralController: StructuralLayerController;const endNudgeBurst = (): void => structuralController.endBurst();- const commitStructural = (label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation): boolean =>- structuralController.commit(label, forward, inverse);- const nudgeSelectedLayer = (dx: number, dy: number): void => structuralController.nudge(dx, dy);/*** The pixel-write bridge shared by undo and redo: put the patch's pixels back@@ -907,7 +907,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},text: {canEdit: () => canEditDocument(),- commitStructural: (label, forward, inverse) => commitStructural(label, forward, inverse),+ commitStructural: (label, forward, inverse) => commitToolStructural(label, forward, inverse),createLayerId,getDocument: () => mirror.getDocument(),invalidate: (payload) => scheduler.invalidate(payload),@@ -1168,7 +1168,32 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCisGuardCurrent: (guard) => isLayerExportGuardCurrent(guard),preparePixels: (layerId, rect, pixels) => prepareGeneratedPaintCache(layerId, rect, pixels),refreshMirror: () => mirror.refresh(),+ subscribeReducer: (listener) => mutationPort.subscribe(listener),});+ structuralController = new StructuralLayerController({+ ctx: mutationContext,+ getSelectedLayerIds: resolveSelectedLayerIds,+ report: (message, label, error) => reportError(message, label, error),+ });+ const commitStructural = (+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation,+ options?: StructuralCommitOptions+ ): StructuralCommitResult => structuralController.commit(label, forward, inverse, options);+ const nudgeSelectedLayer = (dx: number, dy: number): StructuralCommitResult => structuralController.nudge(dx, dy);+ // Tools commit at pointer-up with nowhere to show a refusal; contention is expected, anything else is logged.+ const commitToolStructural = (+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation+ ): StructuralCommitResult => {+ const result = commitStructural(label, forward, inverse);+ if (result.status !== 'committed' && result.status !== 'busy') {+ reportError('Structural edit was refused', label, result.status);+ }+ return result;+ };const canEditDocument = (owner?: symbol): boolean => mutationContext.canEdit(owner);const captureDocumentEditPermit = (owner?: symbol): DocumentEditPermit | null => mutationContext.capturePermit(owner);const isDocumentEditPermitCurrent = (permit: DocumentEditPermit): boolean => mutationContext.isPermitCurrent(permit);@@ -2395,7 +2420,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst openTextEdit = (layerId: string): void => editingController.text.openEdit(layerId);const updateTextEditStyle = (patch: Partial<TextToolOptions>): void => editingController.text.updateStyle(patch);const cancelTextEdit = (): void => editingController.text.cancel();- const commitTextEdit = (content: string, styleChanges?: Partial<TextToolOptions>): void =>+ const commitTextEdit = (content: string, styleChanges?: Partial<TextToolOptions>): StructuralCommitResult | null =>editingController.text.commit(content, styleChanges);const commitOpenTextSession = (): boolean => editingController.text.commitOpen();@@ -2850,6 +2875,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst documentCapability: CanvasDocumentCapability = {captureSnapshot: captureDocumentSnapshot,getDocument: () => mirror.getDocument(),+ getEditRevision: () => mutationContext.getEditRevision(),};const selectionCapability: CanvasEngineSelectionCapability = {deselect,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.tsindex 1fc9c2de96..2f2879a480 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts@@ -1,18 +1,9 @@/*** A structural history entry: a pair of reducer actions (forward + inverse)- * dispatched to undo/redo a document-shape change.- *- * Unlike a pixel {@link createImagePatchEntry | image patch}, a document patch- * carries no bitmaps — just two {@link CanvasProjectMutation}s. Undo dispatches the- * `inverse`, redo dispatches the `forward`. It exists so structural canvas edits- * (add/remove/reorder layer, rename, …) can live on the same engine-owned undo- * stack as paint edits. Phase 3's layers-panel operations lean on this; P2.1 uses- * it lightly (if at all) for composing an auto-created layer into a stroke's undo.- *- * Byte cost is tiny (actions are small plain objects); the default keeps it off- * the byte budget's radar while still counting as one of the entry-count slots.- *- * Zero React, zero DOM, zero import-time side effects.+ * dispatched to undo/redo a document-shape change. Unlike a pixel+ * {@link createImagePatchEntry | image patch}, it carries no bitmaps, so+ * structural edits share the engine-owned undo stack with paint edits at a+ * nominal byte cost.*/import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';@@ -29,10 +20,12 @@ export interface CreateDocumentPatchEntryOptions {forward: CanvasProjectMutation;/** The action that reverses the change (dispatched on undo). */inverse: CanvasProjectMutation;- /** The reducer bridge. */+ /** Applies one side of the patch; may throw to leave a failure-atomic entry in place. */dispatch(action: CanvasProjectMutation): void;/** Approximate retained size (default {@link DOCUMENT_PATCH_DEFAULT_BYTES}). */bytes?: number;+ /** Marks the entry failure-atomic: `dispatch` must throw without applying for History to keep it in place. */+ replayFailureAtomic?: boolean;}/** Creates a reversible structural entry that dispatches inverse on undo, forward on redo. */@@ -45,5 +38,6 @@ export const createDocumentPatchEntry = (opts: CreateDocumentPatchEntryOptions):label,redo: () => dispatch(forward),undo: () => dispatch(inverse),+ ...(opts.replayFailureAtomic ? { replayFailureAtomic: true } : {}),};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.tsindex 5b913a1e90..97d93d9f63 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts@@ -66,7 +66,10 @@ const createHarness = (doc: CanvasDocumentContractV2): Harness => {const stores = createEngineStores();const ctx: ToolContext = {backend: null as never,- commitStructural: (label, forward, inverse) => commits.push({ forward, inverse, label }),+ commitStructural: (label, forward, inverse) => {+ commits.push({ forward, inverse, label });+ return { status: 'committed' as const };+ },createLayerId: () => 'x',createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.tsindex bdd06b14ca..8e99f05891 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts@@ -69,7 +69,10 @@ const createHarness = (doc: CanvasDocumentContractV2) => {let idCounter = 0;const ctx: ToolContext = {backend: null as never,- commitStructural: (label, forward, inverse) => commits.push({ forward, inverse, label }),+ commitStructural: (label, forward, inverse) => {+ commits.push({ forward, inverse, label });+ return { status: 'committed' as const };+ },createLayerId: () => `grad-${++idCounter}`,createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.tsindex be4a1edcb5..45ca9b9107 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts@@ -135,7 +135,10 @@ const createHarness = (doc: CanvasDocumentContractV2, options: HarnessOptions =const ctx: ToolContext = {backend: null as never,commitFloatingSelection: commitFloat,- commitStructural: (label, forward, inverse) => commits.push({ forward, inverse, label }),+ commitStructural: (label, forward, inverse) => {+ commits.push({ forward, inverse, label });+ return { status: 'committed' as const };+ },createLayerId: () => 'x',createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.tsindex f422734bc9..f5dcd78744 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts@@ -46,7 +46,10 @@ const createHarness = (doc: CanvasDocumentContractV2) => {let idCounter = 0;const ctx: ToolContext = {backend: null as never,- commitStructural: (label, forward, inverse) => commits.push({ forward, inverse, label }),+ commitStructural: (label, forward, inverse) => {+ commits.push({ forward, inverse, label });+ return { status: 'committed' as const };+ },createLayerId: () => `shape-${++idCounter}`,createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 997948ad58..ebfe020b5b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -13,6 +13,7 @@* Zero React, zero import-time side effects.*/+import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { EngineStores } from '@workbench/canvas-engine/engineStores';import type { CreatePath2D } from '@workbench/canvas-engine/freehand';@@ -99,7 +100,11 @@ export interface ToolContext {* dispatches `forward` now, and an undo dispatches `inverse` / a redo* re-dispatches `forward`. The move tool commits a layer nudge through this.*/- commitStructural(label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation): void;+ commitStructural(+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation+ ): StructuralCommitResult;/*** Sets (or clears with `null`) a transient per-layer transform override the* compositor and overlay read at render time — a live drag preview that neverdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.tsindex 543d325bb4..dd3e9ee906 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts@@ -102,7 +102,7 @@ const createHarness = (order.push('commit');void label;void forward;- return true;+ return { status: 'committed' as const };});const engine = {document: { getDocument },diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex fa1cf21f36..8351170946 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -144,7 +144,7 @@ const setModel = (project: Project, base: GenerateWidgetValues['model']['base'])const engine = (projectId: string,canCommitStructural: CanvasEngine['layers']['canCommitStructural'] = vi.fn(() => true),- commitStructural: CanvasEngine['layers']['commitStructural'] = vi.fn(() => true)+ commitStructural: CanvasEngine['layers']['commitStructural'] = vi.fn(() => ({ status: 'committed' as const }))): CanvasEngine => ({ layers: { canCommitStructural, commitStructural }, projectId }) as unknown as CanvasEngine;const getForwardLayers = (action: WorkbenchAction | CanvasProjectMutation): readonly CanvasLayerContract[] => {@@ -299,11 +299,12 @@ describe('importGalleryImagesToCanvas', () => {}));+ const canvasEngine = engine(project.id);const result = await importGalleryImagesToCanvas({destination: 'control-resized',applyCanvasMutation: (projectId, mutation) =>dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),- engine: null,+ engine: canvasEngine,fetchImage,...queriesFor(() => state),images: [image('wide.png', 1600, 900), image('square.png', 400, 400)],@@ -331,8 +332,8 @@ describe('importGalleryImagesToCanvas', () => {resizeTo: { height: 1024, width: 1024 },}),]);- expect(dispatch).toHaveBeenCalledOnce();- const forward = dispatch.mock.calls[0]![0];+ expect(canvasEngine.layers.commitStructural).toHaveBeenCalledOnce();+ const [, forward] = vi.mocked(canvasEngine.layers.commitStructural).mock.calls[0]!;const layers = getForwardLayers(forward);expect(layers).toEqual([{@@ -354,14 +355,8 @@ describe('importGalleryImagesToCanvas', () => {{ height: 768, imageName: 'resized-wide.png', width: 1360 },{ height: 1024, imageName: 'resized-square.png', width: 1024 },]);- expect(forward).toMatchObject({- mutation: {- selectedLayerId: layers[1]!.id,- type: 'applyCanvasLayerStackMutation',- },- projectId: project.id,- type: 'applyCanvasProjectMutation',- });+ expect(forward).toMatchObject({ selectedLayerId: layers[1]!.id, type: 'applyCanvasLayerStackMutation' });+ expect(dispatch).not.toHaveBeenCalled();});it('returns empty without committing', async () => {@@ -408,9 +403,7 @@ describe('importGalleryImagesToCanvas', () => {const uploadImage = vi.fn<typeof uploadCanvasImage>(() =>Promise.resolve({ height: 512, imageName: 'resized', width: 512 }));- const commitStructural = vi.fn<- (_label: string, _forward: CanvasProjectMutation, _inverse: CanvasProjectMutation) => boolean- >(() => false);+ const commitStructural = vi.fn<CanvasEngine['layers']['commitStructural']>(() => ({ status: 'busy' as const }));const result = await importGalleryImagesToCanvas({destination: 'control-resized',applyCanvasMutation: () => undefined,@@ -492,7 +485,7 @@ describe('importGalleryImagesToCanvas', () => {const other = { ...project, id: 'other-project' };let current = { ...state, activeProjectId: other.id, projects: [project, other] };const dispatch = vi.fn<(action: WorkbenchAction) => void>();- const commitStructural = vi.fn(() => false);+ const commitStructural = vi.fn(() => ({ status: 'busy' as const }));const matchingEngine = engine(project.id,vi.fn(() => true),@@ -568,7 +561,7 @@ describe('importGalleryImagesToCanvas', () => {const firstImport = importGalleryImagesToCanvas({destination: 'control-resized',applyCanvasMutation: () => undefined,- engine: null,+ engine: engine(first.project.id),fetchImage,...queriesFor(() => first.state),images: [image('a.png')],@@ -578,7 +571,7 @@ describe('importGalleryImagesToCanvas', () => {const overlap = await importGalleryImagesToCanvas({destination: 'raster',applyCanvasMutation: () => undefined,- engine: null,+ engine: engine(first.project.id),...queriesFor(() => first.state),images: [image('b.png')],project: first.project,@@ -586,7 +579,7 @@ describe('importGalleryImagesToCanvas', () => {const independent = await importGalleryImagesToCanvas({destination: 'raster',applyCanvasMutation: () => undefined,- engine: null,+ engine: engine(secondProject.id),...queriesFor(() => secondState),images: [image('c.png')],project: secondProject,@@ -655,11 +648,12 @@ describe('importGalleryImagesToCanvas', () => {return Promise.resolve({ height: 512, imageName: `ok-${options!.fileName}`, width: 512 });});const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const canvasEngine = engine(project.id);const importing = importGalleryImagesToCanvas({destination: 'control-resized',applyCanvasMutation: (projectId, mutation) =>dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),- engine: null,+ engine: canvasEngine,fetchImage,...queriesFor(() => state),images: Array.from({ length: 7 }, (_, index) => image(`${index}.png`)),@@ -677,9 +671,9 @@ describe('importGalleryImagesToCanvas', () => {return;}expect(result.failedImageNames).toEqual(['2.png', '5.png']);- expect(dispatch).toHaveBeenCalledOnce();+ expect(canvasEngine.layers.commitStructural).toHaveBeenCalledOnce();expect(- getForwardLayers(dispatch.mock.calls[0]![0]).map((layer) =>+ getForwardLayers(vi.mocked(canvasEngine.layers.commitStructural).mock.calls[0]![1]).map((layer) =>layer.type === 'control' && layer.source.type === 'image' ? layer.source.image.imageName : null)).toEqual(['ok-0.png', 'ok-1.png', 'ok-3.png', 'ok-4.png', 'ok-6.png']);@@ -690,7 +684,7 @@ describe('importGalleryImagesToCanvas', () => {const options = {destination: 'control-resized' as const,applyCanvasMutation: () => undefined,- engine: null,+ engine: engine(project.id),fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),...queriesFor(() => state),images: [image('a.png'), image('b.png')],diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.tsindex 6b5b306dc6..3258db6b7e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts@@ -304,11 +304,13 @@ export const importGalleryImagesToCanvas = async (options: {return { status: 'stale-document' };}- if (matchingProjectEngine && isActiveProject(project.id)) {- if (!matchingProjectEngine.layers.commitStructural('Import gallery images', forward, inverse)) {+ if (isActiveProject(project.id)) {+ const committed = matchingProjectEngine?.layers.commitStructural('Import gallery images', forward, inverse);+ if (committed?.status !== 'committed') {return { status: 'blocked' };}} else {+ // A background project has no live editing session; the import lands as ingestion.applyCanvasMutation(project.id, forward);}return { failedImageNames, layerIds: layers.map((layer) => layer.id), status: 'imported' };diff --git a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.tsindex e2a77f7bf2..aa9ebdcf19 100644--- a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts@@ -1,7 +1,7 @@/*** Pure builders for the structural document edits shared by the layers panel and* the canvas widget's layer hotkeys: each returns the forward + inverse reducer- * action pair for `engine.layers.commitStructural` / `applyStructural`, so the+ * action pair for `engine.layers.commitStructural`, so the* inverse-construction logic lives in exactly one place.** Index convention matches the contract and the layers panel: index 0 is thediff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsxindex b8ecdba3aa..f236159c1b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx@@ -8,6 +8,7 @@ import { Box, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { useModifierHeld } from '@platform/react/useModifierHeld';import { ConfirmDialog, IconButton, MenuContent, Tooltip } from '@platform/ui';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';+import { useNotify } from '@workbench/useNotify';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import {@@ -47,6 +48,7 @@ import {import { useCanvasCanRedo, useCanvasCanUndo, useCanvasDocumentEditingLocked, useCanvasZoom } from './engineStoreHooks';import { computeFitBboxToLayers, computeFitBboxToMasks } from './fitBbox';import { useCanvasEngine } from './useCanvasEngine';+import { reportStructuralCommit } from './useStructuralCommit';import { formatZoomPercent, zoomMenuOptions } from './zoomOptions';type CanvasHeaderEngine = Pick<CanvasEngineHandle, 'diagnostics' | 'history' | 'interaction' | 'layers' | 'viewport'>;@@ -87,6 +89,7 @@ const CanvasHeaderActionsInner = ({runtime: WidgetViewProps['runtime'];}) => {const { t } = useTranslation();+ const notify = useNotify();const dispatch = useCanvasProjectMutationDispatch();const zoom = useCanvasZoom(engine);const canUndo = useCanvasCanUndo(engine);@@ -119,6 +122,7 @@ const CanvasHeaderActionsInner = ({fitLayersRect,fitMasksRect,openNewCanvas,+ reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),t,});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsxindex 42b72878ca..b8958f2f5b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx@@ -17,6 +17,7 @@ vi.mock('@dnd-kit/core', () => ({ useDndMonitor: () => undefined }));vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectId: () => harness.project!.id,useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project!),+ useOptionalWorkbenchCommands: () => null,useWorkbenchCommands: () => ({canvas: { apply: vi.fn() },notifications: { add: vi.fn(), reportError: vi.fn() },diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 954d7ef0b8..6a7a96f01a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -11,6 +11,7 @@ import { getCanvasStagingSlots } from '@workbench/canvasStagingView';import { recordCanvasImportError } from '@workbench/image-actions/canvasImportError';import { useWorkbenchSettingsSelector } from '@workbench/settings/store';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';+import { useNotify } from '@workbench/useNotify';import { CanvasLayerContextMenu } from '@workbench/widgets/layers/LayerContextMenu';import { getProjectWidgetValues } from '@workbench/widgetState';import {@@ -57,6 +58,7 @@ import { ToolStrip } from './ToolStrip';import { useCanvasEngine } from './useCanvasEngine';import { useCanvasGallerySave } from './useCanvasGallerySave';import { useCreateFromBbox } from './useCreateFromBbox';+import { reportStructuralCommit } from './useStructuralCommit';/*** The canvas widget shell. The engine owns pixels and interaction and renders@@ -67,6 +69,7 @@ import { useCreateFromBbox } from './useCreateFromBbox';*/export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const { t } = useTranslation();+ const notify = useNotify();const { canvas: canvasCommands, notifications, queue } = useWorkbenchCommands();const canvasDispatch = useCanvasProjectMutationDispatch();const queries = useWorkbenchQueries();@@ -378,6 +381,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {notifyLayerDuplicateFailed: () =>notifications.add({ kind: 'error', title: t('widgets.layers.actions.copyFailed') }),pasteFromClipboard,+ reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),selectedLayerIds,t,});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsxindex 03f0df1d45..9afdf1295d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx@@ -3,8 +3,11 @@ import type { TextEditSession } from '@workbench/canvas-engine/api';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent } from 'react';+import { useNotify } from '@workbench/useNotify';import { useTextEditSession } from '@workbench/widgets/canvas/engineStoreHooks';+import { reportStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useSyncExternalStore } from 'react';+import { useTranslation } from 'react-i18next';type TextEditEngine = Pick<CanvasEngineHandle, 'interaction' | 'layers' | 'viewport'>;@@ -101,12 +104,18 @@ const TextEditable = ({ engine, session }: TextEditableProps) => {[engine, source.content]);- const onBlur = useCallback(- (event: { currentTarget: HTMLElement }) => {- engine.layers.commitTextEdit(readEditableText(event.currentTarget));+ const notify = useNotify();+ const { t } = useTranslation();+ const commit = useCallback(+ (element: HTMLElement) => {+ const result = engine.layers.commitTextEdit(readEditableText(element));+ if (result) {+ reportStructuralCommit(result, notify.error, t);+ }},- [engine]+ [engine, notify, t]);+ const onBlur = useCallback((event: { currentTarget: HTMLElement }) => commit(event.currentTarget), [commit]);const onKeyDown = useCallback((event: ReactKeyboardEvent<HTMLDivElement>) => {@@ -119,10 +128,10 @@ const TextEditable = ({ engine, session }: TextEditableProps) => {}if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {event.preventDefault();- engine.layers.commitTextEdit(readEditableText(event.currentTarget));+ commit(event.currentTarget);}},- [engine]+ [commit, engine]);const origin = viewport.documentToScreen({ x: transform.x, y: transform.y });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.tsindex 670148b873..34845430ad 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts@@ -29,7 +29,7 @@ const documentOf = (): CanvasDocumentContractV2 =>const createEngine = (viewportSize = { height: 600, width: 800 }) => {const zoomAtPoint = vi.fn();const engine = {- layers: { commitStructural: vi.fn(() => true) },+ layers: { commitStructural: vi.fn(() => ({ status: 'committed' as const })) },viewport: {fitToView: vi.fn(),getViewport: vi.fn(() => ({ getViewportSize: () => viewportSize, zoomAtPoint })),@@ -41,6 +41,7 @@ const createEngine = (viewportSize = { height: 600, width: 800 }) => {let dispatch: Mock<(mutation: CanvasProjectMutation) => boolean>;const contextOf = (overrides: Partial<CanvasHeaderCommandContext> = {}): CanvasHeaderCommandContext => ({+ reportStructuralCommit: () => undefined,dispatch,document: documentOf(),editingLocked: false,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.tsindex 467a54a314..cb9b6a365f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, Rect } from '@workbench/canvas-engine/api';+import type { CanvasDocumentContractV2, Rect, StructuralCommitResult } from '@workbench/canvas-engine/api';import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { createNewCanvasStateV2 } from '@workbench/canvasMigration';@@ -9,7 +9,7 @@ import { createNewCanvasStateV2 } from '@workbench/canvasMigration';*/export interface CanvasHeaderCommandEngine {readonly layers: {- commitStructural(label: string, forward: unknown, inverse: unknown): boolean;+ commitStructural(label: string, forward: unknown, inverse: unknown): StructuralCommitResult;};readonly viewport: {fitToView(): void;@@ -35,6 +35,7 @@ export interface CanvasHeaderCommandContext extends NewCanvasContext {readonly fitMasksRect: Rect | null;/** Opens the confirm dialog. The destructive replace only runs from its confirm. */readonly openNewCanvas: () => void;+ readonly reportStructuralCommit: (result: StructuralCommitResult) => void;readonly t: (key: string) => string;}@@ -55,12 +56,13 @@ export const applyFitBbox = (ctx: CanvasHeaderCommandContext, rect: Rect | null,if (ctx.editingLocked || !rect) {return;}- ctx.engine.layers.commitStructural(+ const result = ctx.engine.layers.commitStructural(ctx.t('widgets.canvas.commands.fitBbox'),{ bbox: rect, type: 'setCanvasBbox' },{ bbox: ctx.document.bbox, type: 'setCanvasBbox' });- if (refit) {+ ctx.reportStructuralCommit(result);+ if (refit && result.status === 'committed') {ctx.engine.viewport.fitToView();}};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex 4da7140058..e6d025ceb4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@ -68,7 +68,7 @@ const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {})),mergeLayerDown: vi.fn(),- nudgeSelectedLayer: vi.fn(),+ nudgeSelectedLayer: vi.fn(() => ({ status: 'committed' as const })),},selection: {deselect: vi.fn(),@@ -89,6 +89,7 @@ let pasteFromClipboard: Mock<() => void>;const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyContext => ({copySelection,dispatch,+ reportStructuralCommit: () => undefined,document: documentOf([rasterLayer('a'), rasterLayer('b')], 'a'),engine: createEngine(),hasSelectedStagedCandidate: false,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex fd068f8adf..af1395aa77 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@ -1,4 +1,4 @@-import type { CanvasDocumentContractV2, CanvasEngine } from '@workbench/canvas-engine/api';+import type { CanvasDocumentContractV2, CanvasEngine, StructuralCommitResult } from '@workbench/canvas-engine/api';import type { LayerReorderKind, StructuralActions } from '@workbench/canvasLayerOps';import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';@@ -70,6 +70,7 @@ export interface CanvasHotkeyContext {readonly copySelection: (cut: boolean) => void;readonly pasteFromClipboard: () => void;readonly notifyLayerDuplicateFailed: () => void;+ readonly reportStructuralCommit: (result: StructuralCommitResult) => void;readonly t: (key: string) => string;}@@ -112,7 +113,11 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC// Arrow-key nudge: engine owns the bounds/lock logic (no-op with no/locked selection).const nudge = NUDGE_DELTAS[commandId];if (nudge) {- engine?.layers.nudgeSelectedLayer(nudge.dx, nudge.dy);+ const nudged = engine?.layers.nudgeSelectedLayer(nudge.dx, nudge.dy);+ // A nudge with nothing eligible selected is an expected no-op; only a broken commit is news.+ if (nudged?.status === 'postcondition-failed') {+ ctx.reportStructuralCommit(nudged);+ }return;}@@ -128,7 +133,9 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCreturn;}const { forward, inverse } = reorderLayerActions(currentIds, nextIds);- engine.layers.commitStructural(t('widgets.canvas.commands.reorderLayer'), forward, inverse);+ ctx.reportStructuralCommit(+ engine.layers.commitStructural(t('widgets.canvas.commands.reorderLayer'), forward, inverse)+ );return;}@@ -140,7 +147,9 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC} else if (engine && selectedLayer && selectedIndex >= 0 && !selectedLayer.isLocked) {const actions = deleteSelectedLayerActions(layers, ctx.selectedLayerIds, selectedLayer.id);if (actions) {- engine.layers.commitStructural(t('widgets.canvas.commands.deleteLayer'), actions.forward, actions.inverse);+ ctx.reportStructuralCommit(+ engine.layers.commitStructural(t('widgets.canvas.commands.deleteLayer'), actions.forward, actions.inverse)+ );}}} else if (commandId === 'canvas.copySelection' || commandId === 'canvas.cutSelection') {@@ -153,16 +162,18 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCconst hideable = layers.filter(isHideableLayer);if (engine && hideable.length > 0) {const nextHidden = hideable.every((layer) => !isLayerHidden(layer));- engine.layers.commitStructural(- t('widgets.canvas.commands.toggleNonRasterLayers'),- {- type: 'setCanvasLayersHidden',- updates: hideable.map((layer) => ({ id: layer.id, isHidden: nextHidden })),- },- {- type: 'setCanvasLayersHidden',- updates: hideable.map((layer) => ({ id: layer.id, isHidden: isLayerHidden(layer) })),- }+ ctx.reportStructuralCommit(+ engine.layers.commitStructural(+ t('widgets.canvas.commands.toggleNonRasterLayers'),+ {+ type: 'setCanvasLayersHidden',+ updates: hideable.map((layer) => ({ id: layer.id, isHidden: nextHidden })),+ },+ {+ type: 'setCanvasLayersHidden',+ updates: hideable.map((layer) => ({ id: layer.id, isHidden: isLayerHidden(layer) })),+ }+ ));}} else if (commandId === 'canvas.resetSelected') {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsxindex 8d0677490a..9b83a437a2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx@@ -5,6 +5,7 @@ import { createListCollection, HStack, NumberInput, Text } from '@chakra-ui/reacimport { ColorPicker, Select } from '@platform/ui';import { useGradientOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -31,6 +32,7 @@ const SELECT_TRIGGER_PROPS = { minW: '6rem' } as const;*/export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {const { t } = useTranslation();+ const commitStructural = useStructuralCommit(engine);const options = useGradientOptions(engine);const sampleColor = useColorSampler(engine);@@ -72,14 +74,14 @@ export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {if (selected && commit) {const before = selected.source;const after: GradientSource = { ...before, angle: next.angle, kind: next.kind, stops: next.stops };- engine.layers.commitStructural(+ commitStructural(t('widgets.canvas.toolOptions.gradientEdit'),{ id: selected.id, source: after, type: 'updateCanvasLayerSource' },{ id: selected.id, source: before, type: 'updateCanvasLayerSource' });}},- [engine, selected, t]+ [commitStructural, engine, selected, t]);const setStopColor = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsxindex ee2854b0a1..12fa183c84 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx@@ -1,6 +1,7 @@import type { NumberInput as ChakraNumberInput } from '@chakra-ui/react';import { HStack, NumberInput, Text } from '@chakra-ui/react';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -21,6 +22,7 @@ interface SelectedTransform {*/export const MoveOptions = ({ engine }: ToolOptionsComponentProps) => {const { t } = useTranslation();+ const commitStructural = useStructuralCommit(engine);const selected = useActiveProjectSelector((project): SelectedTransform | null => {const { document } = project.canvas;@@ -39,13 +41,13 @@ export const MoveOptions = ({ engine }: ToolOptionsComponentProps) => {}const forwardTransform = axis === 'x' ? { x: next } : { y: next };const inverseTransform = axis === 'x' ? { x: selected.x } : { y: selected.y };- engine.layers.commitStructural(+ commitStructural(t('widgets.canvas.toolOptions.movePosition'),{ id: selected.id, patch: { transform: forwardTransform }, type: 'updateCanvasLayer' },{ id: selected.id, patch: { transform: inverseTransform }, type: 'updateCanvasLayer' });},- [engine, selected, t]+ [commitStructural, selected, t]);const onXChange = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsxindex 792451d657..2225aa0ead 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx@@ -6,6 +6,7 @@ import { ColorPicker, Select, ToggleIconButton } from '@platform/ui';import { MAX_SHAPE_STROKE_WIDTH } from '@workbench/canvas-engine/api';import { useShapeOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { PaintBucketIcon, SquareIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';@@ -36,6 +37,7 @@ const SELECT_TRIGGER_PROPS = { minW: '6rem' } as const;*/export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {const { t } = useTranslation();+ const commitStructural = useStructuralCommit(engine);const options = useShapeOptions(engine);const sampleColor = useColorSampler(engine);@@ -83,14 +85,14 @@ export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {if (selected && commit) {const before = selected.source;const after: ShapeSource = { ...before, ...patch };- engine.layers.commitStructural(+ commitStructural(t('widgets.canvas.toolOptions.shapeEdit'),{ id: selected.id, source: after, type: 'updateCanvasLayerSource' },{ id: selected.id, source: before, type: 'updateCanvasLayerSource' });}},- [engine, fill, kind, stroke, strokeWidth, selected, t]+ [commitStructural, engine, fill, kind, selected, stroke, strokeWidth, t]);const onKindChange = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsxindex 8a3ae57e02..b60061433f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx@@ -11,6 +11,7 @@ import {} from '@workbench/canvas-engine/api';import { useTextEditSession, useTextOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';@@ -87,6 +88,7 @@ const AlignButton = ({*/export const TextOptions = ({ engine }: ToolOptionsComponentProps) => {const { t } = useTranslation();+ const commitStructural = useStructuralCommit(engine);const options = useTextOptions(engine);const sampleColor = useColorSampler(engine);const session = useTextEditSession(engine);@@ -143,14 +145,14 @@ export const TextOptions = ({ engine }: ToolOptionsComponentProps) => {if (selected && commit) {const before = selected.source;const after: TextSource = { ...before, ...patch };- engine.layers.commitStructural(+ commitStructural(t('widgets.canvas.toolOptions.textEdit'),{ id: selected.id, source: after, type: 'updateCanvasLayerSource' },{ id: selected.id, source: before, type: 'updateCanvasLayerSource' });}},- [engine, align, color, fontFamily, fontSize, fontWeight, lineHeight, session, selected, t]+ [align, color, commitStructural, engine, fontFamily, fontSize, fontWeight, lineHeight, selected, session, t]);const onFamilyChange = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.tsnew file mode 100644index 0000000000..ad682c10c2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts@@ -0,0 +1,52 @@+import type { StructuralCommitResult } from '@workbench/canvas-engine/api';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';+import type { TFunction } from 'i18next';++import { describe, expect, it, vi } from 'vitest';++import { commitStructuralEdit, reportStructuralCommit } from './useStructuralCommit';++const forward: CanvasProjectMutation = { ids: ['a'], type: 'removeCanvasLayers' };+const inverse: CanvasProjectMutation = { id: 'a', type: 'setCanvasSelectedLayer' };+const t = ((key: string) => key) as unknown as TFunction;++describe('commitStructuralEdit', () => {+ it('routes through the engine and returns its result', () => {+ const commitStructural = vi.fn(() => ({ status: 'committed' as const }));+ const engine = { layers: { commitStructural } } as unknown as CanvasStructuralEngine;++ expect(commitStructuralEdit(engine, 'Delete layer', forward, inverse)).toEqual({ status: 'committed' });+ expect(commitStructural).toHaveBeenCalledWith('Delete layer', forward, inverse);+ });++ it('refuses as not-ready without an engine instead of dispatching unrecorded', () => {+ expect(commitStructuralEdit(null, 'Delete layer', forward, inverse)).toEqual({ status: 'not-ready' });+ });+});++describe('reportStructuralCommit', () => {+ it.each<StructuralCommitResult>([{ status: 'committed' }, { status: 'busy' }])('stays silent for %j', (result) => {+ const report = vi.fn();++ reportStructuralCommit(result, report, t);++ expect(report).not.toHaveBeenCalled();+ });++ it.each<[StructuralCommitResult, string]>([+ [{ status: 'gesture-active' }, 'widgets.canvas.structural.gestureActive'],+ [{ status: 'not-ready' }, 'widgets.canvas.structural.notReady'],+ [{ actualRevision: 2, expectedRevision: 1, status: 'stale' }, 'widgets.canvas.structural.stale'],+ [{ status: 'dispatch-rejected' }, 'widgets.canvas.structural.rejected'],+ [{ recovered: 'reverted', status: 'postcondition-failed' }, 'widgets.canvas.structural.reverted'],+ [{ recovered: 'reverted-unmirrored', status: 'postcondition-failed' }, 'widgets.canvas.structural.unmirrored'],+ [{ recovered: 'unreverted', status: 'postcondition-failed' }, 'widgets.canvas.structural.unverified'],+ ])('explains %j', (result, message) => {+ const report = vi.fn();++ reportStructuralCommit(result, report, t);++ expect(report).toHaveBeenCalledWith('widgets.canvas.structural.failed', message);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.tsnew file mode 100644index 0000000000..da0dd59ead--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts@@ -0,0 +1,78 @@+import type { CanvasStructuralEngine, StructuralCommitResult } from '@workbench/canvas-engine/api';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { TFunction } from 'i18next';++import { useNotify } from '@workbench/useNotify';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++export type StructuralCommit = (+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation+) => StructuralCommitResult;++/** Commits through the engine's guarded history; without a mounted engine there is no transaction context. */+export const commitStructuralEdit = (+ engine: CanvasStructuralEngine | null,+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation+): StructuralCommitResult =>+ engine ? engine.layers.commitStructural(label, forward, inverse) : { status: 'not-ready' };++/**+ * Explains a refused structural edit. `busy` stays silent because an in-flight operation already+ * disables the controls that could reach here; every other refusal drops the edit and says so.+ */+export const reportStructuralCommit = (+ result: StructuralCommitResult,+ reportError: (title: string, message: string) => void,+ t: TFunction+): void => {+ const title = t('widgets.canvas.structural.failed');+ switch (result.status) {+ case 'committed':+ case 'busy':+ return;+ case 'gesture-active':+ reportError(title, t('widgets.canvas.structural.gestureActive'));+ return;+ case 'not-ready':+ reportError(title, t('widgets.canvas.structural.notReady'));+ return;+ case 'stale':+ reportError(title, t('widgets.canvas.structural.stale'));+ return;+ case 'dispatch-rejected':+ reportError(title, t('widgets.canvas.structural.rejected'));+ return;+ case 'postcondition-failed':+ switch (result.recovered) {+ case 'reverted':+ reportError(title, t('widgets.canvas.structural.reverted'));+ return;+ case 'reverted-unmirrored':+ reportError(title, t('widgets.canvas.structural.unmirrored'));+ return;+ case 'unreverted':+ reportError(title, t('widgets.canvas.structural.unverified'));+ }+ }+};++/** A widget-side structural commit that reports the refusals the user needs to hear about. */+export const useStructuralCommit = (engine: CanvasStructuralEngine | null): StructuralCommit => {+ const notify = useNotify();+ const { t } = useTranslation();++ return useCallback(+ (label, forward, inverse) => {+ const result = commitStructuralEdit(engine, label, forward, inverse);++ reportStructuralCommit(result, notify.error, t);+ return result;+ },+ [engine, notify, t]+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsxindex 757d958e40..889aa1e97e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx@@ -58,7 +58,9 @@ const Harness = () => {return {layers: {applyStructuralPreview: apply,- commitStructural: (_label: string, forward: CanvasProjectMutation) => apply(forward),+ commitStructural: (_label: string, forward: CanvasProjectMutation) => ({+ status: apply(forward) ? ('committed' as const) : ('dispatch-rejected' as const),+ }),},} as unknown as CanvasStructuralEngine;}, []);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsxindex 398b648907..7bbfff48f8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx@@ -6,7 +6,7 @@ import type { PointerEvent as ReactPointerEvent } from 'react';import { chakra, createListCollection, HStack, Stack, Text } from '@chakra-ui/react';import { Button, Field, Select, Slider } from '@platform/ui';import { DEFAULT_ADJUSTMENTS, buildCurveLut } from '@workbench/canvas-engine/api';-import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -18,7 +18,7 @@ import {finishCurveDragResult,getCurveGridCoordinates,} from './curveEditorMath';-import { applyStructural, applyStructuralPreview } from './layerOps';+import { applyStructuralPreview } from './layerOps';const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;@@ -86,31 +86,29 @@ interface AdjustmentsControlsProps {type ScalarKey = 'brightness' | 'contrast' | 'saturation';const AdjustmentsControls = ({ adjustments, engine, layer }: AdjustmentsControlsProps) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();- const dispatch = useCanvasProjectMutationDispatch();const patchLive = useCallback((next: CanvasAdjustmentsContract) => {- applyStructuralPreview(engine, dispatch, {+ applyStructuralPreview(engine, {config: { adjustments: next, layerType: 'raster' },id: layer.id,type: 'updateCanvasLayerConfig',});},- [dispatch, engine, layer.id]+ [engine, layer.id]);const commit = useCallback((label: string, next: CanvasAdjustmentsContract, before: CanvasAdjustmentsContract) => {- applyStructural(- engine,- dispatch,+ commitStructural(label,{ config: { adjustments: next, layerType: 'raster' }, id: layer.id, type: 'updateCanvasLayerConfig' },{ config: { adjustments: before, layerType: 'raster' }, id: layer.id, type: 'updateCanvasLayerConfig' });},- [dispatch, engine, layer.id]+ [commitStructural, layer.id]);const handleScalarLive = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex 22699017e5..420bc50beb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -20,13 +20,13 @@ import {import { useModelsSelector } from '@features/models';import { Field, Select, Slider } from '@platform/ui';import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';-import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { getCompatibleControlModels } from './controlModelOptions';import { LayerFilterOperationButton } from './LayerFilterOperationButton';-import { applyStructural, applyStructuralPreview, CONTROL_ADAPTER_DEFAULTS, CONTROL_WEIGHT_BOUNDS } from './layerOps';+import { applyStructuralPreview, CONTROL_ADAPTER_DEFAULTS, CONTROL_WEIGHT_BOUNDS } from './layerOps';import { runLayerFilterOperation } from './layerPropertiesOperation';import { useSelectedMainModel } from './useSelectedMainModel';@@ -69,7 +69,7 @@ interface ControlLayerSettingsProps {*/export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: ControlLayerSettingsProps) => {const { t } = useTranslation();- const dispatch = useCanvasProjectMutationDispatch();+ const commitStructural = useStructuralCommit(engine);const models = useModelsSelector((snapshot) => snapshot.models);const mainModel = useSelectedMainModel();const base = mainModel?.base ?? null;@@ -78,15 +78,13 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contconst commitAdapter = useCallback((next: Partial<CanvasControlAdapterContract>, before: Partial<CanvasControlAdapterContract>, label: string) => {- applyStructural(- engine,- dispatch,+ commitStructural(label,{ config: { adapter: next, layerType: 'control' }, id: layer.id, type: 'updateCanvasLayerConfig' },{ config: { adapter: before, layerType: 'control' }, id: layer.id, type: 'updateCanvasLayerConfig' });},- [dispatch, engine, layer.id]+ [commitStructural, layer.id]);// Adapter kinds supported by the selected base. Z-Image Control is only shown@@ -170,7 +168,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contreturn;}if (- !applyStructuralPreview(engine, dispatch, {+ !applyStructuralPreview(engine, {config: { adapter: { weight: next }, layerType: 'control' },id: layer.id,type: 'updateCanvasLayerConfig',@@ -182,7 +180,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: ContweightBeforeRef.current = adapter.weight;}},- [adapter.weight, dispatch, engine, layer.id]+ [adapter.weight, engine, layer.id]);const handleWeightChangeEnd = useCallback(({ value }: SliderValueChangeDetails) => {@@ -217,7 +215,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contreturn;}if (- !applyStructuralPreview(engine, dispatch, {+ !applyStructuralPreview(engine, {config: { adapter: { beginEndStepPct: [value[0]!, value[1]!] }, layerType: 'control' },id: layer.id,type: 'updateCanvasLayerConfig',@@ -229,7 +227,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: ContrangeBeforeRef.current = adapter.beginEndStepPct;}},- [adapter.beginEndStepPct, dispatch, engine, layer.id]+ [adapter.beginEndStepPct, engine, layer.id]);const handleRangeChangeEnd = useCallback(({ value }: SliderValueChangeDetails) => {@@ -249,9 +247,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contconst handleTransparencyToggle = useCallback(({ checked }: { checked: boolean }) => {- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.control.transparencyEffect'),{config: { layerType: 'control', withTransparencyEffect: checked },@@ -265,7 +261,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont});},- [dispatch, engine, layer.id, t]+ [commitStructural, layer.id, t]);const controlModeCollection = useMemo(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsxindex d3c7e4f757..a77370edaf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx@@ -4,11 +4,11 @@ import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps'import { createListCollection, HStack, Stack } from '@chakra-ui/react';import { Button, ColorPicker, Field, Select, Slider } from '@platform/ui';-import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { applyStructural, applyStructuralPreview } from './layerOps';+import { applyStructuralPreview } from './layerOps';/** The six mask fill styles, matching `CanvasMaskFillContract['style']` / legacy `zFillStyle`. */const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [@@ -36,12 +36,12 @@ interface InpaintMaskSettingsProps {* denoise-limit sliders (0–1), and an in-place mask invert. `noiseLevel` /* `denoiseLimit` are wired to the contract now (consumed by the NEXT task's graph* builder); they have no generation effect yet. Fill/noise/denoise edits go- * through the canvas undo stack (`applyStructural` → `updateCanvasLayerConfig`);+ * through the canvas undo stack (`commitStructural` → `updateCanvasLayerConfig`);* invert is an engine pixel op (its own undoable image patch).*/export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps) => {const { t } = useTranslation();- const dispatch = useCanvasProjectMutationDispatch();+ const commitStructural = useStructuralCommit(engine);const fillBeforeRef = useRef<CanvasMaskFillContract | null>(null);const noiseBeforeRef = useRef<number | null>(null);const denoiseBeforeRef = useRef<number | null>(null);@@ -63,21 +63,19 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)const commitFill = useCallback((next: CanvasMaskFillContract, before: CanvasMaskFillContract) => {- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.maskFill.fill'),{ config: { layerType: 'inpaint_mask', mask: { fill: next } }, id: layer.id, type: 'updateCanvasLayerConfig' },{ config: { layerType: 'inpaint_mask', mask: { fill: before } }, id: layer.id, type: 'updateCanvasLayerConfig' });},- [dispatch, engine, layer.id, t]+ [commitStructural, layer.id, t]);const handleColorChange = useCallback((hex: string) => {if (- !applyStructuralPreview(engine, dispatch, {+ !applyStructuralPreview(engine, {config: { layerType: 'inpaint_mask', mask: { fill: { ...fill, color: hex } } },id: layer.id,type: 'updateCanvasLayerConfig',@@ -89,7 +87,7 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)fillBeforeRef.current = fill;}},- [dispatch, engine, fill, layer.id]+ [engine, fill, layer.id]);const handleColorChangeEnd = useCallback(@@ -118,7 +116,7 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)return;}if (- !applyStructuralPreview(engine, dispatch, {+ !applyStructuralPreview(engine, {config: noiseConfig(next),id: layer.id,type: 'updateCanvasLayerConfig',@@ -130,7 +128,7 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)noiseBeforeRef.current = noiseLevel;}},- [dispatch, engine, layer.id, noiseLevel]+ [engine, layer.id, noiseLevel]);const handleNoiseChangeEnd = useCallback(@@ -141,15 +139,13 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)if (next === undefined || !Number.isFinite(next)) {return;}- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.maskFill.noiseLevel'),{ config: noiseConfig(next), id: layer.id, type: 'updateCanvasLayerConfig' },{ config: noiseConfig(before), id: layer.id, type: 'updateCanvasLayerConfig' });},- [dispatch, engine, layer.id, noiseLevel, t]+ [commitStructural, layer.id, noiseLevel, t]);const handleDenoiseChange = useCallback(@@ -159,7 +155,7 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)return;}if (- !applyStructuralPreview(engine, dispatch, {+ !applyStructuralPreview(engine, {config: denoiseConfig(next),id: layer.id,type: 'updateCanvasLayerConfig',@@ -171,7 +167,7 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)denoiseBeforeRef.current = denoiseLimit;}},- [dispatch, denoiseLimit, engine, layer.id]+ [denoiseLimit, engine, layer.id]);const handleDenoiseChangeEnd = useCallback(@@ -182,15 +178,13 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)if (next === undefined || !Number.isFinite(next)) {return;}- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.maskFill.denoiseLimit'),{ config: denoiseConfig(next), id: layer.id, type: 'updateCanvasLayerConfig' },{ config: denoiseConfig(before), id: layer.id, type: 'updateCanvasLayerConfig' });},- [dispatch, denoiseLimit, engine, layer.id, t]+ [commitStructural, denoiseLimit, layer.id, t]);const handleInvert = useCallback(() => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex e5c406a49b..ce769496e0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -20,6 +20,7 @@ import { deleteLayerActions, duplicateLayerActions } from '@workbench/canvasLayeimport { useNotify } from '@workbench/useNotify';import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';import { useCanvasDocumentEditingLocked, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { publishLayerPanelSelection, readLayerPanelSelection } from '@workbench/workbenchStore';import {@@ -69,7 +70,6 @@ import { copyBlobToClipboard, saveLayerToAssets } from './layerExportActions';import { reorderWithinGroupByKind } from './layerGroups';import { resolveMenuTargetForRender } from './layerMenuState';import {- applyStructural,convertRasterToControl,convertRasterToInpaintMask,convertRasterToRegionalGuidance,@@ -208,6 +208,7 @@ const LayerMenu = ({beforeDangerItems,showGroupLabels,}: LayerMenuProps) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();const projectId = useActiveProjectId();const { widgets } = useWorkbenchCommands();@@ -245,28 +246,24 @@ const LayerMenu = ({const patchBase = useCallback((label: string, forward: Partial<CanvasLayerContract>, inverse: Partial<CanvasLayerContract>) => {- applyStructural(- engine,- dispatch,+ commitStructural(label,{ id: layer.id, patch: forward, type: 'updateCanvasLayer' },{ id: layer.id, patch: inverse, type: 'updateCanvasLayer' });},- [dispatch, engine, layer.id]+ [commitStructural, layer.id]);const patchConfig = useCallback((label: string, forward: LayerConfigPatch, inverse: LayerConfigPatch) => {- applyStructural(- engine,- dispatch,+ commitStructural(label,{ config: forward, id: layer.id, type: 'updateCanvasLayerConfig' },{ config: inverse, id: layer.id, type: 'updateCanvasLayerConfig' });},- [dispatch, engine, layer.id]+ [commitStructural, layer.id]);const reorder = useCallback(@@ -275,15 +272,13 @@ const LayerMenu = ({if (!next) {return;}- applyStructural(- engine,- dispatch,+ commitStructural(label,{ orderedIds: next, type: 'reorderCanvasLayers' },{ orderedIds: layers.map((entry) => entry.id), type: 'reorderCanvasLayers' });},- [dispatch, engine, layer.id, layers]+ [commitStructural, layer.id, layers]);const actionState = useMemo<LayerContextActionState>(@@ -355,13 +350,13 @@ const LayerMenu = ({return;}const { forward, inverse } = duplicateLayerActions(layer.id, createLayerId());- applyStructural(engine, dispatch, t('widgets.layers.actions.duplicate'), forward, inverse);- }, [dispatch, document.selectedLayerId, engine, layer.id, notify, projectId, t]);+ commitStructural(t('widgets.layers.actions.duplicate'), forward, inverse);+ }, [commitStructural, document.selectedLayerId, engine, layer.id, notify, projectId, t]);const handleDelete = useCallback(() => {const { forward, inverse } = deleteLayerActions(layer, index);- applyStructural(engine, dispatch, t('widgets.layers.actions.delete'), forward, inverse);- }, [dispatch, engine, index, layer, t]);+ commitStructural(t('widgets.layers.actions.delete'), forward, inverse);+ }, [commitStructural, index, layer, t]);const handleMerge = useCallback(() => {// Pixel work: engine-only, and not recorded on the undo history.@@ -379,21 +374,11 @@ const LayerMenu = ({if (!copied) {throw new Error(t('widgets.layers.actions.copyFailed'));}- if (engine) {- if (!engine.layers.commitLayerCopy(label, layer.id, copied, index)) {- throw new Error(t('widgets.layers.actions.copyFailed'));- }- return;+ if (!engine?.layers.commitLayerCopy(label, layer.id, copied, index)) {+ throw new Error(t('widgets.layers.actions.copyFailed'));}- applyStructural(- engine,- dispatch,- label,- { index, layer: copied, type: 'addCanvasLayer' },- { ids: [copied.id], type: 'removeCanvasLayers' }- );},- [dispatch, engine, index, layer.id, t]+ [engine, index, layer.id, t]);const convert = useCallback(@@ -411,26 +396,13 @@ const LayerMenu = ({if (!converted) {throw makeStatusError('unsupported');}- if (engine) {- // Pass the immutable live object: the engine rejects stale menu actions- // by identity and clones the inverse contract internally.- if (!engine.layers.commitLayerConversion(label, layer, converted)) {- throw makeStatusError('not-ready');- }- } else {- // Convert in place, preserving the pixel source + id. The inverse restores- // the layer verbatim (adapter/filter config and all).- const original = structuredClone(layer);- applyStructural(- engine,- dispatch,- label,- { id: layer.id, layer: converted, targetType, type: 'convertCanvasLayer' },- { id: layer.id, layer: original, targetType: layer.type, type: 'convertCanvasLayer' }- );+ // Pass the immutable live object: the engine rejects stale menu actions+ // by identity and clones the inverse contract internally.+ if (!engine?.layers.commitLayerConversion(label, layer, converted)) {+ throw makeStatusError('not-ready');}},- [base, defaultControlModel, dispatch, engine, layer, makeStatusError]+ [base, defaultControlModel, engine, layer, makeStatusError]);const handleToggleVisibility = useCallback(() => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsxindex 1ab4b84059..44439a400f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx@@ -44,6 +44,7 @@ vi.mock('@features/models', () => ({vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectId: () => 'project',useActiveProjectSelector: () => null,+ useOptionalWorkbenchCommands: () => null,useWorkbenchCommands: () => ({ canvas: { apply: vi.fn() } }),}));vi.mock('react-i18next', () => ({diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsxindex fae760753d..ed765b94de 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx@@ -12,6 +12,7 @@ import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'import { IconButton, toaster, Tooltip } from '@platform/ui';import { canMergeVisibleRasters } from '@workbench/canvas-engine/api';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectName } from '@workbench/WorkbenchContext';import { ChevronDownIcon, EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';@@ -31,7 +32,6 @@ import {} from './layerGroupActions';import { reorderSelectionWithinGroup } from './layerGroups';import { LayerListItem, type LayerListItemEngine } from './LayerListItem';-import { applyStructural } from './layerOps';import { getPsdExportNoticeKey } from './psdExportNotice';import { useAddLayer } from './useAddLayer';@@ -73,6 +73,7 @@ export const LayerGroupSection = ({selectedIds,selectedLayerId,}: LayerGroupSectionProps) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();const editingLocked = useCanvasDocumentEditingLocked(engine);@@ -102,15 +103,13 @@ export const LayerGroupSection = ({if (!next) {return;}- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.reorder'),{ orderedIds: next, type: 'reorderCanvasLayers' },{ orderedIds: layers.map((layer) => layer.id), type: 'reorderCanvasLayers' });},- [dispatch, editingLocked, engine, layers, selectedIds, t]+ [commitStructural, editingLocked, layers, selectedIds, t]);const handleToggleCollapse = useCallback(() => onToggleCollapse(groupKey), [groupKey, onToggleCollapse]);@@ -155,7 +154,6 @@ export const LayerGroupSection = ({{t(`widgets.layers.groups.${groupKey}`)} ({groupLayers.length})</Text><GroupActions- dispatch={dispatch}engine={engine}editingLocked={editingLocked}groupKey={groupKey}@@ -205,20 +203,19 @@ export const LayerGroupSection = ({* array + this switch — no new prop wiring.*/const GroupActions = ({- dispatch,editingLocked,engine,groupKey,groupLayers,layers,}: {- dispatch: Dispatch<CanvasProjectMutation>;editingLocked: boolean;engine: LayerGroupEngine | null;groupKey: LayerGroupKey;groupLayers: readonly CanvasLayerContract[];layers: readonly CanvasLayerContract[];}) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();const addLayer = useAddLayer();const projectName = useActiveProjectName();@@ -243,9 +240,7 @@ const GroupActions = ({if (forward.length === 0) {return;}- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.groupActions.toggleHidden'),{ type: 'setCanvasLayersHidden', updates: forward },{ type: 'setCanvasLayersHidden', updates: inverse }@@ -253,14 +248,12 @@ const GroupActions = ({return;}const { forward, inverse } = planGroupVisibilityToggle(groupLayers);- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.groupActions.toggleVisibility'),{ type: 'setCanvasLayersEnabled', updates: forward },{ type: 'setCanvasLayersEnabled', updates: inverse });- }, [dispatch, engine, groupKey, groupLayers, t]);+ }, [commitStructural, groupKey, groupLayers, t]);const handleMergeVisible = useCallback(() => {if (!engine) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsxindex 1dd8fafcbe..b54553d7b9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx@@ -107,7 +107,10 @@ const Harness = () => {() =>({layers: {- commitStructural: (_label: string, mutation: CanvasProjectMutation) => dispatch(mutation),+ commitStructural: (_label: string, mutation: CanvasProjectMutation) => {+ dispatch(mutation);+ return { status: 'committed' as const };+ },},previews: {drawLayerThumbnail: () => false,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsxindex 7e73544ca8..d68693e70f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx@@ -9,6 +9,7 @@ import { CSS } from '@dnd-kit/utilities';import { IconButton, Row, ToggleDot } from '@platform/ui';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { isHideableLayer, isLayerHidden } from '@workbench/canvas-engine/api';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { EyeIcon, EyeOffIcon, LockIcon, LockOpenIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -23,7 +24,6 @@ import {type LayerContextMenuEngine,} from './LayerContextMenu';import { createLayerMenuTargetFromContextEvent } from './layerMenuState';-import { applyStructural } from './layerOps';import { LayerPropertiesPopover, type LayerPropertiesEngine } from './LayerPropertiesPopover';import { LayerThumbnail } from './LayerThumbnail';@@ -111,6 +111,7 @@ export const LayerListItem = ({layers,onSelect,}: LayerListItemProps) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();const interaction = getLayerListItemInteractionState(editingLocked);const { attributes, isDragging, listeners, setActivatorNodeRef, setNodeRef, transform, transition } = useSortable({@@ -149,15 +150,13 @@ export const LayerListItem = ({const patchBase = useCallback((label: string, forward: Partial<CanvasLayerContract>, inverse: Partial<CanvasLayerContract>) => {- applyStructural(- engine,- dispatch,+ commitStructural(label,{ id: layer.id, patch: forward, type: 'updateCanvasLayer' },{ id: layer.id, patch: inverse, type: 'updateCanvasLayer' });},- [dispatch, engine, layer.id]+ [commitStructural, layer.id]);const handleToggleVisible = useCallback(@@ -171,15 +170,13 @@ export const LayerListItem = ({(event: { stopPropagation: () => void }) => {event.stopPropagation();const isHidden = !isLayerHidden(layer);- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.toggleHidden'),{ type: 'setCanvasLayersHidden', updates: [{ id: layer.id, isHidden }] },{ type: 'setCanvasLayersHidden', updates: [{ id: layer.id, isHidden: !isHidden }] });},- [dispatch, engine, layer, t]+ [commitStructural, layer, t]);const handleToggleLock = useCallback(@@ -396,7 +393,7 @@ export const LayerListItem = ({onContextMenu={stopPropagation}onPointerDown={stopPropagation}>- <LayerPropertiesPopover dispatch={dispatch} engine={engine} layer={layer} />+ <LayerPropertiesPopover engine={engine} layer={layer} /></Box><Box display="flex" flexShrink="0" onPointerDown={stopPropagation}><LayerContextMenu dispatch={dispatch} engine={engine} index={index} layer={layer} layers={layers} />diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsxindex 6ff2579ff6..f3c9e6b5ba 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx@@ -1,6 +1,4 @@-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';-import type { Dispatch } from 'react';import { HStack, Text } from '@chakra-ui/react';import { toaster } from '@platform/ui';@@ -9,6 +7,7 @@ import { Tooltip } from '@platform/ui/Tooltip';import { canMergeSelectedRasters, type CanvasLayerContract } from '@workbench/canvas-engine/api';import { reorderSelectionWithinGroupsByKind, type LayerReorderKind } from '@workbench/canvasLayerOps';import { useCanvasRasterContentEpoch } from '@workbench/widgets/canvas/engineStoreHooks';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { publishLayerPanelSelection } from '@workbench/workbenchStore';import {ArrowDownIcon,@@ -32,7 +31,6 @@ type MultiSelectionEngine = Pick<CanvasEngineHandle, 'exports' | 'interaction' |const BULK_TOOLTIP_POSITIONING = { placement: 'top' } as const;interface LayerMultiSelectionActionsProps {- dispatch: Dispatch<CanvasProjectMutation>;editingLocked: boolean;engine: MultiSelectionEngine | null;layers: readonly CanvasLayerContract[];@@ -41,22 +39,7 @@ interface LayerMultiSelectionActionsProps {selectedLayerId: string | null;}-const applyBulkStructural = (- engine: MultiSelectionEngine | null,- dispatch: Dispatch<CanvasProjectMutation>,- label: string,- forward: CanvasProjectMutation,- inverse: CanvasProjectMutation-): void => {- if (engine) {- engine.layers.commitStructural(label, forward, inverse);- } else {- dispatch(forward);- }-};-export const LayerMultiSelectionActions = ({- dispatch,editingLocked,engine,layers,@@ -64,6 +47,7 @@ export const LayerMultiSelectionActions = ({selectedIds,selectedLayerId,}: LayerMultiSelectionActionsProps) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();useCanvasRasterContentEpoch(engine);const selected = useMemo(() => {@@ -121,15 +105,13 @@ export const LayerMultiSelectionActions = ({if (!next) {return;}- applyBulkStructural(- engine,- dispatch,+ commitStructural(label,{ orderedIds: next, type: 'reorderCanvasLayers' },{ orderedIds: layers.map((layer) => layer.id), type: 'reorderCanvasLayers' });},- [dispatch, engine, layers, selectedIds]+ [commitStructural, layers, selectedIds]);const moveToFront = useCallback(@@ -148,9 +130,7 @@ export const LayerMultiSelectionActions = ({const toggleEnabled = useCallback(() => {const isEnabled = !allEnabled;- applyBulkStructural(- engine,- dispatch,+ commitStructural(t(isEnabled ? 'widgets.layers.actions.enableSelected' : 'widgets.layers.actions.disableSelected'),{ type: 'setCanvasLayersEnabled', updates: selected.map((layer) => ({ id: layer.id, isEnabled })) },{@@ -158,13 +138,11 @@ export const LayerMultiSelectionActions = ({updates: selected.map((layer) => ({ id: layer.id, isEnabled: layer.isEnabled })),});- }, [allEnabled, dispatch, engine, selected, t]);+ }, [allEnabled, commitStructural, selected, t]);const toggleLocked = useCallback(() => {const isLocked = !allLocked;- applyBulkStructural(- engine,- dispatch,+ commitStructural(t(isLocked ? 'widgets.layers.actions.lockSelected' : 'widgets.layers.actions.unlockSelected'),{enabledUpdates: [],@@ -177,20 +155,14 @@ export const LayerMultiSelectionActions = ({type: 'applyCanvasLayerStackMutation',});- }, [allLocked, dispatch, engine, selected, t]);+ }, [allLocked, commitStructural, selected, t]);const deleteSelected = useCallback(() => {const actions = deleteLayersActions(layers, selectedIds, selectedLayerId);if (actions) {- applyBulkStructural(- engine,- dispatch,- t('widgets.layers.actions.deleteSelected'),- actions.forward,- actions.inverse- );+ commitStructural(t('widgets.layers.actions.deleteSelected'), actions.forward, actions.inverse);}- }, [dispatch, engine, layers, selectedIds, selectedLayerId, t]);+ }, [commitStructural, layers, selectedIds, selectedLayerId, t]);return (<HStackdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsxindex f68adfb307..d2d73f7852 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerPropertiesPopover.tsx@@ -1,11 +1,10 @@import type { CanvasLayerContract } from '@workbench/canvas-engine/api';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';-import type { Dispatch } from 'react';import { Box, Popover, Portal, Stack, Switch, Text } from '@chakra-ui/react';import { IconButton } from '@platform/ui';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { SlidersHorizontalIcon } from 'lucide-react';import { useCallback, useState } from 'react';@@ -16,7 +15,6 @@ import type { LayerPropertiesRequest } from './layerPropertiesRequestStore';import { AdjustmentsPopover } from './AdjustmentsPopover';import { ControlLayerSettings } from './ControlLayerSettings';import { InpaintMaskSettings } from './InpaintMaskSettings';-import { applyStructural } from './layerOps';import {closeLayerPropertiesForOperation,getLayerPropertiesOwnershipKey,@@ -36,7 +34,6 @@ const POPOVER_POSITIONING = { placement: 'left-start' } as const;const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();interface LayerPropertiesPopoverProps {- dispatch: Dispatch<CanvasProjectMutation>;engine: LayerPropertiesEngine | null;layer: CanvasLayerContract;}@@ -68,7 +65,6 @@ export const LayerPropertiesPopover = (props: LayerPropertiesPopoverProps) => {};const LayerPropertiesPopoverOwnership = ({- dispatch,editingLocked,engine,layer,@@ -133,7 +129,6 @@ const LayerPropertiesPopoverOwnership = ({<Popover.Body p="2.5"><Stack gap="2" inert={editingLocked}><LayerTypeSettings- dispatch={dispatch}documentRevision={documentRevision}engine={engine}layer={layer}@@ -151,13 +146,11 @@ const LayerPropertiesPopoverOwnership = ({/** Dispatches to the correct per-type settings block for the layer. */const LayerTypeSettings = ({- dispatch,documentRevision,engine,layer,onOperationStarted,}: {- dispatch: Dispatch<CanvasProjectMutation>;documentRevision: number;engine: LayerPropertiesEngine | null;layer: CanvasLayerContract;@@ -176,7 +169,6 @@ const LayerTypeSettings = ({return (<RasterLayerSettingskey={`${engine?.projectId ?? 'none'}-${layer.id}-${documentRevision}`}- dispatch={dispatch}engine={engine}layer={layer}onOperationStarted={onOperationStarted}@@ -187,24 +179,21 @@ const LayerTypeSettings = ({/** Raster-layer properties: transparency lock + non-destructive adjustments. */const RasterLayerSettings = ({- dispatch,engine,layer,onOperationStarted,}: {- dispatch: Dispatch<CanvasProjectMutation>;engine: LayerPropertiesEngine | null;layer: Extract<CanvasLayerContract, { type: 'raster' }>;onOperationStarted(): void;}) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();const isLocked = layer.isTransparencyLocked === true;const handleTransparencyLock = useCallback((details: { checked: boolean }) => {- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.adjustments.transparencyLock'),{config: { isTransparencyLocked: details.checked, layerType: 'raster' },@@ -218,7 +207,7 @@ const RasterLayerSettings = ({});},- [dispatch, engine, isLocked, layer.id, t]+ [commitStructural, isLocked, layer.id, t]);return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsxindex 347a533ce6..6a5b45c012 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx@@ -4,14 +4,11 @@ import type {SliderValueChangeDetails,} from '@chakra-ui/react';import type { CanvasBlendMode, CanvasLayerContract, CanvasMaskFillContract } from '@workbench/canvas-engine/api';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';-import type { Dispatch } from 'react';import { Box, createListCollection, Flex, HStack, NumberInput, Stack } from '@chakra-ui/react';import { useDebouncedDraftValue, useRegisterGenerateDraftFlusher } from '@features/generation/react';import { ColorPicker, Field, Select, Slider } from '@platform/ui';-import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';import {CANVAS_DENOISING_STRENGTH_KEY,@@ -21,13 +18,14 @@ import {readCanvasDenoisingStrength,} from '@workbench/widgets/canvas/invoke/canvasStrength';import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { DenoisingStrengthWave } from './DenoisingStrengthWave';-import { applyStructural, applyStructuralPreview, CANVAS_BLEND_MODES } from './layerOps';+import { applyStructuralPreview, CANVAS_BLEND_MODES } from './layerOps';type LayersPanelHeaderEngine = Pick<CanvasEngineHandle, 'interaction' | 'layers'>;@@ -71,7 +69,6 @@ export const isLayerEditingDisabled = (layer: CanvasLayerContract | null, editin*/export const LayersPanelHeader = () => {const engine = useCanvasEngine();- const dispatch = useCanvasProjectMutationDispatch();const layer = useActiveProjectSelector(selectSelectedLayer, isSameSelection);const editingLocked = useCanvasDocumentEditingLocked(engine);@@ -82,8 +79,8 @@ export const LayersPanelHeader = () => {</Box><Box borderBottomWidth={1} px="1.5" py="1"><Flex align="center" gap="2">- <BlendModeControl dispatch={dispatch} editingLocked={editingLocked} engine={engine} layer={layer} />- <OpacityRow dispatch={dispatch} editingLocked={editingLocked} engine={engine} layer={layer} />+ <BlendModeControl editingLocked={editingLocked} engine={engine} layer={layer} />+ <OpacityRow editingLocked={editingLocked} engine={engine} layer={layer} /></Flex></Box></Stack>@@ -96,16 +93,15 @@ interface BlendModeOption {}const BlendModeControl = ({- dispatch,editingLocked,engine,layer,}: {- dispatch: Dispatch<CanvasProjectMutation>;editingLocked: boolean;engine: LayersPanelHeaderEngine | null;layer: CanvasLayerContract | null;}) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();const disabled = isLayerEditingDisabled(layer, editingLocked);const blendMode = layer?.blendMode ?? 'normal';@@ -124,15 +120,13 @@ const BlendModeControl = ({if (!layer || !mode || mode === layer.blendMode) {return;}- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.blendMode'),{ id: layer.id, patch: { blendMode: mode }, type: 'updateCanvasLayer' },{ id: layer.id, patch: { blendMode: layer.blendMode }, type: 'updateCanvasLayer' });},- [dispatch, engine, layer, t]+ [commitStructural, layer, t]);return (@@ -154,16 +148,15 @@ const BlendModeControl = ({};const OpacityRow = ({- dispatch,editingLocked,engine,layer,}: {- dispatch: Dispatch<CanvasProjectMutation>;editingLocked: boolean;engine: LayersPanelHeaderEngine | null;layer: CanvasLayerContract | null;}) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();// The uncommitted opacity edit: captured once per gesture. `before` is the// pre-gesture value (the undo target); `latest` tracks the live value because@@ -182,14 +175,12 @@ const OpacityRow = ({if (!pending || pending.before === pending.latest) {return;}- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.opacity'),{ id: pending.id, patch: { opacity: pending.latest }, type: 'updateCanvasLayer' },{ id: pending.id, patch: { opacity: pending.before }, type: 'updateCanvasLayer' });- }, [dispatch, engine, t]);+ }, [commitStructural, t]);const handleOpacityChange = useCallback(({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {@@ -203,7 +194,7 @@ const OpacityRow = ({}const next = clamp01(valueAsNumber / 100);if (- !applyStructuralPreview(engine, dispatch, {+ !applyStructuralPreview(engine, {id: layer.id,patch: { opacity: next },type: 'updateCanvasLayer',@@ -217,7 +208,7 @@ const OpacityRow = ({pendingRef.current.latest = next;}},- [commitPending, dispatch, engine, layer]+ [commitPending, engine, layer]);// Commit per completed interaction: each spinner click (fires on release, so a@@ -264,9 +255,7 @@ const OpacityRow = ({onKeyUp={handleInputKeyUp}/></NumberInput.Root>- {isMaskLayer(layer) ? (- <MaskFillSwatch disabled={editingLocked} dispatch={dispatch} engine={engine} layer={layer} />- ) : null}+ {isMaskLayer(layer) ? <MaskFillSwatch disabled={editingLocked} engine={engine} layer={layer} /> : null}</HStack></Field>);@@ -278,16 +267,15 @@ const OpacityRow = ({* final colour lands as one undoable history entry, mirroring the slider pattern.*/const MaskFillSwatch = ({- dispatch,disabled,engine,layer,}: {- dispatch: Dispatch<CanvasProjectMutation>;disabled: boolean;engine: LayersPanelHeaderEngine | null;layer: MaskLayer;}) => {+ const commitStructural = useStructuralCommit(engine);const { t } = useTranslation();const fillBeforeRef = useRef<CanvasMaskFillContract | null>(null);const fill = layer.mask.fill;@@ -302,15 +290,13 @@ const MaskFillSwatch = ({layer.type === 'inpaint_mask'? ({ layerType: 'inpaint_mask', mask: { fill: before } } as const): ({ layerType: 'regional_guidance', mask: { fill: before } } as const);- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.maskFill.fill'),{ config, id: layer.id, type: 'updateCanvasLayerConfig' },{ config: inverseConfig, id: layer.id, type: 'updateCanvasLayerConfig' });},- [dispatch, engine, layer.id, layer.type, t]+ [commitStructural, layer.id, layer.type, t]);const handleColorChange = useCallback(@@ -320,14 +306,14 @@ const MaskFillSwatch = ({layer.type === 'inpaint_mask'? ({ layerType: 'inpaint_mask', mask: { fill: next } } as const): ({ layerType: 'regional_guidance', mask: { fill: next } } as const);- if (!applyStructuralPreview(engine, dispatch, { config, id: layer.id, type: 'updateCanvasLayerConfig' })) {+ if (!applyStructuralPreview(engine, { config, id: layer.id, type: 'updateCanvasLayerConfig' })) {return;}if (fillBeforeRef.current === null) {fillBeforeRef.current = fill;}},- [dispatch, engine, fill, layer.id, layer.type]+ [engine, fill, layer.id, layer.type]);const handleColorChangeEnd = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsxindex b4c5d2303e..1739626782 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx@@ -86,7 +86,6 @@ export const LayersWidgetView = () => {<LayersPanelHeader />{selectedIds.length > 1 ? (<LayerMultiSelectionActions- dispatch={dispatch}editingLocked={editingLocked}engine={engine}layers={layers}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex 88fb24ee2f..1dd292e88a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -26,13 +26,13 @@ import {import { Button, ColorPicker, DropZone, Field, Select, Slider } from '@platform/ui';import { useQueryClient } from '@tanstack/react-query';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';-import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useWorkbenchCommands } from '@workbench/WorkbenchContext';import { ImageIcon, PlusIcon, XIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { applyStructural, applyStructuralPreview, createRegionalReferenceImage } from './layerOps';+import { applyStructuralPreview, createRegionalReferenceImage } from './layerOps';import { useSelectedModelBase } from './useSelectedModelBase';/** The regional-guidance fields patchable via `updateCanvasLayerConfig`. */@@ -90,12 +90,12 @@ interface RegionalGuidanceSettingsProps {* positive + negative prompt, an Auto-Negative toggle, the mask fill colour/style* + invert, and a per-region reference-images section (add/remove/enable + model* + weight, mirroring the generate widget's IP-Adapter fields). Prompt/toggle/fill- * edits go through the canvas undo stack (`applyStructural` →+ * edits go through the canvas undo stack (`commitStructural` →* `updateCanvasLayerConfig`); invert is an engine pixel op.*/export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettingsProps) => {const { t } = useTranslation();- const dispatch = useCanvasProjectMutationDispatch();+ const commitStructural = useStructuralCommit(engine);const { notifications } = useWorkbenchCommands();const queryClient = useQueryClient();const models = useModelsSelector((snapshot) => snapshot.models);@@ -116,15 +116,13 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst commitConfig = useCallback((label: string, next: RegionalConfigPatch, before: RegionalConfigPatch) => {- applyStructural(- engine,- dispatch,+ commitStructural(label,{ config: { layerType: 'regional_guidance', ...next }, id: layer.id, type: 'updateCanvasLayerConfig' },{ config: { layerType: 'regional_guidance', ...before }, id: layer.id, type: 'updateCanvasLayerConfig' });},- [dispatch, engine, layer.id]+ [commitStructural, layer.id]);const handlePositiveBlur = useCallback(@@ -203,7 +201,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst handleColorChange = useCallback((hex: string) => {if (- !applyStructuralPreview(engine, dispatch, {+ !applyStructuralPreview(engine, {config: { layerType: 'regional_guidance', mask: { fill: { ...fill, color: hex } } },id: layer.id,type: 'updateCanvasLayerConfig',@@ -215,7 +213,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettfillBeforeRef.current = fill;}},- [dispatch, engine, fill, layer.id]+ [engine, fill, layer.id]);const handleColorChangeEnd = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.tsindex b69b2094aa..f34093bc6c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts@@ -1,11 +1,9 @@import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { describe, expect, it, vi } from 'vitest';import {applyStructuralPreview,- applyStructural,type CanvasStructuralEngine,canConvertRasterControl,canMergeLayerDown,@@ -171,42 +169,19 @@ describe('canMergeLayerDown', () => {});});-describe('applyStructural', () => {- const forward: CanvasProjectMutation = { ids: ['a'], type: 'removeCanvasLayers' };- const inverse: CanvasProjectMutation = { index: 0, layer: paintLayer('a'), type: 'addCanvasLayer' };-- it('routes through the engine history when an engine is attached', () => {- const commitStructural = vi.fn();- const engine = { layers: { commitStructural } } as unknown as CanvasStructuralEngine;- const dispatch = vi.fn();-- applyStructural(engine, dispatch, 'Delete layer', forward, inverse);-- expect(commitStructural).toHaveBeenCalledWith('Delete layer', forward, inverse);- expect(dispatch).not.toHaveBeenCalled();- });-- it('falls back to a plain forward dispatch without an engine', () => {- const dispatch = vi.fn();-- applyStructural(null, dispatch, 'Delete layer', forward, inverse);-- expect(dispatch).toHaveBeenCalledWith(forward);- expect(dispatch).toHaveBeenCalledTimes(1);- });-});-describe('applyStructuralPreview', () => {+ const action = { id: 'layer', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' } as const;+it('routes a live document edit through the engine guard', () => {- const action = { id: 'layer', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' } as const;const applyPreview = vi.fn(() => false);const engine = { layers: { applyStructuralPreview: applyPreview } } as unknown as CanvasStructuralEngine;- const dispatch = vi.fn();-- expect(applyStructuralPreview(engine, dispatch, action)).toBe(false);+ expect(applyStructuralPreview(engine, action)).toBe(false);expect(applyPreview).toHaveBeenCalledWith(action);- expect(dispatch).not.toHaveBeenCalled();+ });++ it('refuses a live edit without an engine', () => {+ expect(applyStructuralPreview(null, action)).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex af3f1e5dc1..e49baddcf9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -1,8 +1,6 @@/*** Shared helpers for the layers panel: id minting, the paint-layer factory, the- * blend-mode list, merge-down eligibility, and the single seam that routes a- * structural edit either through the engine's canvas history (when an engine is- * attached) or as a plain reducer dispatch (when it is not).+ * blend-mode list, merge-down eligibility, and guarded live previews.*/import type {@@ -12,20 +10,19 @@ import type {CanvasImageRef,CanvasInpaintMaskLayerContract,CanvasLayerBaseContract,- CanvasLayerCapability,CanvasLayerContract,CanvasLayerSourceContract,CanvasMaskContract,CanvasMaskFillContract,CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,+ CanvasStructuralEngine,RegionalGuidanceReferenceImage,Rect,} from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { Dispatch } from 'react';-export type CanvasStructuralEngine = { readonly layers: CanvasLayerCapability };+export type { CanvasStructuralEngine } from '@workbench/canvas-engine/api';import { getSourceContentRect, isMergeableRasterLayer } from '@workbench/canvas-engine/api';import { CONTROL_ADAPTER_DEFAULTS } from '@workbench/controlAdapters';@@ -648,34 +645,6 @@ export const canMergeLayerDown = (return !!layer && !!below && isMergeableRasterLayer(layer) && isMergeableRasterLayer(below);};-/**- * Applies a structural document edit. With an engine attached it goes through- * `commitStructural`, joining the canvas undo stack; without one it is a plain- * dispatch (no undo entry — acceptable when the canvas is not mounted).- */-export const applyStructural = (- engine: CanvasStructuralEngine | null,- dispatch: Dispatch<CanvasProjectMutation>,- label: string,- forward: CanvasProjectMutation,- inverse: CanvasProjectMutation-): void => {- if (engine) {- engine.layers.commitStructural(label, forward, inverse);- } else {- dispatch(forward);- }-};-/** Applies a guarded live edit without recording history until the interaction ends. */-export const applyStructuralPreview = (- engine: CanvasStructuralEngine | null,- dispatch: Dispatch<CanvasProjectMutation>,- action: CanvasProjectMutation-): boolean => {- if (engine) {- return engine.layers.applyStructuralPreview(action);- }- dispatch(action);- return true;-};+export const applyStructuralPreview = (engine: CanvasStructuralEngine | null, action: CanvasProjectMutation): boolean =>+ engine?.layers.applyStructuralPreview(action) ?? false;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.tsindex 0ca16114ea..4a3e6d9818 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts@@ -1,6 +1,6 @@import { useModelsSelector } from '@features/models';-import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';+import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { nextLayerName } from '@workbench/workbenchState';import { useCallback } from 'react';@@ -11,7 +11,6 @@ import type { AddLayerItemId } from './addLayerMenu';import { isAddLayerItemAvailable } from './addLayerMenu';import { resolveDefaultControlModelForBase } from './controlModelOptions';import {- applyStructural,createControlLayer,createEmptyPaintLayer,createInpaintMaskLayer,@@ -25,14 +24,14 @@ import { useSelectedModelBase } from './useSelectedModelBase';/*** Returns a single `addLayer(id)` callback that creates a new layer of the given- * kind at the top of the stack via the shared `applyStructural` seam (one undoable+ * kind at the top of the stack through the guarded structural commit (one undoable* history entry per add). Reused by the panel's add-layer menu AND each group* header's "New" button so both surfaces stay in lockstep.*/export const useAddLayer = (): ((id: AddLayerItemId) => void) => {const { t } = useTranslation();const engine = useCanvasEngine();- const dispatch = useCanvasProjectMutationDispatch();+ const commitStructural = useStructuralCommit(engine);const base = useSelectedModelBase();const models = useModelsSelector((snapshot) => snapshot.models);const layerNames = useActiveProjectSelector(@@ -51,9 +50,7 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {switch (id) {case 'raster': {const layer = createEmptyPaintLayer(nextLayerName(layerNames));- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.addRasterLayer'),{ index: 0, layer, type: 'addCanvasLayer' },{ ids: [layer.id], type: 'removeCanvasLayers' }@@ -67,9 +64,7 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {base,resolveDefaultControlModelForBase(models, base));- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.addControlLayer'),{ index: 0, layer, type: 'addCanvasLayer' },{ ids: [layer.id], type: 'removeCanvasLayers' }@@ -78,9 +73,7 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {}case 'inpaint_mask': {const layer = createInpaintMaskLayer(nextInpaintMaskName(layerNames));- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.addInpaintMask'),{ index: 0, layer, type: 'addCanvasLayer' },{ ids: [layer.id], type: 'removeCanvasLayers' }@@ -89,9 +82,7 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {}case 'regional_guidance': {const layer = createRegionalGuidanceLayer(nextRegionalGuidanceName(layerNames), regionalGuidanceCount);- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.addRegionalGuidance'),{ index: 0, layer, type: 'addCanvasLayer' },{ ids: [layer.id], type: 'removeCanvasLayers' }@@ -104,9 +95,7 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {regionalGuidanceCount,base);- applyStructural(- engine,- dispatch,+ commitStructural(t('widgets.layers.actions.addRegionalReferenceImage'),{ index: 0, layer, type: 'addCanvasLayer' },{ ids: [layer.id], type: 'removeCanvasLayers' }@@ -115,6 +104,6 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {}}},- [base, dispatch, engine, layerNames, models, regionalGuidanceCount, t]+ [base, commitStructural, layerNames, models, regionalGuidanceCount, t]);};