Files
gstack/browse/test/watchdog.test.ts
T
Shawn Reddy f3ea49ff6e fix(browse): cancel the parent watchdog when handoff promotes a daemon to headed
The parent-process watchdog assumes connection mode is fixed at boot: headless
daemons outlive their parent, headed ones do not. The env guards
(BROWSE_PARENT_PID=0, BROWSE_HEADED=1) only cover daemons that were headed when
they started.

handoff breaks that assumption. It swaps in a headed context on a RUNNING daemon
and sets connectionMode = 'headed' without a restart, so a daemon that
legitimately registered a watchdog lands on the fatal side of the branch. The
parent is usually a short-lived shell, and Claude Code's Bash tool kills one after
every invocation, so the next 15s poll shuts the daemon down.

The user-visible effect is that handoff destroys the thing it just created. It
exists so a human can log in, solve a CAPTCHA, or clear an MFA prompt; the browser
disappears about fifteen seconds later and takes the session with it. Observed
while driving two registrar control panels: five daemon deaths and three logins,
each one discarding the authenticated session.

BrowserManager now exposes onHeadedPromotion, fired only on runtime promotion and
not on a headed boot, and the server binds it to a canceller for the interval it
already owned but previously discarded. Bound on both the module-level manager and
any embedder-supplied one, since the watchdog reads activeBrowserManager and
binding only the default would let embedders promote silently.

The binding sits next to the browserManager declaration rather than next to
clearParentWatchdog. Placing it with the function, which lives with the watchdog it
cancels, reads better but touches browserManager in its temporal dead zone, which
aborts module evaluation and leaves every later const uninitialized. findport
tests catch that immediately.

Tests: watchdog.test.ts already noted in its header that its three cases all fix
mode via env at spawn time, so none reaches the headed branch. Driving a real
handoff needs a headed Chromium, so the wiring is pinned with static tripwires
instead, matching cdp-session-cleanup.test.ts and server-auth.test.ts. Verified
they fail when the notification call is removed and pass when restored.

Full `bun test` shows the same 6 pre-existing failures on this branch and on main
(gstack-gbrain-detect, gstack-artifacts-init), which pass in isolation on both, so
they are test-order pollution rather than a regression here.
2026-08-14 12:44:16 -07:00

198 lines
8.6 KiB
TypeScript

