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([issue-12617]): relaunch Chrome after it exits instead of waiting for a manual restart (#12743)

[._.]/16c621f9b2d4
diff --git a/browser/server.js b/browser/server.js
index c55b12de6a..f3277c6203 100644
--- a/browser/server.js
+++ b/browser/server.js
@@ -6,6 +6,7 @@ import { resolve, dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { platform, homedir } from 'os';
import { browserExecutablePath, deriveMacAppBundleFromChromePath } from '../server/lib/browserConfig.js';
+import { isDirectlyInvoked } from '../scripts/lib/directInvocation.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = resolve(__dirname, '..');
@@ -17,15 +18,13 @@ const CDP_PORT = parseInt(process.env.CDP_PORT || '5556', 10);
const HEALTH_PORT = parseInt(process.env.PORT || '5557', 10);
const CDP_HOST = process.env.CDP_HOST || '127.0.0.1';
-let chromeProcess = null;
-// Default headed — PortOS runs on a single user's dev machine where seeing
-// the browser window matters (auto-opening the UI on setup/update, debugging
-// CDP automation visually). Set `headless: true` in data/browser-config.json
-// to opt back in for headless workflows.
-let headlessMode = false;
-let downloadWs = null;
-let downloadWsReconnectTimer = null;
-let shuttingDown = false;
+// Two misses at the initial interval ignore a one-off CDP blip. Further launch
+// failures wait 2s, 4s, … capped at 60s, and a CDP answer resets that wait.
+const BACKOFF_INITIAL_MS = 2000;
+const BACKOFF_MAX_MS = 60_000;
+const MISSES_BEFORE_RELAUNCH = 2;
+const LAUNCH_POLL_MS = 500;
+const LAUNCH_POLLS = 20;
const PREFS_MISSING = Symbol('prefs-missing');
const PREFS_UNREADABLE = Symbol('prefs-unreadable');
@@ -53,7 +52,7 @@ async function loadConfig() {
}
}
-const checkCdp = () => probeCdpVersion(`http://${CDP_HOST}:${CDP_PORT}/json/version`);
+const probeConfiguredCdp = () => probeCdpVersion(`http://${CDP_HOST}:${CDP_PORT}/json/version`);
// CDP Browser.setDownloadBehavior replaces Chrome's native download delegate,
// making Open/Show in Finder no-ops (verified on Chrome 151). Set the unprotected
@@ -109,265 +108,525 @@ async function tryReadJson(path) {
}
}
-// A CDP WebSocket held open for the lifetime of this process, used purely to
-// detect Chrome exiting (the 'close' event). On macOS we launch Chrome via
-// `open` and never hold its PID, so this socket is our only liveness signal.
-// It deliberately sends no commands — see applyDownloadDirPreference above for
-// why `Browser.setDownloadBehavior` must not be used here.
-async function openLivenessKeepAlive() {
- // WebSocket is a global in Node.js 21+ (project targets Node 22+)
- if (typeof WebSocket === 'undefined') {
- console.log('⚠️ WebSocket not available — Chrome exit detection disabled (requires Node.js 21+)');
- return;
- }
+/**
+ * PM2 fork mode runs `node ProcessContainerFork.js`, which then imports this
+ * file. `argv[1]` is that container; the script PM2 was asked to run is
+ * `pm_exec_path`. Vitest's argv is not this file and does not set that
+ * variable, so importing the module under test does not bind a port.
+ */
+export function shouldStartSupervisor(moduleUrl, env = process.env, invokedPath = process.argv[1]) {
+ if (isDirectlyInvoked(moduleUrl, invokedPath)) return true;
+ const pmExec = env?.pm_exec_path;
+ return typeof pmExec === 'string' && pmExec.length > 0 && isDirectlyInvoked(moduleUrl, pmExec);
+}
- // Tear down any existing keep-alive before opening a new one
- if (downloadWs) {
- try { downloadWs.close(); } catch {}
+/**
+ * Supervise one managed Chrome. `options.checkCdp` / `options.spawn` (and the
+ * other overrides) exist so tests can run the loop without a real browser.
+ * The health server is listening before the first launch, so a rejection is
+ * reported at /health instead of killing the process.
+ */
+export function createBrowserSupervisor(options = {}) {
+ const deps = {
+ checkCdp: options.checkCdp || probeConfiguredCdp,
+ spawn: options.spawn || spawn,
+ mkdir: options.mkdir || mkdir,
+ sleep: options.sleep || ((ms) => new Promise((resolve) => { setTimeout(resolve, ms); })),
+ loadConfig: options.loadConfig || loadConfig,
+ platform: options.platform || platform(),
+ WebSocket: options.WebSocket || globalThis.WebSocket,
+ applyDownloadDirPreference: options.applyDownloadDirPreference || applyDownloadDirPreference,
+ exitProcess: options.exitProcess,
+ healthPort: options.healthPort ?? HEALTH_PORT,
+ bindSignals: options.bindSignals === true,
+ };
+
+ let chromeProcess = null;
+ let headlessMode = false;
+ let downloadWs = null;
+ let shuttingDown = false;
+ let relaunching = false;
+ let attempt = 0;
+ let lastError = null;
+ let sawFailure = false;
+ let spawnError = null;
+ let consecutiveMisses = 0;
+ let delayMs = BACKOFF_INITIAL_MS;
+ let pendingRecoveryLog = false;
+ let wakeSupervise = null;
+ let shutdownPromise = null;
+
+ function detachKeepAlive({ intentional }) {
+ const ws = downloadWs;
+ if (!ws) return;
downloadWs = null;
+ if (intentional) ws.intentionalClose = true;
+ try { ws.close(); } catch { /* already closed */ }
}
- if (downloadWsReconnectTimer) {
- clearTimeout(downloadWsReconnectTimer);
- downloadWsReconnectTimer = null;
+
+ // A CDP WebSocket held open for the lifetime of this process, used purely to
+ // detect Chrome exiting (the 'close' event). On macOS we launch Chrome via
+ // `open` and never hold its PID, so this socket is our only liveness signal.
+ // It deliberately sends no commands — see applyDownloadDirPreference above for
+ // why `Browser.setDownloadBehavior` must not be used here.
+ async function openLivenessKeepAlive() {
+ const WebSocketImpl = deps.WebSocket;
+ if (typeof WebSocketImpl !== 'function') {
+ console.log('⚠️ WebSocket not available — Chrome exit detection disabled (requires Node.js 21+)');
+ return;
+ }
+
+ if (downloadWs) detachKeepAlive({ intentional: true });
+
+ const version = await deps.checkCdp();
+ const wsUrl = version?.webSocketDebuggerUrl;
+ if (!wsUrl) {
+ console.log('⚠️ CDP unreachable — cannot open keep-alive');
+ return;
+ }
+
+ const ws = new WebSocketImpl(wsUrl);
+ downloadWs = ws;
+
+ ws.addEventListener('close', () => {
+ if (downloadWs === ws) downloadWs = null;
+ if (shuttingDown || ws.intentionalClose) return;
+ console.log('⚠️ Keep-alive WS closed — will reconnect');
+ // A close during the post-failure wait must not skip the backoff.
+ if (!relaunching) wakeSupervise?.();
+ });
+
+ ws.addEventListener('error', (event) => {
+ if (shuttingDown) return;
+ const message = event?.error?.message || event?.message || event?.error?.code || 'connection lost';
+ console.warn(`⚠️ Keep-alive WS reset: ${message} — will reconnect`);
+ });
}
- const version = await checkCdp();
- const wsUrl = version?.webSocketDebuggerUrl;
- if (!wsUrl) {
- console.log('⚠️ CDP unreachable — cannot open keep-alive');
- scheduleDownloadReconnect();
- return;
+ async function ensureKeepAlive() {
+ if (downloadWs || shuttingDown) return;
+ try {
+ await openLivenessKeepAlive();
+ } catch (err) {
+ console.error(`❌ Keep-alive open failed: ${err.message}`);
+ }
}
- const ws = new WebSocket(wsUrl);
- downloadWs = ws;
+ async function launchBrowser() {
+ if (shuttingDown) return;
+ const config = await deps.loadConfig();
+ if (shuttingDown) return;
+ const downloadDir = config.downloadDir || DEFAULT_DOWNLOAD_DIR;
+ headlessMode = config.headless === true;
+ spawnError = null;
+
+ // Reuse existing Chrome if CDP is already reachable (e.g. after PM2 restart)
+ if (await deps.checkCdp()) {
+ if (shuttingDown) return;
+ console.log(`♻️ Existing Chrome CDP found at ${CDP_HOST}:${CDP_PORT}, reusing`);
+ await deps.mkdir(downloadDir, { recursive: true });
+ // Chrome owns Preferences while it runs and rewrites the file from memory
+ // on exit, so a running instance keeps whatever download dir it launched
+ // with; the pref is applied on the next launch.
+ await ensureKeepAlive();
+ return;
+ }
- ws.addEventListener('close', () => {
- if (downloadWs === ws) downloadWs = null;
if (shuttingDown) return;
- console.log('⚠️ Keep-alive WS closed — will reconnect');
- scheduleDownloadReconnect();
- });
+ const profileDir = config.userDataDir || DEFAULT_PROFILE_DIR;
+ const chromePath = browserExecutablePath(config);
+ const macAppBundle = getMacAppBundle(config, chromePath);
- ws.addEventListener('error', (event) => {
+ await deps.mkdir(profileDir, { recursive: true });
+ if (shuttingDown) return;
+ await deps.mkdir(downloadDir, { recursive: true });
if (shuttingDown) return;
- const message = event?.error?.message || event?.message || event?.error?.code || 'connection lost';
- console.warn(`⚠️ Keep-alive WS reset: ${message} — will reconnect`);
- });
-}
-function scheduleDownloadReconnect() {
- if (shuttingDown || downloadWsReconnectTimer) return;
- downloadWsReconnectTimer = setTimeout(async () => {
- downloadWsReconnectTimer = null;
+ // Chrome is not running yet, so Preferences is ours to write.
+ if (await deps.applyDownloadDirPreference(profileDir, downloadDir)) {
+ console.log(`📥 Download directory pref set → ${downloadDir}`);
+ }
if (shuttingDown) return;
- // Contain any rejection from checkCdp/openLivenessKeepAlive so an
- // async setTimeout callback can't escape as an unhandledRejection.
- try {
- if (await checkCdp()) {
- await openLivenessKeepAlive();
- } else {
- scheduleDownloadReconnect();
+
+ const args = [
+ `--remote-debugging-port=${CDP_PORT}`,
+ `--remote-debugging-address=${CDP_HOST}`,
+ `--user-data-dir=${profileDir}`,
+ '--no-first-run',
+ '--no-default-browser-check',
+ '--disable-background-timer-throttling',
+ '--disable-backgrounding-occluded-windows',
+ '--disable-renderer-backgrounding',
+ '--disable-ipc-flooding-protection'
+ ];
+
+ if (headlessMode) args.push('--headless=new');
+
+ console.log(`🌐 Launching Chrome (headless=${headlessMode}, profile=${profileDir}, binary=${deps.platform === 'darwin' && !headlessMode ? macAppBundle : chromePath}) CDP on ${CDP_HOST}:${CDP_PORT}`);
+
+ // macOS headed mode: launch via LaunchServices (`open -na`) so Chrome owns
+ // its own TCC identity. As a direct subprocess of node/PM2, Chrome inherits
+ // PM2's responsibility for AppleEvents + LaunchServices calls — every shell
+ // handoff from the download UI ("Show in Finder", "Open file", chrome://
+ // downloads row click) silently no-ops because PM2 isn't granted Automation
+ // / Files-and-Folders access. `open -na` makes launchd the responsible
+ // launcher, so tccd resolves Chrome's requests against the user's existing
+ // Chrome.app grants. Trade-off: `open` returns immediately, so we lose the
+ // direct PID — shutdown uses CDP `Browser.close` instead of SIGTERM.
+ // Headless mode skips this (no UI to click) and non-darwin platforms don't
+ // have the TCC-responsibility problem at all.
+ let child;
+ if (deps.platform === 'darwin' && !headlessMode) {
+ // `open` has usually already exited, so there is no Chrome PID to signal.
+ // When CDP still answers, close that instance before `open -na` starts
+ // another. A hung Chrome that no longer answers CDP cannot be reaped
+ // from here; the next attempt is the recovery.
+ await closeBrowserViaCdp().catch(() => {});
+ if (chromeProcess && !chromeProcess.killed) return;
+ // windowsHide is a no-op on POSIX and this branch is darwin-only, but every
+ // spawn in this package carries it: portos-browser is a PM2 fork, so the
+ // guard holds the whole tree to one rule rather than reasoning about which
+ // branch runs where. See docs/WINDOWS_CONSOLE.md.
+ child = deps.spawn('/usr/bin/open', ['-na', macAppBundle, '--args', ...args], { stdio: 'ignore', windowsHide: true });
+ child.on('exit', () => {
+ // `open` returns ~immediately once Chrome is handed off to launchd; that
+ // exit is not Chrome's death. Chrome-exit detection happens via the
+ // liveness keep-alive WS close event instead.
+ if (chromeProcess === child) chromeProcess = null;
+ });
+ // A bad macAppBundle (user-editable via the Browser settings UI) emits
+ // 'error'; with no listener that becomes an uncaughtException → PM2
+ // restart-loop. Log and null out so the supervise loop relaunches.
+ child.on('error', (err) => {
+ spawnError = err.message;
+ console.error(`❌ Failed to spawn Chrome via open: ${err.message}`);
+ if (chromeProcess === child) chromeProcess = null;
+ });
+ } else {
+ // A launch that never reached CDP, or a hung Chrome, is still our child.
+ // Spawn the replacement only after signaling that one, or shutdown can
+ // reap only the newest PID and the profile stays locked.
+ if (chromeProcess && !chromeProcess.killed) {
+ try { chromeProcess.kill('SIGTERM'); } catch { /* already gone */ }
+ chromeProcess = null;
+ }
+ child = deps.spawn(chromePath, args, { stdio: 'ignore', windowsHide: true });
+ child.on('exit', (code) => {
+ console.log(`⚠️ Chrome exited with code ${code}`);
+ if (chromeProcess === child) chromeProcess = null;
+ detachKeepAlive({ intentional: false });
+ });
+ // A bad chromePath (user-editable via the Browser settings UI) emits
+ // 'error'; with no listener that becomes an uncaughtException → PM2
+ // restart-loop. Log and null out so the supervise loop relaunches.
+ child.on('error', (err) => {
+ spawnError = err.message;
+ console.error(`❌ Failed to spawn Chrome (${chromePath}): ${err.message}`);
+ if (chromeProcess === child) chromeProcess = null;
+ detachKeepAlive({ intentional: false });
+ });
+ }
+ chromeProcess = child;
+
+ // Listeners are on before the first wait: a failed spawn emits 'error'
+ // on next tick, and an unhandled error would take the process down.
+ for (let i = 0; i < LAUNCH_POLLS; i++) {
+ if (shuttingDown) return;
+ await deps.sleep(LAUNCH_POLL_MS);
+ if (shuttingDown) return;
+ if (await deps.checkCdp()) {
+ console.log(`✅ Chrome launched, CDP available at ws://${CDP_HOST}:${CDP_PORT}`);
+ await ensureKeepAlive();
+ return;
}
- } catch (err) {
- console.error(`⚠️ Keep-alive reconnect failed: ${err.message}`);
- scheduleDownloadReconnect();
}
- }, 2000);
-}
-async function launchBrowser() {
- const config = await loadConfig();
- const downloadDir = config.downloadDir || DEFAULT_DOWNLOAD_DIR;
- headlessMode = config.headless === true;
-
- // Reuse existing Chrome if CDP is already reachable (e.g. after PM2 restart)
- if (await checkCdp()) {
- console.log(`♻️ Existing Chrome CDP found at ${CDP_HOST}:${CDP_PORT}, reusing`);
- await mkdir(downloadDir, { recursive: true });
- // Chrome owns Preferences while it runs and rewrites the file from memory
- // on exit, so a running instance keeps whatever download dir it launched
- // with; the pref is applied on the next launch.
- await openLivenessKeepAlive();
- return;
+ console.error('❌ Chrome launched but CDP not reachable after 10s');
}
- const profileDir = config.userDataDir || DEFAULT_PROFILE_DIR;
- const chromePath = browserExecutablePath(config);
- const macAppBundle = getMacAppBundle(config, chromePath);
+ function noteRecovered() {
+ if (sawFailure || pendingRecoveryLog) console.log('✅ Chrome CDP recovered');
+ pendingRecoveryLog = false;
+ sawFailure = false;
+ lastError = null;
+ relaunching = false;
+ attempt = 0;
+ consecutiveMisses = 0;
+ delayMs = BACKOFF_INITIAL_MS;
+ spawnError = null;
+ }
- await mkdir(profileDir, { recursive: true });
- await mkdir(downloadDir, { recursive: true });
+ function takeFailureWait() {
+ const wait = delayMs;
+ delayMs = Math.min(delayMs * 2, BACKOFF_MAX_MS);
+ return wait;
+ }
- // Chrome is not running yet, so Preferences is ours to write.
- if (await applyDownloadDirPreference(profileDir, downloadDir)) {
- console.log(`📥 Download directory pref set → ${downloadDir}`);
+ async function probeUp() {
+ try {
+ return Boolean(await deps.checkCdp());
+ } catch (err) {
+ lastError = err.message;
+ console.error(`❌ CDP check failed: ${err.message}`);
+ return false;
+ }
}
- const args = [
- `--remote-debugging-port=${CDP_PORT}`,
- `--remote-debugging-address=${CDP_HOST}`,
- `--user-data-dir=${profileDir}`,
- '--no-first-run',
- '--no-default-browser-check',
- '--disable-background-timer-throttling',
- '--disable-backgrounding-occluded-windows',
- '--disable-renderer-backgrounding',
- '--disable-ipc-flooding-protection'
- ];
-
- if (headlessMode) {
- args.push('--headless=new');
+ async function attemptLaunch({ relaunch }) {
+ if (shuttingDown) return false;
+ relaunching = true;
+ attempt += 1;
+ if (relaunch) {
+ pendingRecoveryLog = true;
+ console.log(`🔁 Relaunching Chrome (attempt ${attempt})`);
+ }
+ try {
+ await launchBrowser();
+ } catch (err) {
+ sawFailure = true;
+ lastError = err.message;
+ console.error(`❌ Chrome launch failed: ${err.message}`);
+ return false;
+ }
+ if (shuttingDown) return false;
+ if (await probeUp()) {
+ noteRecovered();
+ return true;
+ }
+ sawFailure = true;
+ lastError = spawnError || 'Chrome launched but CDP not reachable after 10s';
+ return false;
}
- console.log(`🌐 Launching Chrome (headless=${headlessMode}, profile=${profileDir}, binary=${platform() === 'darwin' && !headlessMode ? macAppBundle : chromePath}) CDP on ${CDP_HOST}:${CDP_PORT}`);
-
- // macOS headed mode: launch via LaunchServices (`open -na`) so Chrome owns
- // its own TCC identity. As a direct subprocess of node/PM2, Chrome inherits
- // PM2's responsibility for AppleEvents + LaunchServices calls — every shell
- // handoff from the download UI ("Show in Finder", "Open file", chrome://
- // downloads row click) silently no-ops because PM2 isn't granted Automation
- // / Files-and-Folders access. `open -na` makes launchd the responsible
- // launcher, so tccd resolves Chrome's requests against the user's existing
- // Chrome.app grants. Trade-off: `open` returns immediately, so we lose the
- // direct PID — shutdown uses CDP `Browser.close` instead of SIGTERM.
- // Headless mode skips this (no UI to click) and non-darwin platforms don't
- // have the TCC-responsibility problem at all.
- if (platform() === 'darwin' && !headlessMode) {
- // windowsHide is a no-op on POSIX and this branch is darwin-only, but every
- // spawn in this package carries it: portos-browser is a PM2 fork, so the
- // guard holds the whole tree to one rule rather than reasoning about which
- // branch runs where. See docs/WINDOWS_CONSOLE.md.
- chromeProcess = spawn('/usr/bin/open', ['-na', macAppBundle, '--args', ...args], { stdio: 'ignore', windowsHide: true });
- chromeProcess.on('exit', () => {
- // `open` returns ~immediately once Chrome is handed off to launchd; that
- // exit is not Chrome's death. Chrome-exit detection happens via the
- // liveness keep-alive WS close event + reconnect loop instead.
- chromeProcess = null;
- });
- // A bad macAppBundle (user-editable via the Browser settings UI) emits
- // 'error'; with no listener that becomes an uncaughtException → PM2
- // restart-loop. Log and null out so the CDP-wait loop reports unreachable.
- chromeProcess.on('error', (err) => {
- console.error(`❌ Failed to spawn Chrome via open: ${err.message}`);
- chromeProcess = null;
- });
- } else {
- chromeProcess = spawn(chromePath, args, { stdio: 'ignore', windowsHide: true });
- chromeProcess.on('exit', (code) => {
- console.log(`⚠️ Chrome exited with code ${code}`);
- chromeProcess = null;
- if (downloadWs) {
- try { downloadWs.close(); } catch {}
- downloadWs = null;
- }
- });
- // A bad chromePath (user-editable via the Browser settings UI) emits
- // 'error'; with no listener that becomes an uncaughtException → PM2
- // restart-loop. Log and null out so the CDP-wait loop reports unreachable.
- chromeProcess.on('error', (err) => {
- console.error(`❌ Failed to spawn Chrome (${chromePath}): ${err.message}`);
- chromeProcess = null;
- if (downloadWs) {
- try { downloadWs.close(); } catch {}
- downloadWs = null;
- }
+ function superviseDelay(ms) {
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ if (wakeSupervise === finish) wakeSupervise = null;
+ resolve();
+ };
+ wakeSupervise = finish;
+ Promise.resolve()
+ .then(() => deps.sleep(ms))
+ .then(finish, (err) => {
+ lastError = err?.message || 'sleep failed';
+ sawFailure = true;
+ relaunching = true;
+ console.error(`❌ Browser supervise wait failed: ${lastError}`);
+ finish();
+ });
});
}
- // Wait for CDP to become available
- for (let i = 0; i < 20; i++) {
- await new Promise(r => setTimeout(r, 500));
- if (await checkCdp()) {
- console.log(`✅ Chrome launched, CDP available at ws://${CDP_HOST}:${CDP_PORT}`);
- await openLivenessKeepAlive();
- return;
+ // Replaces the old reconnect-only poll: Chrome exiting (or a launch throw)
+ // stays inside this loop until CDP answers or the process is stopped.
+ async function superviseLoop() {
+ relaunching = true;
+ let booting = true;
+ while (!shuttingDown) {
+ let wait = delayMs;
+ try {
+ if (booting) {
+ booting = false;
+ const ok = await attemptLaunch({ relaunch: false });
+ if (shuttingDown) break;
+ wait = ok ? delayMs : takeFailureWait();
+ } else {
+ const up = await probeUp();
+ if (shuttingDown) break;
+ if (up) {
+ noteRecovered();
+ await ensureKeepAlive();
+ wait = delayMs;
+ } else {
+ detachKeepAlive({ intentional: true });
+ consecutiveMisses += 1;
+ if (relaunching || consecutiveMisses >= MISSES_BEFORE_RELAUNCH) {
+ const ok = await attemptLaunch({ relaunch: true });
+ if (shuttingDown) break;
+ wait = ok ? delayMs : takeFailureWait();
+ } else {
+ wait = delayMs;
+ }
+ }
+ }
+ } catch (err) {
+ sawFailure = true;
+ relaunching = true;
+ lastError = err.message;
+ console.error(`❌ Browser supervise loop error: ${err.message}`);
+ wait = takeFailureWait();
+ }
+ if (shuttingDown) break;
+ await superviseDelay(wait);
}
}
- console.error('❌ Chrome launched but CDP not reachable after 10s');
-}
+ async function healthBody() {
+ let connected = false;
+ try {
+ connected = Boolean(await deps.checkCdp());
+ } catch {
+ connected = false;
+ }
+ const status = connected ? 'healthy' : (relaunching ? 'relaunching' : 'unhealthy');
+ return {
+ httpStatus: connected ? 200 : 503,
+ body: {
+ status,
+ attempt: status === 'relaunching' ? attempt : 0,
+ lastError: status === 'relaunching' ? lastError : null,
+ cdpPort: CDP_PORT,
+ cdpHost: CDP_HOST,
+ cdpEndpoint: `ws://${CDP_HOST}:${CDP_PORT}`,
+ headless: headlessMode,
+ },
+ };
+ }
-// Health check server
-const healthServer = createServer(async (req, res) => {
- if (req.url === '/health') {
- const connected = await checkCdp();
- const status = connected ? 'healthy' : 'unhealthy';
- res.writeHead(connected ? 200 : 503, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status,
- cdpPort: CDP_PORT,
- cdpHost: CDP_HOST,
- cdpEndpoint: `ws://${CDP_HOST}:${CDP_PORT}`,
- headless: headlessMode
- }));
- } else if (req.url === '/') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- service: 'portos-browser',
- cdpPort: CDP_PORT,
- cdpHost: CDP_HOST,
- healthPort: HEALTH_PORT,
- endpoints: {
- health: '/health',
- cdp: `ws://${CDP_HOST}:${CDP_PORT}`
+ const healthServer = createServer(async (req, res) => {
+ try {
+ if (req.url === '/health') {
+ const { httpStatus, body } = await healthBody();
+ res.writeHead(httpStatus, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(body));
+ } else if (req.url === '/') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ service: 'portos-browser',
+ cdpPort: CDP_PORT,
+ cdpHost: CDP_HOST,
+ healthPort: healthServer.address()?.port ?? deps.healthPort,
+ endpoints: {
+ health: '/health',
+ cdp: `ws://${CDP_HOST}:${CDP_PORT}`,
+ },
+ }));
+ } else {
+ res.writeHead(404);
+ res.end('Not Found');
}
- }));
- } else {
- res.writeHead(404);
- res.end('Not Found');
- }
-});
-
-async function closeBrowserViaCdp() {
- if (typeof WebSocket === 'undefined') return;
- const version = await checkCdp();
- const wsUrl = version?.webSocketDebuggerUrl;
- if (!wsUrl) return;
- await new Promise((resolve) => {
- const ws = new WebSocket(wsUrl);
- const done = () => { try { ws.close(); } catch {} resolve(); };
- const safety = setTimeout(done, 2000);
- ws.addEventListener('open', () => {
- try { ws.send(JSON.stringify({ id: 999, method: 'Browser.close' })); } catch {}
- // Give Chrome a moment to tear down before we exit the supervisor
- setTimeout(() => { clearTimeout(safety); done(); }, 500);
- });
- ws.addEventListener('error', () => { clearTimeout(safety); done(); });
+ } catch (err) {
+ console.error(`❌ Browser health request failed: ${err.message}`);
+ if (!res.headersSent) res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ status: 'unhealthy', lastError: err.message }));
+ }
});
-}
-async function shutdown() {
- console.log('🛑 Shutting down browser...');
- shuttingDown = true;
- if (downloadWsReconnectTimer) {
- clearTimeout(downloadWsReconnectTimer);
- downloadWsReconnectTimer = null;
+ async function closeBrowserViaCdp() {
+ const WebSocketImpl = deps.WebSocket;
+ if (typeof WebSocketImpl !== 'function') return;
+ const version = await deps.checkCdp();
+ const wsUrl = version?.webSocketDebuggerUrl;
+ if (!wsUrl) return;
+ await new Promise((resolveClose) => {
+ const ws = new WebSocketImpl(wsUrl);
+ const done = () => { try { ws.close(); } catch { /* already closed */ } resolveClose(); };
+ const safety = setTimeout(done, 2000);
+ ws.addEventListener('open', () => {
+ try { ws.send(JSON.stringify({ id: 999, method: 'Browser.close' })); } catch { /* socket already gone */ }
+ // Give Chrome a moment to tear down before we exit the supervisor
+ setTimeout(() => { clearTimeout(safety); done(); }, 500);
+ });
+ ws.addEventListener('error', () => { clearTimeout(safety); done(); });
+ });
}
- // macOS headed mode: we launched via `open` which exited immediately, so
- // SIGTERM on `chromeProcess` is a no-op. Send CDP Browser.close instead.
- if (platform() === 'darwin' && !headlessMode) {
- await closeBrowserViaCdp().catch(() => {});
- } else if (chromeProcess && !chromeProcess.killed) {
- chromeProcess.kill('SIGTERM');
+
+ function onSignal() {
+ shutdown().catch((err) => {
+ console.error(`❌ Browser shutdown failed: ${err.message}`);
+ });
}
- if (downloadWs) {
- try { downloadWs.close(); } catch {}
- downloadWs = null;
+
+ if (deps.bindSignals) {
+ process.on('SIGTERM', onSignal);
+ process.on('SIGINT', onSignal);
}
- healthServer.close();
- process.exit(0);
-}
-process.on('SIGTERM', shutdown);
-process.on('SIGINT', shutdown);
+ async function doShutdown() {
+ shuttingDown = true;
+ if (deps.bindSignals) {
+ process.off('SIGTERM', onSignal);
+ process.off('SIGINT', onSignal);
+ }
+ wakeSupervise?.();
+ console.log('🛑 Shutting down browser...');
+ // macOS headed mode: we launched via `open` which exited immediately, so
+ // SIGTERM on `chromeProcess` is a no-op. Send CDP Browser.close instead.
+ if (deps.platform === 'darwin' && !headlessMode) {
+ await closeBrowserViaCdp().catch(() => {});
+ } else if (chromeProcess && !chromeProcess.killed) {
+ chromeProcess.kill('SIGTERM');
+ }
+ detachKeepAlive({ intentional: true });
+ healthServer.closeAllConnections?.();
+ await new Promise((resolveClose) => {
+ if (!healthServer.listening) return resolveClose();
+ healthServer.close(() => resolveClose());
+ });
+ if (deps.exitProcess) deps.exitProcess(0);
+ }
-async function main() {
- await launchBrowser();
+ function shutdown() {
+ if (!shutdownPromise) shutdownPromise = doShutdown();
+ return shutdownPromise;
+ }
- healthServer.listen(HEALTH_PORT, '127.0.0.1', () => {
- console.log(`📡 Health check server listening on port ${HEALTH_PORT}`);
+ let resolveReady;
+ let rejectReady;
+ const ready = new Promise((resolve, reject) => {
+ resolveReady = resolve;
+ rejectReady = reject;
});
+
+ async function listenHealth() {
+ await new Promise((resolve, reject) => {
+ let listening = false;
+ healthServer.on('error', (err) => {
+ if (!listening) {
+ listening = true;
+ reject(err);
+ return;
+ }
+ console.error(`❌ Browser health server error: ${err.message}`);
+ });
+ healthServer.once('listening', () => {
+ listening = true;
+ resolve();
+ });
+ healthServer.listen(deps.healthPort, '127.0.0.1');
+ });
+ const address = healthServer.address();
+ console.log(`📡 Health check server listening on port ${address?.port ?? deps.healthPort}`);
+ }
+
+ async function main() {
+ try {
+ await listenHealth();
+ resolveReady();
+ } catch (err) {
+ rejectReady(err);
+ throw err;
+ }
+ await superviseLoop();
+ }
+
+ return { main, shutdown, ready, healthServer };
}
-main();
+if (shouldStartSupervisor(import.meta.url)) {
+ const supervisor = createBrowserSupervisor({
+ exitProcess: (code) => process.exit(code),
+ bindSignals: true,
+ });
+ // listenHealth is the only rejection main() lets out. The supervise loop
+ // retries launch failures itself. A taken health port has no loop to retry
+ // inside, and PM2's IPC channel would keep the caught error alive as a
+ // silent online process. Exit non-zero so PM2 restarts.
+ supervisor.main().catch((err) => {
+ console.error(`❌ Browser supervisor failed: ${err.message}`);
+ process.exit(1);
+ });
+}
diff --git a/browser/server.test.js b/browser/server.test.js
new file mode 100644
index 0000000000..8e77a9edf1
--- /dev/null
+++ b/browser/server.test.js
@@ -0,0 +1,312 @@
+import { spawn } from 'child_process';
+import { EventEmitter } from 'events';
+import { createServer } from 'http';
+import { fileURLToPath } from 'url';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createBrowserSupervisor, shouldStartSupervisor } from './server.js';
+
+const SERVER_MODULE_URL = new URL('./server.js', import.meta.url).href;
+const SERVER_PATH = fileURLToPath(SERVER_MODULE_URL);
+
+const LAUNCH_POLL_MS = 500;
+const CDP_UP = { webSocketDebuggerUrl: 'ws://127.0.0.1/devtools/browser/fixture' };
+
+function fakeChild() {
+ const child = new EventEmitter();
+ child.killed = false;
+ child.kill = () => { child.killed = true; };
+ return child;
+}
+
+function createSleeper() {
+ const pending = [];
+ return {
+ pending,
+ sleep(ms) {
+ return new Promise((resolve) => { pending.push({ ms, resolve }); });
+ },
+ };
+}
+
+async function waitForSleep(sleeper) {
+ const start = Date.now();
+ while (sleeper.pending.length === 0) {
+ if (Date.now() - start > 2000) throw new Error('supervise loop did not reach a sleep');
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ return sleeper.pending[0].ms;
+}
+
+/** Release Chrome's 500ms launch polls and stop on the supervise wait. */
+async function advanceToSuperviseSleep(sleeper) {
+ let ms = await waitForSleep(sleeper);
+ while (ms === LAUNCH_POLL_MS) {
+ sleeper.pending.shift().resolve();
+ ms = await waitForSleep(sleeper);
+ }
+ return ms;
+}
+
+function releasePending(sleeper) {
+ const item = sleeper.pending.shift();
+ if (!item) throw new Error('no pending sleep to release');
+ item.resolve();
+}
+
+async function readHealth(port) {
+ const response = await fetch(`http://127.0.0.1:${port}/health`);
+ return { statusCode: response.status, body: await response.json() };
+}
+
+describe('browser supervisor entry', () => {
+ it('starts for a direct node launch and for PM2 fork mode, and not for an import', () => {
+ const container = '/opt/example/ProcessContainerFork.js';
+ expect(shouldStartSupervisor(SERVER_MODULE_URL, {}, SERVER_PATH)).toBe(true);
+ expect(shouldStartSupervisor(SERVER_MODULE_URL, { pm_exec_path: SERVER_PATH }, container)).toBe(true);
+ expect(shouldStartSupervisor(SERVER_MODULE_URL, {}, container)).toBe(false);
+ expect(shouldStartSupervisor(SERVER_MODULE_URL, { pm_exec_path: '/opt/example/other.js' }, container)).toBe(false);
+ expect(shouldStartSupervisor(SERVER_MODULE_URL, { pm_exec_path: '' }, container)).toBe(false);
+ });
+
+ it('exits non-zero when PM2 names this file and the health port is already taken', async () => {
+ const blocker = createServer();
+ await new Promise((resolve) => blocker.listen(0, '127.0.0.1', resolve));
+ const port = blocker.address().port;
+ try {
+ const child = spawn(process.execPath, [
+ '--input-type=module',
+ '--eval',
+ `await import(${JSON.stringify(SERVER_MODULE_URL)})`,
+ ], {
+ env: {
+ ...process.env,
+ PORT: String(port),
+ pm_exec_path: SERVER_PATH,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const result = await new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ child.kill('SIGKILL');
+ resolve({ code: 'timeout', stderr: '' });
+ }, 5000);
+ let stderr = '';
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
+ child.on('exit', (code) => {
+ clearTimeout(timer);
+ resolve({ code, stderr });
+ });
+ });
+ expect(result.code).toBe(1);
+ expect(result.stderr).toContain('Browser supervisor failed');
+ expect(result.stderr).not.toMatch(/\/Users\/|\/home\//);
+ } finally {
+ await new Promise((resolve) => blocker.close(resolve));
+ }
+ });
+});
+
+describe('browser Chrome supervise loop', () => {
+ let logSpy;
+ let errorSpy;
+ let warnSpy;
+ let current;
+
+ beforeEach(() => {
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(async () => {
+ if (current) {
+ await current.supervisor.shutdown();
+ await current.done;
+ }
+ logSpy.mockRestore();
+ errorSpy.mockRestore();
+ warnSpy.mockRestore();
+ current = null;
+ });
+
+ function start({ checkCdp, mkdir, bindSignals = false }) {
+ const sleeper = createSleeper();
+ const spawn = vi.fn(() => fakeChild());
+ const sockets = [];
+ class FakeWebSocket extends EventTarget {
+ constructor(url) {
+ super();
+ this.url = url;
+ sockets.push(this);
+ }
+ close() { this.dispatchEvent(new Event('close')); }
+ }
+ let loopError = null;
+ const supervisor = createBrowserSupervisor({
+ checkCdp,
+ spawn,
+ mkdir,
+ sleep: sleeper.sleep,
+ loadConfig: async () => ({
+ headless: true,
+ downloadDir: '/tmp/portos-browser-download-fixture',
+ userDataDir: '/tmp/portos-browser-profile-fixture',
+ chromePath: '/opt/example/chrome',
+ }),
+ applyDownloadDirPreference: async () => false,
+ platform: 'linux',
+ healthPort: 0,
+ WebSocket: FakeWebSocket,
+ bindSignals,
+ });
+ const done = supervisor.main().catch((err) => { loopError = err; });
+ current = {
+ supervisor,
+ sleeper,
+ spawn,
+ sockets,
+ done,
+ get loopError() { return loopError; },
+ };
+ return current;
+ }
+
+ it('relaunches within the backoff window after CDP drops and reopens the keep-alive', async () => {
+ let cdpUp = true;
+ const session = start({
+ checkCdp: async () => (cdpUp ? CDP_UP : null),
+ mkdir: async () => {},
+ });
+ await session.supervisor.ready;
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ expect(session.spawn).not.toHaveBeenCalled();
+ const socketsAfterBoot = session.sockets.length;
+ expect(socketsAfterBoot).toBeGreaterThan(0);
+
+ cdpUp = false;
+ releasePending(session.sleeper);
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ expect(session.spawn).not.toHaveBeenCalled();
+
+ releasePending(session.sleeper);
+ expect(await waitForSleep(session.sleeper)).toBe(LAUNCH_POLL_MS);
+ expect(session.spawn).toHaveBeenCalledTimes(1);
+ expect(session.spawn.mock.calls[0][0]).toBe('/opt/example/chrome');
+ expect(session.spawn.mock.calls[0][2]).toMatchObject({ windowsHide: true });
+ expect(logSpy).toHaveBeenCalledWith('🔁 Relaunching Chrome (attempt 1)');
+
+ cdpUp = true;
+ releasePending(session.sleeper);
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ expect(session.sockets.length).toBeGreaterThan(socketsAfterBoot);
+ expect(session.sockets.at(-1).url).toBe(CDP_UP.webSocketDebuggerUrl);
+ expect(logSpy).toHaveBeenCalledWith('✅ Chrome CDP recovered');
+ expect(session.loopError).toBeNull();
+ });
+
+ it('reports a boot launch failure, backs off to 60s, and resets after CDP returns', async () => {
+ let mkdirMode = 'fail';
+ let cdpMode = 'down';
+ let mkdirCalls = 0;
+ const session = start({
+ checkCdp: async () => (
+ cdpMode === 'up' || (cdpMode === 'after-spawn' && session.spawn.mock.calls.length > 0)
+ ? CDP_UP
+ : null
+ ),
+ mkdir: async () => {
+ mkdirCalls += 1;
+ if (mkdirMode === 'fail') throw new Error('download directory unavailable');
+ },
+ });
+ await session.supervisor.ready;
+ const port = session.supervisor.healthServer.address().port;
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ const health = await readHealth(port);
+ expect(health.statusCode).toBe(503);
+ expect(health.body).toMatchObject({
+ status: 'relaunching',
+ attempt: 1,
+ lastError: 'download directory unavailable',
+ });
+ expect(errorSpy).toHaveBeenCalledWith('❌ Chrome launch failed: download directory unavailable');
+ expect(session.spawn).not.toHaveBeenCalled();
+
+ const waits = [2000];
+ let pendingMs = 2000;
+ while (waits.filter((ms) => ms === 60_000).length < 2) {
+ releasePending(session.sleeper);
+ pendingMs = await advanceToSuperviseSleep(session.sleeper);
+ waits.push(pendingMs);
+ }
+ expect(waits).toEqual([2000, 4000, 8000, 16000, 32000, 60_000, 60_000]);
+ expect(session.loopError).toBeNull();
+ expect(session.spawn).not.toHaveBeenCalled();
+
+ mkdirMode = 'ok';
+ cdpMode = 'after-spawn';
+ releasePending(session.sleeper);
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ expect(session.spawn).toHaveBeenCalledTimes(1);
+ expect(await readHealth(port)).toMatchObject({
+ statusCode: 200,
+ body: { status: 'healthy', attempt: 0, lastError: null },
+ });
+ expect(logSpy).toHaveBeenCalledWith('✅ Chrome CDP recovered');
+
+ cdpMode = 'down';
+ mkdirMode = 'fail';
+ const mkdirBefore = mkdirCalls;
+ releasePending(session.sleeper);
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ expect(mkdirCalls).toBe(mkdirBefore);
+ releasePending(session.sleeper);
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ expect(mkdirCalls).toBeGreaterThan(mkdirBefore);
+ expect(session.loopError).toBeNull();
+ });
+
+ it('stops a still-running Chrome before the next launch attempt', async () => {
+ const session = start({
+ checkCdp: async () => null,
+ mkdir: async () => {},
+ });
+ await session.supervisor.ready;
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ expect(session.spawn).toHaveBeenCalledTimes(1);
+ const first = session.spawn.mock.results[0].value;
+ expect(first.killed).toBe(false);
+
+ releasePending(session.sleeper);
+ expect(await waitForSleep(session.sleeper)).toBe(LAUNCH_POLL_MS);
+ expect(first.killed).toBe(true);
+ expect(session.spawn).toHaveBeenCalledTimes(2);
+ // Leave the loop on the supervise wait so shutdown can wake it. The
+ // launch-poll sleeps are the injected sleeper, and nothing else releases them.
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBeGreaterThan(LAUNCH_POLL_MS);
+ expect(session.loopError).toBeNull();
+ });
+
+ it('SIGTERM during a pending relaunch exits without starting Chrome', async () => {
+ const session = start({
+ bindSignals: true,
+ checkCdp: async () => null,
+ mkdir: async () => { throw new Error('download directory unavailable'); },
+ });
+ await session.supervisor.ready;
+ const port = session.supervisor.healthServer.address().port;
+ expect(await advanceToSuperviseSleep(session.sleeper)).toBe(2000);
+ expect(await readHealth(port)).toMatchObject({
+ statusCode: 503,
+ body: { status: 'relaunching', lastError: 'download directory unavailable' },
+ });
+ expect(session.spawn).not.toHaveBeenCalled();
+
+ process.emit('SIGTERM');
+ await session.supervisor.shutdown();
+ await session.done;
+ expect(session.spawn).not.toHaveBeenCalled();
+ expect(session.loopError).toBeNull();
+ await expect(readHealth(port)).rejects.toThrow();
+ });
+});
diff --git a/docs/DEPS.md b/docs/DEPS.md
index 919e6d032c..28143a5a32 100644
--- a/docs/DEPS.md
+++ b/docs/DEPS.md
@@ -88,7 +88,7 @@ Before removing a Tier 3 candidate, run a transitive-dep check (`npm ls <pkg>`).
| **Autofixer deps** | | | | |
| `express` | 1 | KEEP | `autofixer/ui.js` | Same framework and pin (`5.2.1`) as the server workspace, but a separate install prefix with its own lockfile — so it needs its own `overrides` block to inherit the server's express-tree pins |
| **Browser workspace** | | | | |
-| _(none)_ | — | — | `browser/server.js` | Zero dependencies — Node built-ins only, plus one in-repo import from `server/lib/`. No Dependabot entry, and its lockfile is gitignored |
+| _(none)_ | — | — | `browser/server.js` | Zero dependencies — Node built-ins only, plus in-repo imports from `server/lib/` and `scripts/lib/`. No Dependabot entry, and its lockfile is gitignored |
## Detailed Findings — Tier 2/3 Audits
diff --git a/scripts/lib/workspaceTests.js b/scripts/lib/workspaceTests.js
index 7e588ee39a..d103028e65 100644
--- a/scripts/lib/workspaceTests.js
+++ b/scripts/lib/workspaceTests.js
@@ -27,8 +27,9 @@ import { DB_TEST_INCLUDE } from './dbTestFiles.js';
const SKIP_DIRS = new Set(['node_modules', '.git']);
/**
- * The server runner covers server, scripts/migrations, lib, autofixer and the
- * doc-parity guards. The client owns `client/src` (see each config for why).
+ * The server runner covers server, scripts/migrations, lib, autofixer, the
+ * doc-parity guards, and the browser supervisor beside `browser/server.js`.
+ * The client owns `client/src` (see each config for why).
*/
export const SERVER_TEST_INCLUDE = Object.freeze([
'**/*.test.js',
@@ -36,6 +37,7 @@ export const SERVER_TEST_INCLUDE = Object.freeze([
'../lib/**/*.test.js',
'../autofixer/**/*.test.js',
'../docs/**/*.test.js',
+ '../browser/**/*.test.js',
]);
/** The slashdo submodule ships node:test suites; DB suites run only under vitest.config.db.js. */
diff --git a/server/services/browserService.js b/server/services/browserService.js
index 6765ed75a2..5f7ffabc5e 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -107,14 +107,24 @@ export async function getHealthStatus({ strict = false } = {}) {
const response = await fetchWithTimeout(healthUrl, {}, HEALTH_TIMEOUT_MS).catch(() => null);
if (!response || !response.ok) {
+ // 503 while the supervisor is relaunching still carries the reason. The
+ // Browser page already renders `error` when Chrome is down.
+ const detail = response ? await readResponseJson(response) : null;
+ const relaunching = detail?.status === 'relaunching';
+ const lastError = typeof detail?.lastError === 'string' && detail.lastError ? detail.lastError : null;
return {
connected: false,
processRunning: false,
- cdpPort: config.cdpPort,
- cdpHost: config.cdpHost,
+ cdpPort: detail?.cdpPort || config.cdpPort,
+ cdpHost: detail?.cdpHost || config.cdpHost,
healthPort: config.healthPort,
- cdpEndpoint: `ws://${config.cdpHost}:${config.cdpPort}`,
- error: response ? `Health check returned ${response.status}` : 'Health check unreachable'
+ cdpEndpoint: detail?.cdpEndpoint || `ws://${config.cdpHost}:${config.cdpPort}`,
+ headless: detail?.headless ?? config.headless,
+ status: typeof detail?.status === 'string' ? detail.status : undefined,
+ ...(relaunching && Number.isInteger(detail.attempt) && detail.attempt > 0 ? { attempt: detail.attempt } : {}),
+ error: relaunching && lastError
+ ? lastError
+ : (response ? `Health check returned ${response.status}` : 'Health check unreachable')
};
}
diff --git a/server/services/browserService.test.js b/server/services/browserService.test.js
index 4844923ef4..d45134094b 100644
--- a/server/services/browserService.test.js
+++ b/server/services/browserService.test.js
@@ -834,4 +834,32 @@ describe('read-only browser observation', () => {
expect(pm2.execPm2).not.toHaveBeenCalled();
expect(probe.mock.calls.every(([url]) => /\/(health|json\/list|json\/version)$/.test(url))).toBe(true);
});
+
+ it('passes a relaunching health body through as the reason Chrome is down', async () => {
+ probe.mockImplementation(async (url) => new Response(JSON.stringify(
+ url.endsWith('/health')
+ ? {
+ status: 'relaunching',
+ attempt: 3,
+ lastError: 'download directory unavailable',
+ cdpPort: 5556,
+ cdpHost: '127.0.0.1',
+ headless: true,
+ }
+ : url.endsWith('/json/list') ? [] : { Browser: 'Example browser' }
+ ), {
+ status: url.endsWith('/health') ? 503 : 200,
+ headers: { 'Content-Type': 'application/json' },
+ }));
+ const service = await import('./browserService.js');
+ const status = await service.getFullStatus({ strict: true });
+ expect(status).toMatchObject({
+ connected: false,
+ status: 'relaunching',
+ attempt: 3,
+ error: 'download directory unavailable',
+ process: { status: 'online' },
+ pages: [],
+ });
+ });
});