Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(browser): cancel every initialization command promptly

Seth Wilsonfbd967b8a602
diff --git a/src/capabilities/browser/reader.integration.test.ts b/src/capabilities/browser/reader.integration.test.ts
index 50d4f9d8..c821f097 100644
--- a/src/capabilities/browser/reader.integration.test.ts
+++ b/src/capabilities/browser/reader.integration.test.ts
@@ -174,7 +174,7 @@ describe.skipIf(process.env.MERCURY_TEST_BROWSER !== '1')('installed browser aga
await 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 () => {
+ it.each(['Target.getTargets', 'Target.attachToTarget'])('cancels blocked initialization at %s without waiting for its deadline', async (blockedMethod) => {
const browser = reader();
const controller = new AbortController();
let started!: () => void;
@@ -182,9 +182,10 @@ describe.skipIf(process.env.MERCURY_TEST_BROWSER !== '1')('installed browser aga
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') {
+ if (args[0] === blockedMethod) {
// Hold the real browser's reply in its owned pipe. Cancellation must
- // reject the queued request and close the process, not wait 30 seconds.
+ // reject the queued request and close the process, not wait for either
+ // the 30-second bootstrap or a later 10-second command deadline.
(launched.at(-1)!.stdio[4] as Readable).pause();
started();
}
@@ -194,11 +195,13 @@ describe.skipIf(process.env.MERCURY_TEST_BROWSER !== '1')('installed browser aga
const pending = browser.run('cancel-startup', 'navigate', 'https://fixture.public.example/a', controller.signal);
const rejection = expect(pending).rejects.toThrow('closed');
await startup;
+ const cancelledAt = Date.now();
controller.abort();
await rejection;
+ expect(Date.now() - cancelledAt).toBeLessThan(5000);
await expect(browser.run('cancel-startup', 'snapshot')).rejects.toThrow('No isolated page');
} finally { spy.mockRestore(); }
- }, 10_000);
+ }, 40_000);
it('expires idle sessions', async () => {
const browser = reader({ idleMs: 100 });
diff --git a/src/capabilities/browser/reader.ts b/src/capabilities/browser/reader.ts
index 7df298c9..ed0f873b 100644
--- a/src/capabilities/browser/reader.ts
+++ b/src/capabilities/browser/reader.ts
@@ -100,27 +100,26 @@ class ReaderPage {
// 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));
+ const { targetInfos } = await this.pipe.send<{ targetInfos: Array<{ type: string; targetId: string }> }>('Target.getTargets', {}, undefined, 30_000);
+ 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 }));
+ await this.pipe.send('Browser.setDownloadBehavior', { behavior: 'deny' });
+ await this.pipe.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
+ await this.send('Page.enable');
+ await this.send('Emulation.setScriptExecutionDisabled', { value: true });
+ await this.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false });
+ await this.send('Network.setBypassServiceWorker', { bypass: true });
+ await this.send('Network.setCacheDisabled', { cacheDisabled: true });
+ await this.send('Fetch.enable', { patterns: [{ urlPattern: '*', requestStage: 'Request' }] });
+ const { frameTree } = await this.send<{ frameTree: { frame: { id: string } } }>('Page.getFrameTree');
+ this.lifetime.signal.throwIfAborted();
+ this.frameId = frameTree.frame.id;
+ this.touch();
} 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 }));
- await this.pipe.send('Browser.setDownloadBehavior', { behavior: 'deny' });
- await this.pipe.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
- await this.send('Page.enable');
- await this.send('Emulation.setScriptExecutionDisabled', { value: true });
- await this.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false });
- await this.send('Network.setBypassServiceWorker', { bypass: true });
- await this.send('Network.setCacheDisabled', { cacheDisabled: true });
- await this.send('Fetch.enable', { patterns: [{ urlPattern: '*', requestStage: 'Request' }] });
- const { frameTree } = await this.send<{ frameTree: { frame: { id: string } } }>('Page.getFrameTree');
- this.lifetime.signal.throwIfAborted();
- this.frameId = frameTree.frame.id;
- this.touch();
}
private send<T = Record<string, unknown>>(method: string, params: Record<string, unknown> = {}): Promise<T> {