mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-04 18:36:54 +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;
|
||||
|
||||
Reference in new issue
Block a user