Merge origin/main into gbrowser-anti-detection

Brings the branch up to date with main (v1.40.0.2 -> v1.58.1.0).

Conflict resolutions:
- VERSION: take main's 1.58.1.0 (branch re-bumps at /ship time).
- CHANGELOG.md: keep main's full history; slot the branch's unique
  v1.40.0.2 entry into descending-order position (no content lost).
- browse/src/browser-manager.ts: keep main's GSTACK_CHROMIUM_NO_SANDBOX
  override and onDisconnect(exitCode) signature; branch's
  buildGStackLaunchArgs / STEALTH_IGNORE_DEFAULT_ARGS wiring preserved.
- browse/test/browser-manager-unit.test.ts: keep main's override +
  exit-code propagation tests alongside the branch's Cmd+Q
  cause-resolver tests.
- browse/src/stealth.ts: blend the two stealth designs. Layer C
  (buildStealthScript) is the always-on consistency-first default;
  main's GSTACK_STEALTH=extended (EXTENDED_STEALTH_SCRIPT) remains an
  opt-in layer applied on top. Both public APIs and both test suites
  (stealth-layer-c + stealth-extended) preserved; the two applyStealth
  wiring assertions updated to reflect the Layer C default.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Garry Tan
2026-06-17 07:54:24 -07:00
637 changed files with 100152 additions and 18013 deletions
+64
View File
@@ -29,17 +29,20 @@ describe('shouldEnableChromiumSandbox', () => {
const origPlatform = process.platform;
const origCI = process.env.CI;
const origContainer = process.env.CONTAINER;
const origNoSandbox = process.env.GSTACK_CHROMIUM_NO_SANDBOX;
const origGetuid = process.getuid;
beforeEach(() => {
delete process.env.CI;
delete process.env.CONTAINER;
delete process.env.GSTACK_CHROMIUM_NO_SANDBOX;
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: origPlatform });
if (origCI === undefined) delete process.env.CI; else process.env.CI = origCI;
if (origContainer === undefined) delete process.env.CONTAINER; else process.env.CONTAINER = origContainer;
if (origNoSandbox === undefined) delete process.env.GSTACK_CHROMIUM_NO_SANDBOX; else process.env.GSTACK_CHROMIUM_NO_SANDBOX = origNoSandbox;
process.getuid = origGetuid;
});
@@ -90,6 +93,31 @@ describe('shouldEnableChromiumSandbox', () => {
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
// #1562 — Ubuntu/AppArmor opt-in override
it('linux + GSTACK_CHROMIUM_NO_SANDBOX=1 → false (Ubuntu/AppArmor opt-out)', async () => {
setPlatform('linux');
process.env.GSTACK_CHROMIUM_NO_SANDBOX = '1';
process.getuid = (() => 1000) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
it('darwin + GSTACK_CHROMIUM_NO_SANDBOX=1 → false (env override wins on any platform)', async () => {
setPlatform('darwin');
process.env.GSTACK_CHROMIUM_NO_SANDBOX = '1';
process.getuid = (() => 501) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
it('GSTACK_CHROMIUM_NO_SANDBOX=0 → does NOT trigger override (must be exactly "1")', async () => {
setPlatform('linux');
process.env.GSTACK_CHROMIUM_NO_SANDBOX = '0';
process.getuid = (() => 1000) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(true);
});
});
// ─── resolveDisconnectCause ──────────────────────────────────────
@@ -163,3 +191,39 @@ describe('resolveDisconnectCause', () => {
expect(await resolveDisconnectCause(null)).toBe('crash');
});
});
// ─── onDisconnect exit-code propagation (regression test) ──────────
//
// The contract: BrowserManager.onDisconnect is called with the resolved
// exit code (0 for clean Cmd+Q, 2 for crash). server.ts then forwards
// that code to activeShutdown(), which exits the process.
//
// Without this propagation, the headed-mode user-visible Cmd+Q respawn
// bug returns: server.ts hardcoded `activeShutdown?.(2)` ignores the
// resolved 0 and gbrowser's gbd HealthMonitor treats the clean quit as
// a crash, restarting the window.
describe('BrowserManager.onDisconnect exit-code propagation', () => {
it('signature accepts an optional exitCode argument', async () => {
const { BrowserManager } = await import('../src/browser-manager');
const bm = new BrowserManager();
const calls: Array<number | undefined> = [];
bm.onDisconnect = (code?: number) => { calls.push(code); };
bm.onDisconnect(0);
bm.onDisconnect(2);
bm.onDisconnect(undefined);
expect(calls).toEqual([0, 2, undefined]);
});
it('server.ts callback forwards exitCode when provided, falls back to 2', async () => {
// Mirror the production wiring in browse/src/server.ts so a refactor
// that drops the forward (e.g. reverting to `() => activeShutdown?.(2)`)
// fails CI before the user-visible bug returns.
const shutdownCalls: number[] = [];
const activeShutdown = (code: number) => { shutdownCalls.push(code); };
const onDisconnect = (code?: number) => activeShutdown(code ?? 2);
onDisconnect(0);
onDisconnect(2);
onDisconnect(undefined);
expect(shutdownCalls).toEqual([0, 2, 2]);
});
});
+26 -3
View File
@@ -178,7 +178,17 @@ describe('buildSpawnEnv', () => {
process.env.LANG = 'en_US.UTF-8';
});
afterEach(() => {
process.env = origEnv;
// process.env = origEnv replaces only the reference; the underlying
// env stays mutated and leaks to later test files in the same Bun
// process (e.g., breaks Bun.which('bash') in security.test.ts and
// bun-spawn in pair-agent-tunnel-eval.test.ts). Delete every current
// key then re-assign from the snapshot — restores the actual env.
for (const k of Object.keys(process.env)) {
if (!(k in origEnv)) delete process.env[k];
}
for (const [k, v] of Object.entries(origEnv)) {
if (v !== undefined) process.env[k] = v;
}
});
it('untrusted: drops $HOME and secrets', () => {
@@ -293,7 +303,15 @@ describe.skipIf(SKIP_SPAWN)('spawnSkill: lifecycle', () => {
expect(parsed.gh).toBeNull();
expect(parsed.gstack).toBeNull();
} finally {
process.env = origEnv;
// See afterEach comment in `buildSpawnEnv` describe — direct
// reassignment of process.env doesn't actually restore the
// underlying env in Bun. Delete + re-assign instead.
for (const k of Object.keys(process.env)) {
if (!(k in origEnv)) delete process.env[k];
}
for (const [k, v] of Object.entries(origEnv)) {
if (v !== undefined) process.env[k] = v;
}
}
});
@@ -312,7 +330,12 @@ describe.skipIf(SKIP_SPAWN)('spawnSkill: lifecycle', () => {
const parsed = JSON.parse(result.stdout);
expect(parsed.home).toBe('/Users/test-user');
} finally {
process.env = origEnv;
for (const k of Object.keys(process.env)) {
if (!(k in origEnv)) delete process.env[k];
}
for (const [k, v] of Object.entries(origEnv)) {
if (v !== undefined) process.env[k] = v;
}
}
});
@@ -0,0 +1,95 @@
import { describe, test, expect, beforeEach } from 'bun:test';
import type { Page } from 'playwright';
import {
__testInternals,
undoModification,
} from '../src/cdp-inspector';
// Regression tests for the modificationHistory cap (D6 / smoking gun #2).
// Pre-cap, the module-scoped array grew unbounded across the session. Cap is
// 200 entries, oldest evicted on push past the cap. undoModification reports
// "evicted at the cap" in the error message so a user who asks for a
// no-longer-available index understands what happened (instead of seeing the
// pre-cap "No modification at index 500" with no context).
const { pushModification, MOD_HISTORY_CAP, getRawHistory, getTotalPushed, resetForTest } = __testInternals;
function fakeMod(id: number) {
return {
selector: `#node-${id}`,
property: 'color',
oldValue: 'red',
newValue: 'blue',
source: 'inline' as const,
timestamp: id,
method: 'setProperty' as 'setProperty',
};
}
beforeEach(() => {
resetForTest();
});
describe('modificationHistory cap', () => {
test('1. push under cap keeps every entry', () => {
for (let i = 0; i < 50; i++) pushModification(fakeMod(i));
expect(getRawHistory().length).toBe(50);
expect(getTotalPushed()).toBe(50);
expect(getRawHistory()[0].timestamp).toBe(0);
expect(getRawHistory()[49].timestamp).toBe(49);
});
test('2. push exactly cap keeps every entry', () => {
for (let i = 0; i < MOD_HISTORY_CAP; i++) pushModification(fakeMod(i));
expect(getRawHistory().length).toBe(MOD_HISTORY_CAP);
expect(getTotalPushed()).toBe(MOD_HISTORY_CAP);
expect(getRawHistory()[0].timestamp).toBe(0);
});
test('3. push past cap evicts oldest, keeps length at cap', () => {
const total = MOD_HISTORY_CAP + 50;
for (let i = 0; i < total; i++) pushModification(fakeMod(i));
expect(getRawHistory().length).toBe(MOD_HISTORY_CAP);
expect(getTotalPushed()).toBe(total);
// Oldest 50 dropped — entry that was #0 is gone; new oldest is #50.
expect(getRawHistory()[0].timestamp).toBe(50);
expect(getRawHistory()[MOD_HISTORY_CAP - 1].timestamp).toBe(total - 1);
});
test('4. resetForTest clears both buffer and totalPushed', () => {
for (let i = 0; i < 10; i++) pushModification(fakeMod(i));
resetForTest();
expect(getRawHistory().length).toBe(0);
expect(getTotalPushed()).toBe(0);
});
});
describe('undoModification eviction-aware error', () => {
// Stub Page: undoModification throws before any await when idx is out of
// range, so the stub never actually gets called.
const stubPage = {} as unknown as Page;
test('5. out-of-range BEFORE any eviction → no evicted note', async () => {
for (let i = 0; i < 5; i++) pushModification(fakeMod(i));
await expect(undoModification(stubPage, 99)).rejects.toThrow(
'No modification at index 99. History has 5 entries.',
);
});
test('6. out-of-range AFTER eviction → message names the evicted count', async () => {
const total = MOD_HISTORY_CAP + 73;
for (let i = 0; i < total; i++) pushModification(fakeMod(i));
// 273 pushed, 200 in buffer, 73 evicted. Ask for idx=400 (above buffer).
await expect(undoModification(stubPage, 400)).rejects.toThrow(
`No modification at index 400. History has ${MOD_HISTORY_CAP} entries ` +
`(most recent ${MOD_HISTORY_CAP} only — 73 earlier entries evicted at the cap).`,
);
});
test('7. negative explicit index throws cleanly (no NaN propagation)', async () => {
for (let i = 0; i < 10; i++) pushModification(fakeMod(i));
await expect(undoModification(stubPage, -1)).rejects.toThrow(
'No modification at index -1.',
);
});
});
+171
View File
@@ -0,0 +1,171 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import type { Page } from 'playwright';
import { withCdpSession, getOrCreateCdpSession } from '../src/cdp-bridge';
// Static-grep tripwire + behavior tests for the CDP session lifecycle
// helpers introduced as part of the D11 EXPAND_SCOPE memory-leak fix.
//
// Direct calls to `page.context().newCDPSession(page)` are the leak class
// the helpers exist to close — every direct call needs a matching
// `session.detach()` and forgetting it leaves the Chromium-side target
// attached until the underlying transport drops. The tripwire fails CI
// if any source file calls `newCDPSession(` outside `cdp-bridge.ts`
// (the file that owns the helpers).
//
// Pattern mirrors browse/test/terminal-agent-pid-identity.test.ts and
// browse/test/server-sanitize-surrogates.test.ts: read source files
// directly, assert an invariant on their contents.
const SRC_DIR = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src');
function readAllSourceFiles(): Array<{ file: string; content: string }> {
const out: Array<{ file: string; content: string }> = [];
for (const entry of fs.readdirSync(SRC_DIR)) {
if (!entry.endsWith('.ts')) continue;
const full = path.join(SRC_DIR, entry);
out.push({ file: entry, content: fs.readFileSync(full, 'utf-8') });
}
return out;
}
describe('CDP session cleanup invariant', () => {
test('1. no source file calls `newCDPSession(` outside cdp-bridge.ts', () => {
const offenders: Array<{ file: string; line: number; text: string }> = [];
for (const { file, content } of readAllSourceFiles()) {
// The helper file is the ONE allowed home for direct newCDPSession calls.
if (file === 'cdp-bridge.ts') continue;
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!/newCDPSession\s*\(/.test(line)) continue;
// Skip comment lines — documentation mentions are fine.
const trimmed = line.trim();
if (trimmed.startsWith('//') || trimmed.startsWith('*')) continue;
offenders.push({ file, line: i + 1, text: trimmed });
}
}
if (offenders.length > 0) {
const formatted = offenders
.map((o) => ` ${o.file}:${o.line} ${o.text}`)
.join('\n');
throw new Error(
`Direct newCDPSession(...) calls found outside cdp-bridge.ts. ` +
`Route through withCdpSession() (one-shot, finally-detach) or ` +
`getOrCreateCdpSession() (cached, close-detach) instead:\n${formatted}`,
);
}
expect(offenders).toEqual([]);
});
test('2. helper file exports the two documented entry points', () => {
// Sanity: the tripwire is meaningless if the helpers themselves are gone.
expect(typeof withCdpSession).toBe('function');
expect(typeof getOrCreateCdpSession).toBe('function');
});
});
describe('withCdpSession finally-detach', () => {
// Fake Page surface for unit-testing the helper without spinning up a real
// browser. The helper only touches page.context().newCDPSession(page) and
// the returned session's .detach(), so this surface is enough.
function makeFakePage(detachSpy: { called: number; rejected?: Error }) {
const session = {
detach: async () => {
detachSpy.called++;
if (detachSpy.rejected) throw detachSpy.rejected;
},
};
return {
context: () => ({
newCDPSession: async (_p: unknown) => session,
}),
} as unknown as Page;
}
test('3. detaches on the success path', async () => {
const detachSpy = { called: 0 };
const page = makeFakePage(detachSpy);
const result = await withCdpSession(page, async (session) => {
expect(session).toBeDefined();
return 42;
});
expect(result).toBe(42);
expect(detachSpy.called).toBe(1);
});
test('4. detaches even when fn throws (the actual leak fix)', async () => {
const detachSpy = { called: 0 };
const page = makeFakePage(detachSpy);
await expect(
withCdpSession(page, async () => {
throw new Error('boom');
}),
).rejects.toThrow('boom');
expect(detachSpy.called).toBe(1);
});
test('5. swallows detach errors so they do not mask fn errors', async () => {
const detachSpy = { called: 0, rejected: new Error('already detached') };
const page = makeFakePage(detachSpy);
await expect(
withCdpSession(page, async () => {
throw new Error('original');
}),
).rejects.toThrow('original');
expect(detachSpy.called).toBe(1);
});
test('6. swallows detach errors on the success path too', async () => {
const detachSpy = { called: 0, rejected: new Error('target closed') };
const page = makeFakePage(detachSpy);
const result = await withCdpSession(page, async () => 'ok');
expect(result).toBe('ok');
expect(detachSpy.called).toBe(1);
});
});
describe('getOrCreateCdpSession close-detach', () => {
function makeFakePage() {
const closeListeners: Array<() => void> = [];
const session = {
detach: async () => {
session._detachCount++;
},
_detachCount: 0,
};
const page = {
context: () => ({
newCDPSession: async (_p: unknown) => session,
}),
once: (event: string, fn: () => void) => {
if (event === 'close') closeListeners.push(fn);
},
_fireClose: () => {
for (const fn of closeListeners) fn();
},
};
return { page: page as unknown as Page, session, fireClose: page._fireClose };
}
test('7. caches the session across calls', async () => {
const { page } = makeFakePage();
const cache = new WeakMap<Page, any>();
const s1 = await getOrCreateCdpSession(page, cache);
const s2 = await getOrCreateCdpSession(page, cache);
expect(s1).toBe(s2);
});
test('8. close hook detaches the session AND clears the cache', async () => {
const { page, session, fireClose } = makeFakePage();
const cache = new WeakMap<Page, any>();
await getOrCreateCdpSession(page, cache);
expect(cache.get(page)).toBeDefined();
fireClose();
// Detach runs synchronously up to the await in the close hook; let it settle.
await new Promise((r) => setTimeout(r, 0));
expect(cache.get(page)).toBeUndefined();
expect(session._detachCount).toBe(1);
});
});
+75
View File
@@ -0,0 +1,75 @@
/**
* Coverage for #1612 — macOS/Linux server must survive sandboxed-shell
* harnesses by becoming its own session leader (setsid).
*
* Pre-#1612, Bun.spawn().unref() removed the child from Bun's event loop
* but did NOT call setsid(). When the CLI ran inside Claude Code's
* per-command sandbox, Conductor, or CI step runners, the session leader's
* exit sent SIGHUP to every PID in the session, killing the bun server.
*
* The fix routes macOS/Linux spawn through Node's child_process.spawn with
* detached:true, which calls setsid() so the server becomes its own session
* leader (PPID=1 on Linux, similar reparenting on Darwin).
*
* The actual setsid syscall is hard to assert in a unit test without a
* real spawn — testing here is static: the cli.ts source must use the
* Node spawn path on macOS/Linux, with detached:true and .unref(). If a
* future refactor reverts to Bun.spawn().unref() on the macOS/Linux branch
* the regression returns and these tests fail.
*/
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
const ROOT = path.resolve(import.meta.dir, "..", "..");
const CLI = path.join(ROOT, "browse", "src", "cli.ts");
function read(): string {
return fs.readFileSync(CLI, "utf-8");
}
describe("#1612 macOS/Linux daemonize via Node setsid path", () => {
test("cli.ts imports nodeSpawn from child_process (Node spawn alias)", () => {
const body = read();
// The fix relies on Node's child_process.spawn (which calls setsid on
// detached:true), aliased to avoid name collision with Bun.spawn. Match
// either `nodeSpawn` or `spawn as nodeSpawn` to be flexible to the
// exact import style.
expect(body).toMatch(/(spawn as nodeSpawn|nodeSpawn\s*[,}])/);
expect(body).toMatch(/from\s+['"]child_process['"]/);
});
test("non-Windows branch uses nodeSpawn(...).unref() with detached:true", () => {
const body = read();
// Find the non-Windows branch and assert it uses the Node spawn alias
// with detached:true. Match the pattern `nodeSpawn(...) ... detached:true`.
expect(body).toMatch(/nodeSpawn\([\s\S]{0,500}detached:\s*true/);
expect(body).toMatch(/nodeSpawn\([\s\S]{0,500}\.unref\(\)/);
});
test("non-Windows branch comment documents setsid/SIGHUP root cause", () => {
const body = read();
// The comment block must mention setsid() so a future refactor sees the
// why before changing the spawn call.
expect(body).toMatch(/setsid/);
expect(body).toMatch(/SIGHUP/);
});
test("the spawn call on macOS/Linux is nodeSpawn, not Bun.spawn", () => {
const body = read();
// Strip line comments before regex matching, so the "Bun.spawn().unref()"
// mentions inside the explanatory comment don't trigger false positives.
const codeOnly = body
.split("\n")
.filter((line) => !line.trim().startsWith("//"))
.join("\n");
// Find the non-Windows branch. The `} else {` block following the
// Windows branch. We then require its first ~400 chars contain a
// nodeSpawn() call and NOT a Bun.spawn() call (excluding the comment).
const nonWindowsStart = codeOnly.indexOf("nodeSpawn('bun'");
expect(nonWindowsStart).toBeGreaterThan(-1);
const slice = codeOnly.slice(nonWindowsStart, nonWindowsStart + 400);
expect(slice).toMatch(/nodeSpawn\(/);
expect(slice).not.toMatch(/Bun\.spawn\(/);
});
});
+81
View File
@@ -0,0 +1,81 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// v1.44 outer supervisor — static-grep invariants.
//
// Pre-v1.44 `$B connect` was fire-and-forget: spawn server detached, CLI
// exits, server runs unsupervised. If the server crashed, the user had to
// re-run `$B connect`. The opt-in supervisor (--supervise or
// BROWSE_SUPERVISE=1) keeps the CLI attached and respawns the server on
// unexpected exit, with the same crash-loop guard shape as the v1.44
// terminal-agent watchdog.
//
// Live respawn tests belong in the e2e tier (real Bun.spawn cycles take
// 3-8s each). These tripwires defend the load-bearing invariants:
// opt-in by default, signal handlers wired, crash-loop guard, env knobs.
const CLI_TS = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'cli.ts');
describe('CLI outer supervisor (v1.44+)', () => {
test('1. supervisor is opt-in via --supervise flag or BROWSE_SUPERVISE env', () => {
const src = fs.readFileSync(CLI_TS, 'utf-8');
expect(src).toContain("commandArgs.includes('--supervise')");
expect(src).toContain("process.env.BROWSE_SUPERVISE === '1'");
// Default path MUST still exit 0 promptly. The legacy contract is
// that every caller of `$B connect` (Claude Code Bash tool, scripts,
// CI) gets a prompt return.
expect(src).toMatch(/if \(!superviseRequested\) \{\s*process\.exit\(0\);\s*\}/);
});
test('2. SIGINT and SIGTERM trigger clean teardown', () => {
const src = fs.readFileSync(CLI_TS, 'utf-8');
// Both signals must hit the teardown path or the user's Ctrl-C leaves
// an orphaned server (worse than no supervisor).
expect(src).toMatch(/process\.on\('SIGINT'.*teardownAndExit/);
expect(src).toMatch(/process\.on\('SIGTERM'.*teardownAndExit/);
// Teardown must signal the supervised server before exiting itself.
expect(src).toContain("safeKill(state.pid, 'SIGTERM')");
});
test('3. crash-loop guard with 5-in-5min rolling window', () => {
const src = fs.readFileSync(CLI_TS, 'utf-8');
expect(src).toContain('SUPERVISOR_GUARD_WINDOW_MS = 5 * 60_000');
expect(src).toContain('SUPERVISOR_GUARD_MAX = 5');
// Window pruning: a long-lived daemon with sporadic crashes must NOT
// hit the guard (otherwise we punish the user for the supervisor doing
// its job).
expect(src).toMatch(/respawns\.shift\(\)/);
});
test('4. exponential backoff schedule, env-overridable', () => {
const src = fs.readFileSync(CLI_TS, 'utf-8');
expect(src).toContain('GSTACK_SUPERVISOR_BACKOFF');
// Default schedule must include short waits at first (rapid recovery
// from transient crashes) and cap at a sensible long wait.
expect(src).toContain('1000,2000,4000,8000,30000');
});
test('5. tick interval is env-overridable for tests', () => {
const src = fs.readFileSync(CLI_TS, 'utf-8');
expect(src).toContain('GSTACK_SUPERVISOR_TICK_MS');
});
test('6. respawned server gets a fresh terminal-agent too', () => {
const src = fs.readFileSync(CLI_TS, 'utf-8');
// After server respawn, the terminal-agent state is stale (old PID
// record points to a dead agent that exited with its parent). The
// supervisor must re-call spawnTerminalAgent or the PTY path stays
// broken even though the server is back up.
const block = sliceBetween(src, 'Supervisor mode:', '// ─── Headed Disconnect');
expect(block).toContain('spawnTerminalAgent({');
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
+156 -1
View File
@@ -9,7 +9,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { startTestServer } from './test-server';
import { BrowserManager } from '../src/browser-manager';
import { resolveServerScript } from '../src/cli';
import { handleReadCommand as _handleReadCommand } from '../src/read-commands';
import { handleReadCommand as _handleReadCommand, parseOutArgs, hasOutArg, resultToString } from '../src/read-commands';
import { handleWriteCommand as _handleWriteCommand } from '../src/write-commands';
import { handleMetaCommand } from '../src/meta-commands';
import { consoleBuffer, networkBuffer, dialogBuffer, addConsoleEntry, addNetworkEntry, addDialogEntry, CircularBuffer } from '../src/buffers';
@@ -23,6 +23,65 @@ const handleReadCommand = (cmd: string, args: string[], b: BrowserManager) =>
const handleWriteCommand = (cmd: string, args: string[], b: BrowserManager) =>
_handleWriteCommand(cmd, args, b.getActiveSession(), b);
// ─── Pure arg-parser + result-conversion unit tests (no browser) ───
describe('parseOutArgs / hasOutArg', () => {
test('--out <path> splits the flag from the positional', () => {
expect(parseOutArgs(['expr', '--out', '/tmp/x'])).toEqual({ outPath: '/tmp/x', raw: false, rest: ['expr'] });
});
test('--out=<path> form is equivalent', () => {
expect(parseOutArgs(['expr', '--out=/tmp/x'])).toEqual({ outPath: '/tmp/x', raw: false, rest: ['expr'] });
});
test('flag ordering does not matter', () => {
expect(parseOutArgs(['--out', '/tmp/x', 'expr'])).toEqual({ outPath: '/tmp/x', raw: false, rest: ['expr'] });
});
test('--raw and --raw=true|false', () => {
expect(parseOutArgs(['e', '--out', '/tmp/x', '--raw']).raw).toBe(true);
expect(parseOutArgs(['e', '--out', '/tmp/x', '--raw=true']).raw).toBe(true);
expect(parseOutArgs(['e', '--out', '/tmp/x', '--raw=false']).raw).toBe(false);
});
test('repeated --out throws', () => {
expect(() => parseOutArgs(['e', '--out', '/a', '--out', '/b'])).toThrow(/more than once/);
});
test('--out with a missing value throws', () => {
expect(() => parseOutArgs(['e', '--out'])).toThrow(/requires a file path/);
expect(() => parseOutArgs(['e', '--out', '--raw'])).toThrow(/requires a file path/);
expect(() => parseOutArgs(['e', '--out='])).toThrow(/requires a file path/);
});
test('bad --raw value throws', () => {
expect(() => parseOutArgs(['e', '--out', '/a', '--raw=maybe'])).toThrow(/--raw must be true or false/);
});
test('hasOutArg matches --out and --out= exactly, not lookalikes', () => {
expect(hasOutArg(['a', '--out', 'b'])).toBe(true);
expect(hasOutArg(['a', '--out=b'])).toBe(true);
expect(hasOutArg(['a'])).toBe(false);
expect(hasOutArg(['a', '--output', 'b'])).toBe(false);
expect(hasOutArg(['a', '--outx'])).toBe(false);
});
});
describe('resultToString — byte-for-byte with pre-refactor behavior', () => {
test('null becomes "null" (typeof null === object → JSON.stringify)', () => {
expect(resultToString(null)).toBe('null');
});
test('undefined becomes empty string', () => {
expect(resultToString(undefined)).toBe('');
});
test('objects are pretty-printed JSON', () => {
expect(resultToString({ a: 1 })).toBe(JSON.stringify({ a: 1 }, null, 2));
});
test('primitives use String()', () => {
expect(resultToString(42)).toBe('42');
expect(resultToString(true)).toBe('true');
});
});
let testServer: ReturnType<typeof startTestServer>;
let bm: BrowserManager;
let baseUrl: string;
@@ -225,6 +284,102 @@ describe('Inspection', () => {
expect(result).toBe('3');
});
// ─── js/eval --out (render-to-file) ───────────────────────────
test('js (no --out) returns a multi-MB string without truncation', async () => {
// Handler-level guarantee: the result is not sliced/capped before return.
// (Full HTTP egress path is exercised elsewhere; this pins the handler.)
const result = await handleReadCommand('js', ["'x'.repeat(3 * 1024 * 1024)"], bm);
expect(result.length).toBe(3 * 1024 * 1024);
});
test('js --out writes the result to disk and returns a short status, not the payload', async () => {
const out = `/tmp/browse-out-large-${Date.now()}.txt`;
try {
const result = await handleReadCommand('js', ["'y'.repeat(2 * 1024 * 1024)", '--out', out], bm);
expect(result).toContain('JS result written:');
expect(result).toContain(out);
expect(result).toContain(`(${2 * 1024 * 1024} bytes)`);
expect(result.length).toBeLessThan(200); // status, not the 2MB payload
expect(fs.statSync(out).size).toBe(2 * 1024 * 1024);
} finally {
fs.rmSync(out, { force: true });
}
});
test('js --out decodes a base64 PNG data URL to real bytes', async () => {
// 1x1 transparent PNG.
const b64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
const out = `/tmp/browse-out-png-${Date.now()}.png`;
try {
const result = await handleReadCommand('js', [`'data:image/png;base64,' + '${b64}'`, '--out', out], bm);
const buf = fs.readFileSync(out);
// PNG magic bytes: 89 50 4E 47
expect([buf[0], buf[1], buf[2], buf[3]]).toEqual([0x89, 0x50, 0x4e, 0x47]);
const expectedLen = Buffer.from(b64, 'base64').length;
expect(buf.length).toBe(expectedLen);
expect(result).toContain(`(${expectedLen} bytes)`);
} finally {
fs.rmSync(out, { force: true });
}
});
test('js --out --raw writes the literal data-URL string (no decode)', async () => {
const dataUrl = 'data:text/plain;base64,aGVsbG8=';
const out = `/tmp/browse-out-raw-${Date.now()}.txt`;
try {
await handleReadCommand('js', [`'${dataUrl}'`, '--out', out, '--raw'], bm);
expect(fs.readFileSync(out, 'utf-8')).toBe(dataUrl);
} finally {
fs.rmSync(out, { force: true });
}
});
test('js --out throws on a malformed base64 data URL instead of writing corrupt bytes', async () => {
const out = `/tmp/browse-out-bad-${Date.now()}.png`;
try {
await expect(
handleReadCommand('js', ["'data:image/png;base64,!!!not-base64!!!'", '--out', out], bm)
).rejects.toThrow(/malformed base64/);
expect(fs.existsSync(out)).toBe(false);
} finally {
fs.rmSync(out, { force: true });
}
});
test('js --out rejects a path outside the safe directories', async () => {
await expect(
handleReadCommand('js', ['1 + 1', '--out', '/etc/browse-should-not-write.txt'], bm)
).rejects.toThrow();
});
test('js --out creates a missing parent directory', async () => {
// validateOutputPath resolves the parent's realpath, so it permits one level
// of missing dir under a safe root (/tmp). mkdir then materializes it.
const root = `/tmp/browse-out-nested-${Date.now()}`;
const out = `${root}/result.txt`;
try {
await handleReadCommand('js', ["'nested'", '--out', out], bm);
expect(fs.readFileSync(out, 'utf-8')).toBe('nested');
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test('eval --out writes the file result to disk (parity with js)', async () => {
const script = `/tmp/browse-eval-out-src-${Date.now()}.js`;
const out = `/tmp/browse-eval-out-${Date.now()}.txt`;
fs.writeFileSync(script, "'from eval'");
try {
const result = await handleReadCommand('eval', [script, '--out', out], bm);
expect(result).toContain('Eval result written:');
expect(fs.readFileSync(out, 'utf-8')).toBe('from eval');
} finally {
fs.rmSync(script, { force: true });
fs.rmSync(out, { force: true });
}
});
test('css returns computed property', async () => {
const result = await handleReadCommand('css', ['h1', 'color'], bm);
// Navy color
+11
View File
@@ -47,4 +47,15 @@ describe('locateBinary', () => {
expect(typeof locateBinary).toBe('function');
expect(locateBinary.length).toBe(0);
});
test('source-checkout fallback resolves <git-root>/browse/dist/browse[.exe]', () => {
// The windows-setup-e2e.yml workflow builds binaries directly under
// browse/dist/ (no .claude/skills/gstack/ install layout). find-browse
// must resolve those — otherwise every fresh build that hasn't run
// ./setup yet looks broken. Static pin so a future refactor that
// drops the source-checkout branch trips this test.
const src = require('fs').readFileSync(require('path').join(__dirname, '../src/find-browse.ts'), 'utf-8');
expect(src).toContain('Source-checkout fallback');
expect(src).toContain("join(root, 'browse', 'dist', 'browse')");
});
});
+42
View File
@@ -1,6 +1,7 @@
import { describe, test, expect } from 'bun:test';
import * as net from 'net';
import * as path from 'path';
import { __testInternals__ } from '../src/server';
const polyfillPath = path.resolve(import.meta.dir, '../src/bun-polyfill.cjs');
@@ -28,6 +29,47 @@ function getFreePort(): Promise<number> {
}
describe('findPort / isPortAvailable', () => {
test('explicit BROWSE_PORT diagnostic distinguishes bind denial from occupied port', () => {
const blocked = __testInternals__.formatExplicitPortUnavailableError(34567, {
available: false,
code: 'EPERM',
message: 'operation not permitted',
}).message;
expect(blocked).toContain('Cannot bind BROWSE_PORT=34567');
expect(blocked).toContain('localhost port binding is blocked');
expect(blocked).toContain('not that the port is occupied');
const occupied = __testInternals__.formatExplicitPortUnavailableError(34567, {
available: false,
code: 'EADDRINUSE',
message: 'address already in use',
}).message;
expect(occupied).toBe('[browse] Port 34567 (from BROWSE_PORT env) is in use');
});
test('random port diagnostic calls out sandbox-style bind denial', () => {
const message = __testInternals__.formatRandomPortUnavailableError([
{ port: 11001, result: { available: false, code: 'EADDRINUSE', message: 'address already in use' } },
{ port: 12002, result: { available: false, code: 'EPERM', message: 'operation not permitted' } },
]).message;
expect(message).toContain('Cannot bind localhost ports after 2 attempts');
expect(message).toContain('Last error: 12002 (EPERM: operation not permitted)');
expect(message).toContain('not that every sampled port is occupied');
expect(message).toContain('set BROWSE_PORT to an approved port');
});
test('random port diagnostic preserves old busy-port meaning when all attempts are occupied', () => {
const message = __testInternals__.formatRandomPortUnavailableError([
{ port: 11001, result: { available: false, code: 'EADDRINUSE', message: 'address already in use' } },
{ port: 12002, result: { available: false, code: 'EADDRINUSE', message: 'address already in use' } },
]).message;
expect(message).toContain('No available port after 5 attempts');
expect(message).toContain('every sampled port was already in use');
});
test('isPortAvailable returns true for a free port', async () => {
// Use the same isPortAvailable logic from server.ts
+37 -5
View File
@@ -41,9 +41,16 @@ afterEach(() => {
describe('gstack-config', () => {
// ─── get ──────────────────────────────────────────────────
test('get on missing file returns empty, exit 0', () => {
test('get on missing file returns the default, exit 0', () => {
// auto_upgrade has a default of false; get falls back to the defaults table.
const { exitCode, stdout } = run(['get', 'auto_upgrade']);
expect(exitCode).toBe(0);
expect(stdout).toBe('false');
});
test('get unknown key on missing file returns empty, exit 0', () => {
const { exitCode, stdout } = run(['get', 'some_unknown_key']);
expect(exitCode).toBe(0);
expect(stdout).toBe('');
});
@@ -110,10 +117,12 @@ describe('gstack-config', () => {
expect(stdout).toContain('update_check: false');
});
test('list on missing file returns empty, exit 0', () => {
test('list on missing file shows defaults, exit 0', () => {
// list prints the active-values block with defaults for unset keys.
const { exitCode, stdout } = run(['list']);
expect(exitCode).toBe(0);
expect(stdout).toBe('');
expect(stdout).toContain('proactive:');
expect(stdout).toContain('(default)');
});
// ─── usage ────────────────────────────────────────────────
@@ -151,6 +160,29 @@ describe('gstack-config', () => {
expect(content).toContain('skip_eng_review:');
});
// ─── codex_reviews (paid-calls switch: reject-on-set, preserve existing) ──
test('codex_reviews defaults to enabled', () => {
const { exitCode, stdout } = run(['get', 'codex_reviews']);
expect(exitCode).toBe(0);
expect(stdout).toBe('enabled');
});
test('codex_reviews accepts enabled and disabled', () => {
expect(run(['set', 'codex_reviews', 'disabled']).exitCode).toBe(0);
expect(run(['get', 'codex_reviews']).stdout).toBe('disabled');
expect(run(['set', 'codex_reviews', 'enabled']).exitCode).toBe(0);
expect(run(['get', 'codex_reviews']).stdout).toBe('enabled');
});
test('codex_reviews rejects an invalid value and preserves the existing one', () => {
run(['set', 'codex_reviews', 'disabled']);
const { exitCode, stderr } = run(['set', 'codex_reviews', 'disabledd']);
expect(exitCode).not.toBe(0); // rejected, not warn-and-default
expect(stderr).toContain('not recognized');
// existing value must be untouched — a typo never silently flips paid Codex on/off
expect(run(['get', 'codex_reviews']).stdout).toBe('disabled');
});
test('header written only once, not duplicated on second set', () => {
run(['set', 'foo', 'bar']);
run(['set', 'baz', 'qux']);
@@ -176,9 +208,9 @@ describe('gstack-config', () => {
});
// ─── routing_declined ──────────────────────────────────────
test('routing_declined defaults to empty (not set)', () => {
test('routing_declined defaults to false (not set)', () => {
const { stdout } = run(['get', 'routing_declined']);
expect(stdout).toBe('');
expect(stdout).toBe('false');
});
test('routing_declined can be set and read', () => {
+247
View File
@@ -0,0 +1,247 @@
import { describe, test, expect } from 'bun:test';
import { formatBytes, type MemorySnapshot, type MemoryStructureStats } from '../src/memory-snapshot';
// Unit coverage for the $B memory diagnostic surface — formatter, byte
// renderer, and the structures-stats aggregator. The integration path
// ($B memory through the BrowserManager → CDP) requires a real headless
// Chromium and is covered indirectly by browse-basic in the eval suite.
// These tests pin the renderer logic in isolation so format regressions
// (rounded GB drift, missing "and N more" tail, snapshot.notes ordering)
// surface immediately.
// ─── formatBytes() ─────────────────────────────────────────────
describe('formatBytes', () => {
test('1. < 1 KB renders as bytes', () => {
expect(formatBytes(0)).toBe('0 B');
expect(formatBytes(1)).toBe('1 B');
expect(formatBytes(1023)).toBe('1023 B');
});
test('2. KB tier (1024 ... 1024^2-1)', () => {
expect(formatBytes(1024)).toBe('1.0 KB');
expect(formatBytes(1536)).toBe('1.5 KB');
expect(formatBytes(1024 * 1024 - 1)).toMatch(/^1024\.0 KB$|^1023\.\d KB$/);
});
test('3. MB tier', () => {
expect(formatBytes(1024 * 1024)).toBe('1.0 MB');
expect(formatBytes(312 * 1024 * 1024)).toBe('312.0 MB');
});
test('4. GB tier renders with 2 decimals', () => {
expect(formatBytes(1024 * 1024 * 1024)).toBe('1.00 GB');
expect(formatBytes(1.4 * 1024 * 1024 * 1024)).toMatch(/^1\.40 GB$/);
// 160.61 GB — the friend's OOM number from the original screenshot.
// Verify the renderer doesn't blow up at the actual leak scale.
const big = 160.61 * 1024 * 1024 * 1024;
expect(formatBytes(big)).toMatch(/^160\.6\d GB$/);
});
test('5. negative input behavior — coerces to bytes path (best-effort, do not throw)', () => {
// Diagnostic should never crash on a weird CDP reading; render
// something reasonable.
expect(() => formatBytes(-1)).not.toThrow();
});
});
// ─── handleMemoryCommand text + json output ────────────────────
// Build a minimal MemorySnapshot fixture exercising every render branch.
// This is what bm.getMemorySnapshot would return; we stub the BrowserManager
// so the test never spins up real Chromium.
function makeStructureStats(): MemoryStructureStats {
return {
modificationHistory: { current: 42, cap: 200, evicted: 0 },
activitySubscribers: 1,
inspectorSubscribers: 0,
consoleBufferLen: 1842,
networkBufferLen: 12000,
dialogBufferLen: 3,
captureBufferBytes: 0,
};
}
function makeSnapshot(overrides: Partial<MemorySnapshot> = {}): MemorySnapshot {
return {
bunServer: {
rss: 312 * 1024 * 1024,
heapUsed: 84 * 1024 * 1024,
heapTotal: 120 * 1024 * 1024,
external: 21 * 1024 * 1024,
},
tabs: [],
processes: null,
structures: makeStructureStats(),
capturedAt: 1700000000000,
notes: [],
...overrides,
};
}
// Mock BrowserManager surface for handleMemoryCommand. Only
// getMemorySnapshot is touched.
function makeFakeBm(snapshot: MemorySnapshot) {
return {
getMemorySnapshot: async (structures: MemoryStructureStats) => ({
...snapshot,
structures,
}),
} as unknown as import('../src/browser-manager').BrowserManager;
}
describe('handleMemoryCommand', () => {
test('6. --json mode emits parseable JSON with bunServer + structures', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const snapshot = makeSnapshot();
const result = await handleMemoryCommand(['--json'], makeFakeBm(snapshot));
const parsed = JSON.parse(result);
expect(parsed.bunServer.rss).toBe(312 * 1024 * 1024);
expect(parsed.structures).toBeDefined();
expect(parsed.structures.modificationHistory.cap).toBe(200);
});
test('7. text mode renders Bun server line with RSS + heap', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const result = await handleMemoryCommand([], makeFakeBm(makeSnapshot()));
expect(result).toContain('Bun server:');
expect(result).toContain('312.0 MB');
expect(result).toContain('84.0 MB');
});
test('8. text mode renders "no tabs tracked" when tabs array is empty', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const result = await handleMemoryCommand([], makeFakeBm(makeSnapshot({ tabs: [] })));
expect(result).toContain('Renderers:');
expect(result).toContain('(no tabs tracked)');
});
test('9. text mode shows top 10 tabs + "...and N more" tail when > 10', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const tabs = Array.from({ length: 15 }, (_, i) => ({
id: i,
url: `https://example.com/tab${i}`,
title: `Tab ${i}`,
jsHeapUsed: (15 - i) * 50 * 1024 * 1024, // descending so sort matters
jsHeapTotal: (15 - i) * 60 * 1024 * 1024,
documents: 1,
nodes: 100,
listeners: 10,
}));
const result = await handleMemoryCommand([], makeFakeBm(makeSnapshot({ tabs })));
expect(result).toContain('Renderers: 15 tabs');
expect(result).toContain('and 5 more');
// Sorted by JS heap descending — tab 0 (largest) should appear before tab 9
expect(result.indexOf('tab #0 —')).toBeLessThan(result.indexOf('tab #9 —'));
});
test('10. text mode renders Chromium processes grouped by type', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const snapshot = makeSnapshot({
processes: [
{ id: 1, type: 'browser', cpuTime: 1.5 },
{ id: 2, type: 'renderer', cpuTime: 3.2 },
{ id: 3, type: 'renderer', cpuTime: 2.1 },
{ id: 4, type: 'gpu', cpuTime: 0.5 },
],
});
const result = await handleMemoryCommand([], makeFakeBm(snapshot));
expect(result).toContain('Chromium processes: 4 total');
expect(result).toContain('renderer=2');
expect(result).toContain('browser=1');
expect(result).toContain('gpu=1');
});
test('11. text mode renders "unavailable" line when processes is null', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const result = await handleMemoryCommand([], makeFakeBm(makeSnapshot({ processes: null })));
expect(result).toContain('Chromium processes: (unavailable — see notes)');
});
test('12. text mode renders modificationHistory with evicted-count when > 0', async () => {
// formatSnapshotText is what we're really testing here — exercise it
// directly with a known snapshot so the live collectStructureStats
// doesn't override the fixture values.
const mod = await import('../src/memory-command');
// formatSnapshotText is private; reach via re-rendering through
// --json mode then visually validating the JSON shape. The text-mode
// renderer is exercised by test 13 below with live (zero) values.
const stats = makeStructureStats();
stats.modificationHistory = { current: 200, cap: 200, evicted: 47 };
// Synthesize a "would-render" snapshot to assert the eviction note shape.
const renderedExpected =
'modificationHistory: 200 / 200 entries (47 evicted since reset)';
// Since formatSnapshotText isn't exported, validate the format
// contract by re-implementing the line and asserting our expectation
// matches the canonical format. This pins the user-visible string
// shape — a renderer change to drop the "evicted since reset" suffix
// would fail this assertion.
const evicted = stats.modificationHistory.evicted;
const current = stats.modificationHistory.current;
const cap = stats.modificationHistory.cap;
const expected =
`modificationHistory: ${current} / ${cap} entries` +
(evicted > 0 ? ` (${evicted} evicted since reset)` : '');
expect(expected).toBe(renderedExpected);
void mod;
});
test('13. text mode renders modificationHistory line shape', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const result = await handleMemoryCommand([], makeFakeBm(makeSnapshot()));
// collectStructureStats reads live module state; values may be 0 in
// the test env. Verify the LINE SHAPE rather than specific numbers.
expect(result).toMatch(/modificationHistory:\s+\d+ \/ \d+ entries/);
});
test('14. text mode prints notes section when notes are present', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const snapshot = makeSnapshot({
notes: ['Per-Chromium-process RSS not collected — CDP limitation.'],
});
const result = await handleMemoryCommand([], makeFakeBm(snapshot));
expect(result).toContain('Notes:');
expect(result).toContain('CDP limitation.');
});
test('15. text mode omits notes section when notes is empty', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const result = await handleMemoryCommand([], makeFakeBm(makeSnapshot({ notes: [] })));
expect(result).not.toContain('Notes:');
});
test('16. text mode truncates long tab URLs with ellipsis', async () => {
const { handleMemoryCommand } = await import('../src/memory-command');
const longUrl = 'https://example.com/' + 'a'.repeat(120);
const tabs = [{
id: 1,
url: longUrl,
title: 'long',
jsHeapUsed: 1024,
jsHeapTotal: 2048,
documents: 1,
nodes: 10,
listeners: 1,
}];
const result = await handleMemoryCommand([], makeFakeBm(makeSnapshot({ tabs })));
expect(result).toContain('...');
// The truncated URL appears, the full URL does not
expect(result.includes(longUrl)).toBe(false);
});
});
// ─── buildMemorySnapshotJson — server-endpoint entry ──────────
describe('buildMemorySnapshotJson', () => {
test('17. returns the snapshot with structures populated', async () => {
const { buildMemorySnapshotJson } = await import('../src/memory-command');
const snapshot = makeSnapshot();
const result = await buildMemorySnapshotJson(makeFakeBm(snapshot));
expect(result.bunServer.rss).toBe(snapshot.bunServer.rss);
expect(result.structures.modificationHistory.cap).toBe(200);
// structures is populated from live module accessors, not from the
// fixture. Just assert the shape is right.
expect(typeof result.structures.consoleBufferLen).toBe('number');
expect(typeof result.structures.networkBufferLen).toBe('number');
});
});
+132
View File
@@ -0,0 +1,132 @@
import { describe, test, expect } from 'bun:test';
import { BrowserManager } from '../src/browser-manager';
import { networkBuffer } from '../src/buffers';
// Reproducer for the body-materialization leak fixed in the D10
// USE_CDP_EVENT_BATCHED commit. Pre-fix, the wirePageEvents
// `requestfinished` listener called `await res.body()` just to read
// `.length`, allocating the full response body into a Bun Buffer on
// every request — multi-GB/hour of churn on long-lived headed
// Chromium with media-heavy pages.
//
// What this test pins:
// - The handler calls Playwright's structured req.sizes() API
// (which pulls from Network.loadingFinished without
// materializing the body).
// - The handler NEVER calls res.body(), even though a fake response
// exposes the method.
// - networkBuffer entries are still populated with the right size.
//
// What this test does NOT cover:
// - A real Chromium burst measuring peak Bun RSS during concurrent
// fetches. That's a periodic-tier test (browse/test/
// memory-leak-reproducer-e2e.test.ts, deferred — see TODOS).
// - Per-tab JS heap growth on the Chromium side. Outside Bun's
// visibility entirely.
//
// Wall clock target: < 1 second. Gate tier.
interface CallCounters {
sizes: number;
body: number;
}
function makeFakeReq(url: string, responseBodySize: number, counters: CallCounters) {
return {
url: () => url,
sizes: async () => {
counters.sizes++;
return {
requestBodySize: 0,
requestHeadersSize: 100,
responseBodySize,
responseHeadersSize: 200,
};
},
method: () => 'GET',
response: async () => ({
url: () => url,
status: () => 200,
body: async () => {
// If THIS runs, the leak is back. Allocate a real Buffer so a
// future reviewer reading the failing assertion sees what
// pre-fix code was doing on every request.
counters.body++;
return Buffer.alloc(responseBodySize);
},
}),
};
}
interface ListenerMap {
[event: string]: Array<(arg: unknown) => void>;
}
function makeFakePage() {
const listeners: ListenerMap = {};
return {
on(event: string, fn: (arg: unknown) => void): void {
(listeners[event] ||= []).push(fn);
},
emit(event: string, arg: unknown): void {
for (const fn of listeners[event] || []) fn(arg);
},
listenerCount(event: string): number {
return (listeners[event] || []).length;
},
};
}
describe('memory-leak reproducer: requestfinished does not materialize bodies', () => {
test('burst of 200 requestfinished events calls req.sizes() but never res.body()', async () => {
const bm = new BrowserManager();
const page = makeFakePage();
// wirePageEvents is private — access via the same indexed pattern the
// tab-guardrail test uses to drive private methods.
const wirePageEvents = (
bm as unknown as { wirePageEvents: (p: unknown) => void }
).wirePageEvents.bind(bm);
wirePageEvents(page);
// Seed networkBuffer with 200 request entries via the existing
// page.on('request') handler so the requestfinished backward-scan
// has something to match against.
const startLen = networkBuffer.length;
for (let i = 0; i < 200; i++) {
page.emit('request', {
url: () => `https://example.invalid/asset/${i}`,
method: () => 'GET',
});
}
// Fire 200 requestfinished events concurrently. Each notional response
// is 1 MB — pre-fix this would allocate 200 MB of Buffer. With the fix,
// not one byte of body content is allocated.
const counters: CallCounters = { sizes: 0, body: 0 };
const reqs = Array.from({ length: 200 }, (_, i) =>
makeFakeReq(`https://example.invalid/asset/${i}`, 1024 * 1024, counters),
);
for (const req of reqs) page.emit('requestfinished', req);
// Drain the async handler chain — wirePageEvents.requestfinished is
// async; each emit kicks off a microtask that awaits req.sizes().
await new Promise((r) => setTimeout(r, 50));
// One more tick in case of cascading microtasks.
await new Promise((r) => setTimeout(r, 0));
// Every event hit req.sizes().
expect(counters.sizes).toBeGreaterThanOrEqual(200);
// The actual leak fix: res.body() is NEVER called.
expect(counters.body).toBe(0);
// And the size data still made it into networkBuffer.
const populated = Array.from({ length: networkBuffer.length }, (_, i) =>
networkBuffer.get(i),
)
.filter((e) => e && e.url?.startsWith('https://example.invalid/asset/'))
.filter((e) => typeof e?.size === 'number' && e.size > 0).length;
expect(populated).toBeGreaterThanOrEqual(200);
// Sanity: the seed didn't double-count from a previous run.
expect(networkBuffer.length).toBeGreaterThan(startLen);
});
});
+76
View File
@@ -0,0 +1,76 @@
/**
* Tests for the /pty-inject-scan endpoint (#1370).
*
* Verifies the endpoint's invariants without spinning a real browse
* server: auth required, tunnel-listener denial, payload cap, JSON
* shape, and the local-only routing rule (NOT in TUNNEL_PATHS).
*
* Full integration with a live sidecar + Chromium is exercised by the
* existing browser security suite; this file covers the static + unit
* invariants codex's plan review specifically called out.
*/
import { describe, test, expect } from 'bun:test';
import { readFileSync } from 'fs';
import { join } from 'path';
const SERVER_SRC = readFileSync(
join(import.meta.dir, '..', 'src', 'server.ts'),
'utf-8',
);
describe('/pty-inject-scan — server.ts static invariants', () => {
test('endpoint is defined as a POST handler', () => {
expect(SERVER_SRC).toContain(
"url.pathname === '/pty-inject-scan' && req.method === 'POST'",
);
});
test('endpoint requires auth (validateAuth gate)', () => {
// Find the endpoint block, verify it calls validateAuth before doing
// any work.
const start = SERVER_SRC.indexOf("'/pty-inject-scan'");
expect(start).toBeGreaterThan(-1);
const blockEnd = SERVER_SRC.indexOf("\n // ─", start);
const block = SERVER_SRC.slice(start, blockEnd > start ? blockEnd : start + 5000);
expect(block).toContain('validateAuth(req)');
expect(block).toContain('401');
});
test('endpoint caps payload at 64KB', () => {
const start = SERVER_SRC.indexOf("'/pty-inject-scan'");
const block = SERVER_SRC.slice(start, start + 5000);
expect(block).toContain('64 * 1024');
expect(block).toContain('payload-too-large');
expect(block).toContain('413');
});
test('endpoint is NOT in the tunnel listener allowlist', () => {
const tunnelBlockStart = SERVER_SRC.indexOf('const TUNNEL_PATHS = new Set<string>([');
expect(tunnelBlockStart).toBeGreaterThan(-1);
const tunnelBlockEnd = SERVER_SRC.indexOf(']);', tunnelBlockStart);
const tunnelAllowlist = SERVER_SRC.slice(tunnelBlockStart, tunnelBlockEnd);
expect(tunnelAllowlist).not.toContain('/pty-inject-scan');
});
test('response goes through sanitizeReplacer (Unicode egress hardening)', () => {
const start = SERVER_SRC.indexOf("'/pty-inject-scan'");
const block = SERVER_SRC.slice(start, start + 5000);
expect(block).toContain('sanitizeReplacer');
});
test('endpoint surfaces l4 availability shape for D7 degrade-to-WARN path', () => {
const start = SERVER_SRC.indexOf("'/pty-inject-scan'");
const block = SERVER_SRC.slice(start, start + 5000);
expect(block).toContain('isSidecarAvailable');
expect(block).toContain('available');
});
test('endpoint uses the sidecar client, not direct security-classifier import', () => {
// Static check that server.ts imports from security-sidecar-client.ts,
// NOT from security-classifier.ts directly (would brick the compiled
// binary per CLAUDE.md).
expect(SERVER_SRC).toContain("from './security-sidecar-client'");
expect(SERVER_SRC).not.toContain("from './security-classifier'");
});
});
+98
View File
@@ -0,0 +1,98 @@
import { describe, test, expect, beforeEach } from 'bun:test';
// pty-session-lease registers a sessionId space distinct from the pre-v1.44
// attach-token space (browse/src/pty-session-cookie.ts). These tests pin
// the validate-first contract that codex outside-voice flagged as critical:
// refreshLease MUST NOT resurrect expired leases, otherwise the 30-min TTL
// stops bounding leaked-token blast radius.
import {
mintLease,
validateLease,
refreshLease,
revokeLease,
leaseCount,
__resetLeases,
} from '../src/pty-session-lease';
beforeEach(() => {
__resetLeases();
});
describe('pty-session-lease: mint/validate/revoke', () => {
test('mintLease returns a fresh non-secret sessionId + future expiresAt', () => {
const a = mintLease();
const b = mintLease();
expect(a.sessionId).toBeTruthy();
expect(b.sessionId).toBeTruthy();
expect(a.sessionId).not.toBe(b.sessionId);
expect(a.expiresAt).toBeGreaterThan(Date.now());
// base64url alphabet: characters in [A-Za-z0-9_-].
expect(a.sessionId).toMatch(/^[A-Za-z0-9_-]+$/);
expect(leaseCount()).toBe(2);
});
test('validateLease ok for fresh lease, false for unknown', () => {
const { sessionId } = mintLease();
const ok = validateLease(sessionId);
expect(ok.ok).toBe(true);
if (ok.ok) expect(ok.expiresAt).toBeGreaterThan(Date.now());
expect(validateLease('not-a-real-session-id').ok).toBe(false);
expect(validateLease(null).ok).toBe(false);
expect(validateLease(undefined).ok).toBe(false);
});
test('revokeLease removes the lease; subsequent validate returns false', () => {
const { sessionId } = mintLease();
expect(validateLease(sessionId).ok).toBe(true);
revokeLease(sessionId);
expect(validateLease(sessionId).ok).toBe(false);
expect(leaseCount()).toBe(0);
});
test('revokeLease tolerates unknown sessionId without throwing', () => {
expect(() => revokeLease('phantom')).not.toThrow();
expect(() => revokeLease(null)).not.toThrow();
});
});
describe('pty-session-lease: refresh contract (validate-first)', () => {
test('refreshLease extends expiresAt for a valid lease', () => {
const { sessionId, expiresAt: initial } = mintLease();
// Sleep micro-tick — Date.now() is ms-grain so a synchronous extend
// may not move the integer. Use a tight async wait instead.
return new Promise<void>((resolve) => {
setTimeout(() => {
const r = refreshLease(sessionId);
expect(r.ok).toBe(true);
if (r.ok) expect(r.expiresAt).toBeGreaterThan(initial);
resolve();
}, 5);
});
});
test('refreshLease rejects unknown sessionId (validate-first invariant)', () => {
const r = refreshLease('never-minted');
expect(r.ok).toBe(false);
});
test('refreshLease never resurrects an expired lease', async () => {
// Force TTL down to 5ms for this assertion by minting + waiting past expiry.
// Lease internals use Date.now() so the easiest way to expire one is
// to artificially backdate via revoke+remint cycle. Simpler: mint, then
// wait for the registry's own expiry check to trip.
//
// We can't backdate without breaking encapsulation, so this test exercises
// the negative-validate path: minted lease, then prove that refresh after
// explicit revoke still returns ok:false (same as expired-and-pruned).
const { sessionId } = mintLease();
revokeLease(sessionId);
const r = refreshLease(sessionId);
expect(r.ok).toBe(false);
});
test('refreshLease tolerates null / undefined sessionId', () => {
expect(refreshLease(null).ok).toBe(false);
expect(refreshLease(undefined).ok).toBe(false);
});
});
@@ -0,0 +1,83 @@
/**
* Regression test for PR #1169 bug #7 — `pdf --from-file` ran JSON.parse on
* user-supplied file contents with no try/catch. A malformed payload crashed
* the pdf handler with a raw SyntaxError. Codex flagged that JSON.parse
* accepts primitives too (numbers, strings, null) and Array.isArray must be
* checked separately, so the fix added an explicit object-shape gate.
*
* Test surface: parsePdfFromFile, exported for tests at meta-commands.ts:139.
* All fixtures land in process.cwd() (SAFE_DIRECTORIES allows TEMP_DIR or cwd;
* cwd is universally safe on every platform our CI runs on).
*/
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
import { parsePdfFromFile } from "../src/meta-commands";
const FIXTURE_DIR = fs.mkdtempSync(path.join(process.cwd(), "pr1169-pdf-"));
beforeAll(() => {
// mkdtempSync already created the dir
});
afterAll(() => {
fs.rmSync(FIXTURE_DIR, { recursive: true, force: true });
});
function writeFixture(name: string, body: string): string {
const p = path.join(FIXTURE_DIR, name);
fs.writeFileSync(p, body);
return p;
}
describe("parsePdfFromFile — invalid JSON regression (PR #1169 bug #7)", () => {
test("invalid JSON: throws with file path AND parser detail", () => {
const p = writeFixture("invalid.json", "{ not-json");
expect(() => parsePdfFromFile(p)).toThrow(/not valid JSON/);
expect(() => parsePdfFromFile(p)).toThrow(p);
});
test("empty file: throws JSON-parse style error", () => {
const p = writeFixture("empty.json", "");
// Empty string is invalid JSON per ECMA-404.
expect(() => parsePdfFromFile(p)).toThrow(/not valid JSON/);
});
test("top-level array: throws 'must be a JSON object' with type", () => {
const p = writeFixture("array.json", JSON.stringify(["a", "b"]));
expect(() => parsePdfFromFile(p)).toThrow(/must be a JSON object/);
expect(() => parsePdfFromFile(p)).toThrow(/array/);
});
test("top-level number: throws with 'number' type label", () => {
const p = writeFixture("number.json", "42");
expect(() => parsePdfFromFile(p)).toThrow(/must be a JSON object/);
expect(() => parsePdfFromFile(p)).toThrow(/number/);
});
test("top-level string: throws with 'string' type label", () => {
const p = writeFixture("string.json", JSON.stringify("hello"));
expect(() => parsePdfFromFile(p)).toThrow(/must be a JSON object/);
expect(() => parsePdfFromFile(p)).toThrow(/string/);
});
test("top-level null: throws with 'object' type label (JS null typeof === object)", () => {
const p = writeFixture("null.json", "null");
// null passes typeof === 'object' but the fix's `=== null` branch catches it.
expect(() => parsePdfFromFile(p)).toThrow(/must be a JSON object/);
});
test("top-level boolean: throws with 'boolean' type label", () => {
const p = writeFixture("bool.json", "true");
expect(() => parsePdfFromFile(p)).toThrow(/must be a JSON object/);
expect(() => parsePdfFromFile(p)).toThrow(/boolean/);
});
test("valid object: parses successfully (happy-path regression)", () => {
const p = writeFixture("valid.json", JSON.stringify({ format: "A4", pageNumbers: true }));
const result = parsePdfFromFile(p);
expect(result.format).toBe("A4");
expect(result.pageNumbers).toBe(true);
});
});
+39
View File
@@ -0,0 +1,39 @@
import { describe, test, expect } from "bun:test";
import { buildRestartEnv } from "../src/cli";
// #1781: an auto-restart triggered by a plain command (no --headed flag) must
// NOT silently downgrade a headed session to headless. buildRestartEnv reapplies
// headed/proxy/configHash from this invocation OR the persisted server state.
describe("buildRestartEnv (#1781 headed persistence)", () => {
const headedState = { pid: 1, port: 9, token: "t", startedAt: "", serverPath: "", mode: "headed" as const };
const launchedState = { pid: 1, port: 9, token: "t", startedAt: "", serverPath: "", mode: "launched" as const };
test("headed flag on this invocation → BROWSE_HEADED=1", () => {
expect(buildRestartEnv({ headed: true } as any, null).BROWSE_HEADED).toBe("1");
});
test("plain command + persisted headed state → still BROWSE_HEADED=1 (the regression)", () => {
const env = buildRestartEnv({} as any, headedState as any);
expect(env.BROWSE_HEADED).toBe("1");
});
test("plain command + headless state → no BROWSE_HEADED (no spurious headed)", () => {
const env = buildRestartEnv({} as any, launchedState as any);
expect(env.BROWSE_HEADED).toBeUndefined();
});
test("nothing set → empty env", () => {
expect(buildRestartEnv(null, null)).toEqual({});
});
test("proxy + configHash reapplied from flags", () => {
const env = buildRestartEnv({ proxyUrl: "socks5://x", configHash: "abc" } as any, null);
expect(env.BROWSE_PROXY_URL).toBe("socks5://x");
expect(env.BROWSE_CONFIG_HASH).toBe("abc");
});
test("configHash falls back to persisted state", () => {
const env = buildRestartEnv({} as any, { ...launchedState, configHash: "fromstate" } as any);
expect(env.BROWSE_CONFIG_HASH).toBe("fromstate");
});
});
+118
View File
@@ -0,0 +1,118 @@
/**
* Unit tests for the screenshot size guard (#1214).
*
* Verifies that images exceeding 2000px on the longest dimension get
* downscaled to fit the Anthropic vision API cap, while images already
* inside the cap pass through untouched.
*
* Integration with the three callsites (snapshot.ts, meta-commands.ts,
* write-commands.ts) is exercised by the existing browse E2E suite — we
* don't need to spin up Chromium just to verify the helper. The static
* invariant test below pins that all three callsites import the guard.
*/
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import sharp from 'sharp';
import {
SCREENSHOT_MAX_DIMENSION_PX,
guardScreenshotBuffer,
guardScreenshotPath,
} from '../src/screenshot-size-guard';
let tmp: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), 'screenshot-guard-'));
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
async function makePng(width: number, height: number): Promise<Buffer> {
return sharp({
create: { width, height, channels: 3, background: { r: 200, g: 50, b: 50 } },
})
.png()
.toBuffer();
}
describe('guardScreenshotBuffer', () => {
test('passes through images already within the cap', async () => {
const input = await makePng(1500, 1800);
const { buffer, result } = await guardScreenshotBuffer(input);
expect(result.resized).toBe(false);
expect(result.width).toBe(1500);
expect(result.height).toBe(1800);
expect(buffer).toBe(input); // identity — no re-encode
});
test('downscales a 5000px-tall image to fit the cap', async () => {
const input = await makePng(1200, 5000);
const { buffer, result } = await guardScreenshotBuffer(input);
expect(result.resized).toBe(true);
expect(result.originalHeight).toBe(5000);
expect(Math.max(result.width, result.height)).toBeLessThanOrEqual(
SCREENSHOT_MAX_DIMENSION_PX,
);
// Aspect ratio preserved.
expect(result.height / result.width).toBeCloseTo(5000 / 1200, 1);
// Buffer is a different (smaller) PNG.
expect(buffer.length).toBeLessThan(input.length);
});
test('downscales a 6000px-wide image', async () => {
const input = await makePng(6000, 1200);
const { buffer, result } = await guardScreenshotBuffer(input);
expect(result.resized).toBe(true);
expect(result.originalWidth).toBe(6000);
expect(Math.max(result.width, result.height)).toBeLessThanOrEqual(
SCREENSHOT_MAX_DIMENSION_PX,
);
expect(buffer.length).toBeGreaterThan(0);
});
test('treats exactly-2000px images as in-bounds (no resize)', async () => {
const input = await makePng(2000, 1000);
const { result } = await guardScreenshotBuffer(input);
expect(result.resized).toBe(false);
});
});
describe('guardScreenshotPath', () => {
test('rewrites the file in place when downscale is needed', async () => {
const filePath = join(tmp, 'tall.png');
writeFileSync(filePath, await makePng(1200, 5000));
const result = await guardScreenshotPath(filePath);
expect(result.resized).toBe(true);
const written = readFileSync(filePath);
const meta = await sharp(written).metadata();
expect(Math.max(meta.width ?? 0, meta.height ?? 0)).toBeLessThanOrEqual(
SCREENSHOT_MAX_DIMENSION_PX,
);
});
test('leaves the file untouched when already within cap', async () => {
const filePath = join(tmp, 'short.png');
const original = await makePng(800, 600);
writeFileSync(filePath, original);
const result = await guardScreenshotPath(filePath);
expect(result.resized).toBe(false);
const written = readFileSync(filePath);
expect(written.equals(original)).toBe(true);
});
});
describe('static invariant: all three full-page callsites import the guard', () => {
test('snapshot.ts, meta-commands.ts, and write-commands.ts wire the size guard', () => {
const browseSrc = join(import.meta.dir, '..', 'src');
const paths = ['snapshot.ts', 'meta-commands.ts', 'write-commands.ts'];
for (const rel of paths) {
const content = readFileSync(join(browseSrc, rel), 'utf-8');
expect(content).toContain('screenshot-size-guard');
}
});
});
@@ -0,0 +1,138 @@
/**
* Regression test for PR #1169 bug #6 — downloadFile opened a WriteStream to
* `<dest>.tmp.<pid>` but never closed it on error paths. If the reader or
* writer threw mid-download, the FD leaked and the half-written tmp could
* be promoted by a retry's renameSync.
*
* The fix wraps the read loop in try/catch and runs `writer.destroy()` +
* `fs.unlinkSync(tmp)` before rethrowing.
*
* Per codex's pushback, this test must exercise BOTH the reader-throws path
* and the non-2xx-response path, and it must NOT assume the specific tmp
* filename — only that no `<dest>.tmp.*` sibling remains.
*/
import { describe, expect, test, beforeAll, afterAll, beforeEach, afterEach } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
import { downloadFile } from "../src/security-classifier";
function tmpSiblings(destDir: string, destBase: string): string[] {
if (!fs.existsSync(destDir)) return [];
return fs.readdirSync(destDir).filter((f) =>
f.startsWith(destBase + ".tmp.")
);
}
let FIXTURE_DIR = "";
let originalFetch: typeof fetch;
beforeAll(() => {
FIXTURE_DIR = fs.mkdtempSync(path.join(process.cwd(), "pr1169-dl-"));
});
afterAll(() => {
if (FIXTURE_DIR) {
fs.rmSync(FIXTURE_DIR, { recursive: true, force: true });
}
});
beforeEach(() => {
originalFetch = globalThis.fetch;
});
afterEach(() => {
globalThis.fetch = originalFetch;
});
describe("downloadFile error-path cleanup (PR #1169 bug #6)", () => {
test("reader rejects mid-stream: throws, no dest, no tmp sibling left", async () => {
const dest = path.join(FIXTURE_DIR, "reader-fail-model.bin");
const destDir = path.dirname(dest);
const destBase = path.basename(dest);
// Build a ReadableStream that emits one chunk then errors on second pull.
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3, 4]));
},
pull(controller) {
// Second pull triggers the failure path the fix protects against.
controller.error(new Error("simulated mid-stream read failure"));
},
});
// @ts-expect-error — overwrite global fetch for the test
globalThis.fetch = async () =>
new Response(body, { status: 200, statusText: "OK" });
await expect(downloadFile("https://example.com/model.bin", dest)).rejects.toThrow(
/simulated mid-stream read failure/
);
expect(fs.existsSync(dest)).toBe(false);
expect(tmpSiblings(destDir, destBase)).toEqual([]);
});
test("non-2xx response: throws with status, no tmp file created", async () => {
const dest = path.join(FIXTURE_DIR, "http500-model.bin");
const destDir = path.dirname(dest);
const destBase = path.basename(dest);
// @ts-expect-error — overwrite global fetch for the test
globalThis.fetch = async () =>
new Response("server boom", { status: 500, statusText: "Server Error" });
await expect(downloadFile("https://example.com/model.bin", dest)).rejects.toThrow(
/Failed to fetch.*500/
);
expect(fs.existsSync(dest)).toBe(false);
expect(tmpSiblings(destDir, destBase)).toEqual([]);
});
test("missing body: throws, no tmp file created", async () => {
const dest = path.join(FIXTURE_DIR, "nobody-model.bin");
const destDir = path.dirname(dest);
const destBase = path.basename(dest);
// Response with null body (some upstreams send this on edge errors).
// @ts-expect-error — overwrite global fetch for the test
globalThis.fetch = async () =>
new Response(null, { status: 200, statusText: "OK" });
await expect(downloadFile("https://example.com/model.bin", dest)).rejects.toThrow(
/Failed to fetch/
);
expect(fs.existsSync(dest)).toBe(false);
expect(tmpSiblings(destDir, destBase)).toEqual([]);
});
test("happy path: 2xx body completes, dest exists, no tmp sibling remains", async () => {
const dest = path.join(FIXTURE_DIR, "ok-model.bin");
const destDir = path.dirname(dest);
const destBase = path.basename(dest);
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([9, 9, 9, 9]));
controller.close();
},
});
// @ts-expect-error — overwrite global fetch for the test
globalThis.fetch = async () =>
new Response(body, { status: 200, statusText: "OK" });
await downloadFile("https://example.com/model.bin", dest);
expect(fs.existsSync(dest)).toBe(true);
expect(tmpSiblings(destDir, destBase)).toEqual([]);
const written = fs.readFileSync(dest);
expect(Array.from(written)).toEqual([9, 9, 9, 9]);
fs.unlinkSync(dest);
});
});
@@ -0,0 +1,66 @@
/**
* Unit tests for browse/src/security-sidecar-client.ts.
*
* Tests the IPC client's behavior against a fake sidecar (a tiny Node
* script we spawn) — verifies request/response id correlation, timeout,
* payload cap, malformed-response handling, and circuit-breaker tripping.
*
* Does NOT exercise the real classifier — that lives behind the model
* download and is covered by the existing security-classifier tests + the
* E2E browser security suite.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
let tmp: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "sidecar-client-test-"));
});
afterEach(async () => {
const mod = await import("../src/security-sidecar-client");
mod.resetSidecarForTests();
rmSync(tmp, { recursive: true, force: true });
});
describe("security-sidecar-client — payload cap", () => {
test("rejects requests over 64KB without spawning", async () => {
const { scanWithSidecar } = await import("../src/security-sidecar-client");
const huge = "a".repeat(65 * 1024);
await expect(scanWithSidecar(huge)).rejects.toThrow(/payload-too-large/);
});
});
describe("security-sidecar-client — availability probe", () => {
test("isSidecarAvailable returns a shape regardless of platform", async () => {
const { isSidecarAvailable } = await import("../src/security-sidecar-client");
const result = isSidecarAvailable();
expect(typeof result.available).toBe("boolean");
if (!result.available) {
// When unavailable, reason must explain why
expect(typeof result.reason).toBe("string");
}
});
});
describe("security-sidecar-client — circuit breaker after repeated failures", () => {
test("trips after RESPAWN_LIMIT failures and stays unavailable", async () => {
// We can simulate the breaker tripping by repeatedly calling against an
// invalid sidecar entry. The cleanest way without faking spawn() is to
// exercise the payload-too-large path which doesn't trip the breaker
// (it short-circuits before spawn), so this is an indirect proof:
// verify the timeout path can be exercised by an oversized small text
// and that retries don't crash.
const { scanWithSidecar } = await import("../src/security-sidecar-client");
const oversized = "x".repeat(70 * 1024);
for (let i = 0; i < 5; i += 1) {
await expect(scanWithSidecar(oversized)).rejects.toThrow(/payload-too-large/);
}
// Sentinel — if the loop above silently passed, fail fast.
expect(true).toBe(true);
});
});
+12 -7
View File
@@ -63,13 +63,13 @@ describe('Server auth security', () => {
// Test 4: /activity/history requires auth via validateAuth
test('/activity/history requires authentication', () => {
const historyBlock = sliceBetween(SERVER_SRC, "url.pathname === '/activity/history'", 'Sidebar endpoints');
const historyBlock = sliceBetween(SERVER_SRC, "url.pathname === '/activity/history'", 'Batch endpoint');
expect(historyBlock).toContain('validateAuth');
});
// Test 5: /activity/history has no wildcard CORS header
test('/activity/history has no wildcard CORS header', () => {
const historyBlock = sliceBetween(SERVER_SRC, "url.pathname === '/activity/history'", 'Sidebar endpoints');
const historyBlock = sliceBetween(SERVER_SRC, "url.pathname === '/activity/history'", 'Batch endpoint');
expect(historyBlock).not.toContain("'*'");
});
@@ -314,7 +314,7 @@ describe('Server auth security', () => {
// Regression: connect command crashed with "domains is not defined" because
// a stray `domains,` variable was in the status fetch body (cli.ts:852).
test('connect command status fetch body has no undefined variable references', () => {
const connectBlock = sliceBetween(CLI_SRC, 'Launching headed Chromium', 'Sidebar agent started');
const connectBlock = sliceBetween(CLI_SRC, 'Launching headed Chromium', 'Terminal agent started');
// The status fetch should use a clean JSON body
expect(connectBlock).toContain("command: 'status'");
// Must NOT contain a bare `domains` reference in the fetch body
@@ -335,10 +335,15 @@ describe('Server auth security', () => {
// The connect subprocess env must override BROWSE_PARENT_PID
expect(pairBlock).toContain("BROWSE_PARENT_PID");
expect(pairBlock).toContain("'0'");
// The connect command must propagate BROWSE_PARENT_PID=0 to serverEnv
const connectBlock = sliceBetween(CLI_SRC, 'Launching headed Chromium', 'Sidebar agent started');
expect(connectBlock).toContain("BROWSE_PARENT_PID");
expect(connectBlock).toContain("serverEnv.BROWSE_PARENT_PID");
// The connect command must propagate BROWSE_PARENT_PID=0 via the
// serverEnv object literal passed to startServer. The literal text
// `serverEnv.BROWSE_PARENT_PID` is NOT in source — the value is
// assigned via object-literal syntax (`BROWSE_PARENT_PID: '0'`)
// inside the `const serverEnv: Record<string, string> = { ... }`
// declaration. Assert both pieces appear in the connect block.
const connectBlock = sliceBetween(CLI_SRC, 'Launching headed Chromium', 'Terminal agent started');
expect(connectBlock).toContain("const serverEnv");
expect(connectBlock).toContain("BROWSE_PARENT_PID: '0'");
});
// Regression: newtab returned 403 for scoped tokens because the tab ownership
@@ -0,0 +1,232 @@
import { describe, test, expect, beforeEach, beforeAll, afterAll } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import {
buildFetchHandler,
__resetShuttingDown,
type ServerConfig,
} from '../src/server';
import { __resetRegistry } from '../src/token-registry';
import { BrowserManager } from '../src/browser-manager';
import { resolveConfig } from '../src/config';
// Tests for the v1.41+ ownsTerminalAgent flag.
//
// Embedders (gbrowser phoenix overlay) that run their own PTY server and write
// terminal-port / terminal-internal-token / terminal-agent-pid themselves were
// getting those files clobbered by gstack's shutdown(). The flag (default true)
// gates four side effects (v1.44+):
// 1. identity-based kill of the PID in <stateDir>/terminal-agent-pid
// 2. unlink terminal-port
// 3. unlink terminal-internal-token
// 4. unlink terminal-agent-pid
// False = embedder owns them, gstack stays hands-off.
//
// Pre-v1.44 used `pkill -f terminal-agent\.ts` which matched sibling gstack
// sessions on the same host — see browse/src/terminal-agent-control.ts header.
//
// CRITICAL: each test stubs process.exit (so shutdown's exit doesn't kill
// the test runner). The PID in the test agent-record is a guaranteed-dead
// PID (1 = init / launchd — exists but cannot be killed by an unprivileged
// process, so safeKill returns ESRCH-equivalent without affecting anything).
// Use isProcessAlive's false branch by also testing with a PID that does
// not exist (negative PID rejected by the OS).
const stateDir = resolveConfig().stateDir;
const PORT_FILE = path.join(stateDir, 'terminal-port');
const TOKEN_FILE = path.join(stateDir, 'terminal-internal-token');
const AGENT_RECORD_FILE = path.join(stateDir, 'terminal-agent-pid');
const SENTINEL_PORT = 'sentinel-port-65432';
const SENTINEL_TOKEN = 'sentinel-token-abcdef1234567890';
// PID 2^31-1 is the Linux PID_MAX_LIMIT; macOS uses 99998. Either way, no
// real process will ever hold this PID on a developer machine. isProcessAlive
// returns false → killAgentByRecord no-ops without sending any signal.
const SENTINEL_DEAD_PID = 2147483646;
function makeMinimalConfig(overrides: Partial<ServerConfig> = {}): ServerConfig {
const token = 'embedder-test-' + crypto.randomBytes(16).toString('hex');
return {
authToken: token,
browsePort: 34568,
idleTimeoutMs: 1_800_000,
config: resolveConfig(),
browserManager: new BrowserManager(),
startTime: Date.now(),
...overrides,
};
}
function writeSentinels(): void {
fs.mkdirSync(stateDir, { recursive: true });
fs.writeFileSync(PORT_FILE, SENTINEL_PORT);
fs.writeFileSync(TOKEN_FILE, SENTINEL_TOKEN);
fs.writeFileSync(
AGENT_RECORD_FILE,
JSON.stringify({ pid: SENTINEL_DEAD_PID, gen: 'sentinel-gen', startedAt: Date.now() }),
);
}
function readIfExists(p: string): string | null {
try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
}
/**
* Stubs process.exit so shutdown()'s process.exit(0) throws an __exit:N
* marker the test can swallow instead of killing the runner. Also stubs
* process.kill so an accidental kill (regression in killAgentByRecord
* that bypassed isProcessAlive) cannot reach a real PID on the developer
* machine. Returns the captured kill calls so tests can assert kill
* scope.
*/
async function withStubs(
cb: (killCalls: Array<[number, NodeJS.Signals | number]>) => Promise<void>
): Promise<Array<[number, NodeJS.Signals | number]>> {
const origExit = process.exit;
const origKill = process.kill;
const killCalls: Array<[number, NodeJS.Signals | number]> = [];
(process as any).exit = ((code: number) => {
throw new Error(`__exit:${code}`);
}) as any;
(process as any).kill = ((pid: number, signal: NodeJS.Signals | number) => {
killCalls.push([pid, signal ?? 'SIGTERM']);
// signal 0 is a liveness probe — keep the existing 'process is dead'
// semantics so isProcessAlive(SENTINEL_DEAD_PID) returns false.
if (signal === 0) {
const err: any = new Error('No such process');
err.code = 'ESRCH';
throw err;
}
return true;
}) as any;
try {
await cb(killCalls);
} finally {
(process as any).exit = origExit;
(process as any).kill = origKill;
}
return killCalls;
}
async function runShutdown(handle: { shutdown: (code?: number) => Promise<void> }): Promise<void> {
try {
await handle.shutdown(0);
} catch (err: any) {
if (typeof err?.message !== 'string' || !err.message.startsWith('__exit:')) throw err;
}
}
// Filter out the signal=0 liveness probes; only count actual termination signals.
function terminationCalls(
calls: Array<[number, NodeJS.Signals | number]>,
): Array<[number, NodeJS.Signals | number]> {
return calls.filter(([, sig]) => sig !== 0);
}
describe('buildFetchHandler ownsTerminalAgent gate', () => {
// shutdown() reads `path.dirname(config.stateFile)` from module-level config
// (composition gap — see TODOS T9). So unlinks target the real state dir,
// not a per-test temp dir. If a real gstack daemon is running on this host,
// its terminal-port + terminal-internal-token + terminal-agent-pid live
// where this test writes. Save + restore real-daemon file contents around
// the whole suite so the test never clobbers a developer's running session.
let realPortBackup: string | null = null;
let realTokenBackup: string | null = null;
let realAgentRecordBackup: string | null = null;
beforeAll(() => {
realPortBackup = readIfExists(PORT_FILE);
realTokenBackup = readIfExists(TOKEN_FILE);
realAgentRecordBackup = readIfExists(AGENT_RECORD_FILE);
});
afterAll(() => {
if (realPortBackup !== null) {
fs.mkdirSync(stateDir, { recursive: true });
fs.writeFileSync(PORT_FILE, realPortBackup);
} else {
try { fs.unlinkSync(PORT_FILE); } catch {}
}
if (realTokenBackup !== null) {
fs.mkdirSync(stateDir, { recursive: true });
fs.writeFileSync(TOKEN_FILE, realTokenBackup);
} else {
try { fs.unlinkSync(TOKEN_FILE); } catch {}
}
if (realAgentRecordBackup !== null) {
fs.mkdirSync(stateDir, { recursive: true });
fs.writeFileSync(AGENT_RECORD_FILE, realAgentRecordBackup);
} else {
try { fs.unlinkSync(AGENT_RECORD_FILE); } catch {}
}
});
beforeEach(() => {
__resetRegistry();
__resetShuttingDown();
// Clean any leftover sentinels from a prior failed run so the "preserved"
// assertion can't pass spuriously off a stale file.
try { fs.unlinkSync(PORT_FILE); } catch {}
try { fs.unlinkSync(TOKEN_FILE); } catch {}
try { fs.unlinkSync(AGENT_RECORD_FILE); } catch {}
});
test('1. ownsTerminalAgent:false preserves all three files and sends no signal', async () => {
writeSentinels();
const handle = buildFetchHandler(makeMinimalConfig({ ownsTerminalAgent: false }));
const calls = await withStubs(async () => {
await runShutdown(handle);
});
expect(readIfExists(PORT_FILE)).toBe(SENTINEL_PORT);
expect(readIfExists(TOKEN_FILE)).toBe(SENTINEL_TOKEN);
expect(readIfExists(AGENT_RECORD_FILE)).not.toBeNull();
expect(terminationCalls(calls).length).toBe(0);
});
test('2. ownsTerminalAgent:true deletes all three files; identity-based kill probes the recorded PID', async () => {
writeSentinels();
const handle = buildFetchHandler(makeMinimalConfig({ ownsTerminalAgent: true }));
const calls = await withStubs(async () => {
await runShutdown(handle);
});
expect(readIfExists(PORT_FILE)).toBeNull();
expect(readIfExists(TOKEN_FILE)).toBeNull();
expect(readIfExists(AGENT_RECORD_FILE)).toBeNull();
// isProcessAlive sends signal 0; PID is the sentinel-dead PID, so the
// probe returns false and no SIGTERM is sent.
const probes = calls.filter(([pid, sig]) => pid === SENTINEL_DEAD_PID && sig === 0);
expect(probes.length).toBeGreaterThan(0);
expect(terminationCalls(calls).length).toBe(0);
});
test('3. ownsTerminalAgent unset defaults to true (deletes all three; probes recorded PID)', async () => {
writeSentinels();
// Note: no ownsTerminalAgent in the overrides — uses the `?? true` default.
const handle = buildFetchHandler(makeMinimalConfig());
const calls = await withStubs(async () => {
await runShutdown(handle);
});
expect(readIfExists(PORT_FILE)).toBeNull();
expect(readIfExists(TOKEN_FILE)).toBeNull();
expect(readIfExists(AGENT_RECORD_FILE)).toBeNull();
const probes = calls.filter(([pid, sig]) => pid === SENTINEL_DEAD_PID && sig === 0);
expect(probes.length).toBeGreaterThan(0);
});
test('4. CLI start() call site passes ownsTerminalAgent: true literally (static grep)', () => {
// Resolves browse/src/server.ts relative to this test file so the test
// works regardless of cwd. import.meta.url is the test file's URL.
const serverTsPath = path.resolve(
new URL(import.meta.url).pathname,
'..',
'..',
'src',
'server.ts',
);
const source = fs.readFileSync(serverTsPath, 'utf-8');
// Match the call site inside start()'s buildFetchHandler({...}) literal.
// The pattern looks for the trailing comma and trailing context so the
// match cannot be satisfied by the JSDoc reference earlier in the file.
expect(source).toMatch(/ownsTerminalAgent:\s*true,\s*\/\/\s*CLI spawns terminal-agent\.ts/);
});
});
+142 -1
View File
@@ -1,7 +1,8 @@
import { describe, test, expect, beforeEach } from 'bun:test';
import { describe, test, expect, beforeEach, mock } from 'bun:test';
import {
resolveConfigFromEnv,
buildFetchHandler,
__testInternals__,
type ServerConfig,
type ServerHandle,
type Surface,
@@ -11,6 +12,8 @@ import { __resetRegistry, initRegistry } from '../src/token-registry';
import { BrowserManager } from '../src/browser-manager';
import { resolveConfig } from '../src/config';
import * as crypto from 'crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
/**
* Tests for the factory-export API surface added so gbrowser (phoenix) can
@@ -381,3 +384,141 @@ describe('buildFetchHandler factory contract', () => {
expect(() => initRegistry('second-token-pad-to-16-chars')).toThrow(/already initialized/i);
});
});
// ─── Idle timer + onDisconnect dual-instance fix (v1.42.3.0) ──────────
//
// Before this fix, module-level handlers (idleCheckTick, parent watchdog,
// SIGTERM, onDisconnect default wire) all read the module-level
// BrowserManager directly. For embedders (gbrowser) that pass their own
// BrowserManager into buildFetchHandler, the module-level instance never
// has launchHeaded() called on it — so connectionMode stays 'launched'
// forever and headed mode never short-circuits idle-shutdown. Result:
// 30-min auto-shutdown of overlay sessions.
//
// Fix: introduce `let activeBrowserManager` indirection (symmetric with
// the existing `let activeShutdown` pattern). buildFetchHandler retargets
// it at cfg.browserManager AND chains cfg.browserManager.onDisconnect to
// activeShutdown (without clobbering any caller-provided handler).
function makeMockBrowserManager(mode: 'launched' | 'headed') {
return {
getConnectionMode: () => mode,
isWatching: () => false,
stopWatch: () => {},
close: async () => {},
onDisconnect: null as ((code?: number) => void | Promise<void>) | null,
};
}
describe('idle timer + onDisconnect dual-instance fix', () => {
beforeEach(() => {
__resetRegistry();
// Reset module state every test. Bun memoizes the server.ts module
// import for the whole test process, so `lastActivity`, `tunnelActive`,
// `activeShutdown`, `activeBrowserManager`, and `isShuttingDown` leak
// between tests. We reset what we touch here; the rest is fresh
// because each test calls buildFetchHandler with a new mock instance.
__testInternals__.setTunnelActive(false);
__testInternals__.setLastActivity(Date.now());
__testInternals__.resetShutdownState();
});
test('CRITICAL — REGRESSION: headed embedder does not auto-shutdown at idle', () => {
const exitMock = mock((_code?: number) => { throw new Error('process.exit called'); });
const originalExit = process.exit;
(process as any).exit = exitMock;
try {
const mockBM = makeMockBrowserManager('headed');
buildFetchHandler(makeMinimalConfig({ browserManager: mockBM as any }));
// Drive lastActivity past the idle threshold via the test seam instead
// of mutating Date.now — the leaked module-level setInterval would
// see fake-time and could fire shutdown if the timing aligned.
__testInternals__.setLastActivity(Date.now() - (31 * 60 * 1000));
__testInternals__.idleCheckTick();
expect(exitMock).not.toHaveBeenCalled();
} finally {
(process as any).exit = originalExit;
}
});
test('headless still auto-shuts down at idle (paired defensive)', async () => {
// Non-throwing mock: idleCheckTick fires shutdown as a fire-and-forget
// async call. Throwing from process.exit becomes an unhandled rejection
// that the test runner catches. Recording the call is enough.
const exitMock = mock((_code?: number) => {});
const originalExit = process.exit;
(process as any).exit = exitMock;
try {
const mockBM = makeMockBrowserManager('launched');
buildFetchHandler(makeMinimalConfig({ browserManager: mockBM as any }));
__testInternals__.setLastActivity(Date.now() - (31 * 60 * 1000));
__testInternals__.idleCheckTick();
// Drain microtasks: shutdown awaits flushBuffers + cfgBrowserManager.close
// before reaching process.exit.
await Promise.resolve();
await Promise.resolve();
await new Promise<void>(r => setImmediate(r));
await new Promise<void>(r => setImmediate(r));
expect(exitMock).toHaveBeenCalled();
} finally {
(process as any).exit = originalExit;
}
});
test('buildFetchHandler chains cfgBrowserManager.onDisconnect, preserving caller-set handler', async () => {
const mockBM = makeMockBrowserManager('headed');
const callerCb = mock(async (_code?: number) => {});
mockBM.onDisconnect = callerCb;
buildFetchHandler(makeMinimalConfig({ browserManager: mockBM as any }));
// gstack should have wrapped the caller-installed handler instead of
// clobbering it (Codex finding: BrowserManager.onDisconnect is a public
// field; gbrowser may set it before calling buildFetchHandler).
expect(typeof mockBM.onDisconnect).toBe('function');
expect(mockBM.onDisconnect).not.toBe(callerCb);
// Verify the chain: invoking the wrapped handler runs the caller
// callback AND reaches activeShutdown (which calls process.exit at the
// very end of its async path). Stubbing process.exit to throw aborts
// the chain before isShuttingDown can leak into later tests.
const exitMock = mock((_code?: number) => { throw new Error('process.exit called'); });
const originalExit = process.exit;
(process as any).exit = exitMock;
try {
await expect((mockBM.onDisconnect as any)(0)).rejects.toThrow('process.exit called');
expect(callerCb).toHaveBeenCalledWith(0);
expect(exitMock).toHaveBeenCalledWith(0);
} finally {
(process as any).exit = originalExit;
}
});
test('tunnelActive blocks idle-shutdown even in headless mode', () => {
const exitMock = mock((_code?: number) => { throw new Error('process.exit called'); });
const originalExit = process.exit;
(process as any).exit = exitMock;
try {
const mockBM = makeMockBrowserManager('launched');
buildFetchHandler(makeMinimalConfig({ browserManager: mockBM as any }));
__testInternals__.setTunnelActive(true);
__testInternals__.setLastActivity(Date.now() - (31 * 60 * 1000));
__testInternals__.idleCheckTick();
expect(exitMock).not.toHaveBeenCalled();
} finally {
(process as any).exit = originalExit;
}
});
test('lifecycle handlers (idleCheckTick + parent watchdog + SIGTERM) read activeBrowserManager, not module-level browserManager', () => {
// Static guard against a future refactor reintroducing a stale read.
// The 3 lifecycle sites this plan fixed all call getConnectionMode via
// the indirection. Other module-level browserManager reads inside
// handleCommandInternalImpl (informational mode reporting in response
// payloads) are out of scope and intentionally untouched.
const src = fs.readFileSync(path.join(__dirname, '..', 'src', 'server.ts'), 'utf-8');
const factoryStart = src.indexOf('export function buildFetchHandler');
expect(factoryStart).toBeGreaterThan(0);
const moduleLevel = src.slice(0, factoryStart);
const activeCount = (moduleLevel.match(/activeBrowserManager\.getConnectionMode\(\)/g) || []).length;
// Edit 2 (idleCheckTick), Edit 3 (parent watchdog), Edit 6 (SIGTERM).
expect(activeCount).toBe(3);
});
});
@@ -0,0 +1,94 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// Server-side route shape for the v1.44 lease + restart + dispose +
// lease-refresh wiring. Live route exercises require the terminal-agent
// loopback to be live (e2e-tier); these static-grep tripwires pin the
// load-bearing protocol invariants.
const SERVER_TS = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'server.ts');
describe('server: PTY lease routes (v1.44+ Commit 2)', () => {
test('1. /pty-session returns the 4-tuple shape (sessionId, attachToken, leaseExpiresAt)', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/pty-session' &&", "url.pathname === '/pty-session/reattach'");
expect(block).toContain('mintLease()');
expect(block).toContain('grantPtyToken(minted.token, lease.sessionId)');
expect(block).toContain('sessionId: lease.sessionId');
expect(block).toContain('attachToken: minted.token');
expect(block).toContain('leaseExpiresAt: lease.expiresAt');
// Backward compat: legacy ptySessionToken alias preserved for one release.
expect(block).toContain('ptySessionToken: minted.token');
});
test('2. /pty-session/reattach validates lease + mints fresh attachToken', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/pty-session/reattach'", "url.pathname === '/pty-restart'");
// Validate-first: rejects unknown/expired sessionId with 410 Gone so
// the client knows to fall back to a fresh /pty-session.
expect(block).toContain('validateLease(sessionId)');
expect(block).toContain('status: 410');
// Mint fresh token bound to SAME sessionId.
expect(block).toContain('grantPtyToken(minted.token, sessionId!)');
});
test('3. /pty-restart is one transaction — dispose + revoke + fresh mint', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/pty-restart'", "url.pathname === '/pty-dispose'");
// Disposes old session (best-effort — missing sessionId is non-fatal).
expect(block).toContain('restartPtySession(oldSessionId)');
expect(block).toContain('revokeLease(oldSessionId)');
// Then mints fresh sessionId + lease + attachToken in the same handler.
expect(block).toContain('mintLease()');
expect(block).toContain('grantPtyToken(minted.token, lease.sessionId)');
// Returns the same 4-tuple shape so the client doesn't need a
// separate /pty-session round-trip.
expect(block).toContain('attachToken: minted.token');
expect(block).toContain('leaseExpiresAt: lease.expiresAt');
});
test('4. /pty-dispose accepts body-token (sendBeacon-compatible)', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/pty-dispose'", "url.pathname === '/internal/lease-refresh'");
// sendBeacon can't set custom headers, so the route MUST accept the
// auth token in the request body. Otherwise pagehide cleanup fails
// silently every time the user closes the browser.
expect(block).toContain('body?.authToken');
expect(block).toContain('authedByBody');
// Both auth paths must validate against authToken — never just trust
// a body-supplied token without the equality check.
expect(block).toContain('authTokenFromBody === authToken');
});
test('5. /internal/lease-refresh resets the daemon idle timer (T6)', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/internal/lease-refresh'", '─── /pty-inject-scan');
expect(block).toContain('refreshLease(sessionId)');
expect(block).toContain('resetIdleTimer()');
// Refresh failure (unknown / expired) MUST 410, not 200, so the
// agent knows to close the WS and force a clean re-auth.
expect(block).toContain('status: 410');
});
test('6. grantPtyToken loopback carries sessionId binding', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
expect(src).toMatch(/grantPtyToken\(token: string, sessionId\?: string\)/);
expect(src).toContain('sessionId ? { token, sessionId } : { token }');
});
test('7. restartPtySession helper exists and POSTs the agent /internal/restart', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
expect(src).toMatch(/async function restartPtySession\(sessionId: string\)/);
expect(src).toContain('/internal/restart');
expect(src).toContain('JSON.stringify({ sessionId })');
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
+35 -7
View File
@@ -113,17 +113,45 @@ describe('sanitizeLoneSurrogates — wiring invariants', () => {
expect(SERVER_SRC).toContain('result: sanitizeLoneSurrogates(cr.result)');
});
test('SSE activity feed sanitizes outbound frames via sanitizeReplacer', () => {
// Replacer must run DURING stringify; post-stringify regex is ineffective
// because JSON.stringify converts \uD800 → "\\ud800" before our regex sees it.
expect(SERVER_SRC).toContain('JSON.stringify(entry, sanitizeReplacer)');
test('SSE activity feed routes outbound frames through createSseEndpoint', () => {
// v1.51 refactor: /activity/stream no longer inlines its own
// ReadableStream/sanitizer wiring; it routes through createSseEndpoint
// which applies sanitizeReplacer to every JSON.stringify. The grep
// pins both halves of the contract: the endpoint uses the helper,
// and the helper does the sanitization.
const activityBlock = SERVER_SRC.match(
/if \(url\.pathname === '\/activity\/stream'\)[\s\S]*?createSseEndpoint\(/,
);
expect(activityBlock).not.toBeNull();
});
test('SSE inspector stream sanitizes outbound frames via sanitizeReplacer', () => {
expect(SERVER_SRC).toContain('JSON.stringify(event, sanitizeReplacer)');
test('SSE inspector stream routes outbound frames through createSseEndpoint', () => {
// Same v1.51 refactor invariant for /inspector/events.
const inspectorBlock = SERVER_SRC.match(
/if \(url\.pathname === '\/inspector\/events'[\s\S]*?createSseEndpoint\(/,
);
expect(inspectorBlock).not.toBeNull();
});
test('sanitizeReplacer is a function defined in server.ts', () => {
test('createSseEndpoint applies sanitizeReplacer to every JSON.stringify', () => {
// The helper is the single source of truth for SSE sanitization now.
// If a future refactor moves stringify off the replacer (e.g. someone
// adds a fast-path encode), this test fails and the surrogate-escape
// class regresses across every SSE endpoint at once.
const helperPath = path.resolve(import.meta.dir, '..', 'src', 'sse-helpers.ts');
const helperSrc = fs.readFileSync(helperPath, 'utf-8');
expect(helperSrc).toContain('JSON.stringify(');
expect(helperSrc).toContain('sanitizeReplacer');
// The sanitizer itself uses stripLoneSurrogates (the shared utility in
// sanitize.ts) — not a private copy. Re-confirms the helper is wired
// to the canonical sanitizer, not a drift'd duplicate.
expect(helperSrc).toContain("import { stripLoneSurrogates } from './sanitize'");
});
test('sanitizeReplacer is a function defined in server.ts (for non-SSE egress)', () => {
// server.ts keeps its own sanitizeReplacer for the non-SSE JSON egress
// paths (handleCommandInternal etc.). The SSE path uses sse-helpers.ts's
// own sanitizeReplacer; both must exist independently.
expect(SERVER_SRC).toContain('function sanitizeReplacer(');
});
});
+7 -9
View File
@@ -1589,19 +1589,17 @@ describe('tool calls collapse into reasoning disclosure', () => {
});
// ─── Idle timeout disabled in headed mode (server.ts) ───────────
//
// The original 'idle check skips in headed mode' string-grep test was deleted
// in v1.42.3.0 — it would have passed even with the dual-instance bug present
// because it only grepped for "=== 'headed'" + 'return' in the same window.
// Behavioral coverage lives in browse/test/server-factory.test.ts under the
// 'idle timer + onDisconnect dual-instance fix' describe block, which
// exercises the headed/headless/tunnel branches of idleCheckTick directly.
describe('idle timeout behavior (server.ts)', () => {
const serverSrc = fs.readFileSync(path.join(ROOT, 'src', 'server.ts'), 'utf-8');
test('idle check skips in headed mode', () => {
const idleCheck = serverSrc.slice(
serverSrc.indexOf('idleCheckInterval'),
serverSrc.indexOf('idleCheckInterval') + 300,
);
expect(idleCheck).toContain("=== 'headed'");
expect(idleCheck).toContain('return');
});
test('sidebar-command resets idle timer', () => {
const sidebarCmd = serverSrc.slice(
serverSrc.indexOf("url.pathname === '/sidebar-command'"),
@@ -0,0 +1,70 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// v1.44 patient autoConnect — static-grep invariants for the polling loop.
//
// Pre-v1.44 the sidebar gave up at 15s with "Browse server not ready.
// Reload sidebar to retry." Cold-start the browse server takes ~3-8s on a
// healthy laptop, longer on Conductor workspaces / slow CI, so the user
// frequently saw the failure message even when nothing was wrong. The
// fix: poll forever with ascending status messages and only abort on
// explicit unrecoverable signals (401 auth invalid).
const CLIENT_JS = path.resolve(
new URL(import.meta.url).pathname,
'..',
'..',
'..',
'extension',
'sidepanel-terminal.js',
);
describe('sidepanel tryAutoConnect patience (v1.44+)', () => {
test('1. no 15s give-up message', () => {
const src = fs.readFileSync(CLIENT_JS, 'utf-8');
// The v0.x give-up string must NOT reappear — it's the message users
// saw on every cold start and the whole point of v1.44 was to delete it.
expect(src).not.toContain('Browse server not ready. Reload sidebar to retry.');
});
test('2. ascending status messages at 15s / 60s / 5min', () => {
const src = fs.readFileSync(CLIENT_JS, 'utf-8');
expect(src).toContain('Waiting for browse server...');
expect(src).toContain('Still waiting');
expect(src).toContain('still not responding after 5 min');
});
test('3. sticky abort flag prevents loop spam on 401', () => {
const src = fs.readFileSync(CLIENT_JS, 'utf-8');
expect(src).toContain('autoConnectAborted');
// The mint failure branch must short-circuit on 401 specifically.
expect(src).toMatch(/minted\.error.*startsWith\('401'\)/);
// tryAutoConnect tick must respect the flag.
expect(src).toMatch(/if \(autoConnectAborted\) return/);
});
test('4. forceRestart re-arms the loop by clearing the abort flag', () => {
const src = fs.readFileSync(CLIENT_JS, 'utf-8');
// forceRestart is the user's "try again" escape hatch — must reset
// the sticky flag or 401-once means stuck-forever.
const block = sliceBetween(src, 'function forceRestart', 'function repaintIfLive');
expect(block).toContain('autoConnectAborted = false');
});
test('5. poll interval is 2s, not the legacy 200ms tight loop', () => {
const src = fs.readFileSync(CLIENT_JS, 'utf-8');
// 200ms ticks burned CPU and made the give-up window land too fast.
// 2s is the v1.44 cadence — verify the tight-loop literal is gone.
expect(src).toContain('setTimeout(tick, 2000)');
expect(src).not.toContain('setTimeout(tick, 200)');
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
+93
View File
@@ -0,0 +1,93 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// v1.44 Commit 3 — client-side re-attach loop.
//
// On unexpected WS close (anything other than clean 1000 / 4001 / 4404),
// the sidebar now silently posts /pty-session/reattach with backoff,
// opens a new WS with the fresh attachToken, writes RIS to xterm when
// the agent sends {type:"reattach-begin"}, then treats the next binary
// frame as the scrollback replay payload. Static-grep tripwires defend
// the load-bearing protocol invariants; live re-attach exercises belong
// in the e2e tier.
const TERMINAL_JS = path.resolve(
new URL(import.meta.url).pathname, '..', '..', '..', 'extension', 'sidepanel-terminal.js',
);
describe('sidepanel re-attach loop (v1.44+ Commit 3)', () => {
test('1. STATE.RECONNECTING exists for the in-flight re-attach window', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
expect(src).toContain("RECONNECTING: 'reconnecting'");
});
test('2. backoff schedule matches the eng-review plan (1s/2s/4s/8s, 60s window)', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
expect(src).toContain('REATTACH_BACKOFF_MS = [1000, 2000, 4000, 8000]');
expect(src).toContain('REATTACH_WINDOW_MS = 60_000');
});
test('3. startReattachLoop posts /pty-session/reattach with sessionId', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
expect(src).toMatch(/function startReattachLoop\(prevSessionId\)/);
const block = sliceBetween(src, 'function startReattachLoop', 'function openReattachWebSocket');
expect(block).toContain('/pty-session/reattach');
expect(block).toContain('sessionId: prevSessionId');
});
test('4. 410 Gone from re-attach short-circuits to ENDED (no retry loop)', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
const block = sliceBetween(src, 'function startReattachLoop', 'function openReattachWebSocket');
// 410 = lease window expired. Retrying wouldn't help; fall through
// so the user clicks Restart for a fresh session.
expect(block).toContain('resp.status === 410');
expect(block).toContain('setState(STATE.ENDED)');
});
test('5. 401 from re-attach sticky-aborts auto-connect', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
const block = sliceBetween(src, 'function startReattachLoop', 'function openReattachWebSocket');
expect(block).toContain('resp.status === 401');
expect(block).toContain('autoConnectAborted = true');
});
test('6. openReattachWebSocket handles {type:"reattach-begin"} → RIS to xterm', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
const block = sliceBetween(src, 'function openReattachWebSocket', 'async function checkClaudeAvailable');
expect(block).toContain("msg.type === 'reattach-begin'");
// RIS (\x1bc) is the full-reset escape that clears xterm cleanly
// before the replay binary arrives.
expect(block).toContain("term.write('\\x1bc')");
expect(block).toContain('nextBinaryIsReplay = true');
});
test('7. live connect()/forceRestart() close handlers trigger re-attach on transient close', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
// Both the connect() and forceRestart() close handlers must route
// through startReattachLoop for non-clean codes. Count = 3
// (open-reattach close handler + connect close + forceRestart close).
const occurrences = (src.match(/startReattachLoop\(currentSessionId\)/g) || []).length;
expect(occurrences).toBeGreaterThanOrEqual(3);
});
test('8. clean codes (1000 / 4001 / 4404) bypass the re-attach loop', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
// The branch guard MUST exclude these codes from re-attach. 1000 =
// PTY exited (claude quit), 4001 = intentional restart, 4404 = no
// claude on PATH. Re-attaching in those cases would be wasted work
// (or actively wrong — a force-restart that re-attaches to its own
// pre-restart session is the bug we're avoiding).
expect(src).toContain('code === 1000');
expect(src).toContain('code === 4001');
expect(src).toContain('code === 4404');
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
@@ -0,0 +1,106 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// v1.44 Commit 2C — client-side restart + dispose wiring.
//
// Pre-v1.44 forceRestart only closed the client WS and disposed xterm;
// the old PTY died asynchronously via the agent's WS close handler.
// Race window between kill and mint, two claude instances briefly,
// no prompt visible until the user typed.
//
// Now forceRestart POSTs /pty-restart (one transaction: dispose + mint),
// opens the new WS with the fresh attachToken from the response, and
// sends {type:"start"} for the eager spawn. pagehide handler in
// sidepanel.js sendBeacon /pty-dispose so browser quit / panel close
// doesn't leak a 60s-zombie claude.
const TERMINAL_JS = path.resolve(
new URL(import.meta.url).pathname, '..', '..', '..', 'extension', 'sidepanel-terminal.js',
);
const SIDEPANEL_JS = path.resolve(
new URL(import.meta.url).pathname, '..', '..', '..', 'extension', 'sidepanel.js',
);
describe('sidepanel-terminal: forceRestart via /pty-restart (v1.44+)', () => {
test('1. mintSession callers read the 4-tuple (sessionId + attachToken)', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
// The new shape lands in `minted.sessionId` and `minted.attachToken`.
expect(src).toContain('const { terminalPort, sessionId } = minted');
expect(src).toContain('minted.attachToken || minted.ptySessionToken');
// Backward-compat fallback to ptySessionToken kept so a partially-
// updated extension still works against a fresh server.
});
test('2. eager spawn via {type:"start"} on ws.open', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
// Replaces the legacy `ws.send(TextEncoder().encode("\\n"))` newline
// hack that nudged the lazy-binary-spawn.
expect(src).toMatch(/ws\.send\(JSON\.stringify\(\{\s*type:\s*'start'\s*\}\)\)/);
expect(src).not.toContain("TextEncoder().encode('\\n')");
});
test('3. forceRestart sends 4001 close code (intentional restart)', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
expect(src).toMatch(/ws\.close\(4001/);
});
test('4. forceRestart POSTs /pty-restart with current sessionId', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
expect(src).toContain('/pty-restart');
expect(src).toContain('priorSessionId ? { sessionId: priorSessionId } : {}');
});
test('5. forceRestart 401 triggers sticky abort (no spam loop)', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
// Same defense pattern as connect() — 401 must flip the sticky flag
// or every 2s the user sees a fresh "Auth invalid" message.
const block = sliceBetween(src, 'async function forceRestart', 'function repaintIfLive');
expect(block).toContain('resp.status === 401');
expect(block).toContain('autoConnectAborted = true');
});
test('6. currentSessionId is exposed on window for sidepanel.js pagehide', () => {
const src = fs.readFileSync(TERMINAL_JS, 'utf-8');
expect(src).toContain('window.gstackPtySession = currentSessionId');
});
});
describe('sidepanel: pagehide → sendBeacon /pty-dispose (v1.44+)', () => {
test('7. pagehide handler fires sendBeacon to /pty-dispose', () => {
const src = fs.readFileSync(SIDEPANEL_JS, 'utf-8');
expect(src).toMatch(/window\.addEventListener\('pagehide'/);
expect(src).toContain('navigator.sendBeacon');
expect(src).toContain('/pty-dispose');
});
test('8. pagehide payload carries sessionId + authToken in body (sendBeacon-compat)', () => {
const src = fs.readFileSync(SIDEPANEL_JS, 'utf-8');
// sendBeacon can't set custom headers — server route accepts body-auth.
// Both fields must be in the payload or the server rejects.
expect(src).toMatch(/JSON\.stringify\(\{\s*sessionId,\s*authToken\s*\}\)/);
expect(src).toContain('window.gstackPtySession');
expect(src).toContain('window.gstackAuthToken');
});
test('9. pagehide handler is best-effort (try/catch swallows failures)', () => {
const src = fs.readFileSync(SIDEPANEL_JS, 'utf-8');
// The 60s detach window catches any sendBeacon that fails, so the
// handler MUST not throw — uncaught throws can interfere with the
// browser's unload sequence. Slice between pagehide and end-of-file
// (it's the last addEventListener in sidepanel.js by design).
const i = src.indexOf("addEventListener('pagehide'");
expect(i).toBeGreaterThan(-1);
const block = src.slice(i);
expect(block).toMatch(/try \{/);
expect(block).toMatch(/} catch /);
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
+194
View File
@@ -0,0 +1,194 @@
import { describe, test, expect } from 'bun:test';
import { createSseEndpoint } from '../src/sse-helpers';
// Unit tests for the SSE cleanup contract introduced by D6 EXTRACT_HELPER.
//
// The pre-helper bug: /activity/stream and /inspector/events ran cleanup
// only on the `req.signal.abort` edge. If the underlying TCP died without
// firing abort (Chromium MV3 service-worker suspend, intermediate proxy
// half-close), the subscriber closure stayed in the Set capturing the
// ReadableStreamDefaultController and any payloads queued behind it.
//
// These tests pin the three cleanup edges:
// 1. abort signal → cleanup
// 2. enqueue throws (consumer gone) → cleanup
// 3. heartbeat enqueue throws → cleanup
// And the idempotency invariant: cleanup running twice is a no-op.
function makeRequest(): { req: Request; abort: () => void } {
const controller = new AbortController();
// Minimal Request — we only use req.signal here. URL is irrelevant.
const req = new Request('http://localhost/test', { signal: controller.signal });
return { req, abort: () => controller.abort() };
}
/** Pull SSE bytes from a Response stream, return decoded text. */
async function readAll(res: Response, ms: number): Promise<string> {
if (!res.body) return '';
const reader = res.body.getReader();
const decoder = new TextDecoder();
let out = '';
const deadline = Date.now() + ms;
while (Date.now() < deadline) {
try {
const { value, done } = await Promise.race([
reader.read(),
new Promise<{ value: undefined; done: true }>((resolve) =>
setTimeout(() => resolve({ value: undefined, done: true }), deadline - Date.now()),
),
]);
if (done) break;
if (value) out += decoder.decode(value, { stream: true });
} catch {
break;
}
}
try { reader.cancel().catch(() => {}); } catch {}
return out;
}
describe('createSseEndpoint cleanup contract', () => {
test('1. abort signal triggers unsubscribe', async () => {
let unsubscribed = 0;
const { req, abort } = makeRequest();
const res = createSseEndpoint(req, {
subscribe: () => () => {
unsubscribed++;
},
liveEventName: 'test',
heartbeatMs: 60_000, // long enough that we don't see heartbeats in this test
});
// Start the stream by reading once, then abort.
const reader = res.body!.getReader();
// Yield to let start() run.
await Promise.resolve();
await Promise.resolve();
abort();
// Let the abort listener fire.
await new Promise((r) => setTimeout(r, 10));
expect(unsubscribed).toBe(1);
reader.cancel().catch(() => {});
});
test('2. enqueue throw triggers unsubscribe + heartbeat clear', async () => {
let unsubscribed = 0;
let notify: ((entry: { msg: string }) => void) | null = null;
const { req } = makeRequest();
const res = createSseEndpoint<{ msg: string }>(req, {
subscribe: (n) => {
notify = n;
return () => {
unsubscribed++;
};
},
liveEventName: 'test',
heartbeatMs: 60_000,
});
// Cancel the reader so subsequent enqueues throw.
const reader = res.body!.getReader();
await Promise.resolve();
await Promise.resolve();
expect(notify).not.toBeNull();
await reader.cancel(); // closes the consumer side
// Now fire a live event — enqueue should throw → cleanup → unsubscribe.
notify!({ msg: 'will fail to enqueue' });
await new Promise((r) => setTimeout(r, 10));
expect(unsubscribed).toBe(1);
});
test('3. cleanup is idempotent (abort then enqueue-fail)', async () => {
let unsubscribed = 0;
let notify: ((entry: { msg: string }) => void) | null = null;
const { req, abort } = makeRequest();
const res = createSseEndpoint<{ msg: string }>(req, {
subscribe: (n) => {
notify = n;
return () => {
unsubscribed++;
};
},
liveEventName: 'test',
heartbeatMs: 60_000,
});
const reader = res.body!.getReader();
await Promise.resolve();
await Promise.resolve();
abort();
await new Promise((r) => setTimeout(r, 10));
// Second cleanup edge — should be a no-op.
notify!({ msg: 'no-op' });
await new Promise((r) => setTimeout(r, 10));
expect(unsubscribed).toBe(1);
reader.cancel().catch(() => {});
});
test('4. initialReplay events reach the client before live events', async () => {
let notify: ((entry: { msg: string }) => void) | null = null;
const { req } = makeRequest();
const res = createSseEndpoint<{ msg: string }>(req, {
initialReplay: (send) => {
send('replay', { msg: 'first' });
},
subscribe: (n) => {
notify = n;
return () => {};
},
liveEventName: 'live',
heartbeatMs: 60_000,
});
// Trigger one live event soon after stream starts.
setTimeout(() => notify?.({ msg: 'second' }), 5);
const text = await readAll(res, 50);
expect(text).toContain('event: replay');
expect(text).toContain('"msg":"first"');
expect(text).toContain('event: live');
expect(text).toContain('"msg":"second"');
// Replay must come before live.
expect(text.indexOf('"first"')).toBeLessThan(text.indexOf('"second"'));
});
test('5. initialReplay throw triggers cleanup without subscribing', async () => {
let subscribed = 0;
const { req } = makeRequest();
const res = createSseEndpoint(req, {
initialReplay: () => {
throw new Error('replay boom');
},
subscribe: () => {
subscribed++;
return () => {};
},
liveEventName: 'test',
heartbeatMs: 60_000,
});
// Drain — stream should close cleanly.
const text = await readAll(res, 30);
expect(text).toBe(''); // no events
expect(subscribed).toBe(0); // never reached subscribe()
});
test('6. lone surrogates in payload string are sanitized', async () => {
let notify: ((entry: { msg: string }) => void) | null = null;
const { req } = makeRequest();
const res = createSseEndpoint<{ msg: string }>(req, {
subscribe: (n) => {
notify = n;
return () => {};
},
liveEventName: 'test',
heartbeatMs: 60_000,
});
setTimeout(() => {
// Lone high surrogate (no matching low). JSON.stringify would emit
// \uD800 escape that breaks Claude API. Helper must strip it.
notify?.({ msg: 'hello \uD800 world' });
}, 5);
const text = await readAll(res, 50);
expect(text).toContain('event: test');
// JSON.stringify emits U+FFFD as the literal character, not as escape.
expect(text).toContain('');
// The raw lone-surrogate escape MUST NOT survive — that's the failure
// mode that breaks the Claude API with HTTP 400.
expect(text.toLowerCase()).not.toContain('\\ud800');
});
});
+122
View File
@@ -0,0 +1,122 @@
/**
* Tests for the opt-in extended stealth mode (#1112 rebased into the
* v1.41 wave).
*
* Pins:
* 1. Default mode applies the always-on Layer C stealth script (and NOT
* the extended script) — the consistency-first default.
* 2. GSTACK_STEALTH=extended adds EXTENDED_STEALTH_SCRIPT on top of Layer C.
* 3. EXTENDED_STEALTH_SCRIPT contains the six detection-vector patches.
* 4. Apply order: Layer C first, extended second (so the extended
* delete-from-prototype path layers on top of Layer C's getter without
* silently overriding it if delete fails).
*
* Live SannySoft pass-rate verification is a periodic-tier E2E test
* (gated behind external network + Chromium); this file pins the
* static + applyStealth semantics that run on every commit.
*/
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
EXTENDED_STEALTH_SCRIPT,
isExtendedStealthEnabled,
applyStealth,
} from '../src/stealth';
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.GSTACK_STEALTH;
});
afterEach(() => {
if (originalEnv === undefined) delete process.env.GSTACK_STEALTH;
else process.env.GSTACK_STEALTH = originalEnv;
});
describe('extended stealth — opt-in mode flag', () => {
test('default mode is OFF (consistency-first contract)', () => {
delete process.env.GSTACK_STEALTH;
expect(isExtendedStealthEnabled()).toBe(false);
});
test('GSTACK_STEALTH=extended enables extended mode', () => {
process.env.GSTACK_STEALTH = 'extended';
expect(isExtendedStealthEnabled()).toBe(true);
});
test('GSTACK_STEALTH=1 also enables (env-style boolean)', () => {
process.env.GSTACK_STEALTH = '1';
expect(isExtendedStealthEnabled()).toBe(true);
});
test('GSTACK_STEALTH=anything-else does NOT enable', () => {
process.env.GSTACK_STEALTH = 'verbose';
expect(isExtendedStealthEnabled()).toBe(false);
});
});
describe('EXTENDED_STEALTH_SCRIPT — six detection-vector patches', () => {
test('1. deletes navigator.webdriver from prototype', () => {
expect(EXTENDED_STEALTH_SCRIPT).toMatch(/delete.*Object\.getPrototypeOf\(navigator\)\.webdriver/);
});
test('2. spoofs WebGL renderer to Apple M1 Pro', () => {
expect(EXTENDED_STEALTH_SCRIPT).toContain('Apple M1 Pro');
expect(EXTENDED_STEALTH_SCRIPT).toContain('UNMASKED_VENDOR_WEBGL');
});
test('3. installs PluginArray-prototype-passing navigator.plugins', () => {
expect(EXTENDED_STEALTH_SCRIPT).toContain('PluginArray');
expect(EXTENDED_STEALTH_SCRIPT).toContain('MimeType');
});
test('4. populates window.chrome with app, runtime, loadTimes, csi', () => {
expect(EXTENDED_STEALTH_SCRIPT).toContain('chrome.app');
expect(EXTENDED_STEALTH_SCRIPT).toContain('chrome.runtime');
expect(EXTENDED_STEALTH_SCRIPT).toContain('chrome.loadTimes');
expect(EXTENDED_STEALTH_SCRIPT).toContain('chrome.csi');
});
test('5. backfills navigator.mediaDevices when missing', () => {
expect(EXTENDED_STEALTH_SCRIPT).toContain('mediaDevices');
expect(EXTENDED_STEALTH_SCRIPT).toContain('enumerateDevices');
});
test('6. clears CDP cdc_* property names from window', () => {
expect(EXTENDED_STEALTH_SCRIPT).toContain("startsWith('cdc_')");
});
});
describe('applyStealth — script wiring', () => {
test('default mode applies ONLY the Layer C script (not extended)', async () => {
delete process.env.GSTACK_STEALTH;
const calls: string[] = [];
const fakeCtx = {
addInitScript: async (opts: { content: string }) => {
calls.push(opts.content);
},
} as unknown as Parameters<typeof applyStealth>[0];
await applyStealth(fakeCtx);
expect(calls).toHaveLength(1);
// Layer C signatures: toString-proxy native-code lie + webdriver mask.
expect(calls[0]).toContain('[native code]');
expect(calls[0]).toContain('webdriver');
expect(calls[0]).not.toBe(EXTENDED_STEALTH_SCRIPT);
});
test('extended mode applies BOTH scripts in order (Layer C first, extended second)', async () => {
process.env.GSTACK_STEALTH = 'extended';
const calls: string[] = [];
const fakeCtx = {
addInitScript: async (opts: { content: string }) => {
calls.push(opts.content);
},
} as unknown as Parameters<typeof applyStealth>[0];
await applyStealth(fakeCtx);
expect(calls).toHaveLength(2);
// Layer C first (its native-code lie), extended second.
expect(calls[0]).toContain('[native code]');
expect(calls[1]).toBe(EXTENDED_STEALTH_SCRIPT);
});
});
+118
View File
@@ -0,0 +1,118 @@
import { describe, test, expect, beforeEach } from 'bun:test';
import { BrowserManager } from '../src/browser-manager';
import { subscribe } from '../src/activity';
// Tests for the tab-count guardrail. Each threshold fires exactly once per
// upward crossing and re-arms when the count drops back below. The toast
// UX lives in the sidebar; this exercises the server-side audit-trail
// invariant that an activity entry is emitted at each crossing.
interface CapturedEntry {
type: string;
command?: string;
error?: string;
tabs?: number;
}
function captureGuardrailEntries(): { entries: CapturedEntry[]; unsubscribe: () => void } {
const entries: CapturedEntry[] = [];
const unsubscribe = subscribe((entry) => {
if (entry.command === 'tab-guardrail') {
entries.push({
type: entry.type,
command: entry.command,
error: entry.error,
tabs: entry.tabs,
});
}
});
return { entries, unsubscribe };
}
/** Drive the guardrail by writing directly into the manager's pages map. */
async function setTabCount(bm: BrowserManager, n: number): Promise<void> {
// Reach into private state via index access — test-only manipulation that
// avoids spinning up a real Chromium just to verify the threshold math.
const inner = bm as unknown as {
pages: Map<number, unknown>;
checkTabGuardrails: () => void;
recheckTabGuardrailsOnClose: () => void;
};
inner.pages.clear();
for (let i = 0; i < n; i++) inner.pages.set(i, { fakeTab: true });
// Drive whichever direction matches the count change.
inner.checkTabGuardrails();
inner.recheckTabGuardrailsOnClose();
// emitActivity dispatches subscribers via queueMicrotask, so let the
// microtask queue drain before the test assertion runs.
await new Promise((r) => setTimeout(r, 0));
}
describe('tab-count guardrail', () => {
let bm: BrowserManager;
let capture: ReturnType<typeof captureGuardrailEntries>;
beforeEach(() => {
bm = new BrowserManager();
capture = captureGuardrailEntries();
});
test('1. no entry fires under the soft threshold', async () => {
await setTabCount(bm, 10);
await setTabCount(bm, 49);
expect(capture.entries).toEqual([]);
capture.unsubscribe();
});
test('2. soft threshold (50) fires exactly once on upward crossing', async () => {
await setTabCount(bm, 49);
await setTabCount(bm, 50);
await setTabCount(bm, 51);
await setTabCount(bm, 60);
expect(capture.entries.length).toBe(1);
expect(capture.entries[0].tabs).toBe(50);
expect(capture.entries[0].error).toContain('crossed 50');
capture.unsubscribe();
});
test('3. hard threshold (200) fires exactly once on upward crossing', async () => {
await setTabCount(bm, 199);
await setTabCount(bm, 200);
await setTabCount(bm, 201);
await setTabCount(bm, 220);
// 0 → 199 fired the soft threshold; 199 → 200 fires the hard one once.
const hardEntries = capture.entries.filter((e) => e.error?.includes('crossed 200'));
expect(hardEntries.length).toBe(1);
expect(hardEntries[0].tabs).toBe(200);
capture.unsubscribe();
});
test('4. both thresholds fire in order when count jumps from 0 → 250', async () => {
await setTabCount(bm, 250);
expect(capture.entries.length).toBe(2);
expect(capture.entries[0].error).toContain('crossed 50');
expect(capture.entries[1].error).toContain('crossed 200');
capture.unsubscribe();
});
test('5. soft threshold re-arms when tab count drops below it', async () => {
await setTabCount(bm, 60);
expect(capture.entries.length).toBe(1);
await setTabCount(bm, 30);
await setTabCount(bm, 55);
expect(capture.entries.length).toBe(2);
expect(capture.entries[1].error).toContain('crossed 50');
capture.unsubscribe();
});
test('6. hard threshold re-arms when tab count drops below it', async () => {
await setTabCount(bm, 210);
const beforeReArm = capture.entries.filter((e) => e.error?.includes('crossed 200')).length;
expect(beforeReArm).toBe(1);
await setTabCount(bm, 150);
await setTabCount(bm, 220);
const afterReArm = capture.entries.filter((e) => e.error?.includes('crossed 200')).length;
expect(afterReArm).toBe(2);
capture.unsubscribe();
});
});
@@ -0,0 +1,127 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// v1.44 Commit 3 — detach state machine + ring buffer + re-attach replay.
//
// The state machine is what turns a single network blip from "fall through
// to ENDED state, click Restart" into "silent re-attach with scrollback
// intact, keep typing." Live WS cycles + buffer-overflow exercises belong
// in the e2e tier; these static-grep tripwires defend the load-bearing
// protocol + correctness properties.
const AGENT_TS = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'terminal-agent.ts');
describe('terminal-agent detach + re-attach (v1.44+ Commit 3)', () => {
test('1. PtySession carries ring buffer + alt-screen + detach state', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
const i = src.indexOf('interface PtySession {');
const j = src.indexOf('\n}', i);
const block = src.slice(i, j);
expect(block).toContain('liveWs: any | null');
expect(block).toContain('ringBuffer: Buffer[]');
expect(block).toContain('ringBufferBytes: number');
expect(block).toContain('altScreenActive: boolean');
expect(block).toContain('detached: boolean');
expect(block).toContain('detachTimer:');
});
test('2. RING_BUFFER_MAX_BYTES default is 1 MB, env-overridable', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toContain('GSTACK_PTY_RING_BUFFER_BYTES');
expect(src).toContain('1024 * 1024');
});
test('3. DETACH_WINDOW_MS default is 60s, env-overridable', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toContain('GSTACK_PTY_DETACH_WINDOW_MS');
expect(src).toContain("'60000'");
});
test('4. appendToRingBuffer evicts oldest frames past the cap', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toMatch(/function appendToRingBuffer\(/);
// Eviction loop: must keep at least one frame even at extreme caps
// (otherwise a single oversized frame would empty the buffer).
expect(src).toMatch(/session\.ringBufferBytes > RING_BUFFER_MAX_BYTES/);
expect(src).toContain('session.ringBuffer.length > 1');
expect(src).toContain('session.ringBuffer.shift()');
});
test('5. alt-screen tracking watches for CSI ?1049h / CSI ?1049l', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
// Canonical xterm enter/exit alt-screen sequences. Must update
// session.altScreenActive so the replay prelude knows.
expect(src).toContain('\\x1b[?1049h');
expect(src).toContain('\\x1b[?1049l');
expect(src).toContain('session.altScreenActive');
});
test('6. buildReplayPayload prefixes soft-reset (+ alt-screen if active)', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toMatch(/function buildReplayPayload\(/);
// DECSTR soft reset — re-defaults character attributes after the
// client's RIS clears the xterm buffer.
expect(src).toContain('\\x1b[!p');
// Conditionally re-enter alt-screen if claude was in a tool-call
// (alt-screen mode) at detach.
expect(src).toContain('session.altScreenActive');
});
test('7. WS open() re-attaches when sessionId already lives in sessionsById', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
const block = sliceBetween(src, 'open(ws) {', 'message(ws, raw) {');
expect(block).toContain('sessionsById.get(sessionId)');
expect(block).toContain('existing.liveWs = ws');
expect(block).toContain('clearTimeout(existing.detachTimer)');
// Tells the client to write RIS before treating the next binary
// frame as replay.
expect(block).toContain("type: 'reattach-begin'");
expect(block).toContain('sendBinary(buildReplayPayload(existing))');
});
test('8. WS close starts detach timer for non-intentional close codes', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
const i = src.indexOf('close(ws');
const j = src.indexOf('function handleTabState', i);
const block = src.slice(i, j);
// 4001 = intentional restart (Commit 2), 4404 = no-claude, 1000 = clean
// exit. Any other code (1006 abnormal, 1001 going-away, etc.) gets the
// 60s detach grace.
expect(block).toContain('code === 4001');
expect(block).toContain('code === 4404');
expect(block).toContain('code === 1000');
expect(block).toContain('session.detached = true');
expect(block).toContain('session.detachTimer = setTimeout');
expect(block).toContain('DETACH_WINDOW_MS');
// Detach timer must unref so the bun process can exit cleanly.
expect(block).toContain('detachTimer as any)?.unref?.()');
});
test('9. /internal/restart cancels detach timer before disposal', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/internal/restart'", "// /claude-available");
// Without the cancellation, a later detach-timer fire would dispose a
// session that's already been disposed by the explicit restart path.
expect(block).toContain('clearTimeout(session.detachTimer)');
});
test('10. PTY on-data writes through session.liveWs (not the original ws closure)', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
// Critical for re-attach correctness: the PTY's on-data callback
// closes over `session`, not the original `ws`, so after re-attach
// it routes to the new liveWs automatically.
expect(src).toContain('session.liveWs.sendBinary');
// Always append to the ring buffer regardless of attach state — so
// a detached session still captures output for the next re-attach.
expect(src).toContain('appendToRingBuffer(session, flush)');
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
@@ -0,0 +1,51 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// Static-grep tripwire for the v1.44 internalHandler refactor.
//
// /internal/grant and /internal/revoke were copies of the same dance:
// bearer-auth → x-browse-gen check → req.json().then(...).catch(...).
// internalHandler<T>(req, fn) collapses that into a single helper call.
// This test fails CI if the helper goes away or the existing routes
// regress to inline auth + JSON parse boilerplate. Wiring tests
// (token grant/revoke behavior) already live in
// browse/test/terminal-agent-integration.test.ts.
const AGENT_TS = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'terminal-agent.ts');
describe('terminal-agent internalHandler refactor (v1.44+)', () => {
test('1. internalHandler<T> exists with the documented signature', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toMatch(/async function internalHandler<T>\s*\(/);
// Body must include the auth gate, body parse, and result coercion.
expect(src).toContain('checkInternalAuth(req)');
expect(src).toContain('await req.json()');
expect(src).toContain('instanceof Response');
});
test('2. /internal/grant routes through internalHandler', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
// Match the route handler block.
const block = sliceBetween(src, "url.pathname === '/internal/grant'", "url.pathname === '/internal/revoke'");
expect(block).toContain('internalHandler(req');
// Must NOT have the old inline pattern (would be a regression).
expect(block).not.toContain('req.headers.get(\'authorization\')');
expect(block).not.toContain('req.json().then(');
});
test('3. /internal/revoke routes through internalHandler', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/internal/revoke'", "url.pathname === '/internal/healthz'");
expect(block).toContain('internalHandler(req');
expect(block).not.toContain('req.json().then(');
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
@@ -0,0 +1,88 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// v1.44 WS keepalive — static-grep invariants for the protocol contract.
//
// terminal-agent.ts and sidepanel-terminal.js cooperate on a 25s ping/pong +
// keepalive cycle so long-idle PTY connections survive NAT idle timeouts and
// Chromium's MV3 panel suspension heuristics. The wiring is invisible to
// integration tests (you'd have to wait 25s to observe a ping) but trivially
// regressed by a refactor. These tests fail CI if either side stops sending
// or stops accepting the protocol frames.
const AGENT_TS = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'terminal-agent.ts');
const CLIENT_JS = path.resolve(new URL(import.meta.url).pathname, '..', '..', '..', 'extension', 'sidepanel-terminal.js');
describe('terminal-agent WS keepalive (v1.44+)', () => {
test('1. agent has a KEEPALIVE_INTERVAL_MS env knob, default 25000', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toContain('GSTACK_PTY_KEEPALIVE_INTERVAL_MS');
expect(src).toMatch(/KEEPALIVE_INTERVAL_MS\s*=\s*parseInt\(/);
// Default constant present so the env knob has a fallback.
expect(src).toContain("'25000'");
});
test('2. WS open handler starts a ping interval on the session', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
// The open(ws) handler in the websocket: { ... } block must call
// setInterval to drive the ping cadence and store the handle.
const wsBlock = sliceBetween(src, 'websocket: {', 'function handleTabState');
expect(wsBlock).toMatch(/open\s*\(\s*ws\s*\)/);
expect(wsBlock).toContain('setInterval');
expect(wsBlock).toContain("type: 'ping'");
expect(wsBlock).toContain('pingInterval');
});
test('3. WS close handler clears the ping interval', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
const wsBlock = sliceBetween(src, 'websocket: {', 'function handleTabState');
// close(ws, code?, reason?) MUST clearInterval the pingInterval —
// otherwise we leak timers across reconnects and the ping handler
// captures a dead ws ref. Signature widened in Commit 3 to include
// the close code for the detach state machine, hence the loose match.
expect(wsBlock).toMatch(/close\s*\(\s*ws/);
expect(wsBlock).toContain('clearInterval(session.pingInterval)');
});
test('4. message handler accepts pong / keepalive frames silently', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
// The text-frame router must recognize the keepalive vocabulary —
// if a future refactor strips this branch, unknown-text-frame
// suppression would still drop them but we lose intent.
expect(src).toMatch(/msg\?\.type === 'pong'/);
expect(src).toMatch(/msg\?\.type === 'keepalive'/);
});
test('5. client sends keepalive every 25s on ws.open', () => {
const src = fs.readFileSync(CLIENT_JS, 'utf-8');
expect(src).toContain('keepaliveInterval');
expect(src).toMatch(/setInterval\(/);
expect(src).toContain("type: 'keepalive'");
expect(src).toContain('KEEPALIVE_INTERVAL_MS = 25000');
});
test('6. client replies pong to server ping', () => {
const src = fs.readFileSync(CLIENT_JS, 'utf-8');
// The ws.message handler must short-circuit on msg.type === 'ping'
// and reply with {type: 'pong', ts: msg.ts}.
expect(src).toMatch(/msg\.type === 'ping'/);
expect(src).toMatch(/type: 'pong'/);
});
test('7. client clears keepalive in close + teardown + forceRestart', () => {
const src = fs.readFileSync(CLIENT_JS, 'utf-8');
// Three teardown paths exist; all three must drop the interval to
// avoid leaking timers across reconnect attempts.
const occurrences = (src.match(/clearInterval\(keepaliveInterval\)/g) || []).length;
expect(occurrences).toBeGreaterThanOrEqual(3);
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
@@ -0,0 +1,161 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import {
readAgentRecord,
writeAgentRecord,
clearAgentRecord,
killAgentByRecord,
agentRecordPath,
type AgentRecord,
} from '../src/terminal-agent-control';
// REGRESSION TEST for the v1.44 PID-identity migration.
//
// Pre-v1.44, both `cli.ts` and `server.ts` killed the terminal-agent with
// `spawnSync('pkill', ['-f', 'terminal-agent\\.ts'])`. That command matches
// by argv regex — any process whose command line contains the string
// `terminal-agent.ts` got SIGTERM'd. In practice this killed:
//
// * sibling gstack sessions on the same host
// * editor processes (vim, code, less) that had the file open
// * any second gstack run on the host
//
// The v1.44 migration replaces both kill sites with identity-based PID kill
// against the record written at `<stateDir>/terminal-agent-pid` by the
// agent's own boot path. This test is the static-grep tripwire that prevents
// reintroducing the regex teardown anywhere in the source tree.
//
// Pattern mirrors browse/test/server-embedder-terminal-port.test.ts (Test 4)
// and browse/test/server-sanitize-surrogates.test.ts: read source files
// directly, assert an invariant on their contents.
const SRC_DIR = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src');
function readAllSourceFiles(): Array<{ file: string; content: string }> {
const out: Array<{ file: string; content: string }> = [];
for (const entry of fs.readdirSync(SRC_DIR)) {
if (!entry.endsWith('.ts')) continue;
const full = path.join(SRC_DIR, entry);
out.push({ file: entry, content: fs.readFileSync(full, 'utf-8') });
}
return out;
}
describe('terminal-agent PID identity (v1.44+)', () => {
test('1. no source file calls `pkill -f terminal-agent`', () => {
// The regex matches both `pkill -f terminal-agent\.ts` (escaped form
// used in spawnSync args) and `pkill -f terminal-agent.ts` (literal),
// since the dot is the only difference and both are footguns.
const offenders: string[] = [];
for (const { file, content } of readAllSourceFiles()) {
// Walk line by line so we can skip comments that mention the historical
// pattern (acceptable as documentation, not as code).
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!/pkill/.test(line)) continue;
if (!/terminal-agent/.test(line)) continue;
// Skip comment lines — historical mentions in JSDoc are fine.
const trimmed = line.trim();
if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*')) continue;
offenders.push(`${file}:${i + 1}: ${trimmed}`);
}
}
expect(offenders).toEqual([]);
});
test('2. neither cli.ts nor server.ts calls spawnSync with pkill', () => {
// Tighter check — even if someone routes through a different code path,
// any spawnSync('pkill', ...) anywhere in src/ is the smell.
const offenders: string[] = [];
for (const { file, content } of readAllSourceFiles()) {
if (/spawnSync\s*\(\s*['"]pkill['"]/.test(content)) {
offenders.push(file);
}
}
expect(offenders).toEqual([]);
});
test('3. readAgentRecord round-trips writeAgentRecord', () => {
const tmpDir = fs.mkdtempSync(path.join(require('os').tmpdir(), 'gstack-pid-id-'));
try {
const record: AgentRecord = {
pid: 12345,
gen: 'test-gen-abcdef',
startedAt: Date.now(),
};
writeAgentRecord(tmpDir, record);
const read = readAgentRecord(tmpDir);
expect(read).toEqual(record);
expect(fs.existsSync(agentRecordPath(tmpDir))).toBe(true);
clearAgentRecord(tmpDir);
expect(readAgentRecord(tmpDir)).toBeNull();
expect(fs.existsSync(agentRecordPath(tmpDir))).toBe(false);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test('4. readAgentRecord returns null on missing or malformed file', () => {
const tmpDir = fs.mkdtempSync(path.join(require('os').tmpdir(), 'gstack-pid-id-'));
try {
// Missing.
expect(readAgentRecord(tmpDir)).toBeNull();
// Malformed: wrong type for pid.
fs.writeFileSync(agentRecordPath(tmpDir), JSON.stringify({ pid: 'not-a-number', gen: 'x', startedAt: 0 }));
expect(readAgentRecord(tmpDir)).toBeNull();
// Malformed: not JSON.
fs.writeFileSync(agentRecordPath(tmpDir), 'definitely not json');
expect(readAgentRecord(tmpDir)).toBeNull();
// Missing field.
fs.writeFileSync(agentRecordPath(tmpDir), JSON.stringify({ pid: 1, gen: 'x' }));
expect(readAgentRecord(tmpDir)).toBeNull();
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test('5. killAgentByRecord returns false for a dead PID and never throws', () => {
// PID 2147483646 is below Linux PID_MAX_LIMIT but way above macOS's
// typical max — no real process will ever hold it. isProcessAlive
// returns false; killAgentByRecord no-ops.
const record: AgentRecord = {
pid: 2147483646,
gen: 'sentinel',
startedAt: Date.now(),
};
const result = killAgentByRecord(record, 'SIGTERM');
expect(result).toBe(false);
});
test('6. killAgentByRecord skips the kill when isProcessAlive is false', () => {
// Guard via process.kill stub: confirm killAgentByRecord does NOT call
// process.kill with a non-zero signal when the PID is dead. This is the
// belt-and-suspenders defense against PID-reuse: even if isProcessAlive
// changes implementation, killAgentByRecord must validate liveness first.
const origKill = process.kill;
const kills: Array<[number, NodeJS.Signals | number]> = [];
(process as any).kill = ((pid: number, sig: NodeJS.Signals | number) => {
kills.push([pid, sig ?? 'SIGTERM']);
if (sig === 0) {
const err: any = new Error('ESRCH');
err.code = 'ESRCH';
throw err;
}
return true;
}) as any;
try {
const record: AgentRecord = { pid: 9999999, gen: 'x', startedAt: Date.now() };
killAgentByRecord(record, 'SIGTERM');
const terminations = kills.filter(([, s]) => s !== 0);
expect(terminations).toEqual([]);
} finally {
(process as any).kill = origKill;
}
});
});
@@ -0,0 +1,154 @@
import { describe, test, expect, beforeEach } from 'bun:test';
import {
appendToRingBuffer,
buildReplayPayload,
type PtySession,
} from '../src/terminal-agent';
// Runtime exercises for the v1.44 Commit 3 ring buffer + replay prelude.
// Companion to browse/test/terminal-agent-detach-reattach.test.ts which
// covers the structural invariants; this file calls the helpers directly
// to prove behavioral correctness without spinning up a real Bun.serve
// listener.
function fresh(): PtySession {
return {
proc: null,
cols: 80,
rows: 24,
cookie: 'test-cookie',
liveWs: null,
sessionId: 'test-session',
spawned: false,
pingInterval: null,
ringBuffer: [],
ringBufferBytes: 0,
altScreenActive: false,
detached: false,
detachTimer: null,
};
}
describe('appendToRingBuffer runtime', () => {
test('appends frames in order and tracks byte count', () => {
const s = fresh();
appendToRingBuffer(s, Buffer.from('hello '));
appendToRingBuffer(s, Buffer.from('world'));
expect(s.ringBuffer).toHaveLength(2);
expect(s.ringBufferBytes).toBe(11);
expect(Buffer.concat(s.ringBuffer).toString()).toBe('hello world');
});
test('evicts oldest frames when cap exceeded', () => {
// Default cap is 1 MB. Override via env wouldn't help inside this
// running process (constant was read at module load), so use frames
// big enough to exceed it deterministically.
const s = fresh();
const big = Buffer.alloc(400_000, 0x41); // 400 KB of 'A'
appendToRingBuffer(s, big);
appendToRingBuffer(s, big);
appendToRingBuffer(s, big); // total 1.2 MB — exceeds default cap
// Eviction must drop frames until under cap; first 400 KB chunk goes.
expect(s.ringBuffer.length).toBeLessThan(3);
expect(s.ringBufferBytes).toBeLessThanOrEqual(1024 * 1024);
});
test('keeps at least one frame even when a single frame exceeds the cap', () => {
const s = fresh();
// 2 MB single frame — bigger than the 1 MB cap. The eviction loop
// guards on `ringBuffer.length > 1`, so the single oversized frame
// stays. Without that guard, the buffer would empty itself, defeating
// the whole point of replay on re-attach.
const huge = Buffer.alloc(2 * 1024 * 1024, 0x42);
appendToRingBuffer(s, huge);
expect(s.ringBuffer.length).toBe(1);
expect(s.ringBufferBytes).toBe(huge.length);
});
test('tracks alt-screen enter (CSI ?1049h)', () => {
const s = fresh();
expect(s.altScreenActive).toBe(false);
appendToRingBuffer(s, Buffer.from('plain text'));
expect(s.altScreenActive).toBe(false);
appendToRingBuffer(s, Buffer.from('\x1b[?1049h'));
expect(s.altScreenActive).toBe(true);
});
test('tracks alt-screen exit (CSI ?1049l)', () => {
const s = fresh();
appendToRingBuffer(s, Buffer.from('\x1b[?1049h'));
expect(s.altScreenActive).toBe(true);
appendToRingBuffer(s, Buffer.from('\x1b[?1049l'));
expect(s.altScreenActive).toBe(false);
});
test('trailing state wins when enter + exit appear in one frame', () => {
const s = fresh();
// Tool call opened alt-screen then closed it inside one render — net
// state is back to main screen. lastIndexOf comparison handles this.
appendToRingBuffer(s, Buffer.from('start\x1b[?1049hmiddle\x1b[?1049lend'));
expect(s.altScreenActive).toBe(false);
const s2 = fresh();
// Reverse order: exited then re-entered — net state alt-screen.
appendToRingBuffer(s2, Buffer.from('\x1b[?1049l\x1b[?1049h'));
expect(s2.altScreenActive).toBe(true);
});
});
describe('buildReplayPayload runtime', () => {
test('prepends DECSTR soft reset before ring buffer contents', () => {
const s = fresh();
appendToRingBuffer(s, Buffer.from('prompt> '));
const payload = buildReplayPayload(s).toString('latin1');
expect(payload.startsWith('\x1b[!p')).toBe(true);
expect(payload.endsWith('prompt> ')).toBe(true);
});
test('re-enters alt-screen when session was in alt-screen at detach', () => {
const s = fresh();
appendToRingBuffer(s, Buffer.from('\x1b[?1049h tool output '));
const payload = buildReplayPayload(s).toString('latin1');
// Order: soft reset, alt-screen re-enter, ring buffer.
expect(payload.indexOf('\x1b[!p')).toBeLessThan(payload.indexOf('\x1b[?1049h'));
expect(payload.indexOf('\x1b[?1049h')).toBeLessThan(payload.indexOf('tool output'));
});
test('omits alt-screen re-enter when session was on main screen', () => {
const s = fresh();
appendToRingBuffer(s, Buffer.from('regular prompt'));
const payload = buildReplayPayload(s).toString('latin1');
// Soft reset is present, but alt-screen enter is NOT. Both substrings
// are otherwise identical 8 bytes apart in the alphabet, so equal-
// substring checks need to be strict.
expect(payload).toContain('\x1b[!p');
expect(payload).not.toContain('\x1b[?1049h');
});
test('replay buffer length = soft-reset + (optional alt-screen) + ring bytes', () => {
const s = fresh();
appendToRingBuffer(s, Buffer.from('abc'));
appendToRingBuffer(s, Buffer.from('def'));
const payload = buildReplayPayload(s);
// 4 bytes (DECSTR) + 6 bytes (abc/def) = 10 bytes. No alt-screen.
expect(payload.length).toBe(4 + 6);
});
});
describe('lease lifecycle interplay (via pty-session-lease)', () => {
// Cross-module behavior: lease + ring buffer are both per-session.
// This catches the case where a refactor accidentally couples them.
test('lease registry is independent of ring buffer state', async () => {
const { mintLease, validateLease, __resetLeases } = await import('../src/pty-session-lease');
__resetLeases();
const a = mintLease();
const b = mintLease();
expect(a.sessionId).not.toBe(b.sessionId);
const va = validateLease(a.sessionId);
const vb = validateLease(b.sessionId);
expect(va.ok && vb.ok).toBe(true);
if (va.ok && vb.ok) {
expect(va.expiresAt).toBe(vb.expiresAt);
}
});
});
@@ -0,0 +1,96 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// v1.44 Commit 2 — terminal-agent sessionId routing + eager spawn.
//
// Live spawn tests would require a real claude binary on PATH and a Bun.serve
// listener; both are e2e-tier. These static-grep tripwires defend the load-
// bearing protocol changes:
// - validTokens carries the sessionId binding (Map, not Set)
// - sessionsById index exists for /internal/restart + (Commit 3) re-attach
// - /internal/restart is scoped to one sessionId (codex T2 fix)
// - {type:"start"} triggers spawn for eager UX after forceRestart
// - maybeSpawnPty helper is the single entry point for both spawn paths
const AGENT_TS = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'terminal-agent.ts');
describe('terminal-agent session routing (v1.44+ Commit 2)', () => {
test('1. validTokens is a Map binding token → sessionId', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
// Pre-Commit 2 was `Set<string>`; the Map carries the sessionId
// binding that /internal/restart and (Commit 3) re-attach depend on.
expect(src).toMatch(/const validTokens = new Map<string, string \| null>\(\)/);
expect(src).not.toMatch(/const validTokens = new Set</);
});
test('2. sessionsById reverse index exists', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toMatch(/const sessionsById = new Map<string, PtySession>\(\)/);
// Populated in open() — required so /internal/restart can find the session.
expect(src).toMatch(/if \(sessionId\) sessionsById\.set\(sessionId, session\)/);
});
test('3. /internal/grant binds an optional sessionId to the token', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/internal/grant'", "url.pathname === '/internal/revoke'");
expect(block).toContain('validTokens.set(body.token, sid)');
expect(block).toContain('body?.sessionId');
});
test('4. /internal/restart is scoped to one sessionId, not dispose-all', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
const block = sliceBetween(src, "url.pathname === '/internal/restart'", "// /claude-available");
expect(block).toContain('sessionsById.get(sid)');
expect(block).toContain('disposeSession(session)');
expect(block).toContain('sessionsById.delete(sid)');
// Negative: must NOT enumerate all live sessions and dispose them
// (codex T2 caught this — pre-spec the route killed every PTY on the
// agent, breaking multi-sidebar / pair-agent setups).
expect(block).not.toMatch(/for\s*\(\s*const\s+\[?ws/);
});
test('5. WS upgrade surfaces sessionId on ws.data', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toContain('validTokens.get(token) ?? null');
expect(src).toMatch(/data:\s*\{\s*cookie:\s*token,\s*sessionId\s*\}/);
});
test('6. eager spawn via {type:"start"} text frame', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
expect(src).toMatch(/msg\?\.type === 'start'/);
// Both spawn paths route through the same helper for parity.
expect(src).toContain('function maybeSpawnPty(');
expect(src).toMatch(/maybeSpawnPty\(ws, session\)/);
});
test('7. close() drops sessionsById entry alongside ws cleanup', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
// Commit 3 widened the close signature to `close(ws, code, _reason)`
// for the detach state machine. Match either shape so test is stable
// across the rest of the long-lived-sidebar PR.
const i = src.indexOf('close(ws');
expect(i).toBeGreaterThan(-1);
const j = src.indexOf('function handleTabState', i);
const block = src.slice(i, j);
expect(block).toContain('sessionsById.delete(session.sessionId)');
});
test('8. PtySession interface carries the sessionId field', () => {
const src = fs.readFileSync(AGENT_TS, 'utf-8');
// Whole interface — close paren is sufficient.
const i = src.indexOf('interface PtySession {');
expect(i).toBeGreaterThan(-1);
const j = src.indexOf('\n}', i);
const block = src.slice(i, j);
expect(block).toContain('sessionId: string | null');
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
@@ -0,0 +1,91 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
// v1.44 terminal-agent watchdog — static-grep invariants.
//
// The watchdog respawns terminal-agent when its PID dies. Live process-tree
// tests would require spawning, killing, and observing across two real Bun
// processes — slow and flaky in the free tier. These tripwires defend the
// load-bearing properties: identity-based liveness check (not name match),
// crash-loop guard, gated on ownsTerminalAgent, and cleared on shutdown.
const SERVER_TS = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'server.ts');
const CONTROL_TS = path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'terminal-agent-control.ts');
describe('terminal-agent watchdog (v1.44+)', () => {
test('1. spawnTerminalAgent helper exists with PID return type', () => {
const src = fs.readFileSync(CONTROL_TS, 'utf-8');
expect(src).toMatch(/export function spawnTerminalAgent\(/);
// Must clean up prior PID before spawning (no zombies).
expect(src).toContain('readAgentRecord(stateDir)');
expect(src).toContain('killAgentByRecord(prior');
expect(src).toContain('clearAgentRecord(stateDir)');
});
test('2. watchdog is gated on ownsTerminalAgent', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
// Match the comment + the guard. The guard MUST be a positive check;
// an inverted check would respawn for embedders and trample their PTY.
const block = sliceBetween(src, '─── Terminal-Agent Watchdog', 'Factory-scoped validateAuth');
expect(block).toMatch(/if \(ownsTerminalAgent\)/);
expect(block).toContain('agentWatchdogInterval = setInterval');
});
test('3. watchdog uses PID liveness, not process name probe', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
const block = sliceBetween(src, '─── Terminal-Agent Watchdog', 'Factory-scoped validateAuth');
// The whole point of the v1.44 watchdog over v1.43- pkill teardown:
// identity-based liveness. Slow-but-alive agents must NOT trigger
// respawn (split-brain defense).
expect(block).toContain('readAgentRecord(stateDir)');
expect(block).toContain('isProcessAlive(record.pid)');
// Negative: no executable name-based process lookup. Allow the strings
// to appear in prose comments (the watchdog doc explains what it
// replaces), reject only actual invocations.
expect(block).not.toMatch(/spawnSync\s*\(\s*['"]pkill/);
expect(block).not.toMatch(/Bun\.spawn\s*\(\s*\[\s*['"]pgrep/);
});
test('4. crash-loop guard with rolling window', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
const block = sliceBetween(src, '─── Terminal-Agent Watchdog', 'Factory-scoped validateAuth');
expect(block).toContain('RESPAWN_GUARD_WINDOW_MS = 60_000');
expect(block).toContain('RESPAWN_GUARD_MAX = 3');
expect(block).toContain('respawnHistory');
expect(block).toContain('agentRespawnGuardTripped');
// Window pruning: old entries must be evicted before counting toward
// the limit. Otherwise a daemon up for a week with one crash a day
// would eventually trip the guard.
expect(block).toMatch(/respawnHistory\.shift\(\)/);
});
test('5. watchdog interval is cleared on shutdown', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
expect(src).toContain('if (agentWatchdogInterval) clearInterval(agentWatchdogInterval)');
});
test('6. tick interval is env-overridable for tests', () => {
const src = fs.readFileSync(SERVER_TS, 'utf-8');
expect(src).toContain('GSTACK_AGENT_WATCHDOG_TICK_MS');
});
test('7. CLI cold-start path uses the same spawnTerminalAgent helper', () => {
const cli = fs.readFileSync(
path.resolve(new URL(import.meta.url).pathname, '..', '..', 'src', 'cli.ts'),
'utf-8',
);
// Otherwise the CLI and watchdog could drift on spawn env/cwd, and
// teardown invariants tested against one would silently miss the other.
expect(cli).toContain('spawnTerminalAgent({');
expect(cli).toContain("from './terminal-agent-control'");
});
});
function sliceBetween(source: string, start: string, end: string): string {
const i = source.indexOf(start);
if (i === -1) throw new Error(`marker not found: ${start}`);
const j = source.indexOf(end, i + start.length);
if (j === -1) throw new Error(`end marker not found: ${end}`);
return source.slice(i, j);
}
+32
View File
@@ -95,3 +95,35 @@ describe('canDispatchOverTunnel — alias canonicalization', () => {
expect(canDispatchOverTunnel('closetab')).toBe(true);
});
});
describe('canDispatchOverTunnel — --out writes are never tunnel-dispatchable', () => {
// `--out` turns an otherwise-readable command into a local-disk WRITE. The
// tunnel surface never grants disk-write to remote paired agents, so any
// --out invocation must be 403'd even when the bare command is allowlisted.
test('bare eval dispatches, but eval --out does not', () => {
expect(canDispatchOverTunnel('eval', ['/tmp/x.js'])).toBe(true);
expect(canDispatchOverTunnel('eval', ['/tmp/x.js', '--out', '/tmp/o.png'])).toBe(false);
});
test('--out= form is rejected too (no parser-shape bypass)', () => {
expect(canDispatchOverTunnel('eval', ['/tmp/x.js', '--out=/tmp/o.png'])).toBe(false);
});
test('--out anywhere in args is caught regardless of ordering', () => {
expect(canDispatchOverTunnel('eval', ['--out', '/tmp/o.png', '/tmp/x.js'])).toBe(false);
});
test('args without --out still dispatch', () => {
expect(canDispatchOverTunnel('goto', ['https://example.com'])).toBe(true);
expect(canDispatchOverTunnel('eval', ['/tmp/x.js'])).toBe(true);
});
test('omitting args preserves the old command-only behavior', () => {
expect(canDispatchOverTunnel('eval')).toBe(true);
});
test('a lookalike flag (--output) is NOT treated as --out', () => {
// hasOutArg matches '--out' exactly or '--out='; '--output' must not trip it.
expect(canDispatchOverTunnel('eval', ['/tmp/x.js', '--output', '/tmp/o'])).toBe(true);
});
});