Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(canvas): close the seam gaps the enforcement named
Josh Corbett18ab1607eda6
diff --git a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.tsindex 3ee7985636..bd313401a5 100644--- a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts+++ b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts@@ -19,26 +19,22 @@ afterAll(closeSourceAnalysis);/** Modules that may take part in stack order and selection repair: the reducer and the document seam. */const DOCUMENT_SEAM_OWNERS = [/^workbench\/canvasProjectMutations\.ts$/,- /^workbench\/canvas-engine\/(?:api|capabilities)\.ts$/,/^workbench\/canvas-engine\/document\//,/^workbench\/canvas-engine\/document-model\//,];/** Modules whose namespace import would hide a seam-only symbol behind a qualifier. */const SEAM_MODULES = [- 'workbench/canvas-engine/api',- 'workbench/canvas-engine/capabilities','workbench/canvas-engine/document/layerStacks','workbench/canvas-engine/document/selectionRepair',];/**- * Mutations that restructure the layer list. Outside the engine and the reducer they may only be- * built by gallery import, which ingests into projects that have no mounted engine, and by the- * new-canvas confirmation, which swaps the whole document rather than editing layers. The engine- * grant covers every engine module: tools and raster controllers still dispatch some of these- * through the mutation port rather than the structural controller, which is engine-owned but not- * yet the single transaction module. The scan matches the formatted literal `type: '…'`.+ * Mutations that restructure the layer list. Outside the engine and the reducer only gallery import+ * builds them, because it ingests into projects that have no mounted engine. The engine grant covers+ * every engine module: controllers build these as forward/inverse pairs for the prepared-dispatch+ * protocol, history replays them raw, and the paint tool creates and rolls back its auto-created+ * layer outside history by design. The scan matches the formatted literal `type: '…'`.*/const STRUCTURAL_MUTATION_TYPES = ['addCanvasLayer',@@ -60,7 +56,6 @@ const STRUCTURAL_MUTATION_OWNERS = [/^workbench\/canvasProjectMutations\.ts$/,/^workbench\/canvas-engine\//,/^workbench\/canvas-operations\/importGalleryImages\.ts$/,- /^workbench\/widgets\/canvas\/canvasHeaderCommands\.ts$/,];const structuralLiteral = new RegExp(`type: '(?:${STRUCTURAL_MUTATION_TYPES.join('|')})'`, 'g');diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.tsindex f7a64e7ede..3cf2663774 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts@@ -143,6 +143,19 @@ describe('dependency policy rules', () => {);});+ it('lets the reducer share the document seam helpers without widening the public API', () => {+ const reducer = 'workbench/canvasProjectMutations.ts';+ expect(checkDependency(reducer, '@workbench/canvas-engine/document/layerStacks')).toEqual([]);+ expect(checkDependency(reducer, '@workbench/canvas-engine/document/selectionRepair')).toEqual([]);+ expect(checkDependency(reducer, '@workbench/canvas-engine/document/insertionAnchors')).toEqual([]);+ expect(checkDependency(reducer, '@workbench/canvas-engine/document/sources')).toContainEqual(+ expect.objectContaining({ rule: 'canvas-private-interface' })+ );+ expect(+ checkDependency('workbench/widgets/layers/layerGroups.ts', '@workbench/canvas-engine/document/layerStacks')+ ).toContainEqual(expect.objectContaining({ rule: 'canvas-private-interface' }));+ });+it('permits the pure document model to read document facts, math and contracts', () => {const source = 'workbench/canvas-engine/document-model/flatDocumentModel.ts';expect(checkDependency(source, './semanticLeaf')).toEqual([]);diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.tsindex 0bb7e17ef0..df8e521703 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts@@ -154,6 +154,14 @@ const isFeatureCoreForbiddenDependency = (specifier: string, target: string | nu/\/(?:data|ui)(?:\/|$)/.test(target)));+/** The reducer shares the document seam's stack, anchor and repair helpers instead of the public API. */+const CANVAS_REDUCER = 'workbench/canvasProjectMutations.ts';+const REDUCER_DOCUMENT_MODULES = [+ 'workbench/canvas-engine/document/insertionAnchors',+ 'workbench/canvas-engine/document/layerStacks',+ 'workbench/canvas-engine/document/selectionRepair',+];+const DOCUMENT_MODEL_ROOT = 'workbench/canvas-engine/document-model/';const DOCUMENT_MODEL_DEPENDENCY_ROOTS = [DOCUMENT_MODEL_ROOT, 'workbench/canvas-engine/math/'];const DOCUMENT_MODEL_DEPENDENCY_MODULES = [@@ -230,7 +238,11 @@ export const checkDependency = (source: string, specifier: string): DependencyViadd('feature-private-interface');}- if (!isCanvasOwnedPath(sourcePath) && isCanvasPrivatePath(target)) {+ if (+ !isCanvasOwnedPath(sourcePath) &&+ isCanvasPrivatePath(target) &&+ !(sourcePath === CANVAS_REDUCER && REDUCER_DOCUMENT_MODULES.includes(target))+ ) {add('canvas-private-interface');}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 2ccf7a7669..c08890b163 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -152,6 +152,8 @@ export interface CanvasDocumentCapability {captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor;/** The anchor that restores `layerId` between its current same-stack neighbours; null when absent. */captureRestoreAnchor(layerId: string): FlatLayerInsertionAnchor | null;+ /** Swaps in a whole new document; the mirror treats it as a document swap and history clears. */+ replaceDocument(document: CanvasDocumentContractV2): boolean;/** The pure model over the current document; the same instance until the document changes. */model(): FlatCanvasDocumentModel | null;}@@ -596,10 +598,8 @@ export {layerStackOf,type LayerStackKind,type LayerStackMoveKind,- reorderLayerStack,type ReorderFlatStackCommand,} from './document/layerStacks';-export { repairSelectedLayerId } from './document/selectionRepair';export {type HideableLayer,isHideableLayer,@@ -622,6 +622,7 @@ export {export {createFlatDocumentModel,type FlatCanvasDocumentModel,+ lookupLayerBelow,mergeDownEligibility,} from './document-model/flatDocumentModel';export { checkFlatEditPostconditions, type FlatEditPostcondition } from './document-model/postconditions';@@ -634,7 +635,6 @@ export { type SemanticLeafV2 } from './document-model/semanticLeaf';export {captureInsertionAnchor,captureRestoreAnchor,- insertLayersAtAnchor,resolveInsertionIndex,type FlatLayerInsertion,type FlatLayerInsertionAnchor,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.tsindex 27bfcb90ac..2ed5f63e08 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts@@ -17,6 +17,7 @@ import {flatDocumentModelCounters,lookupDocumentLayer,lookupDocumentLeaf,+ lookupLayerBelow,mergeDownEligibility,} from './flatDocumentModel';import { checkFlatEditPostconditions } from './postconditions';@@ -653,6 +654,13 @@ describe('document-level seam', () => {expect(recompiled.find((leaf) => leaf.id === 'r1')).not.toBe(untouched.find((leaf) => leaf.id === 'r1'));});+ it('finds the layer directly below in flat order across stacks', () => {+ const document = projectWith(interleaved(), 'r1').canvas.document;+ expect(lookupLayerBelow(document, 'r1')?.id).toBe('c1');+ expect(lookupLayerBelow(document, 'r3')).toBeNull();+ expect(lookupLayerBelow(document, 'nope')).toBeNull();+ });+it('shares the merge-down rule with the model', () => {const project = projectWith(interleaved(), 'r1');const model = modelOf(project);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.tsindex 8c9732be6d..8c8a1ea8c4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts@@ -169,6 +169,12 @@ export const lookupDocumentLeaf = (document: CanvasDocumentContractV2, id: strinreturn entry ? (compileDocumentLeaves(document)[entry.index] ?? null) : null;};+/** The layer directly below `id` in flat order, whatever its stack; `null` at the bottom or when absent. */+export const lookupLayerBelow = (document: CanvasDocumentContractV2, id: string): CanvasLayerContract | null => {+ const entry = indexOf(document).byId.get(id);+ return entry ? (document.layers[entry.index + 1] ?? null) : null;+};+/** Merge-down joins a raster layer with the layer directly below it in flat order, mirroring the reducer. */export const mergeDownEligibility = (document: CanvasDocumentContractV2, upperId: string): MergeDownEligibility => {const upper = indexOf(document).byId.get(upperId);@@ -178,7 +184,7 @@ export const mergeDownEligibility = (document: CanvasDocumentContractV2, upperIdif (upper.stack !== 'raster') {return { actual: upper.stack, expected: ['raster'], status: 'wrong-type' };}- const lower = document.layers[upper.index + 1];+ const lower = lookupLayerBelow(document, upperId);if (!lower) {return { reason: 'no-layer-below', status: 'invalid-target', targetId: upperId };}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 2c672e974a..86dc29a9b8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -627,6 +627,25 @@ describe('createCanvasEngine', () => {engine.lifecycle.dispose();});+ it('replaces the whole document through its own mutation port', () => {+ const document = makeDoc();+ const { store } = createFakeStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const replacement = { ...makeDoc(), height: 32, width: 32 };++ engine.document.replaceDocument(replacement);++ expect(store.dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ document: replacement, type: 'replaceCanvasDocument' })+ );+ engine.lifecycle.dispose();+ });+it('returns stale and releases a partial raster snapshot when the document changes during detachment', async () => {const pending = createDeferred<Blob>();const document = makeDoc();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 3d874f92ee..594864e035 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -2891,6 +2891,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetDocument: () => mirror.getDocument(),getEditRevision: () => mutationContext.getEditRevision(),model: currentDocumentModel,+ replaceDocument: (document) => dispatchCanvasMutation({ document, type: 'replaceCanvasDocument' }, 'user'),};const selectionCapability: CanvasEngineSelectionCapability = {deselect,diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex f7be0520a0..440e5b79b0 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -11,11 +11,11 @@ import {type FlatLayerInsertion,type FlatLayerInsertionAnchor,type ReorderFlatStackCommand,- insertLayersAtAnchor,isHideableLayer,- reorderLayerStack,- repairSelectedLayerId,} from '@workbench/canvas-engine/api';+import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import { reorderLayerStack } from '@workbench/canvas-engine/document/layerStacks';+import { repairSelectedLayerId } from '@workbench/canvas-engine/document/selectionRepair';import { normalizeCanvasDocumentContract } from './canvasMigration';import {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsxindex f236159c1b..4c69fe5ebc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx@@ -7,7 +7,6 @@ import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngiimport { 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';@@ -51,7 +50,10 @@ import { useCanvasEngine } from './useCanvasEngine';import { reportStructuralCommit } from './useStructuralCommit';import { formatZoomPercent, zoomMenuOptions } from './zoomOptions';-type CanvasHeaderEngine = Pick<CanvasEngineHandle, 'diagnostics' | 'history' | 'interaction' | 'layers' | 'viewport'>;+type CanvasHeaderEngine = Pick<+ CanvasEngineHandle,+ 'diagnostics' | 'document' | 'history' | 'interaction' | 'layers' | 'viewport'+>;const ZOOM_OPTIONS = zoomMenuOptions();const MENU_POSITIONING = { placement: 'bottom-end' } as const;@@ -90,7 +92,6 @@ const CanvasHeaderActionsInner = ({}) => {const { t } = useTranslation();const notify = useNotify();- const dispatch = useCanvasProjectMutationDispatch();const zoom = useCanvasZoom(engine);const canUndo = useCanvasCanUndo(engine);const canRedo = useCanvasCanRedo(engine);@@ -115,7 +116,6 @@ const CanvasHeaderActionsInner = ({const fitMasksRect = useMemo(() => computeFitBboxToMasks(document, gridSize), [document, gridSize]);const commandContext = (): CanvasHeaderCommandContext => ({- dispatch,document,editingLocked,engine,@@ -129,8 +129,8 @@ const CanvasHeaderActionsInner = ({const applyFit = (rect: Rect | null, refit: boolean) => applyFitBbox(commandContext(), rect, refit);const confirmNewCanvas = useCallback(- () => confirmNewCanvasDocument({ dispatch, document, editingLocked }),- [dispatch, document, editingLocked]+ () => confirmNewCanvasDocument({ document, editingLocked, engine }),+ [document, editingLocked, engine]);// Commands (hotkey-assignable; catalog ids `canvas.fitBboxToLayers` /diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.tsindex 34845430ad..478b7dfb20 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts@@ -1,7 +1,6 @@import type { CanvasDocumentContractV2, Rect } from '@workbench/canvas-engine/api';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';+import { describe, expect, it, vi, type Mock } from 'vitest';import {applyFitBbox,@@ -29,6 +28,7 @@ const documentOf = (): CanvasDocumentContractV2 =>const createEngine = (viewportSize = { height: 600, width: 800 }) => {const zoomAtPoint = vi.fn();const engine = {+ document: { replaceDocument: vi.fn(() => true) },layers: { commitStructural: vi.fn(() => ({ status: 'committed' as const })) },viewport: {fitToView: vi.fn(),@@ -38,11 +38,8 @@ const createEngine = (viewportSize = { height: 600, width: 800 }) => {return { engine, zoomAtPoint };};-let dispatch: Mock<(mutation: CanvasProjectMutation) => boolean>;-const contextOf = (overrides: Partial<CanvasHeaderCommandContext> = {}): CanvasHeaderCommandContext => ({reportStructuralCommit: () => undefined,- dispatch,document: documentOf(),editingLocked: false,engine: createEngine().engine,@@ -53,10 +50,6 @@ const contextOf = (overrides: Partial<CanvasHeaderCommandContext> = {}): CanvasH...overrides,});-beforeEach(() => {- dispatch = vi.fn(() => true);-});-describe('zoomAtViewportCentre', () => {it('anchors the zoom at the viewport centre', () => {const { engine, zoomAtPoint } = createEngine({ height: 600, width: 800 });@@ -108,25 +101,28 @@ describe('applyFitBbox', () => {});describe('confirmNewCanvas', () => {- it('replaces the document at the current dimensions', () => {- confirmNewCanvas({ dispatch, document: { height: 512, width: 768 }, editingLocked: false });- expect(dispatch).toHaveBeenCalledTimes(1);- const mutation = dispatch.mock.calls[0]?.[0] as Extract<CanvasProjectMutation, { type: 'replaceCanvasDocument' }>;- expect(mutation.type).toBe('replaceCanvasDocument');- expect(mutation.document.width).toBe(768);- expect(mutation.document.height).toBe(512);+ const replaced = (engine: ReturnType<typeof createEngine>['engine']) =>+ (engine.document.replaceDocument as Mock).mock.calls[0]?.[0] as CanvasDocumentContractV2;++ it('replaces the document at the current dimensions through the engine', () => {+ const { engine } = createEngine();+ confirmNewCanvas({ document: { height: 512, width: 768 }, editingLocked: false, engine });+ expect(engine.document.replaceDocument).toHaveBeenCalledTimes(1);+ expect(replaced(engine).width).toBe(768);+ expect(replaced(engine).height).toBe(512);});it('seeds exactly one empty inpaint mask', () => {- confirmNewCanvas({ dispatch, document: { height: 64, width: 64 }, editingLocked: false });- const mutation = dispatch.mock.calls[0]?.[0] as Extract<CanvasProjectMutation, { type: 'replaceCanvasDocument' }>;- expect(mutation.document.layers).toHaveLength(1);- expect(mutation.document.layers[0]?.type).toBe('inpaint_mask');+ const { engine } = createEngine();+ confirmNewCanvas({ document: { height: 64, width: 64 }, editingLocked: false, engine });+ expect(replaced(engine).layers).toHaveLength(1);+ expect(replaced(engine).layers[0]?.type).toBe('inpaint_mask');});it('refuses while editing is locked — the second gate behind the confirm dialog', () => {- confirmNewCanvas({ dispatch, document: { height: 512, width: 768 }, editingLocked: true });- expect(dispatch).not.toHaveBeenCalled();+ const { engine } = createEngine();+ confirmNewCanvas({ document: { height: 512, width: 768 }, editingLocked: true, engine });+ expect(engine.document.replaceDocument).not.toHaveBeenCalled();});});@@ -154,10 +150,11 @@ describe('executeCanvasHeaderCommand', () => {});it('newSession opens the confirm dialog instead of replacing directly', () => {+ const { engine } = createEngine();const openNewCanvas = vi.fn();- executeCanvasHeaderCommand('canvas.newSession', contextOf({ openNewCanvas }));+ executeCanvasHeaderCommand('canvas.newSession', contextOf({ engine, openNewCanvas }));expect(openNewCanvas).toHaveBeenCalled();- expect(dispatch).not.toHaveBeenCalled();+ expect(engine.document.replaceDocument).not.toHaveBeenCalled();});it('fit commands are inert with no rect to fit to', () => {@@ -174,6 +171,6 @@ describe('executeCanvasHeaderCommand', () => {executeCanvasHeaderCommand('canvas.nonexistent', contextOf({ engine, openNewCanvas }));expect(engine.layers.commitStructural).not.toHaveBeenCalled();expect(openNewCanvas).not.toHaveBeenCalled();- expect(dispatch).not.toHaveBeenCalled();+ expect(engine.document.replaceDocument).not.toHaveBeenCalled();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.tsindex cb9b6a365f..503bbce32f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts@@ -1,5 +1,9 @@-import type { CanvasDocumentContractV2, Rect, StructuralCommitResult } from '@workbench/canvas-engine/api';-import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';+import type {+ CanvasDocumentCapability,+ CanvasDocumentContractV2,+ Rect,+ StructuralCommitResult,+} from '@workbench/canvas-engine/api';import { createNewCanvasStateV2 } from '@workbench/canvasMigration';@@ -8,6 +12,7 @@ import { createNewCanvasStateV2 } from '@workbench/canvasMigration';* full handle, so this module stays React-free and testable with a plain double.*/export interface CanvasHeaderCommandEngine {+ readonly document: Pick<CanvasDocumentCapability, 'replaceDocument'>;readonly layers: {commitStructural(label: string, forward: unknown, inverse: unknown): StructuralCommitResult;};@@ -25,7 +30,7 @@ export interface NewCanvasContext {readonly document: Pick<CanvasDocumentContractV2, 'width' | 'height'>;/** An in-flight operation owns the document; every mutating header action is inert. */readonly editingLocked: boolean;- readonly dispatch: CanvasProjectMutationDispatch;+ readonly engine: Pick<CanvasHeaderCommandEngine, 'document'>;}export interface CanvasHeaderCommandContext extends NewCanvasContext {@@ -77,10 +82,7 @@ export const confirmNewCanvas = (ctx: NewCanvasContext): void => {if (ctx.editingLocked) {return;}- ctx.dispatch({- document: createNewCanvasStateV2(ctx.document.width, ctx.document.height).document,- type: 'replaceCanvasDocument',- });+ ctx.engine.document.replaceDocument(createNewCanvasStateV2(ctx.document.width, ctx.document.height).document);};/**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 376f417854..55e8cd1117 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@@ -43,6 +43,7 @@ const createLayer = (): CanvasRasterLayerContractV2 =>}) as unknown as CanvasRasterLayerContractV2;const commits: PreparedFlatEdit[] = [];+let latestAdjustments: unknown = 'untouched';const Harness = () => {const [layer, setLayer] = useState(createLayer);@@ -51,6 +52,7 @@ const Harness = () => {const apply = (mutation: CanvasProjectMutation): boolean => {const candidate = mutation as { type: string; config?: { adjustments?: unknown } };if (candidate.type === 'updateCanvasLayerConfig') {+ latestAdjustments = candidate.config?.adjustments;setLayer((current) => ({ ...current, adjustments: candidate.config?.adjustments }) as CanvasRasterLayerContractV2);@@ -123,6 +125,7 @@ const pointer = (target: Element, type: string, x: number, y: number): void => {afterEach(async () => {commits.length = 0;+ latestAdjustments = 'untouched';await settle(() => root?.unmount());host?.remove();host = null;@@ -155,6 +158,22 @@ describe('curves editor', () => {).not.toEqual(createLayer().adjustments?.curves?.r);});+ it('records nothing when a drag ends where it started', async () => {+ const svg = await render();+ const target = handles(svg).at(-1)!;+ const before = Number(target.getAttribute('cy'));+ const start = centreOf(target);++ await settle(() => pointer(target, 'pointerdown', start.x, start.y));+ await settle(() => pointer(target, 'pointermove', start.x, start.y + 40));+ await settle(() => pointer(target, 'pointermove', start.x, start.y));+ await settle(() => pointer(target, 'pointerup', start.x, start.y));++ expect(Number(handles(svg).at(-1)!.getAttribute('cy'))).toBeCloseTo(before, 5);+ expect(commits).toHaveLength(0);+ expect(latestAdjustments).toBeUndefined();+ });+it('restores the pre-drag curve and records nothing when the drag is cancelled', async () => {const svg = await render();const target = handles(svg).at(-1)!;@@ -167,6 +186,7 @@ describe('curves editor', () => {expect(Number(handles(svg).at(-1)!.getAttribute('cy'))).toBeCloseTo(before, 5);expect(commits).toHaveLength(0);+ expect(latestAdjustments).toBeUndefined();});it('adds a point under the pointer rather than offset from it', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsxindex d77ba08c1a..f7f6ca69ae 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.tsx@@ -66,6 +66,13 @@ const withCurve = (},});+const sameCurves = (left: CanvasAdjustmentsContract, right: CanvasAdjustmentsContract): boolean =>+ CURVE_CHANNELS.every(+ (channel) =>+ JSON.stringify(left.curves?.[channel] ?? IDENTITY_CURVE) ===+ JSON.stringify(right.curves?.[channel] ?? IDENTITY_CURVE)+ );+const formatSigned = (value: number): string => `${value > 0 ? '+' : ''}${Math.round(value * 100)}`;interface AdjustmentsPopoverProps {@@ -148,17 +155,26 @@ const AdjustmentsControls = ({ adjustments, engine, layer }: AdjustmentsControlsconst handleCurveCancel = useCallback((before: CanvasAdjustmentsContract) => {- patchLive(before);+ const baseline = gestureBaselineRef.current ? gestureBaselineRef.current.adjustments : before;gestureBaselineRef.current = null;+ applyStructuralPreview(engine, {+ config: { adjustments: baseline, layerType: 'raster' },+ id: layer.id,+ type: 'updateCanvasLayerConfig',+ });},- [patchLive]+ [engine, layer.id]);const handleCurveCommit = useCallback((current: CanvasAdjustmentsContract, before: CanvasAdjustmentsContract) => {+ if (sameCurves(current, before)) {+ handleCurveCancel(before);+ return;+ }commit(t('widgets.layers.adjustments.curves'), current, before);},- [commit, t]+ [commit, handleCurveCancel, t]);return (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex b164195029..2dfff805b1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -151,7 +151,6 @@ const hasPureExportableLayerContent = (layer: CanvasLayerContract, document: Caninterface LayerMenuProps {dispatch: Dispatch<CanvasProjectMutation>;engine: LayerContextMenuEngine | null;- index: number;layer: CanvasLayerContract;/** Where the menu opens: the panel anchors to its trigger; the canvas uses a* virtual rect at the cursor. */@@ -191,7 +190,6 @@ interface LayerMenuProps {const LayerMenu = ({dispatch,engine,- index,layer,positioning,withTrigger,@@ -268,7 +266,6 @@ const LayerMenu = ({hasEngine: engine !== null,hasSupportedContent,hasWorkflowBindings: workflowAvailability.hasWorkflowBindings,- index,interactionLocked,layer,}),@@ -276,7 +273,6 @@ const LayerMenu = ({document,engine,hasSupportedContent,- index,interactionLocked,layer,workflowAvailability.canRunWorkflow,@@ -772,7 +768,6 @@ const LayerMenu = ({interface LayerRowMenuProps {dispatch: Dispatch<CanvasProjectMutation>;engine: LayerContextMenuEngine | null;- index: number;layer: CanvasLayerContract;layers: readonly CanvasLayerContract[];}@@ -793,7 +788,7 @@ export interface CanvasLayerContextMenuTarget {* The canvas-surface right-click menu: the SAME {@link LayerMenu}, anchored at the* cursor via a 1×1 virtual rect (no trigger DOM), controlled by `target`. The* canvas widget sets `target` to the hit layer + pointer position after selecting- * it; `null` closes the menu. The layer and its global index are resolved from+ * it; `null` closes the menu. The layer is resolved from* `target.layerId` against the live layer list, so the shared items get the exact* same inputs the panel passes. Keyed by layer id so switching target resets the* menu's sibling-dialog state.@@ -824,8 +819,7 @@ export const CanvasLayerContextMenu = ({const [dialogState, setDialogState] = useState<LayerMenuDialogState | null>(null);const renderTarget = resolveMenuTargetForRender(target, dialogState);- const index = renderTarget ? layers.findIndex((entry) => entry.id === renderTarget.layerId) : -1;- const layer = index >= 0 ? layers[index] : undefined;+ const layer = renderTarget ? layers.find((entry) => entry.id === renderTarget.layerId) : undefined;const anchorX = renderTarget?.x ?? 0;const anchorY = renderTarget?.y ?? 0;@@ -862,7 +856,6 @@ export const CanvasLayerContextMenu = ({dispatch={dispatch}dialogKind={dialogState?.kind ?? null}engine={engine}- index={index}layer={layer}lazyMount// The menu itself is visible only while the live target is set; once adiff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsxindex 8c1715f8a0..868280484e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx@@ -81,12 +81,6 @@ export const LayerGroupSection = ({useSensor(KeyboardSensor, LAYER_KEYBOARD_SENSOR_OPTIONS));- const globalIndexById = useMemo(() => {- const map = new Map<string, number>();- layers.forEach((layer, index) => map.set(layer.id, index));- return map;- }, [layers]);-const groupIds = useMemo(() => groupLayers.map((layer) => layer.id), [groupLayers]);const handleDragEnd = useCallback(@@ -177,7 +171,6 @@ export const LayerGroupSection = ({dispatch={dispatch}editingLocked={editingLocked}engine={engine}- index={globalIndexById.get(layer.id) ?? 0}isPrimarySelected={layer.id === selectedLayerId}isSelected={selectedIds.includes(layer.id)}layer={layer}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 fdaaa8a275..a4ef766398 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@@ -148,13 +148,12 @@ const Harness = () => {return (<DndContext collisionDetection={closestCenter} sensors={sensors} onDragEnd={handleDragEnd}><SortableContext items={layerIds} strategy={verticalListSortingStrategy}>- {layers.map((layer, index) => (+ {layers.map((layer) => (<LayerListItemkey={layer.id}dispatch={dispatch}editingLocked={false}engine={engine}- index={index}isPrimarySelected={selectedLayerId === layer.id}isSelected={selection.selectedIds.includes(layer.id)}layer={layer}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsxindex 8207ffc5a1..70d0e13afe 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx@@ -83,7 +83,6 @@ interface LayerListItemProps {dispatch: Dispatch<CanvasProjectMutation>;editingLocked: boolean;engine: LayerListItemEngine | null;- index: number;isPrimarySelected: boolean;isSelected: boolean;layer: CanvasLayerContract;@@ -103,7 +102,6 @@ export const LayerListItem = ({dispatch,editingLocked,engine,- index,isPrimarySelected,isSelected,layer,@@ -389,7 +387,7 @@ export const LayerListItem = ({<LayerPropertiesPopover engine={engine} layer={layer} /></Box><Box display="flex" flexShrink="0" onPointerDown={stopPropagation}>- <LayerContextMenu dispatch={dispatch} engine={engine} index={index} layer={layer} layers={layers} />+ <LayerContextMenu dispatch={dispatch} engine={engine} layer={layer} layers={layers} /></Box></HStack></HStack>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex 24f88f6a9d..5e8e28da8a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -75,7 +75,6 @@ const makeState = (hasEngine: true,hasSupportedContent: true,hasWorkflowBindings: true,- index: document.layers.findIndex((entry) => entry.id === layer.id),interactionLocked: false,layer,...overrides,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex f81cad3efe..ae38bc6c81 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -6,7 +6,7 @@ import type {} from '@workbench/canvas-engine/api';import type { LucideIcon } from 'lucide-react';-import { getSourceContentRect, isPixelBackedLayer } from '@workbench/canvas-engine/api';+import { getSourceContentRect, isPixelBackedLayer, lookupLayerBelow } from '@workbench/canvas-engine/api';import {ArrowDownIcon,ArrowDownToLineIcon,@@ -85,7 +85,6 @@ export interface LayerContextActionState {hasEngine: boolean;hasSupportedContent: boolean;hasWorkflowBindings: boolean;- index: number;interactionLocked: boolean;layer: CanvasLayerContract;}@@ -222,12 +221,11 @@ const canMoveBackward = (context: LayerContextActionState): boolean => {const hasMergeableLayerBelow = (context: LayerContextActionState): boolean =>canMergeLayerDown(context.document, context.layer.id, true);-const isBooleanRasterLayer = (layer: CanvasLayerContract | undefined): boolean =>+const isBooleanRasterLayer = (layer: CanvasLayerContract | null): boolean =>!!layer && layer.isEnabled && layer.type === 'raster' && isPixelBackedLayer(layer);const hasBooleanRasterPair = (context: LayerContextActionState): boolean =>- isBooleanRasterLayer(context.document.layers[context.index]) &&- isBooleanRasterLayer(context.document.layers[context.index + 1]);+ isBooleanRasterLayer(context.layer) && isBooleanRasterLayer(lookupLayerBelow(context.document, context.layer.id));export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinition[] = [{diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex db8efd890f..9ec35a4e6e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -44,7 +44,6 @@ const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerConthasEngine: true,hasSupportedContent: true,hasWorkflowBindings: true,- index: layers.indexOf(layer),interactionLocked: false,layer,});