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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Bound cleanup of owned server browser test fixtures (#11575)
[._.]/4838975f7dfd
diff --git a/client/src/test/browserFixture.js b/client/src/test/browserFixture.jsindex 7b9ec622c6..a99c01d934 100644--- a/client/src/test/browserFixture.js+++ b/client/src/test/browserFixture.js@@ -63,6 +63,7 @@ import { appendFileSync, closeSync, openSync, opendirSync, readSync } from 'nodeimport { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { browserCleanupDeadline as withDeadline, reapOwnedBrowser } from '../../../scripts/lib/ownedBrowserCleanup.js';import { _testChromeProcessFacts } from '../../../server/services/htmlComposition/testBrowserCleanup.js';export const BROWSER_FIXTURE_STARTUP_MS = 60000;@@ -187,42 +188,6 @@ const retainLine = (line) => {try { appendFileSync(summary, `- ${line}\n`); } catch { /* evidence only */ }};-const withDeadline = (promise, ms, onTimeout) => {- let timer;- const deadline = new Promise((_, reject) => {- timer = setTimeout(() => reject(onTimeout()), ms);- });- return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));-};--// Resolves to null once the work succeeds within `ms`, or else to why it did not.-const failureWithin = (work, ms) => withDeadline(- Promise.resolve().then(work).then(() => null, error => `failed: ${error.message}`),- ms, () => timeoutError(ms),-).catch(() => `stalled after ${ms}ms`);--/**- * Closes a browser server the fixture launched, inside `budgetMs`: a graceful- * close for 30% of it, then the server's own kill for 60%, which signals only- * the process Playwright spawned (and its process group) and resolves once- * that process closed and its profile was removed. Each step counts only with- * the child's exit status in hand, never because a signal was sent; when- * neither produces one, the close rejects, saying whether the process had- * exited — the kill then waits on Playwright's own stdio and profile cleanup.- */-const reapOwnedBrowser = async (server, budgetMs) => {- const child = server.process();- const exitStatus = () => child?.exitCode ?? child?.signalCode ?? null;- const confirmed = failure => failure ?? (exitStatus() === null ? 'returned without an exit status' : null);- const closeFailure = confirmed(await failureWithin(() => server.close(), Math.floor(budgetMs * 0.3)));- if (!closeFailure) return;- const killFailure = confirmed(await failureWithin(() => server.kill(), Math.floor(budgetMs * 0.6)));- if (!killFailure) return;- const exit = exitStatus();- const state = exit !== null ? ` (process exited with ${exit})` : killFailure.endsWith('exit status') ? '' : ' (no exit status)';- throw new Error(`browser close ${closeFailure}, then its kill ${killFailure}${state}`);-};-/*** @param {object} options* @param {string} options.name - fixture label used in errors and the temp-dir prefixdiff --git a/scripts/lib/ownedBrowserCleanup.js b/scripts/lib/ownedBrowserCleanup.jsnew file mode 100644index 0000000000..d2b388f218--- /dev/null+++ b/scripts/lib/ownedBrowserCleanup.js@@ -0,0 +1,38 @@+/** Test-only owned Playwright lifecycle shared by the server and client fixtures. */+const timeoutError = ms => Object.assign(new Error(`timed out after ${ms}ms`), { name: 'TimeoutError' });++export const browserCleanupDeadline = (promise, ms, onTimeout) => {+ let timer;+ const deadline = new Promise((_, reject) => {+ timer = setTimeout(() => reject(onTimeout()), ms);+ });+ return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));+};++// Resolves to null once the work succeeds within `ms`, or else to why it did not.+const failureWithin = (work, ms) => browserCleanupDeadline(+ Promise.resolve().then(work).then(() => null, error => `failed: ${error.message}`),+ ms, () => timeoutError(ms),+).catch(() => `stalled after ${ms}ms`);++/**+ * Closes a browser server the fixture launched, inside `budgetMs`: a graceful+ * close for 30% of it, then the server's own kill for 60%, which signals only+ * the process Playwright spawned (and its process group) and resolves once+ * that process closed and its profile was removed. Each step counts only with+ * the child's exit status in hand, never because a signal was sent; when+ * neither produces one, the close rejects, saying whether the process had+ * exited — the kill then waits on Playwright's own stdio and profile cleanup.+ */+export const reapOwnedBrowser = async (server, budgetMs) => {+ const child = server.process();+ const exitStatus = () => child?.exitCode ?? child?.signalCode ?? null;+ const confirmed = failure => failure ?? (exitStatus() === null ? 'returned without an exit status' : null);+ const closeFailure = confirmed(await failureWithin(() => server.close(), Math.floor(budgetMs * 0.3)));+ if (!closeFailure) return;+ const killFailure = confirmed(await failureWithin(() => server.kill(), Math.floor(budgetMs * 0.6)));+ if (!killFailure) return;+ const exit = exitStatus();+ const state = exit !== null ? ` (process exited with ${exit})` : killFailure.endsWith('exit status') ? '' : ' (no exit status)';+ throw new Error(`browser close ${closeFailure}, then its kill ${killFailure}${state}`);+};diff --git a/server/lib/filmLook.browser.test.js b/server/lib/filmLook.browser.test.jsindex 35f4e7fc72..51f0c8c13d 100644--- a/server/lib/filmLook.browser.test.js+++ b/server/lib/filmLook.browser.test.js@@ -3,6 +3,7 @@ import { existsSync } from 'node:fs';import { mkdir, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { chromium } from 'playwright-core';+import { startOwnedBrowserFixture } from '../test/browserFixture.js';import sharp from 'sharp';import { browserSuiteCanRun } from './browserSuiteGate.js';import { filmLookFilterMarkup, filmLookPreset, filmLookRuntimeSource } from './filmLook.js';@@ -25,9 +26,12 @@ const composition = '<script>portosComposition = { fps: 30, seek() {} };</scriptconst html = (head, body) => `<!doctype html><html><head><style>html,body{margin:0;width:100%;height:100%}</style>${head}</head><body>${body}</body></html>`;describe.skipIf(!canRun)('film look runtime in Chrome', () => {- let browser;- beforeAll(async () => { browser = await chromium.launch({ executablePath: chrome, headless: true }); });- afterAll(async () => { await browser?.close(); });+ let browser, browserFixture;+ beforeAll(async () => {+ browserFixture = await startOwnedBrowserFixture({ chromium, launchOptions: { executablePath: chrome, headless: true } });+ browser = browserFixture.browser;+ });+ afterAll(async () => { await browserFixture?.close(); });it('paints cached grain and tape under the worker media CSP and blends the cast with the document pixels', async ({ signal }) => {const { PATHS } = await import('./paths.js');diff --git a/server/lib/musicVideoTitleCard.browser.test.js b/server/lib/musicVideoTitleCard.browser.test.jsindex 72d2448525..db1a23b88b 100644--- a/server/lib/musicVideoTitleCard.browser.test.js+++ b/server/lib/musicVideoTitleCard.browser.test.js@@ -1,6 +1,7 @@import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { existsSync, readFileSync } from 'node:fs';import { chromium } from 'playwright-core';+import { startOwnedBrowserFixture } from '../test/browserFixture.js';import sharp from 'sharp';import { browserSuiteCanRun } from './browserSuiteGate.js';import { filmLookRuntimeSource } from './filmLook.js';@@ -37,7 +38,7 @@ async function brightIn(png, { left, top, width, height }) {}describe.skipIf(!canRun)('title card runtime in Chrome', () => {- let browser;+ let browser, browserFixture;let page;const errors = [];const lowerLeft = { left: 0, top: H / 2, width: W / 2, height: H / 2 };@@ -45,14 +46,15 @@ describe.skipIf(!canRun)('title card runtime in Chrome', () => {const shotAt = async (t) => { await page.evaluate((at) => globalThis.portosComposition.seek(at), t); return page.screenshot(); };beforeAll(async () => {- browser = await chromium.launch({ executablePath: chrome, headless: true });+ browserFixture = await startOwnedBrowserFixture({ chromium, launchOptions: { executablePath: chrome, headless: true } });+ browser = browserFixture.browser;page = await browser.newPage({ viewport: { width: W, height: H } });page.on('pageerror', (error) => errors.push(error.message));const card = { title: 'Example Song', artist: 'Example Artist', year: '2026', startSec: 2, endSec: 8, fadeSec: 0.5 };await page.setContent(`<!doctype html><html><head><style>html,body{margin:0;background:#000}</style><script>${filmLookRuntimeSource({ preset: 'none' })}</script><script>${titleCardRuntimeSource(card)}</script></head><body>${DOCUMENT}</body></html>`);}, 30000);- afterAll(async () => { await browser?.close(); });+ afterAll(async () => { await browserFixture?.close(); });it('draws the card in the lower-left inside its window, nothing outside it, and the same pixels on a repeat seek', async () => {const before = await shotAt(1);diff --git a/server/services/musicVideo/documentTemplates/layered/engine.overlay.test.js b/server/services/musicVideo/documentTemplates/layered/engine.overlay.test.jsindex ebdfc5a284..8712063795 100644--- a/server/services/musicVideo/documentTemplates/layered/engine.overlay.test.js+++ b/server/services/musicVideo/documentTemplates/layered/engine.overlay.test.js@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { chromium } from 'playwright-core';+import { startOwnedBrowserFixture } from '../../../../test/browserFixture.js';import { gateAutoReview } from '../../autoReviewJudge.js';// The layered engine is a browser template copied into each document, so the overlay@@ -64,9 +65,12 @@ const chrome = [process.env.CHROME_PATH, chromium.executablePath(),].find(path => path && existsSync(path));describe.skipIf(!chrome)('layered footage review through rendered browser pixels', () => {- let browser;- beforeAll(async () => { browser = await chromium.launch({ executablePath: chrome, headless: true }); }, 30000);- afterAll(async () => { await browser?.close(); });+ let browser, browserFixture;+ beforeAll(async () => {+ browserFixture = await startOwnedBrowserFixture({ chromium, launchOptions: { executablePath: chrome, headless: true } });+ browser = browserFixture.browser;+ }, 30000);+ afterAll(async () => { await browserFixture?.close(); });async function composed(source, flat = false) {const page = await browser.newPage();diff --git a/server/services/musicVideo/documentTemplates/shared/lyricType.test.js b/server/services/musicVideo/documentTemplates/shared/lyricType.test.jsindex 9b6614cdc8..0a45336798 100644--- a/server/services/musicVideo/documentTemplates/shared/lyricType.test.js+++ b/server/services/musicVideo/documentTemplates/shared/lyricType.test.js@@ -1,6 +1,7 @@import { existsSync, readFileSync } from 'node:fs';import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { chromium } from 'playwright-core';+import { startOwnedBrowserFixture } from '../../../../test/browserFixture.js';import { createLyricType, LYRIC_FIT, TEXT_ZONES } from './lyricType.js';// zoneRect is the module's public text-zone geometry, reached through the global classic scripts use.@@ -299,9 +300,12 @@ const chrome = [process.env.CHROME_PATH, chromium.executablePath(), '/usr/bin/go'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find((path) => path && existsSync(path));describe.skipIf(!chrome)('lyricType in the layered template (browser pixels)', () => {- let browser;- beforeAll(async () => { browser = await chromium.launch({ executablePath: chrome, headless: true }); }, 30000);- afterAll(async () => { await browser?.close(); });+ let browser, browserFixture;+ beforeAll(async () => {+ browserFixture = await startOwnedBrowserFixture({ chromium, launchOptions: { executablePath: chrome, headless: true } });+ browser = browserFixture.browser;+ }, 30000);+ afterAll(async () => { await browserFixture?.close(); });it('keeps the hook accent outlined in ink on cream, pale-sky and busy light frames', async () => {const page = await browser.newPage();diff --git a/server/services/musicVideo/documentTemplates/shared/toonWorld.browser.test.js b/server/services/musicVideo/documentTemplates/shared/toonWorld.browser.test.jsindex b421422597..da6bb03a70 100644--- a/server/services/musicVideo/documentTemplates/shared/toonWorld.browser.test.js+++ b/server/services/musicVideo/documentTemplates/shared/toonWorld.browser.test.js@@ -5,6 +5,7 @@ import { dirname, join } from 'node:path';import { createRequire } from 'node:module';import { fileURLToPath } from 'node:url';import { chromium } from 'playwright-core';+import { startOwnedBrowserFixture } from '../../../../test/browserFixture.js';import { browserSuiteCanRun } from '../../../../lib/browserSuiteGate.js';const require = createRequire(import.meta.url);@@ -16,12 +17,13 @@ const root = dirname(fileURLToPath(import.meta.url));const threeRoot = dirname(require.resolve('three'));describe.skipIf(!canRun)('toon world headless dish proof', () => {- let browser, page;+ let browser, browserFixture, page;const errors = [];beforeAll(async () => {- browser = await chromium.launch({ executablePath: chrome, headless: true,+ browserFixture = await startOwnedBrowserFixture({ chromium, launchOptions: { executablePath: chrome, headless: true,args: ['--mute-audio', '--use-angle=swiftshader', '--enable-unsafe-swiftshader',- '--disable-frame-rate-limit', '--disable-background-timer-throttling', '--disable-renderer-backgrounding'] });+ '--disable-frame-rate-limit', '--disable-background-timer-throttling', '--disable-renderer-backgrounding'] } });+ browser = browserFixture.browser;page = await browser.newPage({ viewport: { width: 640, height: 360 } });page.on('pageerror', error => errors.push(error.message));page.on('console', message => { if (message.type() === 'error') errors.push(message.text()); });@@ -37,7 +39,7 @@ describe.skipIf(!canRun)('toon world headless dish proof', () => {await page.goto('http://toon.test/');await page.waitForFunction(() => window.proof);}, 30000);- afterAll(async () => { await browser?.close(); });+ afterAll(async () => { await browserFixture?.close(); });it('renders thick, separated dishes and refuses hidden ink with optical passes on/off', async () => {const results = await page.evaluate(() => window.proof());diff --git a/server/test/browserFixture.js b/server/test/browserFixture.jsnew file mode 100644index 0000000000..8b56745faf--- /dev/null+++ b/server/test/browserFixture.js@@ -0,0 +1,132 @@+import { lstatSync, mkdtempSync, realpathSync } from 'node:fs';+import { lstat, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { basename, dirname, isAbsolute, join, normalize } from 'node:path';+import { browserCleanupDeadline, reapOwnedBrowser } from '../../scripts/lib/ownedBrowserCleanup.js';++// The capability is the retained BrowserServer's exact ChildProcess, not a+// process search or a prefix match. Playwright has no public launchServer+// userDataDir option: its generated profile lives beside our private root.+const captureProfile = (child, parentTemp) => {+ const args = child?.spawnargs ?? [];+ const paths = [];+ for (let i = 0; i < args.length; i++) {+ if (args[i] === '--user-data-dir') paths.push(args[++i]);+ else if (args[i].startsWith('--user-data-dir=')) paths.push(args[i].slice('--user-data-dir='.length));+ }+ const path = paths[0];+ if (paths.length !== 1 || !path || !isAbsolute(path) || normalize(path) !== path+ || !/^playwright_chromiumdev_profile-[\w-]+$/.test(basename(path))) return null;+ try {+ if (realpathSync(dirname(path)) !== parentTemp) return null;+ const canonical = join(parentTemp, basename(path));+ const stat = lstatSync(canonical, { throwIfNoEntry: false });+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) return null;+ return { path: canonical, stat };+ } catch { return null; }+};++/**+ * Test-only browser owned by this fixture, with no Vite or production graph.+ * launchServer/connect retain the supported process/kill capability; external+ * CDP adapters are deliberately ineligible. Startup plus cleanup fit the+ * existing 30s hooks. No retries: a failed launch remains a failed fixture.+ */+export async function startOwnedBrowserFixture({+ chromium, launchOptions = {}, startupMs = 20000, cleanupMs = 5000,+}) {+ if (typeof chromium.launchServer !== 'function' || typeof chromium.connect !== 'function') {+ throw new Error('Owned browser fixture requires launchServer/connect');+ }+ if (![startupMs, cleanupMs].every(ms => Number.isFinite(ms) && ms > 0)+ || startupMs + cleanupMs >= 30000) {+ throw new Error('Browser startup and cleanup budgets must fit inside the 30000ms hook');+ }+ const parentTemp = realpathSync(tmpdir());+ const temp = mkdtempSync(join(parentTemp, 'portos-owned-browser-'));+ const bounded = (work, ms, label) => browserCleanupDeadline(Promise.resolve().then(work), ms,+ () => new Error(`${label} stalled after ${ms}ms`));+ // No absolute fixture paths or raw launch errors in asynchronous diagnostics.+ const reportLate = promise => promise.catch(() => {+ console.error('❌ Owned browser fixture late cleanup failed; exit or private root removal is unconfirmed');+ });+ let server, child, browser, profile, abandoned = false;+ let removing, reaping, disconnecting, closing;+ const requireAbsent = async (path, label) => {+ const remaining = await lstat(path).catch(error => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (remaining) throw new Error(`${label} still exists after removal`);+ };+ const removeRoot = () => removing ??= bounded(async () => {+ // Playwright creates its profile using the parent's os.tmpdir(), not the+ // child's env. Verify/remove only the captured directory after owned exit;+ // a swapped directory or symlink is not the resource we launched with.+ if (server) {+ if (!profile) throw new Error('Owned browser profile path is unconfirmed');+ const remaining = await lstat(profile.path).catch(error => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (remaining) {+ if (!remaining.isDirectory() || remaining.isSymbolicLink() || !profile.stat+ || remaining.dev !== profile.stat.dev || remaining.ino !== profile.stat.ino) {+ throw new Error('Owned browser profile identity changed');+ }+ await rm(profile.path, { recursive: true, force: true });+ }+ await requireAbsent(profile.path, 'Owned browser profile');+ }+ await rm(temp, { recursive: true, force: true });+ await requireAbsent(temp, 'Browser private root');+ }, Math.max(1, Math.floor(cleanupMs * 0.1)), 'Browser private root removal');+ const reap = () => reaping ??= bounded(async () => {+ if (server.process() !== child) throw new Error('Owned browser process identity changed');+ await reapOwnedBrowser(server, cleanupMs);+ // A timeout or missing exit status above preserves the root as evidence.+ await removeRoot();+ }, cleanupMs, 'Owned browser cleanup');+ const disconnect = () => disconnecting ??= bounded(() => browser.close(), cleanupMs, 'Browser client disconnect');+ const launching = Promise.resolve().then(() => chromium.launchServer({+ ...launchOptions, timeout: startupMs, artifactsDir: temp,+ env: { ...process.env, ...launchOptions.env,+ TMPDIR: temp, TMP: temp, TEMP: temp, MAC_CHROMIUM_TMPDIR: temp },+ })).then(value => {+ server = value;+ child = server.process();+ profile = captureProfile(child, parentTemp);+ // Even after close's deadline rejected, the eventual capability is ours.+ if (abandoned) reportLate(reap());+ return value;+ }, error => {+ if (abandoned) reportLate(removeRoot());+ throw error;+ });+ // Cache the verdict as well as the work, including failures. A second close+ // must not signal again or turn an unconfirmed first close into success.+ const close = () => closing ??= bounded(async () => {+ await launching.catch(async () => { await removeRoot(); });+ if (server) {+ const results = await Promise.allSettled([reap(), ...(browser ? [disconnect()] : [])]);+ const failures = results.filter(result => result.status === 'rejected');+ if (failures.length) throw new AggregateError(failures.map(result => result.reason), 'Owned browser cleanup failed');+ }+ }, cleanupMs, 'Owned browser cleanup');+ try {+ await bounded(async () => {+ await launching;+ if (abandoned) return;+ const connected = await chromium.connect(server.wsEndpoint(), { timeout: startupMs });+ browser = connected;+ // A connection can finish after the server was already reaped. Release+ // that client independently; never delay owned termination for it.+ if (abandoned) reportLate(disconnect());+ }, startupMs, 'Owned browser startup');+ return { browser, temp, close };+ } catch (error) {+ abandoned = true;+ const cleanup = await close().then(() => 'cleaned up', () => 'cleanup unconfirmed');+ throw new Error(`Owned browser startup failed; ${cleanup}`, { cause: error });+ }+}diff --git a/server/test/browserFixture.test.js b/server/test/browserFixture.test.jsnew file mode 100644index 0000000000..4773cb0cad--- /dev/null+++ b/server/test/browserFixture.test.js@@ -0,0 +1,325 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { lstat, rm } from 'node:fs/promises';+import { startOwnedBrowserFixture } from './browserFixture.js';++vi.mock('node:fs/promises', async original => {+ const actual = await original();+ return { ...actual, lstat: vi.fn(actual.lstat), rm: vi.fn(actual.rm) };+});++const stalls = () => new Promise(() => {});+const deferred = () => {+ let resolve, reject;+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });+ return { promise, resolve, reject };+};+const roots = [];+const owned = () => {+ const profile = mkdtempSync(join(tmpdir(), 'playwright_chromiumdev_profile-'));+ roots.push(profile);+ const canonicalProfile = realpathSync(profile);+ const clearProfile = () => rmSync(profile, { recursive: true, force: true });+ const child = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null,+ spawnargs: ['example-chrome', `--user-data-dir=${profile}`] });+ const server = {+ process: () => child, wsEndpoint: () => 'ws://127.0.0.1:1/owned',+ close: vi.fn(async () => { child.exitCode = 0; clearProfile(); }),+ kill: vi.fn(async () => { child.signalCode = 'SIGKILL'; clearProfile(); }),+ };+ const browser = { close: vi.fn(async () => {}) };+ const chromium = { launchServer: vi.fn(async () => server), connect: vi.fn(async () => browser) };+ const start = () => startOwnedBrowserFixture({ chromium, startupMs: 100, cleanupMs: 100,+ launchOptions: { executablePath: 'example-chrome', headless: true, args: ['--mute-audio'] } });+ return { child, server, browser, chromium, start, profile, canonicalProfile, clearProfile };+};+// Synthetic launch/connect readiness only; real filesystem completion uses the+// operation handshake below rather than a number of event-loop turns.+const flushUntil = async check => {+ for (let i = 0; i < 1000; i++) {+ if (check()) return;+ await new Promise(resolve => setImmediate(resolve));+ }+ throw new Error('Synthetic fixture did not settle');+};+const recordRoot = fixture => {+ const temp = fixture.chromium.launchServer.mock.calls[0][0].env.TMPDIR;+ roots.push(temp);+ mkdirSync(join(temp, 'playwright_chromiumdev_profile-example'));+ writeFileSync(join(temp, 'playwright_chromiumdev_profile-example', 'owned'), 'fixture');+ return temp;+};+const rootRemoval = temp => {+ const completed = deferred();+ const remove = rm.getMockImplementation();+ const stat = lstat.getMockImplementation();+ let removed = false;+ rm.mockImplementation(async (...args) => {+ const result = await remove(...args);+ if (args[0] === temp) removed = true;+ return result;+ });+ lstat.mockImplementation((...args) => stat(...args).catch(error => {+ if (removed && args[0] === temp && error.code === 'ENOENT') {+ // The real removal and final absence check have completed. One turn+ // drains their promise continuations, including deadline disposal; no+ // filesystem work is being polled or presumed complete after N turns.+ setImmediate(completed.resolve);+ }+ throw error;+ }));+ return completed.promise;+};++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ lstat.mockReset();+ rm.mockReset();+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe('owned server browser fixture lifecycle', () => {+ it('reaps only its owned server after hung graceful close, confirms profile removal, and caches close', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const fixture = owned();+ const other = owned();+ fixture.child.spawnargs = ['example-chrome', '--user-data-dir', fixture.profile];+ fixture.server.close.mockImplementation(stalls);+ const exit = deferred();+ fixture.server.kill.mockImplementation(async () => { await exit.promise; fixture.child.signalCode = 'SIGKILL'; });+ const started = await fixture.start();+ const temp = recordRoot(fixture);+ expect(fixture.chromium.launchServer).toHaveBeenCalledWith(expect.objectContaining({+ executablePath: 'example-chrome', headless: true, args: ['--mute-audio'], timeout: 100, artifactsDir: temp,+ env: expect.objectContaining({ TMPDIR: temp, TMP: temp, TEMP: temp, MAC_CHROMIUM_TMPDIR: temp }),+ }));+ const closing = started.close();+ expect(started.close()).toBe(closing);+ await vi.advanceTimersByTimeAsync(29);+ expect(fixture.server.kill).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(fixture.server.kill).toHaveBeenCalledTimes(1);+ expect(existsSync(temp)).toBe(true);+ expect(rm).not.toHaveBeenCalled();+ exit.resolve();+ await closing;+ expect(started.close()).toBe(closing);+ expect(existsSync(temp)).toBe(false);+ expect(rm.mock.calls).toEqual([+ [fixture.canonicalProfile, { recursive: true, force: true }],+ [temp, { recursive: true, force: true }],+ ]);+ expect(fixture.browser.close).toHaveBeenCalledTimes(1);+ expect(existsSync(fixture.profile)).toBe(false);+ expect(existsSync(other.profile)).toBe(true);+ expect(other.server.kill).not.toHaveBeenCalled();+ expect(other.server.close).not.toHaveBeenCalled();+ expect(fixture.child.eventNames()).toEqual([]);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(['returns without exit', 'never settles'])('rejects when owned kill %s and preserves the private root', async mode => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const fixture = owned();+ fixture.server.close.mockImplementation(stalls);+ fixture.server.kill.mockImplementation(mode === 'never settles' ? stalls : async () => {});+ const started = await fixture.start();+ const temp = recordRoot(fixture);+ const closing = started.close();+ const result = closing.catch(error => error);+ await vi.advanceTimersByTimeAsync(100);+ expect(await result).toBeInstanceOf(Error);+ expect(started.close()).toBe(closing);+ expect(fixture.server.kill).toHaveBeenCalledTimes(1);+ expect(rm).not.toHaveBeenCalled();+ expect(existsSync(temp)).toBe(true);+ expect(fixture.child.eventNames()).toEqual([]);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(['fails', 'stalls', 'leaves root'])('rejects when private root removal %s despite confirmed exit', async mode => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const fixture = owned();+ const started = await fixture.start();+ const temp = recordRoot(fixture);+ rm.mockImplementation(mode === 'stalls' ? stalls : mode === 'fails'+ ? async () => { throw new Error('synthetic removal failure'); } : async () => {});+ const closing = started.close();+ const result = closing.catch(error => error);+ await vi.advanceTimersByTimeAsync(100);+ expect(await result).toBeInstanceOf(Error);+ expect(started.close()).toBe(closing);+ expect(fixture.child.exitCode).toBe(0);+ expect(existsSync(temp)).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(['missing', 'duplicate', 'escaped', 'unrelated', 'symlink'])('refuses %s profile ownership without removing other directories', async mode => {+ const fixture = owned();+ const other = owned();+ const external = mkdtempSync(join(tmpdir(), 'unrelated-browser-'));+ roots.push(external);+ const unrelated = join(external, 'playwright_chromiumdev_profile-example');+ mkdirSync(unrelated);+ if (mode === 'missing') fixture.child.spawnargs = ['example-chrome'];+ if (mode === 'duplicate') fixture.child.spawnargs.push(`--user-data-dir=${other.profile}`);+ if (mode === 'escaped') fixture.child.spawnargs = [`--user-data-dir=${external}/../playwright_chromiumdev_profile-example`];+ if (mode === 'unrelated') fixture.child.spawnargs = [`--user-data-dir=${unrelated}`];+ if (mode === 'symlink') {+ fixture.clearProfile();+ symlinkSync(other.profile, fixture.profile, 'dir');+ }+ const started = await fixture.start();+ const temp = recordRoot(fixture);+ await expect(started.close()).rejects.toThrow('cleanup failed');+ expect(fixture.child.exitCode).toBe(0);+ expect(rm).not.toHaveBeenCalled();+ expect(existsSync(temp)).toBe(true);+ expect(existsSync(other.profile)).toBe(true);+ expect(existsSync(unrelated)).toBe(true);+ });++ it('does not wait for a stalled connected client before reaping the owned process', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const fixture = owned();+ fixture.browser.close.mockImplementation(stalls);+ const started = await fixture.start();+ const temp = recordRoot(fixture);+ const removed = rootRemoval(temp);+ const closing = started.close().catch(error => error);+ await removed;+ expect(existsSync(temp)).toBe(false);+ expect(fixture.child.exitCode).toBe(0);+ await vi.advanceTimersByTimeAsync(100);+ expect(await closing).toBeInstanceOf(Error);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('preserves a profile replaced with a symlink after launch instead of deleting its target', async () => {+ const fixture = owned();+ const other = owned();+ fixture.server.close.mockImplementation(async () => { fixture.child.exitCode = 0; });+ const started = await fixture.start();+ const temp = recordRoot(fixture);+ fixture.clearProfile();+ symlinkSync(other.profile, fixture.profile, 'dir');+ await expect(started.close()).rejects.toThrow('cleanup failed');+ expect(rm).not.toHaveBeenCalled();+ expect(existsSync(temp)).toBe(true);+ expect(existsSync(other.profile)).toBe(true);+ });++ it.each(['launch', 'connect'])('cleans failed %s before rejecting startup', async phase => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const fixture = owned();+ const failure = deferred();+ fixture.chromium[phase === 'launch' ? 'launchServer' : 'connect'].mockReturnValue(failure.promise);+ const starting = fixture.start().catch(error => error);+ await flushUntil(() => fixture.chromium.launchServer.mock.calls.length > 0);+ const temp = recordRoot(fixture);+ failure.reject(new Error('synthetic startup failure'));+ const error = await starting;+ expect(error.message).toBe('Owned browser startup failed; cleaned up');+ expect(existsSync(temp)).toBe(false);+ expect(fixture.server.close).toHaveBeenCalledTimes(phase === 'launch' ? 0 : 1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('rejects abandoned launch with unconfirmed cleanup, then reaps its late server exactly once without connecting', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const fixture = owned();+ const launch = deferred();+ fixture.chromium.launchServer.mockReturnValue(launch.promise);+ fixture.server.close.mockImplementation(stalls);+ const starting = fixture.start().catch(error => error);+ await flushUntil(() => fixture.chromium.launchServer.mock.calls.length > 0);+ const temp = recordRoot(fixture);+ const removed = rootRemoval(temp);+ await vi.advanceTimersByTimeAsync(200);+ expect((await starting).message).toBe('Owned browser startup failed; cleanup unconfirmed');+ expect(existsSync(temp)).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ launch.resolve(fixture.server);+ await vi.advanceTimersByTimeAsync(30);+ await removed;+ expect(existsSync(temp)).toBe(false);+ expect(fixture.chromium.connect).not.toHaveBeenCalled();+ expect(fixture.server.close).toHaveBeenCalledTimes(1);+ expect(fixture.server.kill).toHaveBeenCalledTimes(1);+ expect(rm).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('reaps during an abandoned connection and disconnects its late client without repeating cleanup', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const fixture = owned();+ const connection = deferred();+ fixture.chromium.connect.mockReturnValue(connection.promise);+ const starting = fixture.start().catch(error => error);+ await flushUntil(() => fixture.chromium.connect.mock.calls.length > 0);+ const temp = recordRoot(fixture);+ await vi.advanceTimersByTimeAsync(100);+ expect((await starting).message).toBe('Owned browser startup failed; cleaned up');+ expect(existsSync(temp)).toBe(false);+ connection.resolve(fixture.browser);+ await vi.advanceTimersByTimeAsync(0);+ expect(fixture.browser.close).toHaveBeenCalledTimes(1);+ expect(fixture.server.close).toHaveBeenCalledTimes(1);+ expect(rm).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('reports an unconfirmed late reap and preserves its evidence after startup has already rejected', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const failure = vi.spyOn(console, 'error').mockImplementation(() => {});+ const fixture = owned();+ const launch = deferred();+ fixture.chromium.launchServer.mockReturnValue(launch.promise);+ fixture.server.close.mockImplementation(stalls);+ fixture.server.kill.mockImplementation(stalls);+ const starting = fixture.start().catch(error => error);+ await flushUntil(() => fixture.chromium.launchServer.mock.calls.length > 0);+ const temp = recordRoot(fixture);+ await vi.advanceTimersByTimeAsync(200);+ expect((await starting).message).toContain('cleanup unconfirmed');+ launch.resolve(fixture.server);+ await vi.advanceTimersByTimeAsync(100);+ expect(failure).toHaveBeenCalledExactlyOnceWith(+ '❌ Owned browser fixture late cleanup failed; exit or private root removal is unconfirmed');+ expect(fixture.server.kill).toHaveBeenCalledTimes(1);+ expect(existsSync(temp)).toBe(true);+ expect(existsSync(fixture.profile)).toBe(true);+ expect(rm).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('removes the private root when an abandoned launch eventually rejects', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const fixture = owned();+ const launch = deferred();+ fixture.chromium.launchServer.mockReturnValue(launch.promise);+ const starting = fixture.start().catch(error => error);+ await flushUntil(() => fixture.chromium.launchServer.mock.calls.length > 0);+ const temp = recordRoot(fixture);+ const removed = rootRemoval(temp);+ await vi.advanceTimersByTimeAsync(200);+ expect((await starting).message).toContain('cleanup unconfirmed');+ launch.reject(new Error('synthetic abandoned launch failure'));+ await removed;+ expect(existsSync(temp)).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ expect(rm).toHaveBeenCalledTimes(1);+ expect(fixture.server.close).not.toHaveBeenCalled();+ });++ it('never gives an external/CDP adapter a process termination capability', async () => {+ const external = { launch: vi.fn(stalls), connectOverCDP: vi.fn(stalls) };+ await expect(startOwnedBrowserFixture({ chromium: external })).rejects.toThrow('requires launchServer/connect');+ expect(external.launch).not.toHaveBeenCalled();+ expect(external.connectOverCDP).not.toHaveBeenCalled();+ });+});