Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: clean up client test runner caches after every run (#9464)

[._.]/ Adam Eivya22276835d0f
diff --git a/client/vitest.config.js b/client/vitest.config.js
index c3e21b54c2..2330c73e28 100644
--- a/client/vitest.config.js
+++ b/client/vitest.config.js
@@ -1,9 +1,13 @@
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
+import { fileURLToPath } from 'node:url';
+import { bootstrapVitestTempRoot } from '../scripts/lib/vitestTempRoot.js';
import { vitestCiPool } from '../scripts/vitestCiPool.js';
import { TEST_TIMEOUT_MS } from './src/test/timeouts.js';
+const RUN_TEMP_ROOT = bootstrapVitestTempRoot();
+
export default defineConfig({
plugins: [react()],
resolve: {
@@ -11,6 +15,13 @@ export default defineConfig({
dedupe: ['three'],
},
test: {
+ globalSetup: [fileURLToPath(new URL('../scripts/vitestTempRootSetup.js', import.meta.url))],
+ env: {
+ TMPDIR: RUN_TEMP_ROOT,
+ TMP: RUN_TEMP_ROOT,
+ TEMP: RUN_TEMP_ROOT,
+ NODE_DISABLE_COMPILE_CACHE: '1',
+ },
// Four DOM workers exhausted Testing Library's async budget on the public
// runner before ChiefOfStaff's config panel settled. Keep the proven
// two-worker client cap; the Node/server runner uses all four CPUs.
diff --git a/scripts/lib/vitestStaleRunRoots.js b/scripts/lib/vitestStaleRunRoots.js
new file mode 100644
index 0000000000..30661271c1
--- /dev/null
+++ b/scripts/lib/vitestStaleRunRoots.js
@@ -0,0 +1,94 @@
+/**
+ * Owner-aware sweep of `pvt-*` run-scoped temp roots (#9113).
+ *
+ * `vitest.config.js` mints one root per run and stamps `.owner.pid` in it. A
+ * killed run never reaches `teardown()` in `runTempRoot.js`, so its root is
+ * left behind; the next config load calls `sweepStaleRunRoots()` to reclaim
+ * it. A recorded owner that is provably gone frees the root immediately, an
+ * owner that is alive keeps it however old it is (a >6h run must not be swept
+ * from under itself), and a root whose owner cannot be determined falls back
+ * to the conservative 6h age rule.
+ */
+import { execFileSync } from 'node:child_process';
+import { readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+export const OWNER_FILE = '.owner.pid';
+export const STALE_ROOT_AGE_MS = 6 * 60 * 60 * 1000;
+// `ps -o lstart=` has 1s resolution and the recorded start is derived from
+// process.uptime(), so allow slack before calling a pid "reused".
+const START_TOLERANCE_MS = 5000;
+
+/** Record this process as the root's owner: `<pid> <start-ms>`. */
+export function writeOwnerFile(root) {
+ const startMs = Math.round(Date.now() - process.uptime() * 1000);
+ writeFileSync(join(root, OWNER_FILE), `${process.pid} ${startMs}\n`);
+}
+
+/** Start time of a live pid in ms, or null when it cannot be read (always null on win32). */
+function readProcessStartMs(pid) {
+ if (process.platform === 'win32') return null;
+ try {
+ const out = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {
+ encoding: 'utf8',
+ windowsHide: true,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ env: { ...process.env, LC_ALL: 'C' },
+ }).trim();
+ const ms = Date.parse(out);
+ return Number.isNaN(ms) ? null : ms;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * true = owner alive, false = owner gone (or pid reused), null = unknown.
+ * `process.kill(pid, 0)` throws ESRCH for a missing pid and EPERM for a live
+ * pid owned by someone else (alive).
+ */
+export function isOwnerAlive({ pid, startMs }) {
+ try {
+ process.kill(pid, 0);
+ } catch (err) {
+ if (err.code === 'ESRCH') return false;
+ if (err.code !== 'EPERM') return null;
+ }
+ const liveStart = readProcessStartMs(pid);
+ if (liveStart === null || !Number.isFinite(startMs)) return true;
+ return Math.abs(liveStart - startMs) <= START_TOLERANCE_MS;
+}
+
+function readOwner(path) {
+ try {
+ const [pid, startMs] = readFileSync(join(path, OWNER_FILE), 'utf8').trim().split(/\s+/).map(Number);
+ return Number.isInteger(pid) && pid > 0 ? { pid, startMs } : null;
+ } catch {
+ return null;
+ }
+}
+
+export function sweepStaleRunRoots(tmpRoot, { now = Date.now(), probe = isOwnerAlive } = {}) {
+ let names;
+ try {
+ names = readdirSync(tmpRoot);
+ } catch {
+ return; // unreadable tmp dir — skip rather than fail config load
+ }
+ for (const name of names) {
+ if (!name.startsWith('pvt-')) continue;
+ const path = join(tmpRoot, name);
+ try {
+ const stat = statSync(path);
+ if (!stat.isDirectory()) continue;
+ const owner = readOwner(path);
+ const alive = owner ? probe(owner) : null;
+ if (alive === true) continue;
+ if (alive === false || now - stat.mtimeMs > STALE_ROOT_AGE_MS) {
+ rmSync(path, { recursive: true, force: true });
+ }
+ } catch {
+ // Already gone, or a permissions/race hiccup — best-effort sweep only.
+ }
+ }
+}
diff --git a/scripts/lib/vitestTempRoot.js b/scripts/lib/vitestTempRoot.js
new file mode 100644
index 0000000000..829ff70ff8
--- /dev/null
+++ b/scripts/lib/vitestTempRoot.js
@@ -0,0 +1,22 @@
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { sweepStaleRunRoots, writeOwnerFile } from './vitestStaleRunRoots.js';
+
+/** Establish containment at config-load time, before Vitest creates its cache or workers. */
+export function bootstrapVitestTempRoot() {
+ const hostRoot = tmpdir();
+ let root = process.env.PORTOS_TEST_TEMP_ROOT;
+ if (!root) {
+ sweepStaleRunRoots(hostRoot);
+ // Keep Unix socket paths below macOS's short sockaddr_un limit.
+ root = mkdtempSync(join(hostRoot, 'pvt-'));
+ writeOwnerFile(root);
+ process.env.PORTOS_TEST_TEMP_ROOT = root;
+ }
+ process.env.TMPDIR = root;
+ process.env.TMP = root;
+ process.env.TEMP = root;
+ process.env.NODE_DISABLE_COMPILE_CACHE = '1';
+ return root;
+}
diff --git a/scripts/vitestTempRoot.test.js b/scripts/vitestTempRoot.test.js
new file mode 100644
index 0000000000..45e755eb96
--- /dev/null
+++ b/scripts/vitestTempRoot.test.js
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest';
+import { spawn, spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { sweepStaleRunRoots, writeOwnerFile } from './lib/vitestStaleRunRoots.js';
+
+const repo = fileURLToPath(new URL('../', import.meta.url));
+
+function fixture(host, workspace, body) {
+ const root = join(host, 'fixture');
+ mkdirSync(root);
+ symlinkSync(join(repo, workspace, 'node_modules'), join(root, 'node_modules'),
+ process.platform === 'win32' ? 'junction' : 'dir');
+ mkdirSync(join(root, 'src/test'), { recursive: true });
+ writeFileSync(join(root, 'src/test/setup.js'), '');
+ writeFileSync(join(root, 'vitest.setup.js'), '');
+ const testFile = workspace === 'client' ? 'src/lifecycle.test.js' : 'lifecycle.test.js';
+ writeFileSync(join(root, testFile), `
+ import { test, expect } from 'vitest';
+ import { tmpdir } from 'node:os';
+ import { join } from 'node:path';
+ import { writeFileSync } from 'node:fs';
+ import { bootstrapVitestTempRoot } from ${JSON.stringify(new URL('./lib/vitestTempRoot.js', import.meta.url).href)};
+ test('lifecycle', async () => {
+ const first = tmpdir();
+ expect(bootstrapVitestTempRoot()).toBe(first);
+ expect(process.env.PORTOS_TEST_TEMP_ROOT).toBe(first);
+ ${body}
+ });
+ `);
+ const env = { ...process.env, TMPDIR: host, TMP: host, TEMP: host, NODE_DISABLE_COMPILE_CACHE: '1' };
+ delete env.PORTOS_TEST_TEMP_ROOT;
+ delete env.VITEST_FAST;
+ return {
+ args: [join(repo, workspace, 'node_modules/vitest/vitest.mjs'), 'run',
+ '--config', join(repo, workspace, 'vitest.config.js'), '--root', root, '--maxWorkers', '1'],
+ options: { cwd: join(repo, workspace), env, encoding: 'utf8', timeout: 20000 },
+ };
+}
+
+describe('real workspace runner temp lifecycle', () => {
+ for (const workspace of ['server', 'client']) {
+ for (const outcome of ['success', 'failure', 'leak']) {
+ it(`${workspace} removes framework scratch on ${outcome}, preserving host artifacts`, () => {
+ const host = mkdtempSync(join(tmpdir(), 'vrt-'));
+ try {
+ // Even nanoid-looking pre-existing directories belong to the host.
+ const untouched = 'A'.repeat(21);
+ mkdirSync(join(host, untouched));
+ writeFileSync(join(host, untouched, 'keep'), 'host data');
+ const body = outcome === 'failure' ? "expect(true).toBe(false);"
+ : outcome === 'leak' ? "writeFileSync(join(tmpdir(), 'fixture-leak'), 'unexpected');"
+ : 'expect(true).toBe(true);';
+ const { args, options } = fixture(host, workspace, body);
+ const result = spawnSync(process.execPath, args, options);
+ expect(result.error).toBeUndefined();
+ expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(outcome === 'success' ? 0 : 1);
+ if (outcome === 'leak') expect(result.stderr).toContain('test temp leak: fixture-leak');
+ expect(readdirSync(host).sort()).toEqual([untouched, 'fixture'].sort());
+ } finally {
+ rmSync(host, { recursive: true, force: true });
+ }
+ }, 25000);
+ }
+ }
+
+ it('reuses config ownership on reimport and reclaims it after interruption, preserving a live owner', async () => {
+ const host = mkdtempSync(join(tmpdir(), 'vrt-'));
+ let child;
+ try {
+ const live = join(host, 'pvt-live');
+ mkdirSync(live);
+ writeOwnerFile(live);
+ const env = { ...process.env, TMPDIR: host, TMP: host, TEMP: host };
+ delete env.PORTOS_TEST_TEMP_ROOT;
+ // Load the real config in an interrupted process; IPC acknowledges that
+ // ownership is stamped before the parent kills it, without sleeps.
+ child = spawn(process.execPath, ['--input-type=module', '-e',
+ `await import(${JSON.stringify(new URL('../client/vitest.config.js', import.meta.url).href)});
+ const root = process.env.PORTOS_TEST_TEMP_ROOT;
+ await import(${JSON.stringify(new URL('../client/vitest.config.js?reimport', import.meta.url).href)});
+ if (process.env.PORTOS_TEST_TEMP_ROOT !== root) throw Error('reimport created another root');
+ process.send(root);`],
+ { env, stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
+ const closed = new Promise((resolve, reject) => {
+ child.once('error', reject);
+ child.once('close', resolve);
+ });
+ const owned = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(Error('config did not start')), 15000);
+ child.once('message', root => { clearTimeout(timer); resolve(root); });
+ child.once('error', err => { clearTimeout(timer); reject(err); });
+ child.once('exit', () => { clearTimeout(timer); reject(Error('config exited before handshake')); });
+ });
+ expect(existsSync(owned)).toBe(true);
+ sweepStaleRunRoots(host);
+ expect(existsSync(owned)).toBe(true);
+ child.kill('SIGKILL');
+ await closed;
+ sweepStaleRunRoots(host);
+ expect(existsSync(owned)).toBe(false);
+ expect(existsSync(live)).toBe(true);
+ } finally {
+ child?.kill('SIGKILL');
+ rmSync(host, { recursive: true, force: true });
+ }
+ }, 20000);
+});
diff --git a/scripts/vitestTempRootSetup.js b/scripts/vitestTempRootSetup.js
new file mode 100644
index 0000000000..946e6d9332
--- /dev/null
+++ b/scripts/vitestTempRootSetup.js
@@ -0,0 +1,70 @@
+/**
+ * Run-wide teardown shared by both workspace configs. Config-load bootstrap
+ * redirects temp APIs before Vitest creates its module-transform cache.
+ * The server's exclusive capture projects share this single global owner.
+ */
+import { readdirSync, rmSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { OWNER_FILE } from './lib/vitestStaleRunRoots.js';
+
+export function setup() {}
+
+// Vitest's nanoid transform scratch still exists when global teardown runs.
+// Exclude it only inside our owned root; never sweep arbitrary host directories.
+const VITEST_INTERNAL_SCRATCH_DIR = /^[A-Za-z0-9_-]{21}$/;
+
+export function groupLeakPrefix(name) {
+ return name.replace(/[0-9a-zA-Z]{6,}$/, '') || name;
+}
+
+/** Empty shared containers/zero-byte logs contain no leaked fixture data. */
+export function isEffectivelyEmpty(path) {
+ let stat;
+ try {
+ stat = statSync(path);
+ } catch {
+ return true;
+ }
+ if (stat.isFile()) return stat.size === 0;
+ if (!stat.isDirectory()) return false;
+ let children;
+ try {
+ children = readdirSync(path);
+ } catch {
+ return true;
+ }
+ return children.every((child) => isEffectivelyEmpty(join(path, child)));
+}
+
+export function teardown() {
+ const root = process.env.PORTOS_TEST_TEMP_ROOT;
+ if (!root) return;
+ let entries;
+ try {
+ entries = readdirSync(root);
+ } catch {
+ return;
+ }
+ entries = entries
+ .filter((name) => name !== OWNER_FILE)
+ .filter((name) => !VITEST_INTERNAL_SCRATCH_DIR.test(name))
+ .filter((name) => !isEffectivelyEmpty(join(root, name)));
+
+ const byPrefix = new Map();
+ for (const name of entries) {
+ const prefix = groupLeakPrefix(name);
+ byPrefix.set(prefix, (byPrefix.get(prefix) || 0) + 1);
+ }
+ for (const [prefix, count] of byPrefix) {
+ console.warn(`⚠️ test temp leak: ${prefix} ×${count}`);
+ }
+ if (entries.length) process.exitCode = 1;
+
+ try {
+ rmSync(root, { recursive: true, force: true });
+ } catch (err) {
+ // A Windows worker may still hold an open handle. Leave ownership stamped
+ // so the next runner can reclaim it once the owner is gone.
+ console.warn(`⚠️ could not remove run temp root ${root}: ${err.message}`);
+ }
+}
diff --git a/server/test/runTempRoot.js b/server/test/runTempRoot.js
index 4ae87f63a6..41e0ad1795 100644
--- a/server/test/runTempRoot.js
+++ b/server/test/runTempRoot.js
@@ -1,182 +1,2 @@
-/**
- * Vitest globalSetup — the other half of the run-scoped temp root (#9032).
- *
- * `server/vitest.config.js` creates a run-scoped `mkdtempSync` root and
- * points `TMPDIR`/`TMP`/`TEMP` at it, at config-load time, before any worker
- * spawns. `os.tmpdir()` reads those env vars dynamically, so every call in
- * this process, in a forked worker (workers inherit `process.env` unless a
- * suite overrides it), or in any spawned child that inherits `process.env`
- * (Python's `tempfile` module, `ffmpeg`, `git`) resolves inside that root
- * instead of the host's real temp directory — a leaked directory can no
- * longer escape into `$TMPDIR` no matter which file left it behind.
- *
- * This module is that root's lifecycle manager as a Vitest `globalSetup`:
- * it runs once in the main process, before test collection starts and again
- * once after every test has finished (see
- * https://vitest.dev/config/#globalsetup). `setup()` has nothing to do — the
- * root already exists by the time this loads. `teardown()` reports and
- * removes whatever is still sitting in the root: this is the STRICT check
- * the issue asks for — once every per-file leaker in the tree is fixed, any
- * new leak fails the run instead of silently reappearing in $TMPDIR.
- */
-import { readdirSync, rmSync, statSync } from 'node:fs';
-import { join } from 'node:path';
-import { OWNER_FILE } from './staleRunRoots.js';
-
-export function setup() {
- // No-op: server/vitest.config.js already created the root and pointed
- // TMPDIR/TMP/TEMP at it before this module loaded.
-}
-
-// Vitest itself keeps a per-run module-transform scratch dir under
-// os.tmpdir() (vite-node's SSR/module fetch cache — `join(tmpdir(), nanoid())`
-// in vitest's own source) and removes it via `project.close()` -> `clearTmpDir
-// ()`. That close() call happens AFTER `_teardownGlobalSetup()` runs (see
-// vitest's `Vitest.close()`), so this module's own teardown always observes
-// it as still present — not a leak from PortOS test code, just an ordering
-// artifact of two independent teardown sequences. nanoid()'s default alphabet
-// (`A-Za-z0-9_-`) and length (21) make a false-negative collision with a real
-// PortOS leak (which always mkdtemps with a human-readable `prefix-` name)
-// effectively impossible, so entries matching it are excluded from the
-// report — the root-level rmSync below still removes them either way.
-const VITEST_INTERNAL_SCRATCH_DIR = /^[A-Za-z0-9_-]{21}$/;
-
-// A handful of PortOS's own provider-availability tests used to spawn a REAL,
-// installed third-party CLI (kilo, opencode, …) when one is present on the
-// developer's PATH (`hasCli()`-style gates) — a binary that then wrote its OWN
-// scratch/cache state (a config dir, a Node module compile cache, …) into
-// whatever TMPDIR it inherited, which since this file is our run root. #9039
-// traced every entry that used to land here to a real, fixable cause rather
-// than an unavoidable side effect of invoking a real binary:
-// - `kilo` / `opencode` — the top-level scratch dirs those two binaries
-// wrote on every invocation. Fixed by isolating TMPDIR/TMP/TEMP per spawn
-// (`probe()` in `server/lib/commandExists.js`) AND by no longer spawning
-// them at all from an incidental test: `providerRuntimeInstaller.js`'s
-// `getProviderRuntimeStatus(es)` now skips the real PATH scan/`--version`
-// probe under the test runner unless a test explicitly injects its own
-// `findCommand`/`probeCommand` (every genuinely real-CLI-probe test
-// already does), the same guard `codexOssSupport.js`'s `getCodexOssSupport`
-// applies to its own `codex exec --help` probe.
-// - `escape` — was never a third-party leak: it was
-// `agentRunReconciler.test.js`'s own path-traversal fixture, deliberately
-// written one level outside its RUNS_DIR and simply never swept in
-// `afterAll`. Fixed by sweeping it there.
-// - `node-compile-cache` — narrowed in #9051. `npmGlobalBin.js`'s own
-// `npm prefix -g` spawn was already TMPDIR-isolated by the time #9051
-// started (the fix above landed for it in #9039), yet the directory still
-// turned up rarely (~1 in 2,500 files) with no real-CLI spawn correlated
-// in the trace — Node's module compile cache (written whenever
-// `NODE_COMPILE_CACHE` is set or a CLI calls `module.enableCompileCache()`
-// for itself, which recent npm/npx builds do) is per-process, not tied to
-// one call site, so no single spawn helper's isolation can be proven to
-// cover every child that might inherit the run's TMPDIR. Disabled
-// tree-wide for the whole test run instead: `server/vitest.config.js` sets
-// `NODE_DISABLE_COMPILE_CACHE=1` in both the main process env and every
-// worker's `test.env`, honored since Node v22.1 (this repo requires
-// `^22.22.2 || ^24.15.0 || >=26.0.0`), so any child that inherits
-// `process.env` — isolated TMPDIR or not — never writes the cache in the
-// first place. No longer allowlisted below; a recurrence is a real,
-// unknown leak again.
-
-const KNOWN_PENDING_LEAKS = new Set();
-
-/**
- * Groups a leaked entry's basename by its mkdtemp call site as closely as a
- * cheap heuristic can: mkdtemp appends a short random alphanumeric suffix
- * directly after the prefix a caller passed in, so stripping a trailing run
- * of 6+ alphanumeric characters recovers the prefix, e.g.
- * `portos-dump-a1b2c3` -> `portos-dump-`. Fixed-name files (`*-out.log`)
- * pass through unchanged and are reported individually. Exported for the
- * regression test.
- */
-export function groupLeakPrefix(name) {
- return name.replace(/[0-9a-zA-Z]{6,}$/, '') || name;
-}
-
-/**
- * True when `path` holds no real content: a zero-byte file, or a directory
- * whose entries (recursively) are all themselves empty. A shared,
- * production-managed scratch container — `creativeDirectorScratchCwd`'s
- * `portos-cd-cwd`, or a fixed-name log a service truncates with `writeFile
- * (path, '')` before every start — is meant to persist across runs and be
- * reused; once its own per-run content is cleaned up (as production code
- * already does), what remains costs nothing and is not a leak worth
- * reporting or failing over. This also sidesteps a real hazard two files
- * sharing that literal path would otherwise create: each file removing the
- * whole shared container in its own `afterAll` races the other if Vitest
- * runs them concurrently, and one can delete a sibling's still-in-use
- * fixture. Skipping empty entries here means neither file needs to touch
- * the shared path at all — production's own per-item cleanup is trusted,
- * and this function only asks "is anything really left". Exported for the
- * regression test.
- */
-export function isEffectivelyEmpty(path) {
- let stat;
- try {
- stat = statSync(path);
- } catch {
- return true; // already gone
- }
- if (stat.isFile()) return stat.size === 0;
- if (!stat.isDirectory()) return false; // a socket, symlink, etc. — never silently drop it
- let children;
- try {
- children = readdirSync(path);
- } catch {
- return true;
- }
- return children.every((child) => isEffectivelyEmpty(join(path, child)));
-}
-
-export function teardown() {
- const root = process.env.TMPDIR;
- if (!root) return;
-
- let entries = [];
- try {
- entries = readdirSync(root);
- } catch {
- // Root was never created (config didn't run, e.g. a unit test of this
- // module) or was already removed — nothing to report or clean.
- return;
- }
-
- entries = entries
- .filter((name) => name !== OWNER_FILE) // the run's own owner stamp (#9113), not a leak
- .filter((name) => !VITEST_INTERNAL_SCRATCH_DIR.test(name))
- .filter((name) => !isEffectivelyEmpty(join(root, name)));
-
- if (entries.length > 0) {
- const byPrefix = new Map();
- for (const name of entries) {
- const prefix = groupLeakPrefix(name);
- byPrefix.set(prefix, (byPrefix.get(prefix) || 0) + 1);
- }
- let hasUnknownLeak = false;
- for (const [prefix, count] of byPrefix) {
- const knownPending = KNOWN_PENDING_LEAKS.has(prefix);
- if (!knownPending) hasUnknownLeak = true;
- const note = knownPending ? ' (known pending leak, see KNOWN_PENDING_LEAKS above)' : '';
- console.warn(`⚠️ test temp leak: ${prefix} ×${count}${note}`);
- }
- // Strict mode (#9032): a leftover entry means some suite wrote outside
- // its own cleanup path. Fail the run so a new leaker is caught locally
- // and in CI instead of quietly growing $TMPDIR — the run root itself is
- // still removed below either way, so the failure never reaches the
- // host's real temp directory. A KNOWN_PENDING_LEAKS entry is still
- // reported (so it does not silently balloon) but does not fail the run —
- // see that constant's comment.
- if (hasUnknownLeak) process.exitCode = 1;
- }
-
- try {
- rmSync(root, { recursive: true, force: true });
- } catch (err) {
- // Best-effort — a lingering open handle on a worker that hasn't fully
- // exited yet (most often on Windows) must not crash teardown and mask
- // the leak report above. Not silent, though: warn so a stubborn root is
- // visible rather than just reappearing next run — the stale-root sweep
- // in vitest.config.js cleans it up once it's 6h old either way.
- console.warn(`⚠️ could not remove run temp root ${root}: ${err.message}`);
- }
-}
+// Compatibility entrypoint for existing fixtures and leak-verdict tests.
+export * from '../../scripts/vitestTempRootSetup.js';
diff --git a/server/test/staleRunRoots.js b/server/test/staleRunRoots.js
index 8312812cef..251b8e2c7a 100644
--- a/server/test/staleRunRoots.js
+++ b/server/test/staleRunRoots.js
@@ -1,93 +1,2 @@
-/**
- * Owner-aware sweep of `pvt-*` run-scoped temp roots (#9113).
- *
- * `vitest.config.js` mints one root per run and stamps `.owner.pid` in it. A
- * killed run never reaches `teardown()` in `runTempRoot.js`, so its root is
- * left behind; the next config load calls `sweepStaleRunRoots()` to reclaim
- * it. A recorded owner that is provably gone frees the root immediately, an
- * owner that is alive keeps it however old it is (a >6h run must not be swept
- * from under itself), and a root whose owner cannot be determined falls back
- * to the conservative 6h age rule.
- */
-import { execFileSync } from '../lib/childProcess.js';
-import { readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
-
-export const OWNER_FILE = '.owner.pid';
-export const STALE_ROOT_AGE_MS = 6 * 60 * 60 * 1000;
-// `ps -o lstart=` has 1s resolution and the recorded start is derived from
-// process.uptime(), so allow slack before calling a pid "reused".
-const START_TOLERANCE_MS = 5000;
-
-/** Record this process as the root's owner: `<pid> <start-ms>`. */
-export function writeOwnerFile(root) {
- const startMs = Math.round(Date.now() - process.uptime() * 1000);
- writeFileSync(join(root, OWNER_FILE), `${process.pid} ${startMs}\n`);
-}
-
-/** Start time of a live pid in ms, or null when it cannot be read (always null on win32). */
-function readProcessStartMs(pid) {
- if (process.platform === 'win32') return null;
- try {
- const out = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'ignore'],
- env: { ...process.env, LC_ALL: 'C' },
- }).trim();
- const ms = Date.parse(out);
- return Number.isNaN(ms) ? null : ms;
- } catch {
- return null;
- }
-}
-
-/**
- * true = owner alive, false = owner gone (or pid reused), null = unknown.
- * `process.kill(pid, 0)` throws ESRCH for a missing pid and EPERM for a live
- * pid owned by someone else (alive).
- */
-export function isOwnerAlive({ pid, startMs }) {
- try {
- process.kill(pid, 0);
- } catch (err) {
- if (err.code === 'ESRCH') return false;
- if (err.code !== 'EPERM') return null;
- }
- const liveStart = readProcessStartMs(pid);
- if (liveStart === null || !Number.isFinite(startMs)) return true;
- return Math.abs(liveStart - startMs) <= START_TOLERANCE_MS;
-}
-
-function readOwner(path) {
- try {
- const [pid, startMs] = readFileSync(join(path, OWNER_FILE), 'utf8').trim().split(/\s+/).map(Number);
- return Number.isInteger(pid) && pid > 0 ? { pid, startMs } : null;
- } catch {
- return null;
- }
-}
-
-export function sweepStaleRunRoots(tmpRoot, { now = Date.now(), probe = isOwnerAlive } = {}) {
- let names;
- try {
- names = readdirSync(tmpRoot);
- } catch {
- return; // unreadable tmp dir — skip rather than fail config load
- }
- for (const name of names) {
- if (!name.startsWith('pvt-')) continue;
- const path = join(tmpRoot, name);
- try {
- const stat = statSync(path);
- if (!stat.isDirectory()) continue;
- const owner = readOwner(path);
- const alive = owner ? probe(owner) : null;
- if (alive === true) continue;
- if (alive === false || now - stat.mtimeMs > STALE_ROOT_AGE_MS) {
- rmSync(path, { recursive: true, force: true });
- }
- } catch {
- // Already gone, or a permissions/race hiccup — best-effort sweep only.
- }
- }
-}
+// Shared with the client runner; retain the established test import boundary.
+export * from '../../scripts/lib/vitestStaleRunRoots.js';
diff --git a/server/vitest.config.js b/server/vitest.config.js
index 89fe780982..d9e76fddab 100644
--- a/server/vitest.config.js
+++ b/server/vitest.config.js
@@ -1,10 +1,8 @@
import { defineConfig } from 'vitest/config';
-import { mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
import { vitestCaptureProjects, vitestCiPool } from '../scripts/vitestCiPool.js';
import { DB_TEST_INCLUDE } from './vitest.config.db.js';
-import { sweepStaleRunRoots, writeOwnerFile } from './test/staleRunRoots.js';
+import { bootstrapVitestTempRoot } from '../scripts/lib/vitestTempRoot.js';
// `npm run test:fast` is the Windows-safe way to set the flag (a
// `VITEST_FAST=1 vitest` script is parsed as an executable name on cmd.exe).
@@ -12,51 +10,8 @@ if (process.env.npm_lifecycle_event === 'test:fast') {
process.env.VITEST_FAST = '1';
}
-// Run-scoped temp root (#9032). #9000 added the static `mkdtempCleanup.guards
-// .test.js` scan, and #9009 documented it as file-wide (any rmSync anywhere in
-// a file satisfies it for every mkdtemp call in that file) — a heuristic that
-// cannot see a leak driven by a spawned child process, a fixed-name log file,
-// or a partially-cleaned file. Rather than chasing more static patterns, give
-// every mkdtemp/tmpdir() call in the run nowhere to leak TO: create one root
-// for the whole run, in the REAL host tmpdir, and point TMPDIR/TMP/TEMP at it
-// before any worker spawns. `os.tmpdir()` reads those env vars dynamically —
-// in this process, in a forked worker (workers inherit process.env), and in
-// any spawned child that inherits process.env (Python's tempfile module,
-// ffmpeg, git) — so every one of those calls resolves inside the root instead
-// of the host's real temp directory. `server/test/runTempRoot.js` (wired
-// below as globalSetup) is the other half: it reports and removes whatever is
-// left in the root after the run.
-//
-// Stale-root sweep: see `test/staleRunRoots.js` (owner pid, 6h fallback).
-// Idempotency guard: `server/vitest.config.test.js` (and any other suite
-// that asserts on this file's own NODE_ENV-forcing behavior) dynamically
-// re-imports this module after `vi.resetModules()`, re-running every
-// top-level statement — including the mkdtempSync below — even though a real
-// `vitest run` only ever loads this config once. Without a guard, each of
-// those re-imports mints and abandons its OWN "pvt-*" root (nobody's
-// globalSetup teardown owns it), which is itself a leak this same change is
-// fixing (#9032). `process.env.PORTOS_TEST_TEMP_ROOT` marks that this
-// process already has a run root; reuse it instead of minting another.
-const REAL_TMPDIR = tmpdir();
-let RUN_TEMP_ROOT = process.env.PORTOS_TEST_TEMP_ROOT;
-
-if (!RUN_TEMP_ROOT) {
- // Stale-root sweep (#9113): reclaim `pvt-*` roots of killed runs — at once
- // when the recorded owner pid is gone, after 6h when no owner is recorded,
- // never while the owner lives. Uses the REAL tmpdir, before the override below.
- sweepStaleRunRoots(REAL_TMPDIR);
-
- // Short prefix: Unix-socket tests (e.g. services/itermBridge.test.js) build
- // a `join(tmpdir(), 'prefix-XXXXXX', 'name.sock')` path, and macOS caps
- // `sockaddr_un.sun_path` at 104 bytes — a long run-root prefix nested under
- // another temp dir could push a legitimate socket path over that limit.
- RUN_TEMP_ROOT = mkdtempSync(join(REAL_TMPDIR, 'pvt-'));
- writeOwnerFile(RUN_TEMP_ROOT);
- process.env.PORTOS_TEST_TEMP_ROOT = RUN_TEMP_ROOT;
-}
-process.env.TMPDIR = RUN_TEMP_ROOT;
-process.env.TMP = RUN_TEMP_ROOT;
-process.env.TEMP = RUN_TEMP_ROOT;
+// Reimports reuse the enclosing run root; capture projects share its one owner.
+const RUN_TEMP_ROOT = bootstrapVitestTempRoot();
// The suite REQUIRES NODE_ENV=test: it is what selects the file storage backend
// (memoryBackend.js and every store facade) so no suite talks to the real
@@ -232,7 +187,7 @@ const config = defineConfig({
// after the whole run finishes (unlike setupFiles, which runs per test
// file, per worker). Reports and removes whatever is left in
// RUN_TEMP_ROOT once every test has finished (#9032).
- globalSetup: ['./test/runTempRoot.js'],
+ globalSetup: [fileURLToPath(new URL('../scripts/vitestTempRootSetup.js', import.meta.url))],
}
});