mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 01:46:55 +02:00
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>
This commit is contained in:
204 files changed
+9958
-1705
No files matched your search
+118
-34
@@ -23,7 +23,7 @@ import { validateNavigationUrl } from './url-validation';
|
||||
import { TabSession, type RefEntry } from './tab-session';
|
||||
import { resolveChromiumProfile, cleanSingletonLocks } from './config';
|
||||
import { launchWithXProtectHeal } from './xprotect-heal';
|
||||
import { readPidStartTime } from './xvfb';
|
||||
import { readPidStartTime, shouldSpawnXvfb, pickFreeDisplay, spawnXvfb, xvfbInstallHint, type XvfbHandle } from './xvfb';
|
||||
import { withCdpSession } from './cdp-bridge';
|
||||
import type { MemorySnapshot, MemoryStructureStats, MemoryTabSnapshot, MemoryProcess } from './memory-snapshot';
|
||||
|
||||
@@ -341,6 +341,41 @@ export class BrowserManager {
|
||||
*/
|
||||
onHeadedPromotion?: () => void;
|
||||
private intentionalDisconnect = false;
|
||||
private xvfb: XvfbHandle | null = null;
|
||||
private displayAllocation: Promise<void> | null = null;
|
||||
private handoffPending: Promise<string> | null = null;
|
||||
private closing = false;
|
||||
private handoffPrevious: { browser: Browser; pages: Map<number, Page>; tabSessions: Map<number, TabSession>; activeTabId: number } | null = null;
|
||||
|
||||
getXvfbHandle(): XvfbHandle | null { return this.xvfb; }
|
||||
|
||||
async ensureHeadedDisplay(): Promise<void> {
|
||||
if (this.closing) throw new Error('Browser is shutting down');
|
||||
if (this.xvfb) return;
|
||||
if (this.displayAllocation) return this.displayAllocation;
|
||||
if (!shouldSpawnXvfb({ ...process.env, BROWSE_HEADED: '1' }, process.platform).spawn) return;
|
||||
this.displayAllocation = (async () => {
|
||||
const displayNum = pickFreeDisplay();
|
||||
if (displayNum == null) throw new Error('no free X display in range :99-:120 — refusing to clobber existing X servers');
|
||||
try {
|
||||
const handle = await spawnXvfb(displayNum);
|
||||
if (this.closing) {
|
||||
handle.close();
|
||||
throw new Error('Browser is shutting down');
|
||||
}
|
||||
this.xvfb = handle;
|
||||
} catch (err) {
|
||||
throw new Error(`${err instanceof Error ? err.message : String(err)}. ${xvfbInstallHint()}`);
|
||||
}
|
||||
})();
|
||||
try { await this.displayAllocation; }
|
||||
finally { this.displayAllocation = null; }
|
||||
}
|
||||
|
||||
closeOwnedDisplay(): void {
|
||||
this.xvfb?.close();
|
||||
this.xvfb = null;
|
||||
}
|
||||
|
||||
// ─── Tab Count Guardrail (D5 + Codex single-tab flag) ───────
|
||||
// Idempotent threshold trackers: each guardrail fires exactly once per
|
||||
@@ -483,6 +518,7 @@ export class BrowserManager {
|
||||
}
|
||||
|
||||
async launch() {
|
||||
this.closing = false;
|
||||
// ─── Extension Support ────────────────────────────────────
|
||||
// BROWSE_EXTENSIONS_DIR points to an unpacked Chrome extension directory.
|
||||
// Extensions only work in headed mode, so we use an off-screen window.
|
||||
@@ -605,6 +641,8 @@ export class BrowserManager {
|
||||
* every action Claude takes in real time.
|
||||
*/
|
||||
async launchHeaded(authToken?: string): Promise<void> {
|
||||
this.closing = false;
|
||||
await this.ensureHeadedDisplay();
|
||||
// Clear old state before repopulating
|
||||
this.pages.clear();
|
||||
this.tabSessions.clear();
|
||||
@@ -743,6 +781,7 @@ export class BrowserManager {
|
||||
// reinstalled over (probePoisonedChromiumBundle's scope contract).
|
||||
this.context = await launchWithXProtectHeal(() => chromium.launchPersistentContext(userDataDir, {
|
||||
headless: false,
|
||||
...(this.xvfb ? { env: { ...process.env, DISPLAY: this.xvfb.display } } : {}),
|
||||
// #2220: daemon owns signal policy — see launch() for the rationale.
|
||||
handleSIGINT: false,
|
||||
handleSIGTERM: false,
|
||||
@@ -898,14 +937,17 @@ export class BrowserManager {
|
||||
private closeRaceMs = 5000;
|
||||
|
||||
async close() {
|
||||
this.closing = true;
|
||||
const previousBrowser = this.handoffPrevious?.browser;
|
||||
const currentBrowser = this.browser;
|
||||
// unref'd race timer: without unref, every successful close still pins
|
||||
// the caller's event loop for the full window.
|
||||
const raceTimeout = (ms: number) => new Promise<false>((resolve) => {
|
||||
const t = setTimeout(() => resolve(false), ms);
|
||||
(t as { unref?: () => void }).unref?.();
|
||||
});
|
||||
if (this.browser || (this.connectionMode === 'headed' && this.context)) {
|
||||
if (this.connectionMode === 'headed') {
|
||||
if (this.browser || ((this.connectionMode === 'headed' || this.handoffPrevious) && this.context)) {
|
||||
if (this.connectionMode === 'headed' || this.handoffPrevious) {
|
||||
// Headed/persistent context mode: close the context (which closes the browser)
|
||||
this.intentionalDisconnect = true;
|
||||
if (this.browser) this.browser.removeAllListeners('disconnected');
|
||||
@@ -932,6 +974,18 @@ export class BrowserManager {
|
||||
}
|
||||
this.browser = null;
|
||||
}
|
||||
if (previousBrowser && previousBrowser !== currentBrowser) {
|
||||
previousBrowser.removeAllListeners('disconnected');
|
||||
const child = previousBrowser.process?.();
|
||||
const closed = await Promise.race([
|
||||
previousBrowser.close().then(() => true), raceTimeout(this.closeRaceMs),
|
||||
]).catch(() => false);
|
||||
if (!closed && child && child.exitCode === null && !child.killed) {
|
||||
try { child.kill('SIGKILL'); } catch {}
|
||||
}
|
||||
}
|
||||
await this.displayAllocation?.catch(() => {});
|
||||
this.closeOwnedDisplay();
|
||||
}
|
||||
|
||||
/** Health check — verifies Chromium is connected AND responsive */
|
||||
@@ -1756,6 +1810,14 @@ export class BrowserManager {
|
||||
* If step 2 fails → return error, headless browser untouched
|
||||
*/
|
||||
async handoff(message: string): Promise<string> {
|
||||
if (this.handoffPending) return this.handoffPending;
|
||||
this.handoffPending = this.promoteToHeaded(message);
|
||||
try { return await this.handoffPending; }
|
||||
finally { this.handoffPending = null; }
|
||||
}
|
||||
|
||||
private async promoteToHeaded(message: string): Promise<string> {
|
||||
if (this.closing) return 'ERROR: Browser is shutting down';
|
||||
if (this.connectionMode === 'headed' || this.isHeaded) {
|
||||
return `HANDOFF: Already in headed mode at ${this.getCurrentUrl()}`;
|
||||
}
|
||||
@@ -1765,12 +1827,15 @@ export class BrowserManager {
|
||||
|
||||
// 1. Save state from current browser
|
||||
const state = await this.saveState();
|
||||
if (this.closing) return 'ERROR: Browser is shutting down';
|
||||
const currentUrl = this.getCurrentUrl();
|
||||
const previousDisplay = this.xvfb;
|
||||
|
||||
// 2. Launch new headed browser with extension (same as launchHeaded)
|
||||
// Uses launchPersistentContext so the extension auto-loads.
|
||||
let newContext: BrowserContext;
|
||||
try {
|
||||
await this.ensureHeadedDisplay();
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const extensionPath = this.findExtensionPath();
|
||||
@@ -1820,6 +1885,7 @@ export class BrowserManager {
|
||||
// exactly as in launch()/launchHeaded().
|
||||
newContext = await launchWithXProtectHeal(() => chromium.launchPersistentContext(userDataDir, {
|
||||
headless: false,
|
||||
...(this.xvfb ? { env: { ...process.env, DISPLAY: this.xvfb.display } } : {}),
|
||||
// #2220: daemon owns signal policy — see launch() for the rationale.
|
||||
handleSIGINT: false,
|
||||
handleSIGTERM: false,
|
||||
@@ -1834,29 +1900,33 @@ export class BrowserManager {
|
||||
ignoreDefaultArgs: STEALTH_IGNORE_DEFAULT_ARGS,
|
||||
timeout: 15000,
|
||||
}));
|
||||
if (this.closing) {
|
||||
await newContext.close().catch(() => {});
|
||||
throw new Error('Browser is shutting down');
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (!previousDisplay) this.closeOwnedDisplay();
|
||||
if (this.closing) return 'ERROR: Browser is shutting down';
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return `ERROR: Cannot open headed browser — ${msg}. Headless browser still running.`;
|
||||
}
|
||||
|
||||
// 3. Restore state into new headed browser
|
||||
const previous = {
|
||||
browser: this.browser, context: this.context,
|
||||
pages: this.pages, tabSessions: this.tabSessions, tabOwnership: this.tabOwnership,
|
||||
activeTabId: this.activeTabId, nextTabId: this.nextTabId,
|
||||
connectionMode: this.connectionMode, isHeaded: this.isHeaded,
|
||||
dialogAutoAccept: this.dialogAutoAccept, intentionalDisconnect: this.intentionalDisconnect,
|
||||
chromiumProcInfo: this.chromiumProcInfo,
|
||||
tabGuardrailSoftHit: this.tabGuardrailSoftHit, tabGuardrailHardHit: this.tabGuardrailHardHit,
|
||||
};
|
||||
this.handoffPrevious = previous;
|
||||
try {
|
||||
// Swap to new browser/context before restoreState (it uses this.context)
|
||||
const oldBrowser = this.browser;
|
||||
|
||||
this.context = newContext;
|
||||
this.browser = newContext.browser();
|
||||
this.pages.clear();
|
||||
this.tabSessions.clear();
|
||||
this.connectionMode = 'headed';
|
||||
|
||||
// Promotion, not a headed boot. The server registered a parent-process
|
||||
// watchdog because this daemon started headless, and that watchdog kills
|
||||
// headed daemons when their parent exits — which for a CLI-spawned daemon
|
||||
// is immediately. Without this the handed-off browser dies ~15s later,
|
||||
// taking whatever the user was mid-way through (a login, an MFA prompt)
|
||||
// with it.
|
||||
this.onHeadedPromotion?.();
|
||||
this.pages = new Map();
|
||||
this.tabSessions = new Map();
|
||||
this.tabOwnership = new Map();
|
||||
|
||||
// Same Layer C stealth as launch()/launchHeaded(). Must run BEFORE
|
||||
// restoreState() navigates so the init scripts apply to the restored
|
||||
@@ -1869,9 +1939,9 @@ export class BrowserManager {
|
||||
await newContext.setExtraHTTPHeaders(this.extraHeaders);
|
||||
}
|
||||
|
||||
// Register disconnect handler on new browser. Same clean-vs-crash
|
||||
// discrimination as launch() / launchHeaded() above so a user-initiated
|
||||
// Cmd+Q after a handoff doesn't trigger gbd's restart loop.
|
||||
await this.restoreState(state);
|
||||
if (this.closing) throw new Error('Browser is shutting down');
|
||||
|
||||
if (this.browser) {
|
||||
const browserRef = this.browser;
|
||||
this.browser.on('disconnected', () => {
|
||||
@@ -1880,24 +1950,35 @@ export class BrowserManager {
|
||||
});
|
||||
}
|
||||
|
||||
await this.restoreState(state);
|
||||
this.connectionMode = 'headed';
|
||||
this.isHeaded = true;
|
||||
this.dialogAutoAccept = false; // User controls dialogs in headed mode
|
||||
this.chromiumProcInfo = null;
|
||||
try { this.onHeadedPromotion?.(); }
|
||||
catch (err) { console.warn('[browse] Headed promotion callback failed:', err); }
|
||||
|
||||
// 4. Close old headless browser (fire-and-forget)
|
||||
oldBrowser.removeAllListeners('disconnected');
|
||||
oldBrowser.close().catch(() => {});
|
||||
previous.browser.removeAllListeners('disconnected');
|
||||
previous.browser.close().catch(() => {});
|
||||
|
||||
return [
|
||||
`HANDOFF: Browser opened at ${currentUrl}`,
|
||||
...(this.xvfb ? ['DISPLAY: Off-screen Xvfb; a separate remote desktop is required for human interaction.'] : []),
|
||||
`MESSAGE: ${message}`,
|
||||
`STATUS: Waiting for user. Run 'resume' when done.`,
|
||||
].join('\n');
|
||||
} catch (err: unknown) {
|
||||
// Restore failed — close the new context, keep old state
|
||||
await newContext.close().catch(() => {});
|
||||
if (!this.closing) {
|
||||
Object.assign(this, previous);
|
||||
this.recheckTabGuardrailsOnClose();
|
||||
}
|
||||
if (!previousDisplay) this.closeOwnedDisplay();
|
||||
if (this.closing) return 'ERROR: Browser is shutting down';
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return `ERROR: Handoff failed during state restore — ${msg}. Headless browser still running.`;
|
||||
} finally {
|
||||
this.handoffPrevious = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1938,22 +2019,25 @@ export class BrowserManager {
|
||||
|
||||
// ─── Console/Network/Dialog/Ref Wiring ────────────────────
|
||||
private wirePageEvents(page: Page) {
|
||||
const pages = this.pages;
|
||||
const tabSessions = this.tabSessions;
|
||||
// Track tab close — remove from pages and sessions maps, switch to another tab
|
||||
page.on('close', () => {
|
||||
for (const [id, p] of this.pages) {
|
||||
for (const [id, p] of pages) {
|
||||
if (p === page) {
|
||||
this.pages.delete(id);
|
||||
this.tabSessions.delete(id);
|
||||
console.log(`[browse] Tab closed (id=${id}, remaining=${this.pages.size})`);
|
||||
pages.delete(id);
|
||||
tabSessions.delete(id);
|
||||
console.log(`[browse] Tab closed (id=${id}, remaining=${pages.size})`);
|
||||
// If the closed tab was active, switch to another
|
||||
if (this.activeTabId === id) {
|
||||
const remaining = [...this.pages.keys()];
|
||||
this.activeTabId = remaining.length > 0 ? remaining[remaining.length - 1] : 0;
|
||||
const state = pages === this.pages ? this : this.handoffPrevious?.pages === pages ? this.handoffPrevious : null;
|
||||
if (state?.activeTabId === id) {
|
||||
const remaining = [...pages.keys()];
|
||||
state.activeTabId = remaining.length > 0 ? remaining[remaining.length - 1] : 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.recheckTabGuardrailsOnClose();
|
||||
if (pages === this.pages) this.recheckTabGuardrailsOnClose();
|
||||
});
|
||||
|
||||
// Clear ref map on navigation — refs point to stale elements after page change
|
||||
@@ -1961,7 +2045,7 @@ export class BrowserManager {
|
||||
page.on('framenavigated', (frame) => {
|
||||
if (frame === page.mainFrame()) {
|
||||
// Find the TabSession for this page and clear its per-tab state
|
||||
for (const session of this.tabSessions.values()) {
|
||||
for (const session of tabSessions.values()) {
|
||||
if (session.page === page) {
|
||||
session.onMainFrameNavigated();
|
||||
break;
|
||||
|
||||
+46
-49
@@ -58,7 +58,7 @@ import { startSocksBridge, testUpstream, type BridgeHandle } from './socks-bridg
|
||||
import { parseProxyConfig, toUpstreamConfig, ProxyConfigError } from './proxy-config';
|
||||
import { writeReceipt } from '../../lib/egress-receipt';
|
||||
import { redactProxyUrl } from './proxy-redact';
|
||||
import { shouldSpawnXvfb, pickFreeDisplay, spawnXvfb, xvfbInstallHint, type XvfbHandle } from './xvfb';
|
||||
import { type XvfbHandle } from './xvfb';
|
||||
import { logTunnelDenial } from './tunnel-denial-log';
|
||||
import {
|
||||
mintSseSessionToken, validateSseSessionToken, extractSseCookie,
|
||||
@@ -662,8 +662,8 @@ const DIALOG_LOG_PATH = config.dialogLog;
|
||||
* for the final state.json content; the only behavior change is that
|
||||
* concurrent writers no longer kill each other on the rename.
|
||||
*/
|
||||
function tmpStatePath(): string {
|
||||
return `${config.stateFile}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
|
||||
function tmpStatePath(stateFile: string = config.stateFile): string {
|
||||
return `${stateFile}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -868,9 +868,29 @@ if (BROWSE_PARENT_PID > 0 && !IS_HEADED_WATCHDOG) {
|
||||
* death no longer kills the daemon for BEING HEADED, but still kills it when
|
||||
* a tunnel is active.
|
||||
*/
|
||||
function suppressHeadedParentShutdown(): void {
|
||||
function suppressHeadedParentShutdown(stateConfig: ServerConfig['config'] = config, manager: BrowserManager = activeBrowserManager): void {
|
||||
if (headedParentShutdownSuppressed) return;
|
||||
headedParentShutdownSuppressed = true;
|
||||
try {
|
||||
const release = acquireAgentStateLock(stateConfig.stateDir);
|
||||
try {
|
||||
const state = JSON.parse(fs.readFileSync(stateConfig.stateFile, 'utf8'));
|
||||
if (state.pid === process.pid && state.instanceId === SERVER_INSTANCE_ID) {
|
||||
const xvfb = manager.getXvfbHandle();
|
||||
state.mode = 'headed';
|
||||
delete state.chromiumPid;
|
||||
delete state.chromiumStartTime;
|
||||
if (xvfb) Object.assign(state, { xvfbPid: xvfb.pid, xvfbStartTime: xvfb.startTime, xvfbDisplay: xvfb.display });
|
||||
const tmpFile = tmpStatePath(stateConfig.stateFile);
|
||||
try {
|
||||
fs.writeFileSync(tmpFile, JSON.stringify(state, null, 2), { mode: 0o600 });
|
||||
fs.renameSync(tmpFile, stateConfig.stateFile);
|
||||
} finally { safeUnlinkQuiet(tmpFile); }
|
||||
}
|
||||
} finally { release(); }
|
||||
} catch (err) {
|
||||
console.warn('[browse] Could not persist headed promotion:', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
console.log('[browse] Parent-death headed shutdown suppressed (promoted to headed at runtime); watchdog stays armed as the tunnel-orphan reaper');
|
||||
}
|
||||
|
||||
@@ -1798,7 +1818,7 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
||||
// suppress the headed parent-death branch. An embedder-supplied manager
|
||||
// otherwise promotes silently and the watchdog keeps shutting down on a
|
||||
// promotion it can no longer see.
|
||||
cfgBrowserManager.onHeadedPromotion = suppressHeadedParentShutdown;
|
||||
cfgBrowserManager.onHeadedPromotion = () => suppressHeadedParentShutdown(cfg.config, cfgBrowserManager);
|
||||
|
||||
// Wire the cfg-instance's onDisconnect to run shutdown when the user
|
||||
// closes the headed browser window. CHAIN any caller-provided handler
|
||||
@@ -3167,32 +3187,7 @@ export async function start() {
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Xvfb auto-spawn (Linux + headed + no DISPLAY) ─────────────
|
||||
// codex F2: walk display range to pick a free one (never hardcode :99);
|
||||
// record start-time alongside PID so cleanup can validate ownership and
|
||||
// not kill a recycled PID.
|
||||
let xvfb: XvfbHandle | null = null;
|
||||
const xvfbDecision = shouldSpawnXvfb(process.env, process.platform);
|
||||
if (xvfbDecision.spawn) {
|
||||
const displayNum = pickFreeDisplay();
|
||||
if (displayNum == null) {
|
||||
console.error('[browse] no free X display in range :99-:120 — refusing to clobber existing X servers');
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
xvfb = await spawnXvfb(displayNum);
|
||||
process.env.DISPLAY = xvfb.display;
|
||||
console.log(`[browse] [xvfb] spawned on ${xvfb.display} (pid ${xvfb.pid})`);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`[browse] [xvfb] FAILED: ${msg}`);
|
||||
console.error(`[browse] [xvfb] hint: ${xvfbInstallHint()}`);
|
||||
process.exit(1);
|
||||
}
|
||||
process.on('exit', () => { try { xvfb?.close(); } catch { /* shutting down */ } });
|
||||
} else if (process.env.BROWSE_HEADED === '1') {
|
||||
console.log(`[browse] [xvfb] skipped: ${xvfbDecision.reason}`);
|
||||
}
|
||||
process.on('exit', () => { browserManager.closeOwnedDisplay(); });
|
||||
|
||||
// Read env once — single source of truth for authToken (and other env).
|
||||
// Threaded through launchHeaded, buildFetchHandler, and the state file
|
||||
@@ -3222,7 +3217,6 @@ export async function start() {
|
||||
...envCfg,
|
||||
browsePort: port, // actual bound port (resolveConfigFromEnv default is 0)
|
||||
browserManager, // module-level instance, same as today
|
||||
xvfb,
|
||||
proxyBridge,
|
||||
startTime,
|
||||
ownsTerminalAgent: true, // CLI spawns terminal-agent.ts itself (see cli.ts:1037-1063)
|
||||
@@ -3234,7 +3228,27 @@ export async function start() {
|
||||
fetch: handle.fetchLocal,
|
||||
});
|
||||
|
||||
browserManager.serverPort = port;
|
||||
|
||||
// Navigate to welcome page if in headed mode and still on about:blank
|
||||
if (browserManager.getConnectionMode() === 'headed') {
|
||||
try {
|
||||
const currentUrl = browserManager.getCurrentUrl();
|
||||
if (currentUrl === 'about:blank' || currentUrl === '') {
|
||||
const page = browserManager.getPage();
|
||||
await page.goto(`http://127.0.0.1:${port}/welcome`, { timeout: 3000 }).catch((err: any) => {
|
||||
console.warn('[browse] Failed to navigate to welcome page:', err.message);
|
||||
});
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.warn('[browse] Welcome page navigation setup failed:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
if (isShuttingDown) return;
|
||||
|
||||
// Write state file (atomic: write .tmp then rename)
|
||||
const xvfb = browserManager.getXvfbHandle();
|
||||
const state: Record<string, unknown> = {
|
||||
pid: process.pid,
|
||||
instanceId: SERVER_INSTANCE_ID,
|
||||
@@ -3285,8 +3299,6 @@ export async function start() {
|
||||
(stateWatch as any).unref?.();
|
||||
}
|
||||
|
||||
browserManager.serverPort = port;
|
||||
|
||||
// ─── Opt-in session persistence (#778 class) ─────────────────
|
||||
// BROWSE_PERSIST_STATE=1: restore cookies/storage/tabs from the last
|
||||
// snapshot, then keep snapshotting on an interval. Launched mode only —
|
||||
@@ -3339,21 +3351,6 @@ export async function start() {
|
||||
(sessionPersistInterval as any)?.unref?.();
|
||||
}
|
||||
|
||||
// Navigate to welcome page if in headed mode and still on about:blank
|
||||
if (browserManager.getConnectionMode() === 'headed') {
|
||||
try {
|
||||
const currentUrl = browserManager.getCurrentUrl();
|
||||
if (currentUrl === 'about:blank' || currentUrl === '') {
|
||||
const page = browserManager.getPage();
|
||||
page.goto(`http://127.0.0.1:${port}/welcome`, { timeout: 3000 }).catch((err: any) => {
|
||||
console.warn('[browse] Failed to navigate to welcome page:', err.message);
|
||||
});
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.warn('[browse] Welcome page navigation setup failed:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up stale state files (older than 7 days)
|
||||
try {
|
||||
const stateDir = path.join(config.stateDir, 'browse-states');
|
||||
|
||||
@@ -137,12 +137,6 @@ export function buildStealthScript(hw: HostProfile): string {
|
||||
MAC: 'mac', OPENBSD: 'openbsd', WIN: 'win' },
|
||||
RequestUpdateCheckStatus: { NO_UPDATE: 'no_update', THROTTLED: 'throttled',
|
||||
UPDATE_AVAILABLE: 'update_available' },
|
||||
connect: markNative(function connect() {
|
||||
throw new TypeError('Error in invocation of runtime.connect: No matching signature.');
|
||||
}, 'connect'),
|
||||
sendMessage: markNative(function sendMessage() {
|
||||
throw new TypeError('Error in invocation of runtime.sendMessage: No matching signature.');
|
||||
}, 'sendMessage'),
|
||||
id: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,16 +41,79 @@ export function readAgentStartTime(pid: number): string {
|
||||
|
||||
const pendingAgentExits = new Set<any>();
|
||||
|
||||
export function acquireAgentStateLock(stateDir: string, waitMs = 5000): () => void {
|
||||
function reclaimPublicationLock(stateDir: string, lockPath: string): boolean {
|
||||
try {
|
||||
const inode = fs.lstatSync(lockPath, { bigint: true });
|
||||
if (!inode.isFile() || inode.size === 0n || inode.size > 4096n) return false;
|
||||
const contents = fs.readFileSync(lockPath, 'utf8');
|
||||
const lock = JSON.parse(contents);
|
||||
const record = readAgentRecord(stateDir);
|
||||
if (lock?.kind !== 'agent-publication-v1' || !record
|
||||
|| !Number.isSafeInteger(record.pid) || record.pid <= 0
|
||||
|| typeof record.gen !== 'string' || !record.gen
|
||||
|| typeof record.startTime !== 'string' || !record.startTime
|
||||
|| record.ownerPid !== process.pid
|
||||
|| typeof record.ownerStartTime !== 'string' || !record.ownerStartTime) return false;
|
||||
const fields = ['pid', 'gen', 'startTime', 'ownerPid', 'ownerStartTime'] as const;
|
||||
if (fields.some(field => lock[field] !== record[field])
|
||||
|| readAgentStartTime(process.pid) !== record.ownerStartTime) return false;
|
||||
let present = true;
|
||||
try { process.kill(record.pid, 0); }
|
||||
catch (err: any) {
|
||||
if (err?.code !== 'ESRCH') return false;
|
||||
present = false;
|
||||
}
|
||||
if (present) {
|
||||
if (readAgentStartTime(record.pid) !== record.startTime) return false;
|
||||
if (process.platform === 'linux') {
|
||||
const state = fs.readFileSync(`/proc/${record.pid}/stat`, 'utf8').match(/^\d+ \(.*\) ([A-Z])/u)?.[1];
|
||||
if (state !== 'Z') return false;
|
||||
} else if (process.platform === 'darwin') {
|
||||
const result = spawnSync('ps', ['-p', String(record.pid), '-o', 'stat='], { encoding: 'utf8', windowsHide: true, timeout: 2000 });
|
||||
if (result.status !== 0 || result.stdout?.trim()?.[0] !== 'Z') return false;
|
||||
} else return false;
|
||||
}
|
||||
const currentRecord = readAgentRecord(stateDir);
|
||||
if (!currentRecord || fields.some(field => currentRecord[field] !== record[field])) return false;
|
||||
if (present && readAgentStartTime(record.pid) !== record.startTime) return false;
|
||||
if (fs.readFileSync(lockPath, 'utf8') !== contents) return false;
|
||||
const current = fs.lstatSync(lockPath, { bigint: true });
|
||||
if (!current.isFile() || current.dev !== inode.dev || current.ino !== inode.ino) return false;
|
||||
fs.unlinkSync(lockPath);
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
export function acquireAgentStateLock(stateDir: string, waitMs = 5000, publicationGen?: string): () => void {
|
||||
mkdirSecure(stateDir);
|
||||
const lockPath = path.join(stateDir, 'terminal-agent-pid.lock');
|
||||
let publication: string | undefined;
|
||||
if (publicationGen !== undefined) {
|
||||
const record = readAgentRecord(stateDir);
|
||||
if (!record || record.pid !== process.pid || record.gen !== publicationGen
|
||||
|| !record.ownerPid || !isOurAgent(record, record.ownerPid)) {
|
||||
throw new Error('terminal-agent publication lock identity is unavailable');
|
||||
}
|
||||
publication = JSON.stringify({ kind: 'agent-publication-v1', pid: record.pid, gen: record.gen,
|
||||
startTime: record.startTime, ownerPid: record.ownerPid, ownerStartTime: record.ownerStartTime });
|
||||
}
|
||||
const deadline = Date.now() + waitMs;
|
||||
let reclaimed = false;
|
||||
let fd: number;
|
||||
while (true) {
|
||||
try {
|
||||
fd = fs.openSync(lockPath, 'wx', 0o600);
|
||||
if (publication !== undefined) {
|
||||
atomicWriteSync(lockPath, publication, { mode: 0o600, noReplace: true });
|
||||
fd = fs.openSync(lockPath, 'r');
|
||||
} else {
|
||||
fd = fs.openSync(lockPath, 'wx', 0o600);
|
||||
}
|
||||
break;
|
||||
} catch (err: any) {
|
||||
if (err?.code === 'EEXIST' && !reclaimed && reclaimPublicationLock(stateDir, lockPath)) {
|
||||
reclaimed = true;
|
||||
continue;
|
||||
}
|
||||
if (err?.code !== 'EEXIST' || Date.now() >= deadline) {
|
||||
throw new Error(`terminal-agent state lock unavailable at ${lockPath}: ${err?.code || err}; inspect the owning process before manual recovery`);
|
||||
}
|
||||
|
||||
@@ -83,13 +83,6 @@ const sessionsById = new Map<string, PtySession>();
|
||||
// Active PTY session per WS. One terminal per connection. Codex finding #4:
|
||||
// uncaught handlers below catch bugs in framing/cleanup so they don't kill
|
||||
// the listener loop.
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('[terminal-agent] uncaughtException:', err);
|
||||
});
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
console.error('[terminal-agent] unhandledRejection:', reason);
|
||||
});
|
||||
|
||||
export interface PtySession {
|
||||
proc: any | null; // Bun.Subprocess once spawned
|
||||
lifecycle?: PtyLifecycle | null;
|
||||
@@ -1052,7 +1045,7 @@ async function main() {
|
||||
|
||||
// Write port file atomically so the parent server can pick it up.
|
||||
// Throws on failure — a boot without a discoverable port file is broken.
|
||||
const releasePublication = acquireAgentStateLock(dir);
|
||||
const releasePublication = acquireAgentStateLock(dir, 5000, process.env.BROWSE_AGENT_GEN);
|
||||
let record;
|
||||
try {
|
||||
const current = readAgentRecord(dir);
|
||||
@@ -1116,7 +1109,15 @@ async function main() {
|
||||
// to a state file the parent reads. This avoids env-passing races. See main().
|
||||
const INTERNAL_TOKEN_FILE = path.join(path.dirname(STATE_FILE), 'terminal-internal-token');
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(`[terminal-agent] boot failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
process.exit(1);
|
||||
});
|
||||
if (import.meta.main) {
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('[terminal-agent] uncaughtException:', err);
|
||||
});
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
console.error('[terminal-agent] unhandledRejection:', reason);
|
||||
});
|
||||
main().catch((err) => {
|
||||
console.error(`[terminal-agent] boot failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -600,29 +600,21 @@ export async function handleWriteCommand(
|
||||
const [selector, ...filePaths] = args;
|
||||
if (!selector || filePaths.length === 0) throw new Error('Usage: browse upload <selector> <file1> [file2...]');
|
||||
|
||||
// Validate paths are within safe directories (same check as cookie-import)
|
||||
for (const fp of filePaths) {
|
||||
const validatedPaths = filePaths.map(fp => {
|
||||
if (!fs.existsSync(fp)) throw new Error(`File not found: ${fp}`);
|
||||
if (path.isAbsolute(fp)) {
|
||||
let resolvedFp: string;
|
||||
try { resolvedFp = fs.realpathSync(path.resolve(fp)); } catch (err: any) { if (err?.code !== 'ENOENT') throw err; resolvedFp = path.resolve(fp); }
|
||||
if (!SAFE_DIRECTORIES.some(dir => isPathWithin(resolvedFp, dir))) {
|
||||
throw new Error(`Path must be within: ${SAFE_DIRECTORIES.join(', ')}`);
|
||||
}
|
||||
}
|
||||
if (path.normalize(fp).includes('..')) {
|
||||
throw new Error('Path traversal sequences (..) are not allowed');
|
||||
}
|
||||
}
|
||||
const realPath = fs.realpathSync(path.resolve(fp));
|
||||
validateReadPath(realPath);
|
||||
return realPath;
|
||||
});
|
||||
|
||||
const resolved = await session.resolveRef(selector);
|
||||
if ('locator' in resolved) {
|
||||
await resolved.locator.setInputFiles(filePaths);
|
||||
await resolved.locator.setInputFiles(validatedPaths);
|
||||
} else {
|
||||
await target.locator(resolved.selector).setInputFiles(filePaths);
|
||||
await target.locator(resolved.selector).setInputFiles(validatedPaths);
|
||||
}
|
||||
|
||||
const fileInfo = filePaths.map(fp => {
|
||||
const fileInfo = validatedPaths.map(fp => {
|
||||
const stat = fs.statSync(fp);
|
||||
return `${path.basename(fp)} (${stat.size}B)`;
|
||||
}).join(', ');
|
||||
|
||||
+22
-6
@@ -57,6 +57,10 @@ export function shouldSpawnXvfb(env: NodeJS.ProcessEnv, platform: NodeJS.Platfor
|
||||
* 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
|
||||
@@ -68,8 +72,7 @@ export function isDisplayFree(displayNum: number): boolean {
|
||||
});
|
||||
return result.exitCode !== 0;
|
||||
} catch {
|
||||
return !fs.existsSync(`/tmp/.X11-unix/X${displayNum}`)
|
||||
&& !fs.existsSync(`/tmp/.X${displayNum}-lock`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,6 +181,8 @@ export function isOurXvfb(pid: number, recordedStartTime: string): boolean {
|
||||
*/
|
||||
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.
|
||||
@@ -186,6 +191,7 @@ export async function spawnXvfb(displayNum: number): Promise<XvfbHandle> {
|
||||
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.
|
||||
@@ -193,18 +199,27 @@ export async function spawnXvfb(displayNum: number): Promise<XvfbHandle> {
|
||||
let ready = false;
|
||||
while (Date.now() < deadline) {
|
||||
await Bun.sleep(100);
|
||||
if (!isDisplayFree(displayNum)) { ready = true; break; }
|
||||
// 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) {
|
||||
try { proc.kill('SIGKILL'); } catch { /* ignore */ }
|
||||
cleanupXvfb({ pid: proc.pid, startTime, display });
|
||||
throw new Error(`Xvfb on ${display} never became reachable within 3s timeout`);
|
||||
}
|
||||
|
||||
const startTime = readPidStartTime(proc.pid);
|
||||
return {
|
||||
pid: proc.pid,
|
||||
startTime,
|
||||
@@ -227,8 +242,9 @@ export function cleanupXvfb(state: { pid: number; startTime: string; display: st
|
||||
const deadline = Date.now() + 1000;
|
||||
while (Date.now() < deadline) {
|
||||
if (!isProcessAlive(state.pid)) break;
|
||||
Bun.sleepSync(10);
|
||||
}
|
||||
if (isProcessAlive(state.pid)) {
|
||||
if (isOurXvfb(state.pid, state.startTime)) {
|
||||
try { safeKill(state.pid, 'SIGKILL'); } catch { /* swallow */ }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user