Skip to content

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.

test(canvas): add real-browser acceptance coverage

joshistoast545db32cf6db
diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.yml
index 824ec08203..fd7df90a25 100644
--- a/.github/workflows/frontend-tests.yml
+++ b/.github/workflows/frontend-tests.yml
@@ -79,6 +79,7 @@ jobs:
with:
files_yaml: |
webv2:
+ - '.github/workflows/frontend-tests.yml'
- 'invokeai/frontend/webv2/**'
- name: install dependencies
@@ -91,3 +92,13 @@ jobs:
if: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}
run: 'pnpm test'
shell: bash
+
+ - name: install Chromium
+ if: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}
+ run: 'pnpm exec playwright install chromium'
+ shell: bash
+
+ - name: vitest browser
+ if: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}
+ run: 'pnpm test:browser'
+ shell: bash
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 90db66d5b2..27c3e198ca 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -17,7 +17,9 @@
"lint:oxc:fix": "oxlint --react-plugin --import-plugin --fix .",
"lint:tsc": "tsc --noEmit",
"preview": "vite preview",
- "test": "vitest run"
+ "test": "vitest run --config vitest.config.mts",
+ "test:all": "pnpm run test && pnpm run test:browser",
+ "test:browser": "vitest run --config vitest.browser.config.mts"
},
"dependencies": {
"@chakra-ui/react": "^3.36.0",
@@ -31,7 +33,6 @@
"@tanstack/react-virtual": "^3.14.3",
"@xyflow/react": "^12.11.1",
"ag-psd": "^31.0.1",
- "fflate": "^0.8.3",
"i18next": "^25.7.3",
"i18next-http-backend": "^3.0.2",
"lucide-react": "^1.21.0",
@@ -53,6 +54,7 @@
"@types/react-dom": "^19.2.3",
"@types/use-sync-external-store": "^1.5.0",
"@vitejs/plugin-react": "^6.0.3",
+ "@vitest/browser-playwright": "4.1.9",
"babel-plugin-react-compiler": "^1.0.0",
"oxfmt": "^0.56.0",
"oxlint": "^1.71.0",
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index ca505a02e8..f326182a3d 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -41,9 +41,6 @@ importers:
ag-psd:
specifier: ^31.0.1
version: 31.0.1
- fflate:
- specifier: ^0.8.3
- version: 0.8.3
i18next:
specifier: ^25.7.3
version: 25.10.10([email protected])
@@ -102,6 +99,9 @@ importers:
'@vitejs/plugin-react':
specifier: ^6.0.3
+ '@vitest/browser-playwright':
+ specifier: 4.1.9
babel-plugin-react-compiler:
specifier: ^1.0.0
version: 1.0.0
@@ -119,7 +119,7 @@ importers:
version: 8.1.0(@types/[email protected])([email protected])
vitest:
specifier: ^4.1.9
packages:
@@ -200,6 +200,9 @@ packages:
resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}
engines: {node: '>=6.9.0'}
+ '@blazediff/[email protected]':
+ resolution: {integrity: sha512-ehg3jIkYKulZh+8om/O25vkvSsXXwC+skXmyA87FFx6A/45eqOkZsBltMw/TVteb0mloiGT8oGRTcjRAz66zaA==}
+
'@chakra-ui/[email protected]':
resolution: {integrity: sha512-6AxUbJsC6yyTzPeYL8sxyAL07lflT0NA+S6tcPzEuwdMux+benRMFOpPktnkifWKl/Vq/JD7fhxDyMuDQ4M0gA==}
peerDependencies:
@@ -719,6 +722,9 @@ packages:
resolution: {integrity: sha512-YaHK+p5DaN8AUpsRx5OqqGxaZzn8uNIdVhP+K1cjvjv3+Qa9D/75/A1dPyLmfKrSRJc8UoR9WN9fxQX0rVzhzQ==}
engines: {node: '>=20'}
+ '@polka/[email protected]':
+ resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
+
'@rolldown/[email protected]':
resolution: {integrity: sha512-DT6Z3PhvioeHMvxo+xHc3KtqggrI7CCTXCmC2h/5zUlp5jVitv7XEy+9q5/7v8IolhlioawpMo8Kg0EEBy7J0g==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -930,6 +936,17 @@ packages:
babel-plugin-react-compiler:
optional: true
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-Bq1rOGf9waevzG3EOkO/dene6bvKTUsZMVg8S1i+WH3JcMjuXEjiahP9rAqZRELUqjBySOJsvvSWqK/B3wjKQw==}
+ peerDependencies:
+ playwright: '*'
+ vitest: 4.1.9
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-j1BKtWmPcqpMhmx/L9EPLgAJpCb0zKfwoWLmqBbxaogCXHjOwHFSEoHCBfnGtx93xKQwilZ26m+UOsHqHMkRNg==}
+ peerDependencies:
+ vitest: 4.1.9
+
'@vitest/[email protected]':
resolution: {integrity: sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==}
@@ -1369,12 +1386,14 @@ packages:
picomatch:
optional: true
- resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
-
resolution: {integrity: sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==}
+ resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -1523,6 +1542,10 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -1605,6 +1628,20 @@ packages:
resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ resolution: {integrity: sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==}
+ engines: {node: '>=14.19.0'}
+
resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}
engines: {node: ^10 || ^12 || >=14}
@@ -1690,6 +1727,10 @@ packages:
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
+ resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==}
engines: {node: '>=10.0.0'}
@@ -1742,6 +1783,10 @@ packages:
resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
engines: {node: '>=14.0.0'}
+ resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}
@@ -2086,6 +2131,8 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
+ '@blazediff/[email protected]': {}
+
dependencies:
@@ -2458,6 +2505,8 @@ snapshots:
'@pandacss/[email protected]': {}
+ '@polka/[email protected]': {}
+
'@rolldown/[email protected]':
optional: true
@@ -2620,6 +2669,36 @@ snapshots:
babel-plugin-react-compiler: 1.0.0
+ dependencies:
+ '@vitest/mocker': 4.1.9([email protected](@types/[email protected])([email protected]))
+ playwright: 1.61.1
+ tinyrainbow: 3.1.0
+ transitivePeerDependencies:
+ - bufferutil
+ - msw
+ - utf-8-validate
+ - vite
+
+ dependencies:
+ '@blazediff/core': 1.9.1
+ '@vitest/mocker': 4.1.9([email protected](@types/[email protected])([email protected]))
+ '@vitest/utils': 4.1.9
+ magic-string: 0.30.21
+ pngjs: 7.0.0
+ sirv: 3.0.2
+ tinyrainbow: 3.1.0
+ ws: 8.21.0
+ transitivePeerDependencies:
+ - bufferutil
+ - msw
+ - utf-8-validate
+ - vite
+
'@vitest/[email protected]':
dependencies:
'@standard-schema/spec': 1.1.0
@@ -3422,10 +3501,11 @@ snapshots:
optionalDependencies:
picomatch: 4.0.4
-
+ optional: true
+
optional: true
@@ -3541,6 +3621,8 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
+
@@ -3624,6 +3706,16 @@ snapshots:
+
+ dependencies:
+ playwright-core: 1.61.1
+ optionalDependencies:
+ fsevents: 2.3.2
+
+
dependencies:
nanoid: 3.3.15
@@ -3709,6 +3801,12 @@ snapshots:
+ dependencies:
+ '@polka/url': 1.0.0-next.29
+ mrmime: 2.0.1
+ totalist: 3.0.1
+
dependencies:
'@socket.io/component-emitter': 3.1.2
@@ -3754,6 +3852,8 @@ snapshots:
+
@@ -3786,7 +3886,7 @@ snapshots:
esbuild: 0.27.7
fsevents: 2.3.3
dependencies:
'@vitest/expect': 4.1.9
'@vitest/mocker': 4.1.9([email protected](@types/[email protected])([email protected]))
@@ -3810,6 +3910,7 @@ snapshots:
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 26.0.1
transitivePeerDependencies:
- msw
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts
new file mode 100644
index 0000000000..d21ac5a5a5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts
@@ -0,0 +1,204 @@
+import type { Mat2d } from '@workbench/canvas-engine/types';
+import type {
+ CanvasDocumentContractV2,
+ CanvasLayerSourceContract,
+ CanvasRasterLayerContractV2,
+} from '@workbench/types';
+
+import { executePsdExport, planPsdExport } from '@workbench/canvas-engine/export/psdExport';
+import { createHistory } from '@workbench/canvas-engine/history/history';
+import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';
+import { compositeDocument } from '@workbench/canvas-engine/render/compositor';
+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
+import { createDomRasterBackend, type RasterSurface } from '@workbench/canvas-engine/render/raster';
+import { rasterizeTextSource } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';
+import { describe, expect, it } from 'vitest';
+
+const IDENTITY: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+
+const readPixel = (surface: RasterSurface, x: number, y: number): number[] => [
+ ...surface.ctx.getImageData(x, y, 1, 1).data,
+];
+
+const expectPixel = (surface: RasterSurface, x: number, y: number, expected: number[], tolerance = 0): void => {
+ const actual = readPixel(surface, x, y);
+ expected.forEach((channel, index) => {
+ expect(actual[index]).toBeGreaterThanOrEqual(channel - tolerance);
+ expect(actual[index]).toBeLessThanOrEqual(channel + tolerance);
+ });
+};
+
+const rasterLayer = (
+ id: string,
+ overrides: Partial<CanvasRasterLayerContractV2> = {}
+): CanvasRasterLayerContractV2 => ({
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: { image: { height: 8, imageName: id, width: 8 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ ...overrides,
+});
+
+const documentWith = (layers: CanvasRasterLayerContractV2[]): CanvasDocumentContractV2 => ({
+ background: 'transparent',
+ bbox: { height: 8, width: 8, x: 0, y: 0 },
+ height: 8,
+ layers,
+ selectedLayerId: layers[0]?.id ?? null,
+ version: 2,
+ width: 8,
+});
+
+describe('real browser raster acceptance', () => {
+ it('composites transformed layers through clipping, alpha, and multiply blend mode', () => {
+ const backend = createDomRasterBackend();
+ const caches = createLayerCacheStore(backend);
+ const bottom = caches.getOrCreate('bottom', 8, 8);
+ bottom.surface.ctx.fillStyle = '#ff0000';
+ bottom.surface.ctx.fillRect(0, 0, 8, 8);
+ caches.publishPixels('bottom');
+
+ const top = caches.getOrCreate('top', 4, 8);
+ top.surface.ctx.fillStyle = '#0000ff';
+ top.surface.ctx.fillRect(0, 0, 4, 8);
+ caches.publishPixels('top');
+
+ const target = backend.createSurface(8, 8);
+ compositeDocument(
+ target,
+ documentWith([
+ rasterLayer('top', {
+ blendMode: 'multiply',
+ opacity: 0.5,
+ source: { image: { height: 8, imageName: 'top', width: 4 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 2, y: 0 },
+ }),
+ rasterLayer('bottom'),
+ ]),
+ caches,
+ IDENTITY,
+ { clipRect: { height: 8, width: 4, x: 0, y: 0 } }
+ );
+
+ expectPixel(target, 1, 1, [255, 0, 0, 255]);
+ expectPixel(target, 3, 1, [127, 0, 0, 255], 2);
+ expectPixel(target, 5, 1, [0, 0, 0, 0]);
+ });
+
+ it('uses browser text metrics and produces real glyph pixels', async () => {
+ const backend = createDomRasterBackend();
+ const source: Extract<CanvasLayerSourceContract, { type: 'text' }> = {
+ align: 'left',
+ color: '#ff0000',
+ content: 'Invoke',
+ fontFamily: 'sans-serif',
+ fontSize: 24,
+ fontWeight: 400,
+ lineHeight: 1.2,
+ type: 'text',
+ };
+ const measureSurface = backend.createSurface(1, 1);
+ measureSurface.ctx.font = '400 24px sans-serif';
+ const browserWidth = Math.ceil(measureSurface.ctx.measureText(source.content).width);
+
+ const result = await rasterizeTextSource(source, {
+ backend,
+ documentSize: { height: 64, width: 64 },
+ resolver: () => Promise.resolve(new Blob()),
+ store: createLayerCacheStore(backend),
+ });
+ const pixels = result.surface.ctx.getImageData(0, 0, result.surface.width, result.surface.height).data;
+
+ expect(result.rect.width).toBe(browserWidth);
+ expect(result.rect.height).toBe(Math.ceil(24 * 1.2));
+ expect(pixels.some((channel, index) => index % 4 === 3 && channel > 0)).toBe(true);
+ });
+
+ it('encodes a PNG blob and decodes it through createImageBitmap', async () => {
+ const backend = createDomRasterBackend();
+ const source = backend.createSurface(3, 2);
+ source.ctx.fillStyle = '#00ff00';
+ source.ctx.fillRect(0, 0, 3, 2);
+
+ const blob = await backend.encodeSurface(source);
+ const bitmap = await backend.createImageBitmap(blob);
+ const decoded = backend.createSurface(3, 2);
+ decoded.ctx.drawImage(bitmap, 0, 0);
+
+ expect(blob.type).toBe('image/png');
+ expect(blob.size).toBeGreaterThan(0);
+ expect(bitmap.width).toBe(3);
+ expect(bitmap.height).toBe(2);
+ expectPixel(decoded, 1, 1, [0, 255, 0, 255]);
+ bitmap.close();
+ });
+
+ it('undoes and redoes a real pixel patch', () => {
+ const backend = createDomRasterBackend();
+ const surface = backend.createSurface(1, 1);
+ const before = new ImageData(new Uint8ClampedArray([255, 0, 0, 255]), 1, 1);
+ const after = new ImageData(new Uint8ClampedArray([0, 0, 255, 255]), 1, 1);
+ const history = createHistory();
+ surface.ctx.putImageData(after, 0, 0);
+ history.push(
+ createImagePatchEntry({
+ after,
+ apply: (_layerId, rect, pixels) => surface.ctx.putImageData(pixels, rect.x, rect.y),
+ before,
+ label: 'Browser pixel edit',
+ layerId: 'paint',
+ rect: { height: 1, width: 1, x: 0, y: 0 },
+ })
+ );
+
+ history.undo();
+ expectPixel(surface, 0, 0, [255, 0, 0, 255]);
+ history.redo();
+ expectPixel(surface, 0, 0, [0, 0, 255, 255]);
+ });
+
+ it('round-trips a small real PSD with layer and composite pixels', async () => {
+ const backend = createDomRasterBackend();
+ const layerSurface = backend.createSurface(2, 2);
+ layerSurface.ctx.fillStyle = '#ff0000';
+ layerSurface.ctx.fillRect(0, 0, 2, 2);
+ const plan = planPsdExport([
+ {
+ blendMode: 'normal',
+ contentRect: { height: 2, width: 2, x: 0, y: 0 },
+ id: 'red',
+ isEnabled: true,
+ name: 'Red',
+ opacity: 1,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ },
+ ]);
+ let bytes: ArrayBuffer | null = null;
+
+ await executePsdExport(plan, 'acceptance.psd', {
+ backend,
+ download: (data) => {
+ bytes = data;
+ },
+ getLayerSurface: () =>
+ Promise.resolve({
+ rect: { height: 2, width: 2, x: 0, y: 0 },
+ surface: layerSurface,
+ }),
+ });
+
+ expect(bytes).not.toBeNull();
+ const { readPsd } = await import('ag-psd');
+ const parsed = readPsd(bytes!, { useImageData: true });
+ expect(parsed.width).toBe(2);
+ expect(parsed.height).toBe(2);
+ expect(parsed.children?.map((child) => child.name)).toEqual(['Red']);
+ expect(Array.from(parsed.imageData!.data.slice(0, 4))).toEqual([255, 0, 0, 255]);
+ expect(Array.from(parsed.children![0]!.imageData!.data.slice(0, 4))).toEqual([255, 0, 0, 255]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
new file mode 100644
index 0000000000..9fa5cf971d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
@@ -0,0 +1,210 @@
+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import type { EngineDeps, EngineRegistry } from '@workbench/canvas-operations/engineRegistry';
+import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import type { CanvasStateContractV2 } from '@workbench/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { createEngineRegistry } from '@workbench/canvas-operations/engineRegistry';
+import { createEmptyCanvasStateV2 } from '@workbench/canvasMigration';
+import { act, StrictMode } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { CanvasSurface } from './CanvasSurface';
+
+type Cleanup = () => void | Promise<void>;
+
+const cleanupStack: Cleanup[] = [];
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const addCleanup = (cleanup: Cleanup): void => {
+ cleanupStack.push(cleanup);
+};
+
+const delay = (ms: number): Promise<void> =>
+ new Promise((resolve) => {
+ globalThis.setTimeout(resolve, ms);
+ });
+
+const createTrackedRegistry = (gracePeriodMs: number): EngineRegistry => {
+ const registry = createEngineRegistry({ gracePeriodMs });
+ // Registered before references and roots, so reverse-order cleanup releases
+ // those first and then lets the registry's grace timers finish.
+ addCleanup(() => delay(gracePeriodMs + 20));
+ return registry;
+};
+
+const acquireTrackedEngine = (
+ registry: EngineRegistry,
+ projectId: string,
+ deps: EngineDeps
+): { engine: CanvasEngine; release: () => void } => {
+ const engine = registry.getOrCreateEngine(projectId, deps);
+ let isHeld = true;
+ const release = (): void => {
+ if (!isHeld) {
+ return;
+ }
+ isHeld = false;
+ registry.releaseEngine(projectId);
+ };
+ addCleanup(release);
+ return { engine, release };
+};
+
+const createTrackedRoot = (host: HTMLDivElement) => {
+ const root = createRoot(host);
+ let isMounted = true;
+ const unmount = async (): Promise<void> => {
+ if (!isMounted) {
+ return;
+ }
+ isMounted = false;
+ try {
+ await act(() => {
+ root.unmount();
+ });
+ } finally {
+ host.remove();
+ }
+ };
+ addCleanup(unmount);
+ return { root, unmount };
+};
+
+const createEngineDeps = (state: CanvasStateContractV2): EngineDeps => {
+ const listeners = new Set<() => void>();
+ const mutationPort: CanvasProjectMutationPort = {
+ dispatch: () => false,
+ getCanvasState: () => state,
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+ return {
+ getMainModelBase: () => null,
+ imageResolver: () => Promise.resolve(new Blob()),
+ mutationPort,
+ reportError: () => undefined,
+ };
+};
+
+const nextFrame = (): Promise<void> =>
+ new Promise((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+
+const StrictCanvasHarness = ({ engine }: { engine: CanvasEngine }) => (
+ <StrictMode>
+ <ChakraProvider value={system}>
+ <div data-testid="surface-bounds" style={{ height: 120, width: 160 }}>
+ <CanvasSurface engine={engine} />
+ </div>
+ </ChakraProvider>
+ </StrictMode>
+);
+
+afterEach(async () => {
+ let firstError: unknown;
+ for (const cleanup of cleanupStack.reverse()) {
+ try {
+ await cleanup();
+ } catch (error) {
+ firstError ??= error;
+ }
+ }
+ cleanupStack.length = 0;
+ vi.restoreAllMocks();
+ if (firstError) {
+ throw new Error('CanvasSurface browser-test cleanup failed', { cause: firstError });
+ }
+});
+
+describe('CanvasSurface browser lifecycle', () => {
+ it('is StrictMode-safe across resize, registry reacquisition, detachment, and project switching', async () => {
+ const gracePeriodMs = 80;
+ const registry = createTrackedRegistry(gracePeriodMs);
+ const projectADeps = createEngineDeps(createEmptyCanvasStateV2(64, 64));
+ const firstProjectA = acquireTrackedEngine(registry, 'project-a', projectADeps);
+ const disposeA = vi.spyOn(firstProjectA.engine.lifecycle, 'dispose');
+ const beginCooldownA = vi.spyOn(firstProjectA.engine.lifecycle, 'beginCooldown');
+ const releasedAt = performance.now();
+ firstProjectA.release();
+ expect(beginCooldownA).toHaveBeenCalledOnce();
+ expect(firstProjectA.engine.lifecycle.getLifecycleState()).toBe('cooling');
+
+ await delay(5);
+ const reacquiredProjectA = acquireTrackedEngine(registry, 'project-a', projectADeps);
+ const projectA = reacquiredProjectA.engine;
+ expect(projectA).toBe(firstProjectA.engine);
+ expect(projectA.lifecycle.getLifecycleState()).toBe('active');
+
+ const originalDeadline = releasedAt + gracePeriodMs;
+ await delay(Math.max(0, originalDeadline - performance.now()) + 20);
+ expect(performance.now()).toBeGreaterThan(originalDeadline);
+ expect(registry.getEngine('project-a')).toBe(projectA);
+ expect(disposeA).not.toHaveBeenCalled();
+ expect(projectA.lifecycle.getLifecycleState()).toBe('active');
+
+ const projectBReference = acquireTrackedEngine(
+ registry,
+ 'project-b',
+ createEngineDeps(createEmptyCanvasStateV2(32, 48))
+ );
+ const projectB = projectBReference.engine;
+ const attachA = vi.spyOn(projectA.surface, 'attach');
+ const resizeA = vi.spyOn(projectA.surface, 'resize');
+ const detachA = vi.spyOn(projectA.surface, 'detach');
+ const attachB = vi.spyOn(projectB.surface, 'attach');
+ const resizeB = vi.spyOn(projectB.surface, 'resize');
+ const detachB = vi.spyOn(projectB.surface, 'detach');
+
+ const host = document.createElement('div');
+ document.body.append(host);
+ const { root, unmount } = createTrackedRoot(host);
+
+ await act(async () => {
+ root.render(<StrictCanvasHarness engine={projectA} />);
+ await nextFrame();
+ });
+
+ expect(attachA).toHaveBeenCalled();
+ expect(resizeA).toHaveBeenCalledWith(160, 120, globalThis.devicePixelRatio || 1);
+ const firstScreen = host.querySelector('canvas');
+ expect(firstScreen?.width).toBe(Math.round(160 * Math.min(globalThis.devicePixelRatio || 1, 2)));
+ expect(firstScreen?.height).toBe(Math.round(120 * Math.min(globalThis.devicePixelRatio || 1, 2)));
+
+ const bounds = host.querySelector<HTMLElement>('[data-testid="surface-bounds"]');
+ expect(bounds).not.toBeNull();
+ bounds!.style.width = '180px';
+ bounds!.style.height = '90px';
+ await act(async () => {
+ await nextFrame();
+ await nextFrame();
+ });
+ expect(resizeA).toHaveBeenCalledWith(180, 90, globalThis.devicePixelRatio || 1);
+
+ bounds!.style.width = '160px';
+ bounds!.style.height = '120px';
+
+ await act(async () => {
+ root.render(<StrictCanvasHarness engine={projectB} />);
+ await nextFrame();
+ });
+
+ expect(detachA).toHaveBeenCalled();
+ expect(attachB).toHaveBeenCalled();
+ expect(resizeB).toHaveBeenCalledWith(160, 120, globalThis.devicePixelRatio || 1);
+
+ await unmount();
+ reacquiredProjectA.release();
+ projectBReference.release();
+ expect(detachB).toHaveBeenCalled();
+
+ await delay(gracePeriodMs + 20);
+ expect(registry.getEngine('project-a')).toBeUndefined();
+ expect(registry.getEngine('project-b')).toBeUndefined();
+ });
+});
diff --git a/invokeai/frontend/webv2/vitest.browser.config.mts b/invokeai/frontend/webv2/vitest.browser.config.mts
new file mode 100644
index 0000000000..bb14e561e3
--- /dev/null
+++ b/invokeai/frontend/webv2/vitest.browser.config.mts
@@ -0,0 +1,20 @@
+import { playwright } from '@vitest/browser-playwright';
+import { mergeConfig } from 'vite';
+import { defineConfig } from 'vitest/config';
+
+import viteConfig from './vite.config.mts';
+
+export default mergeConfig(
+ viteConfig,
+ defineConfig({
+ test: {
+ browser: {
+ enabled: true,
+ headless: true,
+ instances: [{ browser: 'chromium' }],
+ provider: playwright(),
+ },
+ include: ['src/**/*.browser.test.{ts,tsx}'],
+ },
+ })
+);
diff --git a/invokeai/frontend/webv2/vitest.config.mts b/invokeai/frontend/webv2/vitest.config.mts
new file mode 100644
index 0000000000..acfb52c53a
--- /dev/null
+++ b/invokeai/frontend/webv2/vitest.config.mts
@@ -0,0 +1,14 @@
+import { mergeConfig } from 'vite';
+import { defineConfig } from 'vitest/config';
+
+import viteConfig from './vite.config.mts';
+
+export default mergeConfig(
+ viteConfig,
+ defineConfig({
+ test: {
+ exclude: ['src/**/*.browser.test.{ts,tsx}'],
+ include: ['src/**/*.test.{ts,tsx}'],
+ },
+ })
+);