Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(canvas): keep bbox pixel aligned
Josh Corbettf0330e113037
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.test.tsindex e38b9046e3..2f2dab39bb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.test.ts@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';import type { ResizeBboxParams } from './bboxHitTest';import {+ BBOX_HANDLES,BBOX_HANDLE_HIT_PX,bboxEquals,bboxHandleAt,@@ -114,9 +115,25 @@ describe('resizeBbox — free (unconstrained)', () => {expect(out).toEqual(rect(0, 0, 112, 100));});- it('bypasses snapping when snap is false (alt held)', () => {- const out = resize({ constrain: false, dx: 13, dy: 0, grid: 8, handle: 'e', ratio: 1, snap: false, start });- expect(out).toEqual(rect(0, 0, 113, 100));+ it('uses whole-pixel edge snapping when model-grid snap is false', () => {+ const out = resize({ constrain: false, dx: 13.4, dy: 13.6, grid: 8, handle: 'se', ratio: 1, snap: false, start });+ expect(out).toEqual(rect(0, 0, 113, 114));+ });++ it('keeps the fixed corner anchored while pixel-snapping at negative coordinates', () => {+ const negativeStart = rect(-20, -10, 96, 96);+ const out = resize({+ constrain: false,+ dx: 0.5,+ dy: 0.5,+ grid: 8,+ handle: 'nw',+ ratio: 1,+ snap: false,+ start: negativeStart,+ });+ expect(out).toEqual(rect(-19, -9, 95, 95));+ expect(bboxHandlePoint(out, 'se')).toEqual(bboxHandlePoint(negativeStart, 'se'));});it('clamps to a minimum of one grid cell when collapsing an edge', () => {@@ -173,6 +190,49 @@ describe('resizeBbox — symmetric (mirrored across the center)', () => {expect(out.x + out.width / 2).toBe(50);});+ it('pixel-snaps a half-pixel symmetric resize without shifting the center', () => {+ const pixelStart = rect(16, 16, 96, 96);+ const out = resize({+ constrain: false,+ dx: 0.5,+ dy: 0,+ grid: 8,+ handle: 'e',+ ratio: 1,+ snap: false,+ start: pixelStart,+ symmetric: true,+ });+ expect(out).toEqual(rect(15, 16, 98, 96));+ expect(out.x + out.width / 2).toBe(64);++ const shrinking = resize({+ constrain: false,+ dx: -0.5,+ dy: 0,+ grid: 8,+ handle: 'e',+ ratio: 1,+ snap: false,+ start: pixelStart,+ symmetric: true,+ });+ expect(shrinking).toEqual(pixelStart);++ const minimum = resize({+ constrain: false,+ dx: 1,+ dy: 0,+ grid: 0,+ handle: 'w',+ ratio: 1,+ snap: false,+ start: rect(0, 0, 2, 2),+ symmetric: true,+ });+ expect(minimum).toEqual(rect(0, 0, 2, 2));+ });+it('mirrors a shrink as well as a grow', () => {const out = resize({constrain: false,@@ -285,14 +345,64 @@ describe('resizeBbox — symmetric (mirrored across the center)', () => {expect(out.height).toBe(100);expect(out.y).toBe(0);});++ it('keeps bypassed resize geometry pixel-aligned across every handle and constraint mode', () => {+ const pixelStart = rect(-21, 13, 95, 96);+ const startRight = pixelStart.x + pixelStart.width;+ const startBottom = pixelStart.y + pixelStart.height;+ const centerX = pixelStart.x + pixelStart.width / 2;+ const centerY = pixelStart.y + pixelStart.height / 2;++ for (const handle of BBOX_HANDLES) {+ for (const constrain of [false, true]) {+ for (const symmetric of [false, true]) {+ const out = resize({+ constrain,+ dx: 13.4,+ dy: -7.6,+ grid: 8,+ handle,+ ratio: 1.7,+ snap: false,+ start: pixelStart,+ symmetric,+ });++ expect([out.x, out.y, out.width, out.height].every(Number.isInteger)).toBe(true);+ if (symmetric) {+ expect(out.x + out.width / 2).toBe(centerX);+ expect(out.y + out.height / 2).toBe(centerY);+ } else {+ if (handle.includes('w')) {+ expect(out.x + out.width).toBe(startRight);+ }+ if (handle.includes('e')) {+ expect(out.x).toBe(pixelStart.x);+ }+ if (handle.includes('n')) {+ expect(out.y + out.height).toBe(startBottom);+ }+ if (handle.includes('s')) {+ expect(out.y).toBe(pixelStart.y);+ }+ }+ }+ }+ }+ });});describe('moveBbox', () => {it('translates and snaps the origin to the grid', () => {expect(moveBbox(rect(10, 10, 100, 100), 5, 5, 8, true)).toEqual(rect(16, 16, 100, 100));});- it('bypasses snap when snap is false', () => {+ it('uses whole-pixel snapping when model-grid snap is false', () => {expect(moveBbox(rect(10, 10, 100, 100), 5, 5, 8, false)).toEqual(rect(15, 15, 100, 100));+ expect(moveBbox(rect(10, 10, 100, 100), 5.4, 5.6, 8, false)).toEqual(rect(15, 16, 100, 100));+ });+ it('normalizes a fractional untouched axis to a whole pixel', () => {+ expect(moveBbox(rect(10.25, 11.75, 100, 100), 5.4, 0, 8, false)).toEqual(rect(16, 12, 100, 100));+ expect(moveBbox(rect(-10.25, -11.75, 100, 100), -5.4, 0, 8, false)).toEqual(rect(-16, -12, 100, 100));});it('does not snap an unchanged axis from an off-grid origin', () => {expect(moveBbox(rect(10, 11, 100, 100), 5, 0, 8, true)).toEqual(rect(16, 11, 100, 100));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.tsindex e466c16c71..1cbe5d3434 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxHitTest.ts@@ -98,12 +98,13 @@ export const bboxTargetAt = (/** Minimum bbox side (document px): one grid cell, but never below 1px. */export const bboxMinSize = (grid: number): number => Math.max(1, grid);-/** Translates `start` by a document-space delta, snapping the origin to `grid` unless bypassed. */+/**+ * Translates `start` by a document-space delta. Model-grid snapping may be+ * bypassed, but the origin always lands on whole document pixels.+ */export const moveBbox = (start: Rect, dx: number, dy: number, grid: number, snap: boolean): Rect => {- const { x, y } = snap- ? snapMovedPoint({ x: start.x, y: start.y }, { x: dx, y: dy }, grid)- : { x: start.x + dx, y: start.y + dy };- return { height: start.height, width: start.width, x, y };+ const moved = snapMovedPoint({ x: start.x, y: start.y }, { x: dx, y: dy }, snap ? grid : 1);+ return { height: start.height, width: start.width, x: Math.round(moved.x), y: Math.round(moved.y) };};export interface ResizeBboxParams {@@ -256,6 +257,115 @@ const centerRectOn = (rect: Rect, centerX: number, centerY: number): Rect => ({y: centerY - rect.height / 2,});+/** A whole-pixel span whose center is held exactly. */+const centeredPixelSpan = (+ center: number,+ desiredSize: number,+ previousSize: number,+ minimumSize: number+): { size: number; start: number } => {+ const doubledCenter = Math.round(center * 2);+ const requiredParity = ((doubledCenter % 2) + 2) % 2;+ const minimum = Math.max(1, Math.ceil(minimumSize));+ const rounded = Math.max(minimum, Math.round(desiredSize));+ let lower = rounded;+ while (((lower % 2) + 2) % 2 !== requiredParity) {+ lower -= 1;+ }+ let upper = rounded;+ while (((upper % 2) + 2) % 2 !== requiredParity || upper < minimum) {+ upper += 1;+ }++ let size: number;+ if (lower < minimum) {+ size = upper;+ } else {+ const lowerDistance = Math.abs(desiredSize - lower);+ const upperDistance = Math.abs(upper - desiredSize);+ size =+ lowerDistance === upperDistance+ ? desiredSize >= previousSize+ ? upper+ : lower+ : lowerDistance < upperDistance+ ? lower+ : upper;+ }++ return { size, start: (doubledCenter - size) / 2 };+};++/** A whole-pixel span mirrored around `center`, derived from its dragged edge. */+const mirroredPixelSpan = (+ center: number,+ movedEdge: number,+ movesStart: boolean,+ previousSize: number,+ minimumSize: number+): { size: number; start: number } => {+ const moved = Math.round(movedEdge);+ const opposite = Math.round(center * 2) - moved;+ const span = movesStart ? { size: opposite - moved, start: moved } : { size: moved - opposite, start: opposite };+ return span.size >= minimumSize ? span : centeredPixelSpan(center, minimumSize, previousSize, minimumSize);+};++/**+ * Quantizes a model-grid-bypassed resize without breaking its fixed anchor or+ * center. The persisted bbox is canonicalized to integer pixels at hydration,+ * so every fixed edge and doubled center is already integral here.+ */+const pixelAlignResize = (rect: Rect, p: ResizeBboxParams): Rect => {+ const startRight = p.start.x + p.start.width;+ const startBottom = p.start.y + p.start.height;+ const centerX = p.start.x + p.start.width / 2;+ const centerY = p.start.y + p.start.height / 2;+ const min = bboxMinSize(p.grid);+ const widthMin = hasWest(p.handle) || hasEast(p.handle) ? min : 1;+ const heightMin = p.constrain && isCornerHandle(p.handle) ? 1 : hasNorth(p.handle) || hasSouth(p.handle) ? min : 1;++ if (p.symmetric) {+ const horizontal =+ hasWest(p.handle) || hasEast(p.handle)+ ? mirroredPixelSpan(+ centerX,+ hasWest(p.handle) ? rect.x : rect.x + rect.width,+ hasWest(p.handle),+ p.start.width,+ widthMin+ )+ : centeredPixelSpan(centerX, rect.width, p.start.width, 1);+ const vertical =+ hasNorth(p.handle) || hasSouth(p.handle)+ ? mirroredPixelSpan(+ centerY,+ hasNorth(p.handle) ? rect.y : rect.y + rect.height,+ hasNorth(p.handle),+ p.start.height,+ heightMin+ )+ : centeredPixelSpan(centerY, rect.height, p.start.height, 1);+ return { height: vertical.size, width: horizontal.size, x: horizontal.start, y: vertical.start };+ }++ let left = hasWest(p.handle) ? Math.round(rect.x) : p.start.x;+ let right = hasEast(p.handle) ? Math.round(rect.x + rect.width) : startRight;+ let top = hasNorth(p.handle) ? Math.round(rect.y) : p.start.y;+ let bottom = hasSouth(p.handle) ? Math.round(rect.y + rect.height) : startBottom;++ if (p.constrain && (p.handle === 'e' || p.handle === 'w')) {+ const vertical = centeredPixelSpan(centerY, rect.height, p.start.height, 1);+ top = vertical.start;+ bottom = vertical.start + vertical.size;+ } else if (p.constrain && (p.handle === 'n' || p.handle === 's')) {+ const horizontal = centeredPixelSpan(centerX, rect.width, p.start.width, 1);+ left = horizontal.start;+ right = horizontal.start + horizontal.size;+ }++ return { height: bottom - top, width: right - left, x: left, y: top };+};+/*** Resizes `start` for a handle drag. Applies (in order) the delta to the moved* edge(s), grid snapping (unless bypassed), min-size clamping, and — when@@ -269,11 +379,14 @@ const centerRectOn = (rect: Rect, centerX: number, centerY: number): Rect => ({* min-size clamping and the aspect constraint all keep applying unchanged.*/export const resizeBbox = (p: ResizeBboxParams): Rect => {- if (!p.symmetric) {- return resizeAnchored(p);- }- const doubled = resizeAnchored({ ...p, dx: p.dx * 2, dy: p.dy * 2 });- return centerRectOn(doubled, p.start.x + p.start.width / 2, p.start.y + p.start.height / 2);+ const resized = p.symmetric+ ? centerRectOn(+ resizeAnchored({ ...p, dx: p.dx * 2, dy: p.dy * 2 }),+ p.start.x + p.start.width / 2,+ p.start.y + p.start.height / 2+ )+ : resizeAnchored(p);+ return p.snap ? resized : pixelAlignResize(resized, p);};/** Re-fits `rect` to `ratio`, keeping its center fixed, then snaps to `grid` and clamps min size. */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 b8290bc0a4..5b913a1e90 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@@ -109,13 +109,26 @@ describe('bbox tool: move gesture', () => {expect(h.previewOf()).toBeNull();});- it('bypasses snapping while alt is held', () => {+ it('bypasses model-grid snapping while alt is held but stays on whole pixels', () => {const h = createHarness(makeDoc());const tool = createBboxTool();down(tool, h.ctx, pointer(60, 60, { alt: true }));- move(tool, h.ctx, pointer(75, 75, { alt: true }));- up(tool, h.ctx, pointer(75, 75, { alt: true }));- expect(h.commits[0]?.forward).toEqual({ bbox: { height: 96, width: 96, x: 31, y: 31 }, type: 'setCanvasBbox' });+ move(tool, h.ctx, pointer(75.4, 75.6, { alt: true }));+ expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 31, y: 32 });++ up(tool, h.ctx, pointer(75.4, 75.6, { alt: true }));+ expect(h.commits[0]?.forward).toEqual({ bbox: { height: 96, width: 96, x: 31, y: 32 }, type: 'setCanvasBbox' });+ });++ it('keeps the live frame on whole pixels when grid snapping is disabled', () => {+ const h = createHarness(makeDoc());+ const tool = createBboxTool();+ h.ctx.stores.snapToGrid.set(false);++ down(tool, h.ctx, pointer(60, 60));+ move(tool, h.ctx, pointer(75.4, 75.6));++ expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 31, y: 32 });});it('constrains movement to the dominant axis while shift is held', () => {@@ -140,9 +153,56 @@ describe('bbox tool: move gesture', () => {move(tool, h.ctx, pointer(91, 69, { shift: true }));expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 48, y: 16 });});++ it('normalizes a fractional origin on the shift-locked axis', () => {+ const doc = makeDoc();+ doc.bbox = { ...bbox, x: 16.25, y: 16.75 };+ const h = createHarness(doc);+ const tool = createBboxTool();+ h.ctx.stores.snapToGrid.set(false);++ down(tool, h.ctx, pointer(60, 60));+ move(tool, h.ctx, pointer(75.4, 60, { shift: true }));++ expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 32, y: 17 });+ });});describe('bbox tool: resize gesture', () => {+ it.each([+ ['grid snapping is disabled', false, false],+ ['Alt bypasses the model grid', true, true],+ ])('keeps the live frame on whole pixels when %s', (_label, snapToGrid, alt) => {+ const h = createHarness(makeDoc());+ const tool = createBboxTool();+ h.ctx.stores.snapToGrid.set(snapToGrid);++ down(tool, h.ctx, pointer(112, 112, { alt }));+ move(tool, h.ctx, pointer(130.4, 130.6, { alt }));++ expect(h.previewOf()).toEqual({ height: 115, width: 114, x: 16, y: 16 });+ up(tool, h.ctx, pointer(130.4, 130.6, { alt }));+ expect(h.commits[0]?.forward).toEqual({+ bbox: { height: 115, width: 114, x: 16, y: 16 },+ type: 'setCanvasBbox',+ });+ });++ it('pixel-snaps a high-zoom NW resize without moving the fixed SE corner', () => {+ const h = createHarness(makeDoc());+ const tool = createBboxTool();+ h.ctx.stores.snapToGrid.set(false);+ const moved = pointer(15.5, 15.5);+ moved.screenPoint = { x: 12, y: 12 };++ down(tool, h.ctx, pointer(16, 16));+ move(tool, h.ctx, moved);++ const preview = h.previewOf();+ expect(preview).toEqual({ height: 96, width: 96, x: 16, y: 16 });+ expect(preview && { x: preview.x + preview.width, y: preview.y + preview.height }).toEqual({ x: 112, y: 112 });+ });+it('resizes from the SE handle and commits the grid-snapped frame', () => {const h = createHarness(makeDoc());const tool = createBboxTool();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.tsindex 04f7005bda..3292af3f56 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.ts@@ -9,7 +9,8 @@* - **Pointer-move** updates an engine-transient preview rect (via* `stores.bboxPreview`) that the overlay renders — it never dispatches. Sizes* and positions snap to the model grid (`stores.bboxGrid`); hold **alt** to- * bypass snapping. While moving, **shift** constrains the frame to the+ * bypass model-grid snapping. Bypassed movement and resize still stay aligned+ * to whole document pixels. While moving, **shift** constrains the frame to the* dominant horizontal or vertical axis. Corner/edge resize preserves the* aspect ratio when the lock is active (`stores.bboxOptions`); **shift*** toggles the constraint on for an unlocked frame (a locked ratio stays@@ -87,6 +88,7 @@ const nextBboxFor = (): Rect => {const grid = ctx.stores.bboxGrid.get();// Snap to the model grid unless Alt bypasses it or the snap-to-grid setting is off.+ // The geometry helpers still apply baseline whole-pixel alignment in either bypass case.const snap = !modifiers.alt && ctx.stores.snapToGrid.get();const dx = point.x - state.startDoc.x;const dy = point.y - state.startDoc.y;diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.tsindex 74f455fbf7..e9c1e75018 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {+ createEmptyCanvasDocumentV2,createEmptyCanvasStateV2,createNewCanvasStateV2,DEFAULT_CANVAS_DOCUMENT_HEIGHT,@@ -455,6 +456,38 @@ describe('migrateCanvasStateToV2', () => {expect(migrated.stagingArea.autoSwitchMode).toBe('latest');});+ it('normalizes persisted bbox geometry to whole pixels in documents and snapshots', () => {+ const state = createEmptyCanvasStateV2();+ const document = {+ ...state.document,+ bbox: { height: 12.6, width: 12.4, x: -3.4, y: -3.6 },+ height: 511.6,+ width: 512.4,+ };++ const migrated = migrateCanvasStateToV2({+ ...state,+ document,+ snapshots: [{ createdAt: 'now', document, id: 'fractional-bbox', name: 'Fractional bbox' }],+ });++ expect(migrated.document.bbox).toEqual({ height: 13, width: 12, x: -3, y: -4 });+ expect({ height: migrated.document.height, width: migrated.document.width }).toEqual({ height: 512, width: 512 });+ expect(migrated.snapshots[0]?.document.bbox).toEqual({ height: 13, width: 12, x: -3, y: -4 });+ });++ it('creates and migrates whole-pixel document dimensions', () => {+ const created = createEmptyCanvasDocumentV2(512.4, 511.6);+ const migrated = migrateCanvasStateToV2({ height: 511.6, layers: [], width: 512.4 });++ expect(created).toMatchObject({ bbox: { height: 512, width: 512, x: 0, y: 0 }, height: 512, width: 512 });+ expect(migrated.document).toMatchObject({+ bbox: { height: 512, width: 512, x: 0, y: 0 },+ height: 512,+ width: 512,+ });+ });+it('preserves the progress canvas staging auto-switch mode', () => {const migrated = migrateCanvasStateToV2({document: { height: 512, layers: [], width: 512 },diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.tsindex 8fbe2dbca4..593bbf89f4 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts@@ -212,6 +212,27 @@ const asPositiveNumber = (value: unknown, fallback: number): number => {return numeric > 0 ? numeric : fallback;};+/** A positive whole-pixel dimension, shared by creation and every migration path. */+const asPositiveInteger = (value: unknown, fallback: number): number =>+ Math.max(1, Math.round(asPositiveNumber(value, fallback)));++/** The canonical whole-pixel geometry for a live or persisted canvas document. */+const normalizeCanvasDocumentGeometry = (rawWidth: unknown, rawHeight: unknown, rawBbox?: unknown) => {+ const width = asPositiveInteger(rawWidth, DEFAULT_CANVAS_DOCUMENT_WIDTH);+ const height = asPositiveInteger(rawHeight, DEFAULT_CANVAS_DOCUMENT_HEIGHT);+ const bbox = isRecord(rawBbox) ? rawBbox : {};+ return {+ bbox: {+ height: asPositiveInteger(bbox.height, height),+ width: asPositiveInteger(bbox.width, width),+ x: Math.round(asNumber(bbox.x, 0)),+ y: Math.round(asNumber(bbox.y, 0)),+ },+ height,+ width,+ };+};+export const createEmptyCanvasStateV2 = (width = DEFAULT_CANVAS_DOCUMENT_WIDTH,height = DEFAULT_CANVAS_DOCUMENT_HEIGHT@@ -226,15 +247,16 @@ export const createEmptyCanvasStateV2 = (export const createEmptyCanvasDocumentV2 = (width = DEFAULT_CANVAS_DOCUMENT_WIDTH,height = DEFAULT_CANVAS_DOCUMENT_HEIGHT-): CanvasDocumentContractV2 => ({- background: 'transparent',- bbox: { height, width, x: 0, y: 0 },- height,- layers: [],- selectedLayerId: null,- version: 2,- width,-});+): CanvasDocumentContractV2 => {+ const geometry = normalizeCanvasDocumentGeometry(width, height);+ return {+ background: 'transparent',+ ...geometry,+ layers: [],+ selectedLayerId: null,+ version: 2,+ };+};/*** A brand-new project's default inpaint mask: one empty mask (no bitmap/strokes)@@ -353,18 +375,14 @@ const migrateLayerToV2 = (rawLayer: unknown, index: number): CanvasRasterLayerCoconst migrateDocumentToV2 = (rawCanvas: Record<string, unknown>): CanvasDocumentContractV2 => {const rawDocument = isRecord(rawCanvas.document) ? rawCanvas.document : rawCanvas;- const width = asPositiveNumber(rawDocument.width, DEFAULT_CANVAS_DOCUMENT_WIDTH);- const height = asPositiveNumber(rawDocument.height, DEFAULT_CANVAS_DOCUMENT_HEIGHT);const rawLayers = Array.isArray(rawDocument.layers) ? rawDocument.layers : [];return {background: 'transparent',- bbox: { height, width, x: 0, y: 0 },- height,+ ...normalizeCanvasDocumentGeometry(rawDocument.width, rawDocument.height),layers: rawLayers.map((rawLayer, index) => migrateLayerToV2(rawLayer, index)),selectedLayerId: null,version: 2,- width,};};@@ -431,10 +449,9 @@ const normalizeCanvasLayer = (value: unknown): CanvasDocumentContractV2['layers'return parsed.success ? (candidate as unknown as CanvasDocumentContractV2['layers'][number]) : null;};-export const normalizeCanvasDocumentControlAdapters = (- document: CanvasDocumentContractV2-): CanvasDocumentContractV2 => ({+export const normalizeCanvasDocumentContract = (document: CanvasDocumentContractV2): CanvasDocumentContractV2 => ({...document,+ ...normalizeCanvasDocumentGeometry(document.width, document.height, document.bbox),layers: document.layers.flatMap((layer) => {const normalized = normalizeCanvasLayer(layer);return normalized ? [normalized] : [];@@ -451,25 +468,15 @@ const normalizeCanvasDocumentV2 = (value: unknown, requireValidLayers: boolean):if (requireValidLayers && (!Array.isArray(rawDocument.layers) || layers.length !== rawLayers.length)) {return null;}- const width = asPositiveNumber(rawDocument.width, DEFAULT_CANVAS_DOCUMENT_WIDTH);- const height = asPositiveNumber(rawDocument.height, DEFAULT_CANVAS_DOCUMENT_HEIGHT);- const bbox = isRecord(rawDocument.bbox) ? rawDocument.bbox : {};return {background:rawDocument.background === 'transparent' || isRecord(rawDocument.background)? (rawDocument.background as CanvasDocumentContractV2['background']): 'transparent',- bbox: {- height: asPositiveNumber(bbox.height, height),- width: asPositiveNumber(bbox.width, width),- x: asNumber(bbox.x, 0),- y: asNumber(bbox.y, 0),- },- height,+ ...normalizeCanvasDocumentGeometry(rawDocument.width, rawDocument.height, rawDocument.bbox),layers,selectedLayerId: typeof rawDocument.selectedLayerId === 'string' ? rawDocument.selectedLayerId : null,version: 2,- width,};};diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex 79d81bfdea..3077a10ca9 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -11,7 +11,7 @@ import type { Project } from '@workbench/projectContracts';import { isHideableLayer } from '@workbench/canvas-engine/api';-import { normalizeCanvasDocumentControlAdapters } from './canvasMigration';+import { normalizeCanvasDocumentContract } from './canvasMigration';import {getCanvasStagingCandidateFingerprint,getCanvasStagingSlotCount,@@ -690,7 +690,7 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProcase 'replaceCanvasDocument':return setCanvasState(project, {...project.canvas,- document: repairSelectedLayerId(normalizeCanvasDocumentControlAdapters(structuredClone(mutation.document))),+ document: repairSelectedLayerId(normalizeCanvasDocumentContract(structuredClone(mutation.document))),documentRevision: project.canvas.documentRevision + 1,stagingArea: clearStagingArea(project.canvas.stagingArea),});@@ -701,7 +701,7 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro...project.canvas.snapshots,{createdAt: mutation.createdAt,- document: normalizeCanvasDocumentControlAdapters(structuredClone(project.canvas.document)),+ document: normalizeCanvasDocumentContract(structuredClone(project.canvas.document)),id: mutation.id,name: mutation.name,},@@ -712,7 +712,7 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProreturn snapshot? setCanvasState(project, {...project.canvas,- document: repairSelectedLayerId(normalizeCanvasDocumentControlAdapters(structuredClone(snapshot.document))),+ document: repairSelectedLayerId(normalizeCanvasDocumentContract(structuredClone(snapshot.document))),documentRevision: project.canvas.documentRevision + 1,}): project;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 96c378a978..75716730e1 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -4698,6 +4698,28 @@ describe('workbenchReducer canvas v2 layer reducers', () => {expect(getCanvas(state).document.layers[0]).not.toBe(replacement.layers[0]);});+ it('canonicalizes whole-pixel geometry across document replacement and snapshots', () => {+ let state = createInitialWorkbenchState();+ const fractional = {+ ...createEmptyCanvasDocumentV2(),+ bbox: { height: 99.6, width: 100.4, x: 1.2, y: -2.6 },+ height: 511.6,+ width: 512.4,+ };+ const expected = { bbox: { height: 100, width: 100, x: 1, y: -3 }, height: 512, width: 512 };++ state = workbenchReducer(state, { document: fractional, type: 'replaceCanvasDocument' });+ expect(getCanvas(state).document).toMatchObject(expected);++ Object.assign(getCanvas(state).document, fractional);+ state = workbenchReducer(state, { createdAt: 'now', id: 'snap-1', name: 'Fractional', type: 'saveCanvasSnapshot' });+ expect(getCanvas(state).snapshots[0]?.document).toMatchObject(expected);++ Object.assign(getCanvas(state).snapshots[0]!.document, fractional);+ state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'restoreCanvasSnapshot' });+ expect(getCanvas(state).document).toMatchObject(expected);+ });+it('clears the staging area on replaceCanvasDocument (staged candidates belong to the outgoing document)', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);const staged: Project['canvas']['stagingArea']['pendingImages'][number] = {