Skip to content

Chrome DevTools for coding agents

fix: do not close a healthy browser when a tool call outlasts 60s (#3149)

Alex Rudenko39c7db11599a
diff --git a/src/BrowserManager.ts b/src/BrowserManager.ts
index 73ac8936..3a3ebab0 100644
--- a/src/BrowserManager.ts
+++ b/src/BrowserManager.ts
@@ -188,9 +188,7 @@ export class BrowserManager {
abandonPendingAttempt(): void {
this.#browserAttempt = new BrowserAttempt();
this.#initPromise = undefined;
- if (this.#browser) {
- this.forget(this.#browser);
- }
+ this.#forgetCurrentBrowser();
}
async #initBrowser(): Promise<Browser> {
@@ -348,14 +346,21 @@ export class BrowserManager {
blocklist,
allowlist,
logger: puppeteerLogger,
+ // Detects a transport that died without a close frame (e.g. an adb
+ // port-forward torn down mid-call). Puppeteer pings the socket
+ // periodically and terminates it on a missed pong, which rejects the
+ // in-flight CDP calls and fires `disconnected` so #evictIfCurrent()
+ // drops the stale handle. Without this, such a call would hang until
+ // protocolTimeout while holding the tool mutex.
+ wsOptions: {
+ keepAlive: true,
+ headers: wsHeaders,
+ },
};
let autoConnect = false;
if (wsEndpoint) {
connectOptions.browserWSEndpoint = wsEndpoint;
- if (wsHeaders) {
- connectOptions.headers = wsHeaders;
- }
} else if (browserURL) {
connectOptions.browserURL = browserURL;
} else if (channel || userDataDir) {
@@ -424,31 +429,30 @@ export class BrowserManager {
}
/**
- * Clears the cached browser handle if it still matches `candidate`, so the
- * next ensureBrowser() call establishes a fresh connection instead of
- * reusing a handle that looks connected but is actually dead (e.g. its CDP
- * transport died without ever emitting a `close`/`disconnected` event — as
- * happens when an adb port-forward is torn down mid-call rather than
- * closed cleanly).
+ * Drops the cached browser handle so the next ensureBrowser() call
+ * establishes a fresh connection. Only called from abandonPendingAttempt()
+ * when a getContext()-level timeout fires after ensureBrowser() already
+ * resolved, which means the handle looks connected but its CDP
+ * initialization is hanging.
*
- * Also actively tears `candidate` down in the background: closes it if it
- * was launched (so the Chrome subprocess doesn't leak), or disconnects if
- * it was only connected to (so the transport and its listeners don't
- * leak). This also settles any CDP call still pending against it —
- * Puppeteer's connection disposal synchronously rejects in-flight
- * callbacks — instead of leaving a hung call to leak forever.
+ * Also tears the browser down in the background: closes it if it was
+ * launched (so the Chrome subprocess doesn't leak), or disconnects if it
+ * was only connected to (so the transport and its listeners don't leak).
+ * Puppeteer's connection disposal rejects any in-flight CDP call, so a hung
+ * call settles instead of leaking forever.
*/
- forget(candidate: Browser): void {
- if (this.#browser !== candidate) {
+ #forgetCurrentBrowser(): void {
+ const browser = this.#browser;
+ if (!browser) {
return;
}
const mode = this.#browserMode;
this.#browser = undefined;
this.#browserMode = undefined;
if (mode === 'launched') {
- void this.#closeLaunchedBrowser(candidate);
+ void this.#closeLaunchedBrowser(browser);
} else {
- void candidate.disconnect().catch(err => {
+ void browser.disconnect().catch(err => {
logger?.('Failed to disconnect forgotten browser', err);
});
}
@@ -460,9 +464,8 @@ export class BrowserManager {
* call reconnects proactively rather than only discovering the staleness
* lazily on the next call's `!this.#browser?.connected` check. No teardown
* here — the browser is already disconnected/closed, that's why this
- * fired — so this shares forget()'s identity guard without its cleanup,
- * making a `disconnected` that fires late on an already-superseded browser
- * a safe no-op.
+ * fired. The identity guard makes a `disconnected` that fires late on an
+ * already-superseded browser a safe no-op.
*/
#evictIfCurrent(candidate: Browser): void {
if (this.#browser !== candidate) {
diff --git a/src/ToolHandler.ts b/src/ToolHandler.ts
index 9b37480e..6f89e617 100644
--- a/src/ToolHandler.ts
+++ b/src/ToolHandler.ts
@@ -10,7 +10,7 @@ import type {McpPage} from './McpPage.js';
import {McpResponse} from './McpResponse.js';
import {SlimMcpResponse} from './SlimMcpResponse.js';
import {ClearcutLogger} from './telemetry/ClearcutLogger.js';
-import type {Browser, CallToolResult, Mutex} from './third_party/index.js';
+import type {CallToolResult, Mutex} from './third_party/index.js';
import {zod} from './third_party/index.js';
import {labels} from './tools/categories.js';
import {categoryToFlagName} from './config/category-options.js';
@@ -26,15 +26,17 @@ import {fileURLToPath, pathToFileURL} from 'node:url';
import {isLocalhost} from './utils/url.js';
/**
- * Upper bound on how long a single tool call may wait on the browser
- * connection. Puppeteer normally rejects in-flight CDP calls when the
- * underlying transport closes, but a transport that dies silently (e.g. an
- * adb port-forward torn down mid-call, rather than closed cleanly) never
- * fires `close`/`error`/`disconnected`, so the call would otherwise hang
- * until an external (client-side) timeout gives up on the whole server. This
- * bound turns that into a fast, clear error instead, and forgets the cached
- * browser handle so the next call reconnects rather than reusing a handle
- * that still looks connected.
+ * Upper bound on how long a tool call may wait to acquire the browser
+ * (connect/launch and McpContext initialization). A connect attempt on a
+ * half-open socket can hang without ever failing; this bound turns that into
+ * a clear error and abandons the attempt so the next call starts fresh.
+ *
+ * This does not bound the tool's own work. A slow but valid call (a long
+ * `wait_for` timeout, an `evaluate_script` awaiting a slow promise, a
+ * Lighthouse audit) must finish on its own terms without the browser being
+ * closed underneath it. A transport that dies mid-call is detected by the
+ * WebSocket keep-alive configured in BrowserManager#connect(), which rejects
+ * the in-flight CDP calls and fires `disconnected`.
*/
export const TOOL_CALL_TIMEOUT_MS = 60_000;
@@ -188,7 +190,6 @@ export class ToolHandler {
private readonly serverArgs: ParsedArguments,
private readonly getContext: () => Promise<McpContext>,
private readonly toolMutex: Mutex,
- private readonly forgetBrowserOnTimeout: (browser: Browser) => void,
private readonly abandonPendingBrowserAttemptOnTimeout: () => void,
) {
const {disabled, reason, unavailableInMode} = getToolStatusInfo(
@@ -206,7 +207,7 @@ export class ToolHandler {
/**
* Races a promise against TOOL_CALL_TIMEOUT_MS, calling onTimeout() if the
* timer wins. The loser of the race is left running — there is no way to
- * cancel a pending Puppeteer call — but since nothing is left awaiting it,
+ * cancel a pending connect/launch — but since nothing is left awaiting it,
* it cannot block subsequent tool calls.
*/
async #raceWithTimeout<T>(
@@ -214,7 +215,7 @@ export class ToolHandler {
onTimeout: () => void,
): Promise<T> {
const timeoutError = new ToolCallTimeoutError(
- `Tool "${this.tool.name}" timed out after ${TOOL_CALL_TIMEOUT_MS}ms waiting on the browser connection. The connection may have been lost (for example, the debugged browser or app restarted). It will be re-established automatically on the next tool call.`,
+ `Tool "${this.tool.name}" timed out after ${TOOL_CALL_TIMEOUT_MS}ms waiting for the browser connection to be established. The connection attempt will be retried automatically on the next tool call.`,
);
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
@@ -274,61 +275,53 @@ export class ToolHandler {
if (context.consumeReconnectNotice()) {
response.setReconnectNotice();
}
- // Shares one budget with tool.handler(): several tools' actual CDP
- // calls happen in response.handle() instead (take_snapshot,
- // list_pages, get_network_request, list_extensions), so it needs
- // covering too. The closure below isn't cancelled on timeout — it
- // keeps running abandoned — but nothing after this point observes its
- // result.
- const {content, structuredContent} = await this.#raceWithTimeout(
- (async () => {
- let page: McpPage | undefined;
- try {
- await validateToolFiles(this.tool, params, context);
- if (isPageScopedTool(this.tool)) {
- const pageId =
- typeof params.pageId === 'number' ? params.pageId : undefined;
- page =
- this.serverArgs.pageIdRouting &&
- pageId !== undefined &&
- !isSlimTool(this.tool)
- ? context.getPageById(pageId)
- : context.getSelectedMcpPage();
- await page?.init();
- response.setPage(page);
- if (this.tool.blockedByDialog) {
- page.throwIfDialogOpen();
- }
- await this.tool.handler(
- {
- params,
- page,
- },
- response,
- context,
- );
- } else {
- await this.tool.handler(
- {
- params,
- },
- response,
- context,
- );
- }
- } catch (err) {
- response.setError(err);
+ let page: McpPage | undefined;
+ try {
+ await validateToolFiles(this.tool, params, context);
+ if (isPageScopedTool(this.tool)) {
+ const pageId =
+ typeof params.pageId === 'number' ? params.pageId : undefined;
+ page =
+ this.serverArgs.pageIdRouting &&
+ pageId !== undefined &&
+ !isSlimTool(this.tool)
+ ? context.getPageById(pageId)
+ : context.getSelectedMcpPage();
+ await page?.init();
+ response.setPage(page);
+ if (this.tool.blockedByDialog) {
+ page.throwIfDialogOpen();
}
- devToolsData = await context.getDevToolsData(page);
- pageUrl = context.getSelectedMcpPageUrl(page);
- // --experimentalDataFormat takes precedence over the legacy
- // --experimentalToonFormat.
- const dataFormat =
- this.serverArgs.experimentalDataFormat ??
- (this.serverArgs.experimentalToonFormat ? 'toon' : 'default');
- return await response.handle(context, dataFormat);
- })(),
- () => this.forgetBrowserOnTimeout(context.browser),
+ await this.tool.handler(
+ {
+ params,
+ page,
+ },
+ response,
+ context,
+ );
+ } else {
+ await this.tool.handler(
+ {
+ params,
+ },
+ response,
+ context,
+ );
+ }
+ } catch (err) {
+ response.setError(err);
+ }
+ devToolsData = await context.getDevToolsData(page);
+ pageUrl = context.getSelectedMcpPageUrl(page);
+ // --experimentalDataFormat takes precedence over the legacy
+ // --experimentalToonFormat.
+ const dataFormat =
+ this.serverArgs.experimentalDataFormat ??
+ (this.serverArgs.experimentalToonFormat ? 'toon' : 'default');
+ const {content, structuredContent} = await response.handle(
+ context,
+ dataFormat,
);
const result: CallToolResult & {
structuredContent?: Record<string, unknown>;
diff --git a/src/index.ts b/src/index.ts
index d29eb18a..4e68ab08 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -309,7 +309,6 @@ export class McpServer {
this.#serverArgs,
() => this.#getContext(),
this.#toolMutex,
- browser => this.#browserManager.forget(browser),
() => this.#browserManager.abandonPendingAttempt(),
);
}
diff --git a/tests/ToolHandler.test.ts b/tests/ToolHandler.test.ts
index 7c244629..1be57da6 100644
--- a/tests/ToolHandler.test.ts
+++ b/tests/ToolHandler.test.ts
@@ -71,7 +71,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(toolHandler.disabled, false);
@@ -118,7 +117,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(toolHandler.disabled, false);
@@ -161,7 +159,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(toolHandler.disabled, false);
@@ -220,7 +217,6 @@ describe('ToolHandler', () => {
async () => mockContext,
new Mutex(),
sinon.spy(),
- sinon.spy(),
).handle({});
sinon.assert.calledOnceWithExactly(handleStub, mockContext, expected);
@@ -297,7 +293,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
await toolHandler.handle({});
@@ -346,7 +341,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const params = {
@@ -402,7 +396,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(toolHandler.disabled, true);
@@ -435,7 +428,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(defaultHandler.disabled, false);
@@ -456,7 +448,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(disabledHandler.disabled, true);
@@ -486,7 +477,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(cliHandler.disabled, false);
const cliResult = await cliHandler.handle({function: '() => 1'});
@@ -518,7 +508,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(defaultHandler.disabled, false);
@@ -539,7 +528,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
assert.strictEqual(disabledHandler.disabled, true);
});
@@ -561,7 +549,6 @@ describe('ToolHandler', () => {
async () => sinon.createStubInstance(McpContext),
new Mutex(),
sinon.spy(),
- sinon.spy(),
);
}
@@ -651,7 +638,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const testFile = path.resolve('/workspace/url-file.txt');
@@ -729,7 +715,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const result = await toolHandler.handle({
@@ -762,7 +747,6 @@ describe('ToolHandler', () => {
async () => mockContext,
new Mutex(),
sinon.spy(),
- sinon.spy(),
);
const sourcePath = path.resolve('/outside/workspace/script.js');
@@ -820,7 +804,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const testPath = path.resolve('/workspace/upload.png');
@@ -879,7 +862,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const bundlePath = path.resolve('/workspace/app.swbn');
@@ -941,7 +923,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const result = await toolHandler.handle({
@@ -993,7 +974,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const result = await toolHandler.handle({
@@ -1043,7 +1023,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const result = await toolHandler.handle({
@@ -1101,7 +1080,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const outputPath = path.resolve('/local/output.json');
@@ -1164,7 +1142,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const result = await toolHandler.handle({
@@ -1220,7 +1197,6 @@ describe('ToolHandler', () => {
async () => mockRemoteContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const remotePath = path.resolve('/remote/file.txt');
@@ -1241,7 +1217,6 @@ describe('ToolHandler', () => {
async () => mockLocalContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
await localToolHandler.handle({remoteFile: remotePath});
@@ -1299,7 +1274,6 @@ describe('ToolHandler', () => {
async () => mockContext,
toolMutex,
sinon.spy(),
- sinon.spy(),
);
const inputPath = path.resolve('/workspace/output.png');
@@ -1352,7 +1326,6 @@ describe('ToolHandler', () => {
async () => mockContext,
new Mutex(),
sinon.spy(),
- sinon.spy(),
);
const result = await toolHandler.handle({
@@ -1368,10 +1341,10 @@ describe('ToolHandler', () => {
});
});
- it('times out a hung tool handler, fails fast, and forgets the browser', async () => {
+ it('does not cut off a slow tool handler on a healthy browser', async () => {
const tool: ToolDefinition = {
- name: 'hanging_tool',
- description: 'A tool whose handler never resolves',
+ name: 'slow_tool',
+ description: 'A tool whose handler legitimately outlasts the timeout',
annotations: {
category: ToolCategory.NAVIGATION,
readOnlyHint: true,
@@ -1379,18 +1352,19 @@ describe('ToolHandler', () => {
schema: {},
blockedByDialog: false,
verifyFilesSchema: {},
- handler: async () => {
- return await new Promise<void>(() => {
- // Simulates a tool call awaiting a CDP response on a transport
- // that died silently: it never resolves or rejects on its own.
+ handler: async (_request, response) => {
+ // Simulates valid slow work, e.g. wait_for with a long timeout or
+ // evaluate_script awaiting a slow promise.
+ await new Promise<void>(resolve => {
+ setTimeout(resolve, TOOL_CALL_TIMEOUT_MS * 2);
});
+ response.appendResponseLine('done');
},
};
const mockContext = sinon.createStubInstance(McpContext);
const mockProcess = sinon.createStubInstance(ChildProcess);
mockContext.browser = getMockBrowser({process: mockProcess});
- const forgetBrowserSpy = sinon.spy();
const toolMutex = new Mutex();
const serverArgs = new ConfigParser('1.0.0', ['node', 'script.js'], {
@@ -1402,83 +1376,20 @@ describe('ToolHandler', () => {
serverArgs,
async () => mockContext,
toolMutex,
- forgetBrowserSpy,
sinon.spy(),
);
const clock = sinon.useFakeTimers();
try {
const resultPromise = toolHandler.handle({});
- await clock.tickAsync(TOOL_CALL_TIMEOUT_MS);
+ await clock.tickAsync(TOOL_CALL_TIMEOUT_MS * 2);
const result = await resultPromise;
- assert.strictEqual(result.isError, true);
- assert.match(
- result.content[0].type === 'text' ? result.content[0].text : '',
- /timed out/,
- );
- sinon.assert.calledOnceWithExactly(forgetBrowserSpy, mockContext.browser);
- } finally {
- clock.restore();
- }
- });
-
- it('times out when response.handle() hangs, even if the tool handler resolves fast', async () => {
- const tool: ToolDefinition = {
- name: 'fast_handler_slow_response_tool',
- description:
- 'A tool whose handler resolves immediately but whose CDP work happens in response.handle()',
- annotations: {
- category: ToolCategory.NAVIGATION,
- readOnlyHint: true,
- },
- schema: {},
- blockedByDialog: false,
- verifyFilesSchema: {},
- handler: async () => {
- // Resolves immediately, like tools such as take_snapshot/list_pages
- // whose actual CDP calls happen in response.handle() instead.
- },
- };
-
- const mockContext = sinon.createStubInstance(McpContext);
- const mockProcess = sinon.createStubInstance(ChildProcess);
- mockContext.browser = getMockBrowser({process: mockProcess});
- const forgetBrowserSpy = sinon.spy();
- const handleStub = sinon.stub(McpResponse.prototype, 'handle').returns(
- new Promise(() => {
- // Simulates response.handle() making a CDP call on a transport
- // that died silently: it never resolves or rejects on its own.
- }),
- );
-
- const toolMutex = new Mutex();
- const serverArgs = new ConfigParser('1.0.0', ['node', 'script.js'], {
- CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS: 'true',
- }).parse();
-
- const toolHandler = new ToolHandler(
- tool,
- serverArgs,
- async () => mockContext,
- toolMutex,
- forgetBrowserSpy,
- sinon.spy(),
- );
-
- const clock = sinon.useFakeTimers();
- try {
- const resultPromise = toolHandler.handle({});
- await clock.tickAsync(TOOL_CALL_TIMEOUT_MS);
- const result = await resultPromise;
-
- assert.strictEqual(result.isError, true);
- assert.match(
+ assert.strictEqual(result.isError, undefined);
+ assert.strictEqual(
result.content[0].type === 'text' ? result.content[0].text : '',
- /timed out/,
+ 'done',
);
- sinon.assert.calledOnce(handleStub);
- sinon.assert.calledOnceWithExactly(forgetBrowserSpy, mockContext.browser);
} finally {
clock.restore();
}
@@ -1500,7 +1411,6 @@ describe('ToolHandler', () => {
},
};
- const forgetBrowserSpy = sinon.spy();
const abandonPendingBrowserAttemptSpy = sinon.spy();
const toolMutex = new Mutex();
@@ -1517,7 +1427,6 @@ describe('ToolHandler', () => {
// socket: it never resolves or rejects on its own.
}),
toolMutex,
- forgetBrowserSpy,
abandonPendingBrowserAttemptSpy,
);
@@ -1533,10 +1442,6 @@ describe('ToolHandler', () => {
/timed out/,
);
sinon.assert.calledOnce(abandonPendingBrowserAttemptSpy);
- // No resolved context/browser exists in this case, so it's
- // abandonPendingBrowserAttemptOnTimeout that fires, not
- // forgetBrowserOnTimeout.
- sinon.assert.notCalled(forgetBrowserSpy);
} finally {
clock.restore();
}
diff --git a/tests/browser.test.ts b/tests/browser.test.ts
index 9ab00c39..4e126ec0 100644
--- a/tests/browser.test.ts
+++ b/tests/browser.test.ts
@@ -150,6 +150,26 @@ describe('browser', () => {
sinon.assert.notCalled(pptrBrowser.close);
});
+ it('enables WebSocket keep-alive and passes wsHeaders when connecting', async () => {
+ const connectStub = sinon
+ .stub(puppeteer, 'connect')
+ .resolves(createMockPuppeteerBrowser());
+
+ const args = createMockParsedArguments({
+ wsEndpoint: 'ws://127.0.0.1:9222/devtools/browser/abc',
+ wsHeaders: {Authorization: 'Bearer token'},
+ });
+ await new BrowserManager(args).ensureBrowser();
+
+ sinon.assert.calledWithMatch(connectStub, {
+ browserWSEndpoint: 'ws://127.0.0.1:9222/devtools/browser/abc',
+ wsOptions: {
+ keepAlive: true,
+ headers: {Authorization: 'Bearer token'},
+ },
+ });
+ });
+
for (const categoryExtensions of [false, true]) {
it(`${categoryExtensions ? 'keeps' : 'drops'} extension targets when connecting with categoryExtensions=${categoryExtensions}`, async () => {
const connectStub = sinon
@@ -325,56 +345,6 @@ describe('browser', () => {
sinon.assert.calledOnceWithExactly(pptrBrowser.close);
});
- describe('forget', () => {
- it('does nothing when the candidate is not the current browser', async () => {
- const pptrBrowser = createMockPuppeteerBrowser();
- const other = createMockPuppeteerBrowser();
- sinon.stub(puppeteer, 'launch').resolves(pptrBrowser);
-
- const manager = new BrowserManager(
- createMockParsedArguments({headless: true, isolated: true}),
- );
- await manager.ensureBrowser();
-
- manager.forget(other);
-
- sinon.assert.notCalled(other.close);
- sinon.assert.notCalled(other.disconnect);
- sinon.assert.notCalled(pptrBrowser.close);
- sinon.assert.notCalled(pptrBrowser.disconnect);
- });
-
- it('disconnects the current browser when it was connected', async () => {
- const pptrBrowser = createMockPuppeteerBrowser();
- sinon.stub(puppeteer, 'connect').resolves(pptrBrowser);
-
- const manager = new BrowserManager(
- createMockParsedArguments({browserUrl: 'http://127.0.0.1:9222'}),
- );
- const browser = await manager.ensureBrowser();
-
- manager.forget(browser);
-
- sinon.assert.calledOnceWithExactly(pptrBrowser.disconnect);
- sinon.assert.notCalled(pptrBrowser.close);
- });
-
- it('closes the current browser when it was launched', async () => {
- const pptrBrowser = createMockPuppeteerBrowser();
- sinon.stub(puppeteer, 'launch').resolves(pptrBrowser);
-
- const manager = new BrowserManager(
- createMockParsedArguments({headless: true, isolated: true}),
- );
- const browser = await manager.ensureBrowser();
-
- manager.forget(browser);
-
- sinon.assert.calledOnceWithExactly(pptrBrowser.close);
- sinon.assert.notCalled(pptrBrowser.disconnect);
- });
- });
-
describe('push-based disconnect eviction', () => {
it('proactively evicts a disconnected browser without waiting for a lazy connected check', async () => {
const firstBrowser = createMockPuppeteerBrowser();
@@ -434,6 +404,33 @@ describe('browser', () => {
assert.strictEqual(third, newBrowser);
sinon.assert.calledTwice(launchStub);
});
+
+ it('disconnects an already-cached connected browser when abandoned', async () => {
+ const firstBrowser = createMockPuppeteerBrowser();
+ const secondBrowser = createMockPuppeteerBrowser();
+ const connectStub = sinon
+ .stub(puppeteer, 'connect')
+ .onFirstCall()
+ .resolves(firstBrowser)
+ .onSecondCall()
+ .resolves(secondBrowser);
+
+ const manager = new BrowserManager(
+ createMockParsedArguments({browserUrl: 'http://127.0.0.1:9222'}),
+ );
+
+ const first = await manager.ensureBrowser();
+ assert.strictEqual(first, firstBrowser);
+
+ manager.abandonPendingAttempt();
+
+ sinon.assert.calledOnceWithExactly(firstBrowser.disconnect);
+ sinon.assert.notCalled(firstBrowser.close);
+
+ const second = await manager.ensureBrowser();
+ assert.strictEqual(second, secondBrowser);
+ sinon.assert.calledTwice(connectStub);
+ });
});
describe('abandonPendingAttempt', () => {