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.

fix(webv2): let the browser-driving scripts run on Windows

Alexander Eichhorn9768212dd0bb
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 9fc4580a6c..dfd18cce68 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -30,7 +30,7 @@
"test:all": "pnpm run test && pnpm run test:browser && pnpm run test:fixtures",
"test:browser": "vitest run --config vitest.browser.config.mts",
"test:browser:update-goldens": "CANVAS_GOLDEN_UPDATE=1 vitest run --config vitest.browser.config.mts src/workbench/canvas-engine/render/golden",
- "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs",
+ "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/preview-server.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs",
"test:performance:architecture": "pnpm run test:performance:build && pnpm run test:performance:browser",
"test:performance:browser": "node scripts/measure-architecture-performance.mjs",
"test:performance:browser:update-baseline": "node scripts/measure-architecture-performance.mjs --update-baseline",
diff --git a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs
index ce86e22e88..3dcfec0be2 100644
--- a/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs
+++ b/invokeai/frontend/webv2/scripts/measure-architecture-performance.mjs
@@ -1,4 +1,3 @@
-import { spawn } from 'node:child_process';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import process from 'node:process';
@@ -15,6 +14,7 @@ import {
waitForRequiredRequests,
waitForStableRequests,
} from './performance-budgets.mjs';
+import { killPreview, spawnPreview } from './preview-server.mjs';
import { getWidgetId } from './widget-sources.mjs';
const root = resolve(import.meta.dirname, '..');
@@ -624,16 +624,12 @@ const runSample = async (browser, fixture, sample) => {
// in-memory mock backend, never a live InvokeAI instance with real data.
const mockBackend = await startMockBackend(backendPort);
-const 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', 'pipe', 'pipe'],
- }
-);
+const preview = spawnPreview({
+ cwd: root,
+ env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },
+ port,
+ stdio: ['ignore', 'pipe', 'pipe'],
+});
let previewError = '';
preview.stderr.on('data', (chunk) => {
previewError += String(chunk);
@@ -855,7 +851,7 @@ try {
await browser?.close();
if (preview.pid) {
try {
- process.kill(-preview.pid, 'SIGTERM');
+ killPreview(preview.pid, 'SIGTERM');
} catch {
// The preview process may have already exited after a startup failure.
}
diff --git a/invokeai/frontend/webv2/scripts/preview-server.mjs b/invokeai/frontend/webv2/scripts/preview-server.mjs
new file mode 100644
index 0000000000..1349c1617b
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/preview-server.mjs
@@ -0,0 +1,68 @@
+/**
+ * The `vite preview` server the browser-driving scripts measure against.
+ *
+ * Three scripts need it — the architecture performance measurement, the accessibility journeys and
+ * the project-file journey — and each needs the same two things: start a preview server on a fixed
+ * port, and take it down again along with anything it spawned. Both halves are platform-sensitive
+ * in ways that are easy to get subtly wrong, so they live here once.
+ *
+ * Starting it as `pnpm exec vite preview` does not work on Windows: `pnpm` there is a `.cmd` shim,
+ * and Node refuses to exec one without `shell: true`. Adding a shell would start it, but it also
+ * puts `cmd.exe` between the script and vite — teardown signals the process it spawned, which would
+ * then be the shell rather than the server, leaving the port bound and the next run failing on
+ * `--strictPort`. Running vite's own entry under this same Node keeps the child a plain process
+ * everywhere and needs no shell at all.
+ */
+
+import { spawn, spawnSync } from 'node:child_process';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+import process from 'node:process';
+
+const isWindows = process.platform === 'win32';
+
+// Resolved through `package.json` rather than `vite/bin/vite.js` directly: vite's `exports` map
+// does not expose the bin path, so asking for it by subpath throws ERR_PACKAGE_PATH_NOT_EXPORTED.
+const viteBin = join(dirname(createRequire(import.meta.url).resolve('vite/package.json')), 'bin', 'vite.js');
+
+/**
+ * Start a preview server on `port`, bound to loopback and refusing to drift to another port.
+ *
+ * Every option other than `port` is passed through to `spawn`, so callers keep control of `cwd`,
+ * `env` and `stdio` — they differ between the three scripts.
+ */
+export const spawnPreview = ({ port, ...options }) =>
+ spawn(process.execPath, [viteBin, 'preview', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], {
+ // What puts the child in its own process group, so `killPreview` can signal the whole tree.
+ // Windows has no process groups, and `detached` there means "own console window" instead —
+ // not useful, and it flashes one up on every run.
+ detached: !isWindows,
+ ...options,
+ });
+
+/**
+ * Stop a preview server started by `spawnPreview`, including any child processes of its own.
+ *
+ * Throws the way `process.kill` does — notably `ESRCH` when the server has already exited, which
+ * callers distinguish from a real failure.
+ */
+export const killPreview = (pid, signal) => {
+ if (!isWindows) {
+ process.kill(-pid, signal);
+ return;
+ }
+
+ // No process groups here, so the tree walk is taskkill's `/T`. `/F` because the signal argument
+ // has no Windows equivalent: a graceful stop would need a console control event, which cannot be
+ // sent to a process that does not share this one's console.
+ const result = spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
+
+ // taskkill reports 128 for "no such process", which is what ESRCH means to every caller here.
+ if (result.status === 128) {
+ throw Object.assign(new Error(`No such process: ${pid}`), { code: 'ESRCH' });
+ }
+
+ if (result.error) {
+ throw result.error;
+ }
+};
diff --git a/invokeai/frontend/webv2/scripts/preview-server.test.mjs b/invokeai/frontend/webv2/scripts/preview-server.test.mjs
new file mode 100644
index 0000000000..466673c0aa
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/preview-server.test.mjs
@@ -0,0 +1,66 @@
+/**
+ * `killPreview` has to report an already-dead process the same way on every platform.
+ *
+ * The project-file journey tears the preview down in two steps — SIGTERM, wait, SIGKILL — and lets
+ * `ESRCH` through as "it already exited" while rethrowing anything else. On POSIX that code comes
+ * from `process.kill`. On Windows there is no process group to signal, so the tree kill is
+ * `taskkill /T`, and its "no such process" exit status is translated by hand. A hand-written
+ * translation is exactly the kind of thing that stops matching when the tool changes, and the
+ * symptom would be a journey that fails during cleanup after passing.
+ */
+
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { resolve } from 'node:path';
+import process from 'node:process';
+import { test } from 'node:test';
+
+import { killPreview, spawnPreview } from './preview-server.mjs';
+
+/** A process that exits immediately, so its pid is real but reaped by the time we signal it. */
+const spawnExited = async () => {
+ const child = spawn(process.execPath, ['-e', ''], { stdio: 'ignore' });
+ await new Promise((resolve) => {
+ child.once('exit', resolve);
+ });
+ return child.pid;
+};
+
+test('reports an already-exited process as ESRCH', async () => {
+ const pid = await spawnExited();
+
+ assert.throws(() => killPreview(pid, 'SIGTERM'), { code: 'ESRCH' });
+});
+
+test('starts a preview server without a shell and stops it again', async (t) => {
+ // Deliberately not one of the three ports the journeys bind, so running this beside them cannot
+ // make either fail on `--strictPort`.
+ const port = 4199;
+ // `import.meta.dirname`, not a URL pathname: on Windows the latter is '/D:/...', which is not
+ // a directory any process can start in.
+ const preview = spawnPreview({
+ cwd: resolve(import.meta.dirname, '..'),
+ port,
+ stdio: ['ignore', 'ignore', 'pipe'],
+ });
+
+ t.after(() => {
+ try {
+ killPreview(preview.pid, 'SIGKILL');
+ } catch (error) {
+ if (error?.code !== 'ESRCH') {
+ throw error;
+ }
+ }
+ });
+
+ // The point of the assertion: a `.cmd` shim spawned without a shell fails here with ENOENT, which
+ // is what this module exists to avoid, and a shell wrapper would make `preview.pid` the shell's.
+ const spawned = await new Promise((resolve) => {
+ preview.once('spawn', () => resolve(true));
+ preview.once('error', () => resolve(false));
+ });
+
+ assert.equal(spawned, true, 'the preview server could not be spawned');
+ assert.ok(preview.pid, 'the preview server has no pid');
+});
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index 74733cdb7b..5324a097d2 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -1,5 +1,4 @@
import assert from 'node:assert/strict';
-import { spawn } from 'node:child_process';
import { resolve } from 'node:path';
import process from 'node:process';
import { chromium } from 'playwright';
@@ -7,6 +6,7 @@ import { chromium } from 'playwright';
import { assertNoAxeViolations } from './accessibility/axe.mjs';
import { MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME } from './mock-backend-fixtures.mjs';
import { startMockBackend } from './mock-backend.mjs';
+import { killPreview, spawnPreview } from './preview-server.mjs';
const root = resolve(import.meta.dirname, '..');
const port = Number(process.env.INVOKEAI_ACCESSIBILITY_PORT ?? 4178);
@@ -967,16 +967,12 @@ const runSettingsJourney = async (browser) => {
};
const mockBackend = await startMockBackend(backendPort, { profile: 'representative' });
-const 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', 'pipe', 'pipe'],
- }
-);
+const preview = spawnPreview({
+ cwd: root,
+ env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },
+ port,
+ stdio: ['ignore', 'pipe', 'pipe'],
+});
let previewError = '';
let browser = null;
@@ -1027,7 +1023,7 @@ try {
if (preview.pid) {
try {
- process.kill(-preview.pid, 'SIGTERM');
+ killPreview(preview.pid, 'SIGTERM');
} catch {
// Preview may already have exited after a startup failure.
}
diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
index df0cb86003..4f63b031df 100644
--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
@@ -1,6 +1,5 @@
import { unzipSync, zipSync } from 'fflate';
import assert from 'node:assert/strict';
-import { spawn } from 'node:child_process';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
@@ -17,6 +16,7 @@ import {
PROJECT_FILE_BOARD_ID,
} from './mock-backend-fixtures.mjs';
import { startMockBackend } from './mock-backend.mjs';
+import { killPreview, spawnPreview } from './preview-server.mjs';
const root = resolve(import.meta.dirname, '..');
const port = Number(process.env.INVOKEAI_PROJECT_FILE_PORT ?? 4180);
@@ -526,16 +526,16 @@ const withTimeout = async (run, durationMs, label) => {
const getDefaultDependencies = () => ({
createTempDirectory: () => mkdtemp(join(tmpdir(), 'invokeai-project-file-journey-')),
- killProcessGroup: (pid, signal) => process.kill(-pid, signal),
+ killPreview,
launchBrowser: ({ timeoutMs }) => chromium.launch({ headless: true, timeout: timeoutMs }),
now: () => performance.now(),
removeTempDirectory: (directory) => rm(directory, { force: true, recursive: true }),
runRoundTrip,
spawnPreview: () =>
- spawn('pnpm', ['exec', 'vite', 'preview', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], {
+ spawnPreview({
cwd: root,
- detached: true,
env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },
+ port,
stdio: ['ignore', 'ignore', 'pipe'],
}),
startBackend: () => startMockBackend(backendPort, { profile: 'representative' }),
@@ -654,7 +654,7 @@ export const executeProjectFileJourney = async ({
});
try {
- dependencies.killProcessGroup(preview.pid, 'SIGTERM');
+ dependencies.killPreview(preview.pid, 'SIGTERM');
} catch (error) {
if (error?.code !== 'ESRCH') {
throw error;
@@ -667,7 +667,7 @@ export const executeProjectFileJourney = async ({
}
try {
- dependencies.killProcessGroup(preview.pid, 'SIGKILL');
+ dependencies.killPreview(preview.pid, 'SIGKILL');
} catch (error) {
if (error?.code !== 'ESRCH') {
throw error;
diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.test.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.test.mjs
index 4991aad2fa..b6e217b876 100644
--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.test.mjs
+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.test.mjs
@@ -25,7 +25,7 @@ const createSuccessfulDependencies = (events, overrides = {}) => {
events.push('temp:create');
return '/tmp/project-file-journey-test';
},
- killProcessGroup: (_pid, signal) => {
+ killPreview: (_pid, signal) => {
events.push(`preview:${signal}`);
queueMicrotask(() => preview.emit('exit', 0, signal));
},
@@ -80,7 +80,7 @@ test('the deadline starts before setup and disposes a backend that resolves afte
test('teardown attempts every owned resource and preserves the primary failure', async () => {
const events = [];
const { dependencies, preview } = createSuccessfulDependencies(events, {
- killProcessGroup: (_pid, signal) => {
+ killPreview: (_pid, signal) => {
events.push(`preview:${signal}`);
if (signal === 'SIGKILL') {