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(webv2): round-trip project files through the mock backend

joshistoasta57f50c8fbe9
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index e4c497d984..e167b43641 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -9,8 +9,8 @@
"scripts": {
"architecture:check": "vitest run --config vitest.config.mts src/architecture/dependencyPolicy.test.ts src/architecture/workbenchOwnership.test.ts src/architecture/architectureWorkflow.test.ts src/architecture/tsSourceAnalysis.test.ts && node scripts/write-workbench-ownership-inventory.mjs && node scripts/write-contract-caller-matrix.mjs && node scripts/write-canvas-import-matrix.mjs",
"build": "pnpm run lint && vite build",
- "check:architecture": "pnpm run lint && pnpm run test:all && pnpm run test:performance:architecture",
- "check:release": "pnpm run lint && pnpm run test:all && pnpm run test:performance:architecture && pnpm run test:accessibility:browser",
+ "check:architecture": "pnpm run lint && pnpm run test:all && pnpm run test:performance:architecture && pnpm run test:project-files:browser",
+ "check:release": "pnpm run check:architecture && pnpm run test:accessibility:browser",
"dev": "vite dev",
"dev:host": "vite dev --host",
"fix": "pnpm run lint:oxc:fix && pnpm run format:write",
@@ -34,7 +34,9 @@
"test:performance:browser": "node scripts/measure-architecture-performance.mjs",
"test:performance:browser:update-baseline": "node scripts/measure-architecture-performance.mjs --update-baseline",
"test:performance:build": "pnpm run test:performance:contracts && vite build && node scripts/check-architecture-performance.mjs",
- "test:performance:contracts": "node --test scripts/performance-budgets.test.mjs"
+ "test:performance:contracts": "node --test scripts/performance-budgets.test.mjs",
+ "test:project-files": "vite build && pnpm run test:project-files:browser",
+ "test:project-files:browser": "node scripts/run-project-file-journey.mjs"
},
"dependencies": {
"@chakra-ui/react": "^3.36.1",
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
index 7c55423e21..660bfd9ad6 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
@@ -431,6 +431,27 @@ const createCanvasLayers = (count) =>
};
});
+const createProjectFileWorkflowNodes = () => {
+ const [node] = createWorkflowNodes(1);
+
+ return [
+ {
+ ...node,
+ data: {
+ ...node.data,
+ inputs: {
+ ...node.data.inputs,
+ video: {
+ label: '',
+ name: 'video',
+ value: { video_name: MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME },
+ },
+ },
+ },
+ },
+ ];
+};
+
const createProjectDocument = ({ index, layers = [], workflowNodes = [] }) => {
const id = `fixture-project-${ordinal(index, 3)}`;
const graphId = `${id}-graph`;
@@ -509,8 +530,9 @@ const createProjects = (count, workflowNodeCount, layerCount) =>
range(count, (index) => {
const data = createProjectDocument({
index,
- layers: index === 0 ? createCanvasLayers(layerCount) : [],
- workflowNodes: index === 0 ? createWorkflowNodes(workflowNodeCount) : [],
+ layers: index === 0 ? createCanvasLayers(layerCount) : index === 1 ? createCanvasLayers(4) : [],
+ workflowNodes:
+ index === 0 ? createWorkflowNodes(workflowNodeCount) : index === 1 ? createProjectFileWorkflowNodes() : [],
});
const timestamp = timestampAt(index);
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
index 9e93db0dbb..28b5c06763 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
@@ -8,6 +8,7 @@ import {
getMockBackendFixtureCounts,
MOCK_BACKEND_PROFILE_COUNTS,
MOCK_BACKEND_PROFILE_NAMES,
+ MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME,
validateMockBackendFixture,
} from './mock-backend-fixtures.mjs';
import { startMockBackend } from './mock-backend.mjs';
@@ -77,6 +78,24 @@ test('representative fixtures keep node discovery and heavy project data coheren
assert.equal(new Set(project.data.canvas.document.layers.map((layer) => layer.id)).size, 64);
});
+test('Fixture Project 002 carries the image and video references used by the project-file journey', () => {
+ const fixture = createMockBackendFixture('representative');
+ const project = fixture.projects[1];
+
+ assert.equal(project.project_id, 'fixture-project-002');
+ assert.deepEqual(
+ project.data.canvas.document.layers.map((layer) => layer.source.image.imageName),
+ ['fixture-image-0001.png', 'fixture-image-0002.png', 'fixture-image-0003.png', 'fixture-image-0004.png']
+ );
+ assert.equal(
+ project.data.canvas.document.layers.every((layer) => layer.type === 'raster'),
+ true
+ );
+ assert.deepEqual(project.data.projectGraph.nodes[0]?.data.inputs.video?.value, {
+ video_name: MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME,
+ });
+});
+
test('the HTTP reset contract selects profiles explicitly and restores the startup profile by default', async () => {
const backend = await startMockBackend(0, { profile: 'empty' });
@@ -101,15 +120,19 @@ test('the HTTP reset contract selects profiles explicitly and restores the start
profile: 'representative',
});
- const [images, itemIds, models, nodeCatalog, openApi, projects] = await Promise.all([
- readJson('/api/v1/images/?limit=17&offset=0'),
- readJson('/api/v1/queue/default/item_ids'),
- readJson('/api/v2/models/'),
- readJson('/api/v2/custom_nodes/'),
- readJson('/openapi.json'),
- readJson('/api/v1/projects/'),
- ]);
-
+ const [generationDevices, images, itemIds, models, nodeCatalog, openApi, projects, runtimeConfig] =
+ await Promise.all([
+ readJson('/api/v1/app/generation_device_options'),
+ readJson('/api/v1/images/?limit=17&offset=0'),
+ readJson('/api/v1/queue/default/item_ids'),
+ readJson('/api/v2/models/'),
+ readJson('/api/v2/custom_nodes/'),
+ readJson('/openapi.json'),
+ readJson('/api/v1/projects/'),
+ readJson('/api/v1/app/runtime_config'),
+ ]);
+
+ assert.deepEqual(generationDevices, [{ device: 'cpu', name: 'CPU' }]);
assert.equal(images.items.length, 17);
assert.equal(images.total, 1_000);
assert.equal(itemIds.item_ids.length, 500);
@@ -120,6 +143,7 @@ test('the HTTP reset contract selects profiles explicitly and restores the start
100
);
assert.equal(projects.length, 40);
+ assert.deepEqual(runtimeConfig, { config: { generation_devices: 'auto' }, set_fields: [] });
assert.deepEqual(await readJson('/__reset', { method: 'POST' }), {
counts: MOCK_BACKEND_PROFILE_COUNTS.empty,
@@ -321,6 +345,58 @@ test('video DTO, Details, poster, full media, HEAD, and Range routes use the che
});
});
+test('image upload preserves restore metadata and is retrievable through every image route', async () => {
+ await withRepresentativeBackend(async (backend) => {
+ const form = new FormData();
+ form.append('file', new Blob(['fixture upload'], { type: 'image/webp' }), 'uploaded fixture.webp');
+ const response = await fetch(
+ `${backend.origin}/api/v1/images/upload?image_category=other&is_intermediate=false&board_id=fixture-board-02`,
+ { body: form, method: 'POST' }
+ );
+ const expectedName = 'fixture-upload-1001-uploaded-fixture.webp.png';
+ const expectedDto = {
+ board_id: 'fixture-board-02',
+ created_at: '2026-01-15T12:00:00.000Z',
+ deleted_at: null,
+ has_workflow: false,
+ height: 1,
+ image_category: 'other',
+ image_name: expectedName,
+ image_origin: 'external',
+ image_subfolder: '',
+ image_url: `/api/v1/images/i/${expectedName}/full`,
+ is_intermediate: false,
+ node_id: null,
+ session_id: null,
+ starred: false,
+ thumbnail_url: `/api/v1/images/i/${expectedName}/thumbnail`,
+ updated_at: '2026-01-15T12:00:00.000Z',
+ width: 1,
+ };
+
+ assert.equal(response.status, 201);
+ assert.equal(response.headers.get('location'), expectedDto.image_url);
+ assert.deepEqual(await response.json(), expectedDto);
+ assert.deepEqual(
+ await getJson(backend, '/api/v1/images/images_by_names', {
+ body: JSON.stringify({ image_names: [expectedName, 'missing.png'] }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ }),
+ [expectedDto]
+ );
+ assert.deepEqual(await getJson(backend, `/api/v1/images/i/${encodeURIComponent(expectedName)}`), expectedDto);
+
+ for (const variant of ['full', 'thumbnail']) {
+ const asset = await fetch(`${backend.origin}/api/v1/images/i/${encodeURIComponent(expectedName)}/${variant}`);
+
+ assert.equal(asset.status, 200);
+ assert.equal(asset.headers.get('content-type'), 'image/png');
+ assert.ok((await asset.arrayBuffer()).byteLength > 0);
+ }
+ });
+});
+
test('video upload, star, delete, board movement, counts, covers, and board deletion return authoritative outcomes', async () => {
await withRepresentativeBackend(async (backend) => {
const boards = await getJson(backend, '/api/v1/boards/?all=true');
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 1b5d43ccbc..aaa8be8e29 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -65,6 +65,7 @@ const createState = (profile) => {
images: new Map(fixture.images.map((image) => [image.image_name, clone(image)])),
models: new Map(fixture.models.map((model) => [model.key, clone(model)])),
mutationClock: 0,
+ nextImageNumber: fixture.images.length + 1,
nextProjectNumber: fixture.projects.length + 1,
nextVideoNumber: fixture.videos.length + 1,
nodeCatalog: clone(fixture.nodeCatalog),
@@ -568,6 +569,14 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, { version: 'fixture' });
}
+ if (method === 'GET' && path === '/api/v1/app/generation_device_options') {
+ return json(200, [{ device: 'cpu', name: 'CPU' }]);
+ }
+
+ if (method === 'GET' && path === '/api/v1/app/runtime_config') {
+ return json(200, { config: { generation_devices: 'auto' }, set_fields: [] });
+ }
+
if (path.startsWith('/api/v1/app/external_providers')) {
return json(200, []);
}
@@ -876,6 +885,39 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
);
}
+ if (method === 'POST' && path === '/api/v1/images/upload') {
+ const multipartBody = await readBody(request);
+ const requestedName = /filename="([^"]+)"/.exec(multipartBody)?.[1] ?? 'uploaded-fixture';
+ const suffix = String(state.nextImageNumber).padStart(3, '0');
+ const imageName = `fixture-upload-${suffix}-${requestedName.replaceAll(/[^a-zA-Z0-9._-]/g, '-')}.png`;
+ const boardId = url.searchParams.get('board_id');
+ const now = timestamp(state);
+ const image = {
+ board_id: boardId && state.boards.has(boardId) ? boardId : null,
+ created_at: now,
+ deleted_at: null,
+ has_workflow: false,
+ height: 1,
+ image_category: url.searchParams.get('image_category') ?? 'general',
+ image_name: imageName,
+ image_origin: 'external',
+ image_subfolder: '',
+ image_url: `/api/v1/images/i/${imageName}/full`,
+ is_intermediate: url.searchParams.get('is_intermediate') === 'true',
+ node_id: null,
+ session_id: null,
+ starred: false,
+ thumbnail_url: `/api/v1/images/i/${imageName}/thumbnail`,
+ updated_at: now,
+ width: 1,
+ };
+
+ state.nextImageNumber += 1;
+ state.images.set(imageName, image);
+ response.setHeader('location', image.image_url);
+ return json(201, image);
+ }
+
if (method === 'GET' && (path === '/api/v1/images' || path === '/api/v1/images/')) {
return json(200, listImages(state, url));
}
diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
new file mode 100644
index 0000000000..d8d2c5fc8a
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
@@ -0,0 +1,371 @@
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { performance } from 'node:perf_hooks';
+import process from 'node:process';
+import { chromium } from 'playwright';
+
+import { MOCK_BACKEND_PROFILE_COUNTS, MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME } from './mock-backend-fixtures.mjs';
+import { startMockBackend } from './mock-backend.mjs';
+
+const root = resolve(import.meta.dirname, '..');
+const port = Number(process.env.INVOKEAI_PROJECT_FILE_PORT ?? 4180);
+const origin = `http://127.0.0.1:${String(port)}`;
+const backendPort = Number(process.env.INVOKEAI_PROJECT_FILE_BACKEND_PORT ?? 4181);
+const backendOrigin = `http://127.0.0.1:${String(backendPort)}`;
+const sourceProjectId = 'fixture-project-002';
+const sourceProjectName = 'Fixture Project 002';
+const sourceProjectPath = `/#/app?project=${sourceProjectId}`;
+const journeyTimeoutMs = 60_000;
+
+const delay = (durationMs) =>
+ new Promise((resolveDelay) => {
+ setTimeout(resolveDelay, durationMs);
+ });
+
+const fetchJson = async (path, init) => {
+ const response = await fetch(`${backendOrigin}${path}`, init);
+ const body = await response.json();
+
+ assert.equal(
+ response.ok,
+ true,
+ `${init?.method ?? 'GET'} ${path} returned ${String(response.status)}: ${JSON.stringify(body)}`
+ );
+
+ return body;
+};
+
+const waitForPreview = async (getPreviewExit) => {
+ const deadline = Date.now() + 20_000;
+
+ while (Date.now() < deadline) {
+ const previewExit = getPreviewExit();
+
+ if (previewExit !== null) {
+ throw new Error(`Vite preview exited before becoming ready (${previewExit}).`);
+ }
+
+ try {
+ const response = await fetch(origin);
+
+ if (response.ok) {
+ return;
+ }
+ } catch {
+ // Preview is still starting.
+ }
+
+ await delay(100);
+ }
+
+ throw new Error(`Vite preview did not become ready at ${origin}.`);
+};
+
+const observeBrowserErrors = (page, phase, errors) => {
+ page.on('pageerror', (error) => {
+ errors.push(new Error(`${phase} page error: ${error.stack ?? error.message}`));
+ });
+ page.on('console', (message) => {
+ if (message.type() === 'error') {
+ const location = message.location();
+
+ // Every release harness deliberately uses the HTTP-only mock backend, so
+ // Socket.IO's transport probe is expected to stay disconnected. Ignore
+ // only that browser-generated 404; application console errors still fail.
+ if (
+ location.url.includes('/ws/socket.io/') &&
+ message.text().includes('the server responded with a status of 404')
+ ) {
+ return;
+ }
+
+ // Video existence has no bulk endpoint. Import deliberately probes the
+ // archived name and treats this exact 404 as the signal to restore it.
+ if (
+ phase === 'import' &&
+ location.url &&
+ new URL(location.url).pathname === `/api/v1/videos/i/${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}` &&
+ message.text().includes('the server responded with a status of 404')
+ ) {
+ return;
+ }
+
+ const where = location.url ? ` (${location.url}:${String(location.lineNumber)})` : '';
+
+ errors.push(new Error(`${phase} console error${where}: ${message.text()}`));
+ }
+ });
+};
+
+const assertNoBrowserErrors = (errors) => {
+ if (errors.length > 0) {
+ throw new AggregateError(errors, 'The project-file journey raised browser errors.');
+ }
+};
+
+const assertAssetRoute = async (basePath, name, variants) => {
+ const encodedName = encodeURIComponent(name);
+ const dto = await fetch(`${backendOrigin}${basePath}/i/${encodedName}`);
+
+ assert.equal(dto.status, 200, `${basePath}/i/${encodedName} returned ${String(dto.status)}.`);
+
+ for (const variant of variants) {
+ const asset = await fetch(`${backendOrigin}${basePath}/i/${encodedName}/${variant}`);
+
+ assert.equal(asset.status, 200, `${basePath}/i/${encodedName}/${variant} returned ${String(asset.status)}.`);
+ assert.ok((await asset.arrayBuffer()).byteLength > 0, `${basePath}/${variant} returned an empty body.`);
+ }
+};
+
+const waitForProjectCover = async (projectId, restoredImageNames) => {
+ const deadline = Date.now() + 10_000;
+
+ while (Date.now() < deadline) {
+ const raw = await fetchJson('/api/v1/client_state/default/get_by_key?key=webv2%3Aproject-covers');
+
+ if (typeof raw === 'string') {
+ const coverIndex = JSON.parse(raw);
+ const coverImageName = coverIndex[projectId];
+
+ if (restoredImageNames.has(coverImageName)) {
+ return coverImageName;
+ }
+ }
+
+ await delay(50);
+ }
+
+ assert.fail(`The project cover index never mapped ${projectId} to a restored image.`);
+};
+
+const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory }) => {
+ const exportContext = await browser.newContext({ acceptDownloads: true });
+
+ contexts.add(exportContext);
+ const exportPage = await exportContext.newPage();
+ observeBrowserErrors(exportPage, 'export', errors);
+ await exportPage.goto(`${origin}${sourceProjectPath}`, { waitUntil: 'domcontentloaded' });
+ await exportPage.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();
+
+ const downloadPromise = exportPage.waitForEvent('download');
+ await exportPage
+ .getByRole('button', { exact: true, name: `Switch project. Current project: ${sourceProjectName}` })
+ .click();
+ await exportPage.getByRole('menuitem', { exact: true, name: 'Export' }).click();
+ const download = await downloadPromise;
+ const archivePath = join(tempDirectory, 'fixture-project-002.invk');
+
+ assert.equal(download.suggestedFilename(), `${sourceProjectName}.invk`);
+ await download.saveAs(archivePath);
+ await exportContext.close();
+ contexts.delete(exportContext);
+ assertNoBrowserErrors(errors);
+
+ const reset = await fetchJson('/__reset?profile=empty', { method: 'POST' });
+
+ assert.equal(reset.profile, 'empty');
+ assert.deepEqual(reset.counts, MOCK_BACKEND_PROFILE_COUNTS.empty);
+ assert.equal(backend.profile(), 'empty');
+
+ const importContext = await browser.newContext();
+
+ contexts.add(importContext);
+ const importPage = await importContext.newPage();
+ const uploadResponses = [];
+
+ importPage.on('response', (response) => {
+ const path = new URL(response.url()).pathname;
+ const kind = path === '/api/v1/images/upload' ? 'image' : path === '/api/v1/videos/upload' ? 'video' : null;
+
+ if (kind !== null && response.request().method() === 'POST') {
+ uploadResponses.push(
+ response.json().then((dto) => ({
+ kind,
+ name: kind === 'image' ? dto.image_name : dto.video_name,
+ status: response.status(),
+ }))
+ );
+ }
+ });
+ observeBrowserErrors(importPage, 'import', errors);
+ await importPage.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });
+ await importPage.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
+
+ const chooserPromise = importPage.waitForEvent('filechooser');
+ await importPage.getByRole('button', { exact: true, name: 'Import…' }).click();
+ const chooser = await chooserPromise;
+
+ await chooser.setFiles(archivePath);
+ await importPage.waitForURL(/#\/app\?project=/);
+ await importPage.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();
+
+ const projects = await fetchJson('/api/v1/projects/');
+
+ assert.equal(projects.length, 1);
+ const [summary] = projects;
+
+ assert.ok(summary);
+ assert.notEqual(summary.project_id, sourceProjectId);
+ assert.equal(importPage.url().includes(`project=${encodeURIComponent(summary.project_id)}`), true);
+
+ const imported = await fetchJson(`/api/v1/projects/${encodeURIComponent(summary.project_id)}`);
+ const images = await fetchJson('/api/v1/images/?categories=other&limit=100&offset=0');
+ const videos = await fetchJson('/api/v1/videos/?categories=other&limit=100&offset=0');
+ const uploads = await Promise.all(uploadResponses);
+
+ assert.equal(imported.project_id, summary.project_id);
+ assert.equal(imported.data.id, summary.project_id);
+ assert.equal(images.total, 4);
+ assert.equal(images.items.length, 4);
+ assert.equal(videos.total, 1);
+ assert.equal(videos.items.length, 1);
+
+ const restoredImageNames = new Set(images.items.map((image) => image.image_name));
+ const restoredVideoNames = new Set(videos.items.map((video) => video.video_name));
+ const uploadedImageNames = uploads.filter(({ kind }) => kind === 'image').map(({ name }) => name);
+ const uploadedVideoNames = uploads.filter(({ kind }) => kind === 'video').map(({ name }) => name);
+ const layerImageNames = imported.data.canvas.document.layers.map((layer) => layer.source.image.imageName);
+ const videoName = imported.data.projectGraph.nodes[0]?.data.inputs.video?.value?.video_name;
+
+ assert.equal(
+ uploads.every(({ status }) => status === 201),
+ true
+ );
+ assert.equal(uploadedImageNames.length, 4);
+ assert.equal(uploadedVideoNames.length, 1);
+ assert.deepEqual([...uploadedImageNames].sort(), [...restoredImageNames].sort());
+ assert.deepEqual(uploadedVideoNames, [...restoredVideoNames]);
+ assert.equal(layerImageNames.length, 4);
+ assert.equal(new Set(layerImageNames).size, 4);
+ assert.deepEqual([...layerImageNames].sort(), [...restoredImageNames].sort());
+ assert.deepEqual([...restoredVideoNames], [videoName]);
+ assert.notEqual(videoName, MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME);
+
+ for (const image of images.items) {
+ assert.equal(image.image_category, 'other');
+ assert.equal(image.is_intermediate, false);
+ await assertAssetRoute('/api/v1/images', image.image_name, ['full', 'thumbnail']);
+ }
+
+ for (const video of videos.items) {
+ assert.equal(video.video_category, 'other');
+ assert.equal(video.is_intermediate, false);
+ await assertAssetRoute('/api/v1/videos', video.video_name, ['full', 'thumbnail']);
+ }
+
+ const coverImageName = await waitForProjectCover(summary.project_id, restoredImageNames);
+
+ assert.ok(layerImageNames.includes(coverImageName));
+ assertNoBrowserErrors(errors);
+
+ return {
+ coverImageName,
+ imageNames: [...restoredImageNames].sort(),
+ projectId: summary.project_id,
+ videoName,
+ };
+};
+
+const startedAt = performance.now();
+const tempDirectory = await mkdtemp(join(tmpdir(), 'invokeai-project-file-journey-'));
+const contexts = new Set();
+const browserErrors = [];
+let backend = null;
+let browser = null;
+let preview = null;
+let previewError = '';
+let previewExit = null;
+let timeoutId;
+let result;
+let failure;
+
+try {
+ const journey = (async () => {
+ backend = await startMockBackend(backendPort, { profile: 'representative' });
+ preview = spawn(
+ 'pnpm',
+ ['exec', 'vite', 'preview', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
+ {
+ cwd: root,
+ detached: true,
+ env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },
+ stdio: ['ignore', 'ignore', 'pipe'],
+ }
+ );
+ preview.stderr.on('data', (chunk) => {
+ previewError += String(chunk);
+ });
+ preview.on('exit', (code, signal) => {
+ previewExit = signal ? `signal ${signal}` : `code ${String(code)}`;
+ });
+
+ await waitForPreview(() => previewExit);
+ browser = await chromium.launch({ headless: true });
+
+ return runRoundTrip({
+ backend,
+ browser,
+ contexts,
+ errors: browserErrors,
+ tempDirectory,
+ });
+ })();
+ const timeout = new Promise((_, reject) => {
+ timeoutId = setTimeout(() => {
+ reject(new Error(`Project-file journey exceeded its ${String(journeyTimeoutMs / 1_000)}-second timeout.`));
+ }, journeyTimeoutMs);
+ });
+
+ result = await Promise.race([journey, timeout]);
+} catch (error) {
+ failure = error;
+} finally {
+ clearTimeout(timeoutId);
+
+ for (const context of contexts) {
+ try {
+ await context.close();
+ } catch {
+ // A timed-out browser may already have torn down this context.
+ }
+ }
+ await browser?.close();
+
+ if (preview?.pid) {
+ try {
+ process.kill(-preview.pid, 'SIGTERM');
+ } catch {
+ // Preview may already have exited after a startup failure.
+ }
+ }
+
+ await backend?.close();
+ await rm(tempDirectory, { force: true, recursive: true });
+}
+
+const durationMs = Math.round(performance.now() - startedAt);
+
+if (failure) {
+ const detail = failure instanceof Error ? (failure.stack ?? failure.message) : String(failure);
+ const browserDetail = browserErrors.length > 0 ? `\n${browserErrors.map((error) => error.message).join('\n')}` : '';
+ const previewDetail = previewError ? `\nVite preview stderr:\n${previewError}` : '';
+
+ throw new Error(`${detail}${browserDetail}${previewDetail}\nJourney duration: ${String(durationMs)} ms.`);
+}
+
+process.stdout.write(
+ `${JSON.stringify(
+ {
+ durationMs,
+ ports: { backend: backendPort, preview: port },
+ result,
+ status: 'passed',
+ timeoutMs: journeyTimeoutMs,
+ },
+ null,
+ 2
+ )}\n`
+);