import { describe, test, expect, afterEach } from 'bun:test';
import { spawn, type Subprocess } from 'bun';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
// End-to-end regression tests for the parent-process watchdog in server.ts.
// The watchdog has layered behavior since v0.18.1.0 (#1025) and v0.18.2.0
// (community wave #994 + our mode-gating follow-up):
//
// 1. BROWSE_PARENT_PID=0 disables the watchdog entirely (opt-in for CI + pair-agent).
// 2. BROWSE_HEADED=1 disables the watchdog entirely (server-side defense for headed
// mode, where the user controls window lifecycle).
// 3. Default headless mode + parent dies: server STAYS ALIVE. The original
// "kill on parent death" was inverted by #994 because Claude Code's Bash
// sandbox kills the parent shell between every tool invocation, and #994
// makes browse persist across $B calls. Idle timeout (30 min) handles
// eventual cleanup.
//
// Tunnel mode coverage (parent dies → shutdown because idle timeout doesn't
// apply) is not covered by an automated test here — tunnelActive is a runtime
// variable set by /pair-agent's tunnel-create flow, not an env var, so faking
// it would require invasive test-only hooks. The mode check is documented
// inline at the watchdog and SIGTERM handlers, and would regress visibly for
// /pair-agent users (server lingers after disconnect).
//
// Each test spawns the real server.ts. Tests 1 and 2 verify behavior via
// stdout log line (fast). Test 3 waits for the watchdog poll cycle to confirm
// the server REMAINS alive after parent death (slow — ~20s observation window).
const ROOT = path.resolve(import.meta.dir, '..');
const SERVER_SCRIPT = path.join(ROOT, 'src', 'server.ts');
let tmpDir: string;
let serverProc: Subprocess | null = null;
let parentProc: Subprocess | null = null;
afterEach(async () => {
// Kill any survivors so subsequent tests get a clean slate.
try { parentProc?.kill('SIGKILL'); } catch {}
try { serverProc?.kill('SIGKILL'); } catch {}
// Give processes a moment to exit before tmpDir cleanup.
await Bun.sleep(100);
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch {}
parentProc = null;
serverProc = null;
});
function spawnServer(env: Record<string, string>, port: number): Subprocess {
const stateFile = path.join(tmpDir, 'browse-state.json');
return spawn(['bun', 'run', SERVER_SCRIPT], {
env: {
...process.env,
BROWSE_STATE_FILE: stateFile,
BROWSE_PORT: String(port),
...env,
},
stdio: ['ignore', 'pipe', 'pipe'],
});
}
function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0); // signal 0 = existence check, no signal sent
return true;
} catch {
return false;
}
}
// Read stdout until we see the expected marker or timeout. Returns the captured
// text. Used to verify the watchdog code path ran as expected at startup.
async function readStdoutUntil(
proc: Subprocess,
marker: string,
timeoutMs: number,
): Promise<string> {
const deadline = Date.now() + timeoutMs;
const decoder = new TextDecoder();
let captured = '';
const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader();
try {
while (Date.now() < deadline) {
const readPromise = reader.read();
const timed = Bun.sleep(Math.max(0, deadline - Date.now()));
const result = await Promise.race([readPromise, timed.then(() => null)]);
if (!result || result.done) break;
captured += decoder.decode(result.value);
if (captured.includes(marker)) return captured;
}
} finally {
try { reader.releaseLock(); } catch {}
}
return captured;
}
describe('parent-process watchdog (v0.18.1.0)', () => {
test('BROWSE_PARENT_PID=0 disables the watchdog', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'watchdog-pid0-'));
serverProc = spawnServer({ BROWSE_PARENT_PID: '0' }, 34901);
const out = await readStdoutUntil(
serverProc,
'Parent-process watchdog disabled (BROWSE_PARENT_PID=0)',
5000,
);
expect(out).toContain('Parent-process watchdog disabled (BROWSE_PARENT_PID=0)');
// Control: the "parent exited, shutting down" line must NOT appear —
// that would mean the watchdog ran after we said to skip it.
expect(out).not.toContain('Parent process');
}, 15_000);
test('BROWSE_HEADED=1 disables the watchdog (server-side guard)', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'watchdog-headed-'));
// Pass a bogus parent PID to prove BROWSE_HEADED takes precedence.
// If the server-side guard regresses, the watchdog would try to poll
// this PID and eventually fire on the "dead parent."
serverProc = spawnServer(
{ BROWSE_HEADED: '1', BROWSE_PARENT_PID: '999999' },
34902,
);
const out = await readStdoutUntil(
serverProc,
'Parent-process watchdog disabled (headed mode)',
5000,
);
expect(out).toContain('Parent-process watchdog disabled (headed mode)');
expect(out).not.toContain('Parent process 999999 exited');
}, 15_000);
test('default headless mode: server STAYS ALIVE when parent dies (#994)', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'watchdog-default-'));
// Spawn a real, short-lived "parent" that the watchdog will poll.
parentProc = spawn(['sleep', '60'], { stdio: ['ignore', 'ignore', 'ignore'] });
const parentPid = parentProc.pid!;
// Default headless: no BROWSE_HEADED, real parent PID — watchdog active.
serverProc = spawnServer({ BROWSE_PARENT_PID: String(parentPid) }, 34903);
const serverPid = serverProc.pid!;
// Give the server a moment to start and register the watchdog interval.
await Bun.sleep(2000);
expect(isProcessAlive(serverPid)).toBe(true);
// Kill the parent. The watchdog polls every 15s, so first tick after
// parent death lands within ~15s. Pre-#994 the server would shutdown
// here. Post-#994 the server logs the parent exit and stays alive.
parentProc.kill('SIGKILL');
// Wait long enough for at least one watchdog tick (15s) plus margin.
// Server should still be alive — that's the whole point of #994.
await Bun.sleep(20_000);
expect(isProcessAlive(serverPid)).toBe(true);
}, 45_000);
});
// The three tests above all fix the mode via env at SPAWN time, so none of them
// reaches the headed branch of the watchdog. That branch is only reachable by a
// RUNTIME promotion, which `handoff` performs: it swaps in a headed context on a
// running daemon without a restart, moving a daemon that legitimately registered
// a watchdog onto the fatal side of the check. The parent is usually a
// short-lived shell (Claude Code's Bash tool kills one after every invocation),
// so the next poll shut the daemon down and discarded whatever the user had been
// handed off to do — observed as repeated session loss mid-login.
//
// Driving a real `handoff` needs a headed Chromium, which does not belong in the
// free tier, so this pins the WIRING instead — the same static-tripwire approach
// used by cdp-session-cleanup.test.ts and server-auth.test.ts. If either half of
// the contract is dropped, the crash returns silently and these fail.
describe('watchdog is cancelled on runtime promotion to headed', () => {
const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), 'utf-8');
test('handoff() notifies the server that it promoted the daemon', () => {
const src = read('src/browser-manager.ts');
const promote = src.indexOf("this.connectionMode = 'headed';", src.indexOf('async handoff('));
expect(promote).toBeGreaterThan(-1);
// The notification must follow the promotion closely; a call left far away
// (or removed) is the regression this guards.
expect(src.slice(promote, promote + 800)).toContain('this.onHeadedPromotion?.()');
});
test('the server binds that callback to the watchdog canceller', () => {
const src = read('src/server.ts');
// The timer must be reachable — `setInterval(` with its return value dropped
// cannot be cleared, which was the original defect.
expect(src).toContain('parentWatchdogTimer = setInterval(');
expect(src).toContain('function clearParentWatchdog()');
expect(src).toContain('clearInterval(parentWatchdogTimer)');
// Bound on BOTH the module-level manager and any embedder-supplied one; the
// watchdog reads activeBrowserManager, so binding only the default instance
// leaves embedders (e.g. gbrowser) promoting silently.
expect(src).toContain('browserManager.onHeadedPromotion = clearParentWatchdog');
expect(src).toContain('cfgBrowserManager.onHeadedPromotion = clearParentWatchdog');
});
});