Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(browser): honor pipe backpressure and bound cold startup
Seth Wilsona865d72f9148
diff --git a/src/capabilities/browser/pipe.test.ts b/src/capabilities/browser/pipe.test.tsindex 7b7af93a..efb4400c 100644--- a/src/capabilities/browser/pipe.test.ts+++ b/src/capabilities/browser/pipe.test.ts@@ -1,17 +1,32 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { EventEmitter } from 'node:events';-import { PassThrough } from 'node:stream';+import { PassThrough, Writable } from 'node:stream';import type { ChildProcess } from 'node:child_process';import { BrowserPipe } from './pipe.js';-function connection() {- const input = new PassThrough();+function connection<T extends Writable = PassThrough>(input: T = new PassThrough() as unknown as T) {const output = new PassThrough();const child = Object.assign(new EventEmitter(), { stdio: [null, null, null, input, output] });const pipe = new BrowserPipe(child as unknown as ChildProcess);return { child, input, output, pipe };}+class SlowInput extends Writable {+ frames: Buffer[] = [];+ callbacks: Array<(error?: Error | null) => void> = [];+ constructor() { super({ highWaterMark: 1 }); }+ _write(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {+ this.frames.push(chunk);+ this.callbacks.push(callback);+ }+ async release(): Promise<void> {+ this.callbacks.shift()?.();+ await new Promise<void>((resolve) => setImmediate(resolve));+ }+}++afterEach(() => vi.useRealTimers());+describe('private CDP pipe bounds and failure handling', () => {it('handles partial frames and routes protocol events separately from command replies', async () => {const { pipe, input, output } = connection();@@ -46,4 +61,52 @@ describe('private CDP pipe bounds and failure handling', () => {await pending;}});++ it('honors pipe backpressure while transporting a full bounded page of base64 bodies', async () => {+ const input = new SlowInput();+ const { pipe, output } = connection(input);+ const body = Buffer.alloc(2_000_000).toString('base64');+ const requests = Array.from({ length: 4 }, () => pipe.send('Fetch.fulfillRequest', { body }));+ expect(input.frames).toHaveLength(1);+ expect(input.writableLength).toBeLessThan(2_700_000);+ for (let i = 1; i <= 4; i++) {+ output.write(JSON.stringify({ id: i, result: {} }) + '\0');+ await input.release();+ expect(input.frames).toHaveLength(Math.min(i + 1, 4));+ }+ await expect(Promise.all(requests)).resolves.toHaveLength(4);+ pipe.fail();+ });++ it('bounds queued wire bytes while the browser is not draining its input', async () => {+ const { pipe } = connection(new SlowInput());+ const body = Buffer.alloc(2_000_000).toString('base64');+ const requests = Array.from({ length: 5 }, () => pipe.send('Fetch.fulfillRequest', { body }).catch((error: Error) => error.message));+ expect((await Promise.all(requests)).every((value) => /closed|budget/.test(String(value)))).toBe(true);+ });++ it.each(['cancel', 'error', 'close'])('releases every queued command on %s without writing after cleanup', async (reason) => {+ const input = new SlowInput();+ const { pipe } = connection(input);+ const requests = [pipe.send('Page.enable'), pipe.send('Page.enable')].map((p) => p.catch((error: Error) => error.message));+ expect(input.frames).toHaveLength(1);+ if (reason === 'cancel') pipe.fail();+ else if (reason === 'error') input.emit('error', new Error('fixture pipe broke'));+ else input.emit('close');+ expect((await Promise.all(requests)).every((value) => /closed/.test(String(value)))).toBe(true);+ await input.release();+ expect(input.frames).toHaveLength(1);+ });++ it.each([undefined, 30_000])('keeps a finite deadline for timeout %s, including blocked writes', async (timeoutMs) => {+ vi.useFakeTimers();+ const { pipe } = connection(new SlowInput());+ const settled = vi.fn();+ const pending = pipe.send('Target.getTargets', {}, undefined, timeoutMs).catch((error: Error) => { settled(); return error.message; });+ await vi.advanceTimersByTimeAsync((timeoutMs ?? 10_000) - 1);+ expect(settled).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(await pending).toContain('timed out');+ expect(settled).toHaveBeenCalledOnce();+ });});diff --git a/src/capabilities/browser/pipe.ts b/src/capabilities/browser/pipe.tsindex fe6d7a2f..142c6203 100644--- a/src/capabilities/browser/pipe.ts+++ b/src/capabilities/browser/pipe.ts@@ -9,6 +9,9 @@ export class BrowserPipe {private buffer = '';private pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }>();private closed = false;+ private queuedBytes = 0;+ private waitingForDrain = false;+ private writes: Array<{ frame: string; bytes: number }> = [];onEvent: (event: ProtocolEvent) => void = () => {};onFailure: () => void = () => {};@@ -36,33 +39,57 @@ export class BrowserPipe {}});read.on('error', () => this.fail());- (child.stdio[3] as Writable).on('error', () => this.fail());+ read.on('end', () => this.fail());+ const write = child.stdio[3] as Writable;+ write.on('error', () => this.fail());+ write.on('close', () => this.fail());+ write.on('drain', () => { this.waitingForDrain = false; this.flushWrites(); });child.on('error', () => this.fail());child.on('exit', () => this.fail());}- send<T = Record<string, unknown>>(method: string, params: Record<string, unknown> = {}, sessionId?: string): Promise<T> {+ send<T = Record<string, unknown>>(method: string, params: Record<string, unknown> = {}, sessionId?: string, timeoutMs = 10_000): Promise<T> {if (this.closed) return Promise.reject(new Error('Browser is closed.'));- if (this.pending.size >= 128 || (this.child.stdio[3] as Writable).writableLength > 8_000_000) {- this.fail();- return Promise.reject(new Error('Browser protocol budget exceeded.'));- }return new Promise((resolve, reject) => {const id = ++this.id;+ const frame = `${JSON.stringify({ id, method, params, sessionId })}\0`;+ const bytes = Buffer.byteLength(frame);+ // An 8 MB page can produce 10.67 MB of base64 response bodies. This+ // bounded wire budget includes queued frames and the actual stream,+ // while content still has its separate, unchanged 8 MB page budget.+ if (this.pending.size >= 128 || this.queuedBytes + (this.child.stdio[3] as Writable).writableLength + bytes > 12_000_000) {+ this.fail();+ reject(new Error('Browser protocol budget exceeded.'));+ return;+ }const timer = setTimeout(() => {this.pending.delete(id);reject(new Error(`Browser ${method} timed out.`));this.fail();- }, 10_000);+ }, timeoutMs);timer.unref();this.pending.set(id, { resolve: (value) => resolve(value as T), reject, timer });- (this.child.stdio[3] as Writable).write(`${JSON.stringify({ id, method, params, sessionId })}\0`);+ this.writes.push({ frame, bytes });+ this.queuedBytes += bytes;+ this.flushWrites();});}+ private flushWrites(): void {+ const write = this.child.stdio[3] as Writable;+ while (!this.closed && !this.waitingForDrain && this.writes.length) {+ const next = this.writes.shift()!;+ this.queuedBytes -= next.bytes;+ try { this.waitingForDrain = !write.write(next.frame); }+ catch { this.fail(); }+ }+ }+fail(): void {if (this.closed) return;this.closed = true;+ this.writes = [];+ this.queuedBytes = 0;for (const entry of this.pending.values()) { clearTimeout(entry.timer); entry.reject(new Error('Browser closed unexpectedly.')); }this.pending.clear();this.onFailure();diff --git a/src/capabilities/browser/reader.integration.test.ts b/src/capabilities/browser/reader.integration.test.tsindex 67cf68b0..50d4f9d8 100644--- a/src/capabilities/browser/reader.integration.test.ts+++ b/src/capabilities/browser/reader.integration.test.ts@@ -2,6 +2,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitestimport { createServer, type Server } from 'node:http';import { stat, mkdir, writeFile } from 'node:fs/promises';import { dirname, join } from 'node:path';+import type { Readable } from 'node:stream';import { IsolatedBrowserReader } from './reader.js';import { BrowserPipe } from './pipe.js';import { browserUrl, requestPublicResource, type BrowserTransport } from './public-request.js';@@ -100,7 +101,7 @@ describe.skipIf(process.env.MERCURY_TEST_BROWSER !== '1')('installed browser agaawait writeFile(join(process.env.MERCURY_BROWSER_EVIDENCE_DIR, 'isolated-reader.jpg'), Buffer.from(result!.image, 'base64'));await writeFile(join(process.env.MERCURY_BROWSER_EVIDENCE_DIR, 'snapshot.txt'), result!.text);}- }, 30_000);+ }, 45_000); // Includes the bounded 30-second cold-browser startup allowance.it('isolates two sessions, enforces capacity and removes profiles on explicit close', async () => {const browser = reader();@@ -173,6 +174,32 @@ describe.skipIf(process.env.MERCURY_TEST_BROWSER !== '1')('installed browser agaawait expect(browser.run('session-a', 'snapshot')).rejects.toThrow('No isolated page');}, 30_000);+ it('cancels a blocked startup without waiting for the longer bootstrap deadline', async () => {+ const browser = reader();+ const controller = new AbortController();+ let started!: () => void;+ const startup = new Promise<void>((resolve) => { started = resolve; });+ const send = BrowserPipe.prototype.send;+ const spy = vi.spyOn(BrowserPipe.prototype, 'send').mockImplementation(function (this: BrowserPipe, ...args: Parameters<BrowserPipe['send']>) {+ const pending = send.apply(this, args);+ if (args[0] === 'Target.getTargets') {+ // Hold the real browser's reply in its owned pipe. Cancellation must+ // reject the queued request and close the process, not wait 30 seconds.+ (launched.at(-1)!.stdio[4] as Readable).pause();+ started();+ }+ return pending;+ } as never);+ try {+ const pending = browser.run('cancel-startup', 'navigate', 'https://fixture.public.example/a', controller.signal);+ const rejection = expect(pending).rejects.toThrow('closed');+ await startup;+ controller.abort();+ await rejection;+ await expect(browser.run('cancel-startup', 'snapshot')).rejects.toThrow('No isolated page');+ } finally { spy.mockRestore(); }+ }, 10_000);+it('expires idle sessions', async () => {const browser = reader({ idleMs: 100 });await browser.run('session-a', 'navigate', 'https://fixture.public.example/a');diff --git a/src/capabilities/browser/reader.ts b/src/capabilities/browser/reader.tsindex 4c2ddbfd..7df298c9 100644--- a/src/capabilities/browser/reader.ts+++ b/src/capabilities/browser/reader.ts@@ -96,7 +96,16 @@ class ReaderPage {this.pipe = new BrowserPipe(this.child);this.pipe.onFailure = () => this.closeInBackground();this.pipe.onEvent = (event) => { void this.handleEvent(event).catch(() => this.closeInBackground()); };- const { targetInfos } = await this.pipe.send<{ targetInfos: Array<{ type: string; targetId: string }> }>('Target.getTargets');+ // A cold installed browser can need longer than an already-running CDP+ // command. Only bootstrap gets 30 seconds, and cancellation stays prompt.+ const cancelStartup = () => this.pipe!.fail();+ this.lifetime.signal.addEventListener('abort', cancelStartup, { once: true });+ let targetInfos: Array<{ type: string; targetId: string }>;+ try {+ ({ targetInfos } = await this.pipe.send<{ targetInfos: Array<{ type: string; targetId: string }> }>('Target.getTargets', {}, undefined, 30_000));+ } finally {+ this.lifetime.signal.removeEventListener('abort', cancelStartup);+ }this.targetId = targetInfos.find((t) => t.type === 'page')?.targetId ?? '';if (!this.targetId) throw new Error('Browser did not create an empty page.');({ sessionId: this.sessionId } = await this.pipe.send<{ sessionId: string }>('Target.attachToTarget', { targetId: this.targetId, flatten: true }));@@ -241,7 +250,8 @@ class ReaderPage {close(): Promise<void> {if (this.closing) return this.closing;- this.closing = this.finishClose().catch((error) => { this.closing = undefined; throw error; });+ // Set the promise before aborting: a startup pipe failure can reenter close.+ this.closing = Promise.resolve().then(() => this.finishClose()).catch((error) => { this.closing = undefined; throw error; });return this.closing;}