Files
gstack/browse/src/xvfb.ts
T
01593aa67c v1.91.2.0 fix: consolidate gstack reliability wave (#2959)
* fix(memory-ingest): --scan-secrets scans the rendered page and fails closed

--scan-secrets ran gitleaks on the raw transcript .jsonl, then imported a
page rendered from it. gitleaks' assignment rules don't match across a
JSON-escaped quote (KEY=\"v\" on disk), so a secret the rendered page
shows as KEY="v" was imported unflagged. And the gate skipped a file only
on scanner "gitleaks" with findings, so a scan that errored (non-zero
exit, 16MB maxBuffer overflow on a file with many findings, unparseable
report) or could not run (gitleaks missing, slow-probe cooldown) imported
the file unscanned.

Scan the rendered page body, the exact bytes writeStaged() writes, via a
new secretScanText() helper, and skip the file whenever the scan did not
complete. Skipped files stay out of the state file, so the next run
retries them. Reword the helper warnings and setup-gbrain/memory.md,
which described the fail-open as intended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(test): reconcile Bun failure markers and footer counts

* fix(sync-gbrain): verify source-scoped reads without mutation

* fix(test): recognize grounded TTHW target choices structurally

* fix(aside): make the readiness probe work under zsh and report why it failed

The probe built its deadline into `_T` and expanded it unquoted, so
`$_T aside repl …` only worked in a shell that word-splits. zsh does not: it
looked for a command literally named "gtimeout 30", the probe answered
ASIDE_NOT_RUNNING with Aside installed and ready, and every browsing skill
fell back to the bundled Chromium in silence. zsh is the macOS default and
Aside is macOS-only, so on a stock Mac the probe could never report READY.

The deadline becomes a function, `_gs_d`. It receives the command as "$@",
already split, so sh, bash and zsh all behave the same, and the gtimeout →
timeout → perl alarm chain is unchanged. A 4th arm runs the call unbounded
when none of the three is present, which is what the empty `_T` did before.
Not `eval`: it re-parses the string, so the parens and `;` of the perl arm
become syntax and that arm dies in bash *and* zsh — on a stock Mac, the arm
that actually runs.

On failure the probe now prints the CLI's reason after ASIDE_NOT_RUNNING:,
the shape gstack-render already uses: the first line that starts with a
capital letter, i.e. the CLI's own sentence or Node's `Error:` line below its
loader frame. "Not running" covers states with different fixes — no window
open for the profile, a NODE_OPTIONS preload that kills the CLI — and a bare
verdict sent all of them to "open the Aside app". The BROWSER SETUP prose
quotes that reason before asking the user to open the app.

The text pin asserted the broken invocation verbatim, so it now pins the
function and asserts neither `$_T aside repl` nor an eval form comes back. A
second test executes the rendered probe in sh, bash and zsh on each of the
four deadline arms with stubbed binaries on a narrowed PATH, plus two failing
CLIs: one that prints its own sentence, one that crashes like Node with the
useful line below the frame.

The deadline function costs zero bytes against the lines it replaces; the
reason costs 53 per copy of the probe (44 where the reworded BROWSER SETUP
line gives 9 back). That moves four guards by the measured amount:
plan-devex-review's skeleton cap to 68,550 (measured 68,544), plan-ceo-review's
skeleton cap to 80,150 (measured 80,111) and union ratio to 1.081 (measured
1.0803), and plan-eng-review's union ratio to 1.151 (measured 1.1504).

Fixes #2842, #2941.

* Clarify engineering review startup and decision flow

* Fix Windows readiness fixture PATH and command shim

* fix(test): recognize grounded TTHW target choices structurally

* Clarify engineering review startup and decision flow

* fix(test): restrict QA-only fixture tools to its no-Edit contract

* v1.90.0.0 fix(sync-gbrain): guard readiness verdicts and refresh metadata

* fix(browse): validate canonical upload targets

* fix(gbrain): classify structured PGLite busy response

* fix(browse): preserve native extension runtime APIs

* Fix displayless browser handoff ownership

* Accept unique installed autoplan methodology aliases

* fix(skills): preserve positional literals during installation

* fix(browse): checksum installer contents through stdin

* fix(test): normalize Windows checksum fixture paths

* test: emulate unavailable shasum in Windows checksum fixture

* fix(investigate): preserve owned freeze lifecycle

* fix(review): preserve N+1 retry and Red Team completion

* fix: bound Aside readiness and preserve safe fallback

* test: exercise setup and Chromium on native ARM

* fix: preserve install ownership and ARM browser selection

* Fix gbrain ingest scan boundaries and seed observation

* Refresh managed ship hooks and supervise expanded paid census

* Reject resumed gbrain pages excluded by current policy

* Recover zombie agent locks safely and enable CI Python venv

* Repair paid actor declarations and Aside pitch assertions

* Bump consolidated wave to next free minor release

* Clarify CEO review admin choices and option tradeoffs

* Preserve CEO mode handoff anchors in clarified workflow

* Make Windows portability fixtures use shell-native paths

* Restore ARM Bun alias and clarify ship review gates

* Refresh ship workflow golden snapshots

* Fix Windows DX documentation controls without piped stdin

* Decode Codex child pipes without Bun's encoded-stream stall

* Bound DX pre-review audit before product questions

* Clarify trusted review-start read in paid revalidation

* Bump consolidated wave to next free minor release

* Clarify CEO review admin choices and option tradeoffs

* Preserve CEO mode handoff anchors in clarified workflow

* Make Windows portability fixtures use shell-native paths

* Restore ARM Bun alias and clarify ship review gates

* Refresh ship workflow golden snapshots

* Fix Windows DX documentation controls without piped stdin

* Decode Codex child pipes without Bun's encoded-stream stall

* Bound DX pre-review audit before product questions

* Clarify trusted review-start read in paid revalidation

* Reconcile new main planning flow and paid judge census

* fix: reconcile rebased planning and source-bound validation

* test: pin cookie workflow judge to scored Sonnet model

* fix: keep terminal agent boot out of module imports

* fix: preserve pending-question uncertainty in engineering review

* fix: stabilize Windows reliability-wave fixtures

* fix: clarify design consultation research workflow

* fix: preserve independent design consultation inputs

* fix: resolve design taste scope and browser research guidance

* fix: make consultation opt-in preflight unambiguous

* test: await native Edge owner readiness or terminal result

---------

Co-authored-by: Bruce Krysiak <brucek@alum.mit.edu>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Antonio Vitalic <antoninte99@gmail.com>
2026-09-26 18:57:53 -04:00

259 lines
9.9 KiB
TypeScript

/**
* Xvfb (X virtual framebuffer) auto-spawn for headed Chromium on Linux
* containers without DISPLAY.
*
* The motivating use case: a headless container needs to run Chromium in
* "headed" mode (visible window) — for example, to run with the
* AutomationControlled flag off and pass anti-bot fingerprint checks. Xvfb
* provides an off-screen X server that Chromium can render into.
*
* Design notes:
* - Pick a free display dynamically (try :99, :100, :101...). NEVER unlink
* /tmp/.X<n>-lock for displays we didn't create — that would steal an
* active X server from another process or user.
* - Validate orphan Xvfb processes by BOTH /proc/<pid>/cmdline matching
* 'Xvfb' AND start-time matching the recorded value. PID reuse is real;
* a one-field check would let us send SIGTERM to an unrelated process
* that happened to inherit a recycled PID.
* - Skip spawn entirely on macOS/Windows (native windowing) and on Linux
* when DISPLAY or WAYLAND_DISPLAY is already set (codex F2).
*/
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { safeKill, isProcessAlive } from './error-handling';
export interface XvfbHandle {
pid: number;
startTime: string;
display: string; // e.g. ":99"
/** Best-effort cleanup. Validates ownership before kill. */
close: () => void;
}
export interface ShouldSpawnDecision {
spawn: boolean;
reason: string;
}
const DISPLAY_RANGE_START = 99;
const DISPLAY_RANGE_END = 120;
/**
* Decide whether the daemon should auto-spawn an Xvfb. Pure: takes env +
* platform and returns a decision. Easy to unit test.
*/
export function shouldSpawnXvfb(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): ShouldSpawnDecision {
if (env.BROWSE_HEADED !== '1') return { spawn: false, reason: 'not headed mode' };
if (platform !== 'linux') return { spawn: false, reason: `platform ${platform} uses native windowing` };
if (env.DISPLAY) return { spawn: false, reason: `DISPLAY=${env.DISPLAY} already set` };
if (env.WAYLAND_DISPLAY) return { spawn: false, reason: `WAYLAND_DISPLAY=${env.WAYLAND_DISPLAY} set; Chromium uses Wayland natively` };
return { spawn: true, reason: 'linux headed without DISPLAY/WAYLAND_DISPLAY' };
}
/**
* Probe a display number — return true if no X server is currently listening
* on it (i.e., we can safely spawn a new Xvfb there).
*/
export function isDisplayFree(displayNum: number): boolean {
for (const reservation of [`/tmp/.X11-unix/X${displayNum}`, `/tmp/.X${displayNum}-lock`]) {
try { if (fs.lstatSync(reservation, { throwIfNoEntry: false })) return false; }
catch { return false; }
}
// xdpyinfo exits 0 if a display is reachable. Exit non-zero means no
// server, which is what we want. xdpyinfo ships in x11-utils, which some
// images with Xvfb still lack (first Linux CI run: ENOENT) — fall back to
// the X socket/lock files, the same signal X servers themselves use.
try {
const result = Bun.spawnSync(['xdpyinfo', '-display', `:${displayNum}`], {
windowsHide: true,
stdout: 'ignore', stderr: 'ignore', timeout: 2000,
});
return result.exitCode !== 0;
} catch {
return true;
}
}
/**
* Walk the display range and return the first free one, or null if all
* displays in the range are taken.
*/
export function pickFreeDisplay(
rangeStart: number = DISPLAY_RANGE_START,
rangeEnd: number = DISPLAY_RANGE_END,
): number | null {
for (let n = rangeStart; n <= rangeEnd; n++) {
if (isDisplayFree(n)) return n;
}
return null;
}
/**
* Read the wall-clock start time of a PID via `ps -o lstart=`. Stable across
* reads (unlike /proc/stat field 22 which reports jiffies since boot in a
* format that's harder to compare). Returns an empty string if the process
* is gone or ps fails.
*/
export function readPidStartTime(pid: number): string {
if (!isProcessAlive(pid)) return '';
try {
const result = Bun.spawnSync(['ps', '-p', String(pid), '-o', 'lstart='], {
windowsHide: true,
stdout: 'pipe', stderr: 'pipe', timeout: 2000,
});
if (result.exitCode !== 0) return '';
return result.stdout.toString().trim();
} catch {
// Bun.spawnSync THROWS when the executable is missing (Windows shells
// without an MSYS `ps`). This function's contract is "empty string if
// ps fails" — a missing ps must not abort the caller (browser-manager
// now calls this on the universal launch path, #2709).
return '';
}
}
/**
* Read the cmdline of a PID via /proc/<pid>/cmdline. Returns empty string
* if the process is gone or the cmdline isn't readable.
*/
export function readPidCmdline(pid: number): string {
try {
return fs.readFileSync(`/proc/${pid}/cmdline`, 'utf-8').replace(/\0/g, ' ').trim();
} catch {
// No /proc on darwin — the platform #2709's reap actually targets. Fall
// back to ps (same pattern as readPidStartTime above); without this the
// reap's cmdline identity gate always saw '' on macOS and the reap was
// a structural no-op exactly where the spinning-GPU orphan lives.
try {
const result = Bun.spawnSync(['ps', '-p', String(pid), '-o', 'command='], {
windowsHide: true,
stdout: 'pipe', stderr: 'pipe', timeout: 2000,
});
if (result.exitCode !== 0) return '';
return result.stdout.toString().trim();
} catch {
return '';
}
}
}
/**
* Read argv[0] of a PID via /proc/<pid>/cmdline (NUL-separated). Returns
* empty string if the process is gone or the cmdline isn't readable.
*/
export function readPidArgv0(pid: number): string {
try {
const raw = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf-8');
return raw.split('\0', 1)[0] ?? '';
} catch {
return '';
}
}
/**
* Validate that PID is still our Xvfb child. Both checks must pass:
* 1. argv[0]'s basename IS the Xvfb binary. A substring match over the
* whole cmdline is identity-kill poison: any process whose ARGUMENTS
* mention xvfb (the test runner executing xvfb.test.ts, an editor with
* the file open) would pass and become killable. First Linux CI run
* caught exactly that — the suite identified itself as our Xvfb.
* 2. Start time matches the recorded value (PID reuse defense)
*/
export function isOurXvfb(pid: number, recordedStartTime: string): boolean {
if (!pid || !recordedStartTime) return false;
const argv0 = readPidArgv0(pid);
if (!argv0) return false;
const base = argv0.split('/').pop() ?? '';
if (base.toLowerCase() !== 'xvfb') return false;
const currentStart = readPidStartTime(pid);
if (!currentStart) return false;
return currentStart === recordedStartTime;
}
/**
* Spawn Xvfb on the given display. Returns a handle including the validated
* start-time so future cleanup can confirm ownership.
*
* Throws if Xvfb isn't installed (caller should print a platform-specific
* install hint).
*/
export async function spawnXvfb(displayNum: number): Promise<XvfbHandle> {
const display = `:${displayNum}`;
if (!isDisplayFree(displayNum)) throw new Error(`X display ${display} is already reserved; refusing to replace it`);
if (!readPidStartTime(process.pid)) throw new Error('Cannot start Xvfb without process start-time ownership checks');
// Spawn detached: Xvfb's lifetime is tied to whether we've explicitly
// killed it via the handle's close() method, not to the parent process.
const proc = Bun.spawn(['Xvfb', display, '-screen', '0', '1920x1080x24', '-ac'], {
windowsHide: true,
stdio: ['ignore', 'ignore', 'ignore'],
});
proc.unref();
const startTime = readPidStartTime(proc.pid);
// Wait for the X server to become reachable — Xvfb takes a few hundred ms
// to bind. Probe via xdpyinfo with retries.
const deadline = Date.now() + 3000;
let ready = false;
while (Date.now() < deadline) {
await Bun.sleep(100);
// If Xvfb crashed during startup, fail fast.
if (proc.exitCode != null) {
throw new Error(`Xvfb on ${display} exited during startup (code ${proc.exitCode}). Hint: install xvfb (apt-get install xvfb / yum install xorg-x11-server-Xvfb).`);
}
let ownsLock = false;
try { ownsLock = Number(fs.readFileSync(`/tmp/.X${displayNum}-lock`, 'utf8').trim()) === proc.pid; } catch {}
if (!ownsLock || !isOurXvfb(proc.pid, startTime)) continue;
try {
ready = Bun.spawnSync(['xdpyinfo', '-display', display], {
windowsHide: true, stdout: 'ignore', stderr: 'ignore', timeout: 2000,
}).exitCode === 0;
} catch {
ready = fs.existsSync(`/tmp/.X11-unix/X${displayNum}`);
}
if (ready) break;
}
if (!ready) {
cleanupXvfb({ pid: proc.pid, startTime, display });
throw new Error(`Xvfb on ${display} never became reachable within 3s timeout`);
}
return {
pid: proc.pid,
startTime,
display,
close: () => cleanupXvfb({ pid: proc.pid, startTime, display }),
};
}
/**
* Cleanup an Xvfb child if it's still ours. Validates ownership first; if
* the PID has been recycled or the cmdline doesn't match, leave it alone.
*
* Best-effort: never throws.
*/
export function cleanupXvfb(state: { pid: number; startTime: string; display: string }): void {
if (!state.pid) return;
if (!isOurXvfb(state.pid, state.startTime)) return;
try { safeKill(state.pid, 'SIGTERM'); } catch { /* swallow */ }
// Wait briefly for Xvfb to exit, then SIGKILL if still alive.
const deadline = Date.now() + 1000;
while (Date.now() < deadline) {
if (!isProcessAlive(state.pid)) break;
Bun.sleepSync(10);
}
if (isOurXvfb(state.pid, state.startTime)) {
try { safeKill(state.pid, 'SIGKILL'); } catch { /* swallow */ }
}
}
/**
* Print a platform-specific install hint and return the message string.
* Used by server.ts when Xvfb isn't installed.
*/
export function xvfbInstallHint(): string {
return 'Xvfb not installed. apt-get install xvfb (Debian/Ubuntu) or yum install xorg-x11-server-Xvfb (RHEL/CentOS). Note: minimal containers (alpine, distroless) may also need fonts, dbus, gtk libs for headed Chromium to render.';
}