Repository navigation
refactor: extract browser in a BrowserManager class - #2787
Conversation
227cbb3 to
7ab367d
Compare
7ab367d to
533d3c1
Compare
OrKoN
left a comment
There was a problem hiding this comment.
Please check these:
Summary of Unintended Changes & Regressions
While the goal of PR #2787 is a pure refactoring to extract src/browser.ts into src/BrowserManager.ts, the 4 commits introduce several unintended behavioral changes, race conditions, and telemetry/lifecycle regressions:
1. Race Conditions in BrowserManager.ensureBrowser() vs. BrowserManager.close()
- Where:
src/BrowserManager.ts(ensureBrowser,close,#mutex,#closingCount) - What changed: Commit 3 replaced the explicit
#pendingBrowser/#closingPromisecoordination from Commit 2 with#mutex = new Mutex()and#closingCount. - Unintended behaviors:
- Queued
ensureBrowser()calls bypass#closingCount > 0and return a browser that is about to be closed:Suppose Call 1 (async ensureBrowser(): Promise<Browser> { using _guard = await this.#mutex.acquire(); if (this.#browser?.connected) { return this.#browser; } const browser = await this.#initBrowser(); if (this.#closingCount > 0) { throw new Error('Browser was closed while initializing.'); } return browser; }
ensureBrowser()) is awaiting#initBrowser(), Call 2 (ensureBrowser()) queues on#mutex, and then Call 3 (close()) increments#closingCountto1and queues on#mutexbehind Call 2:- Call 1 finishes
#launch(), setsthis.#browser = browser, checksthis.#closingCount > 0, and throws'Browser was closed while initializing.'. - Call 2 acquires
#mutexbefore Call 3 (close()). Call 2 checksif (this.#browser?.connected)— which istruebecause Call 3 hasn't acquired the mutex yet! — and returnsthis.#browserwithout checkingthis.#closingCount > 0. - Immediately afterward, Call 3 (
close()) acquires#mutexand closesthis.#browserwhile Call 2 is actively using it.
- Call 1 finishes
ensureBrowser()rejects beforebrowser.close()has actually executed:
Whenclose()is called mid-launch,close()increments#closingCountand blocks on#mutex.acquire().ensureBrowser()throws'Browser was closed while initializing.'while still holding#mutex—meaning at the timeensureBrowser()rejects,close()has not yet run and the Chrome process is still alive.
- Queued
2. Reversed Disposal Order in McpServer.close()
- Where:
src/index.ts(McpServer.close) - What changed:
- Before:
async close(): Promise<void> { this.#context?.dispose(); this.#context = undefined; await this.server.close(); }
- After:
async close(): Promise<void> { await Promise.allSettled([ this.#browserManager.close(), this.server.close(), ]); this.#context?.dispose(); this.#context = undefined; }
- Before:
- Unintended behavior:
- Because
this.#browserManager.close()now runs beforethis.#context?.dispose(),McpContextandServiceWorkerConsoleCollectorstill have theirtargetdestroyedlisteners attached tobrowserwhile Chrome is closing all targets, triggering unnecessary per-target teardown handlers during shutdown. - When
this.#context?.dispose()finally runs, the browser connection/pipe is already closed, causingdevtoolsUniverse?.session.detach()inMcpPage.dispose()andthis.#session?.detach()inServiceWorkerSubscriber.unsubscribe()to send CDP commands over a dead connection and log spurious'Failed to detach DevTools session'errors.
- Because
3. Telemetry Regression from Adding default: false to experimentalDevtools
- Where:
src/config/mcp-options.ts(experimentalDevtools) &src/telemetry/flagUtils.ts(computeFlagUsage) - What changed: Commit 3 added
default: falsetoexperimentalDevtoolsinsrc/config/mcp-options.tsto avoid?? falsein TypeScript. - Unintended behavior:
Insrc/telemetry/flagUtils.ts:if (!('default' in config) || value !== config.default) { usage[`${snakeCaseName}_present`] = value !== undefined && value !== null; } if (config.type === 'boolean' && typeof value === 'boolean') { usage[snakeCaseName] = value; }
- Before: When
--experimentalDevtoolswas omitted by the user,args.experimentalDevtoolswasundefined.computeFlagUsageloggedexperimental_devtools_present: falseand leftexperimental_devtoolsasundefined(matching other experimental flags likeexperimentalVision,experimentalScreencast,experimentalIncludeAllPages). - After: Because
default: falseis now inmcpOptions, Yargs populatesargs.experimentalDevtools = falseon every run.computeFlagUsagenow setsexperimental_devtools_presenttoundefinedand logsexperimental_devtools: falseon every server startup even when the user never passed the flag.
- Before: When
4. enableExtensions Now Passed to puppeteer.connect()
- Where:
src/BrowserManager.ts(#connect) vs.src/index.ts(previouslyensureBrowserConnected) - What changed:
- Before (
src/index.ts):ensureBrowserConnected({...})did not passenableExtensions: this.#serverArgs.categoryExtensions(onlyensureBrowserLaunchedpassedenableExtensions). - After (
src/BrowserManager.ts):#connect()extractscategoryExtensions: enableExtensionsfromthis.#serverArgsand passes it toBrowserManager.makeTargetFilter(enableExtensions).
- Before (
- Unintended behavior: When connecting to an existing browser (
--browserUrl,--wsEndpoint, or--autoConnect) with--categoryExtensions,targetFilternow allowschrome-extension://targets, whereas previouslymakeTargetFilterreceivedundefined(false) inensureBrowserConnected.
5. Delayed Signal & stdin Shutdown Listener Registration
- Where:
src/bin/chrome-devtools-mcp-main.ts - What changed:
const server = await McpServer.from(args, {logFile});was moved aboveprocess.stdin.on('end' | 'close', ...)andprocess.on('SIGTERM' | 'SIGINT' | 'SIGHUP', ...). - Unintended behavior:
McpServer.from()is asynchronous (it awaitsloadIssueDescriptions()). Ifstdincloses immediately orSIGTERM/SIGINT/SIGHUParrives whileMcpServer.from()is still initializing, the shutdown listeners are not yet attached.- In
shutdown(),await closeBrowser()was replaced withawait server.close(), which now also awaitsthis.server.close()(MCP transport teardown) andthis.#context?.dispose()inside the 5-second forced-exit timer.
6. Process-Wide Singleton Browser Replaced with Per-McpServer Instance State
- Where:
src/browser.ts->src/BrowserManager.ts - What changed: Previously,
src/browser.tsheld a module-scoped singletonlet browser: Browser | undefined. Now eachMcpServerinstance creates its ownnew BrowserManager(...). - Unintended behavior: If two
McpServerinstances are created within the same Node process withoutisolated: true, the second instance will no longer reuse the connectedbrowsersingleton and will instead attempt to launch a second Chrome instance using the same default profile directory (~/.cache/chrome-devtools-mcp/chrome-profile), failing withThe browser is already running for ....
6a44de9 to
89611db
Compare
|
Addressed 1, 2, 4, 5. |
Remaining & Newly Introduced Issues in Latest (
|
89611db to
fceecac
Compare
…ntion bound Cherry-pick of upstream commit e98a3ca (ConsoleCollector retention bound) onto fork main, bringing ChromeDevTools#2773 fix. Why cherry-pick single commit: - fork v1.7.0 = upstream v1.7.0 tag (commit 774d78f) - upstream v1.7.0..HEAD: 178 commits, including ChromeDevTools#2408 SDK v2 + ChromeDevTools#2787 BrowserManager (large refactors) - Tier 1 cherry-pick strategy (low-risk bug fixes first) Other Tier 1 commits aborted: - ChromeDevTools#2772 WaitForHelper timeout: conflict with fork's waitForHelperHelper() refactor (equivalent inlining) - ChromeDevTools#2792 preserve input error message: needs puppeteer 25.10+ for TimeoutError export (fork is on 25.5.0) - ChromeDevTools#2794 handle dialogs during input: same puppeteer version dep + input.ts already forked Verification: - PageCollector.ts source: 0 tsc errors - tests/PageCollector.test.ts: passes via node --test - build: tsc --noEmitOnError false + post-build.ts succeeds - baseline tsc has 63 pre-existing errors (pnpm dual puppeteer-core paths) - not introduced by this commit Next: Phase 2A (puppeteer 25.10.0 upgrade) before picking up ChromeDevTools#2792 / ChromeDevTools#2794. Not for upstream PR per fork policy. See tmp/code-backups/tier1-sync-handoff.md for full abort rationale.
🤖 I have created a release *beep* *boop* --- ## [1.10.0](ChromeDevTools/chrome-devtools-mcp@chrome-devtools-mcp-v1.9.0...chrome-devtools-mcp-v1.10.0) (2026-09-23) ### 🎉 Features * add css formatter class ([ChromeDevTools#2707](ChromeDevTools#2707)) ([f0b5fa4](ChromeDevTools@f0b5fa4)) * add get_css_style tool ([ChromeDevTools#2612](ChromeDevTools#2612)) ([4454ae0](ChromeDevTools@4454ae0)) * **performance:** chunked trace buffer parser for large recordings ([ChromeDevTools#2721](ChromeDevTools#2721)) ([23b9a48](ChromeDevTools@23b9a48)) * set default pageSize and pageIdx for get_css_styles tool ([ChromeDevTools#2799](ChromeDevTools#2799)) ([dc9d14d](ChromeDevTools@dc9d14d)) * support config file ([ChromeDevTools#2661](ChromeDevTools#2661)) ([314a5fa](ChromeDevTools@314a5fa)) * **telemetry:** persist date of the last tool call. ([ChromeDevTools#2705](ChromeDevTools#2705)) ([c54a493](ChromeDevTools@c54a493)) * **telemetry:** recording a sanitized version of the client name ([ChromeDevTools#2757](ChromeDevTools#2757)) ([55fbc57](ChromeDevTools@55fbc57)) * **telemetry:** report hermes client usage. ([ChromeDevTools#2703](ChromeDevTools#2703)) ([fb47e6c](ChromeDevTools@fb47e6c)) * update css formatter class to add AtRule, PositionTryRule, PropertyRule, FunctionRule ([ChromeDevTools#2717](ChromeDevTools#2717)) ([d4a0620](ChromeDevTools@d4a0620)) * update css formatter class to add inherited rules ([ChromeDevTools#2715](ChromeDevTools#2715)) ([3d7e7bb](ChromeDevTools@3d7e7bb)) * update css formatter class to add matched rules ([ChromeDevTools#2713](ChromeDevTools#2713)) ([8c8616f](ChromeDevTools@8c8616f)) * update css formatter class to add pseudo element ([ChromeDevTools#2716](ChromeDevTools#2716)) ([df1469a](ChromeDevTools@df1469a)) * update css formatter to add keyframes rules ([ChromeDevTools#2718](ChromeDevTools#2718)) ([cdc365c](ChromeDevTools@cdc365c)) ### 🛠️ Fixes * bound ConsoleCollector retention per navigation ([ChromeDevTools#2773](ChromeDevTools#2773)) ([e98a3ca](ChromeDevTools@e98a3ca)) * **cli:** forward explicit false options on start ([ChromeDevTools#2702](ChromeDevTools#2702)) ([d9a8cb6](ChromeDevTools@d9a8cb6)) * **config:** preserve raw values for config coercion ([ChromeDevTools#2747](ChromeDevTools#2747)) ([906c83b](ChromeDevTools@906c83b)) * don't log Puppeteer logs to file unless requested ([ChromeDevTools#2743](ChromeDevTools#2743)) ([4fbfbc4](ChromeDevTools@4fbfbc4)) * explain launch failures caused by running as root ([ChromeDevTools#2634](ChromeDevTools#2634)) ([9d29223](ChromeDevTools@9d29223)) * handle JavaScript dialogs opened during input tool actions ([ChromeDevTools#2794](ChromeDevTools#2794)) ([266112b](ChromeDevTools@266112b)) * **performance:** prevent memory leak by scoping trace engine model per parse ([ChromeDevTools#2720](ChromeDevTools#2720)) ([d05cbc0](ChromeDevTools@d05cbc0)) * preserve console history across same-document navigations ([ChromeDevTools#2676](ChromeDevTools#2676)) ([aa25562](ChromeDevTools@aa25562)) * preserve underlying error message in input tool actions ([ChromeDevTools#2792](ChromeDevTools#2792)) ([6e47dbb](ChromeDevTools@6e47dbb)) * set emulatedUserAgent and use finalDisplayedUrl in lighthouse_audit ([ChromeDevTools#2795](ChromeDevTools#2795)) ([941f82a](ChromeDevTools@941f82a)) * timout in WaitForHelper.ts ([ChromeDevTools#2772](ChromeDevTools#2772)) ([dc1d055](ChromeDevTools@dc1d055)) ### 📄 Documentation * add FLUJO client configuration ([ChromeDevTools#2690](ChromeDevTools#2690)) ([65a679e](ChromeDevTools@65a679e)) * fix categories not being configured correclty ([ChromeDevTools#2807](ChromeDevTools#2807)) ([2250cdc](ChromeDevTools@2250cdc)) * fix defaults for non-boolean values ([ChromeDevTools#2744](ChromeDevTools#2744)) ([342d243](ChromeDevTools@342d243)) * update page routing option name ([ChromeDevTools#2748](ChromeDevTools#2748)) ([8939965](ChromeDevTools@8939965)) * update SKILL for chrome-devtools to use get_css_styles tool ([ChromeDevTools#2760](ChromeDevTools#2760)) ([421011e](ChromeDevTools@421011e)) ### 🏗️ Refactor * disable tools instead of not registering them ([ChromeDevTools#2636](ChromeDevTools#2636)) ([b455469](ChromeDevTools@b455469)) * extract browser in a BrowserManager class ([ChromeDevTools#2787](ChromeDevTools#2787)) ([3228f44](ChromeDevTools@3228f44)) * migrate the MCP SDK to v2 ([ChromeDevTools#2408](ChromeDevTools#2408)) ([da3c406](ChromeDevTools@da3c406)) * move comments formatting to CommentFormatter class ([ChromeDevTools#2719](ChromeDevTools#2719)) ([e3cded0](ChromeDevTools@e3cded0)) * prepare for SDK v2 ([ChromeDevTools#2771](ChromeDevTools#2771)) ([61780c7](ChromeDevTools@61780c7)) * simplify our gen scritps ([ChromeDevTools#2793](ChromeDevTools#2793)) ([5068584](ChromeDevTools@5068584)) * unify call type and ensure typesafety ([ChromeDevTools#2659](ChromeDevTools#2659)) ([882f93e](ChromeDevTools@882f93e)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please).
…ead connections proactively Ports the abandon-token / forget() / push-based disconnected-eviction mechanism from this branch's pre-rebase browser.ts onto the new BrowserManager introduced by upstream ChromeDevTools#2787 ("refactor: extract browser in a BrowserManager class"). Not a straight merge: browser.ts was deleted upstream and its module-level state / ensureBrowserConnected / ensureBrowserLaunched functions were replaced by a unified ensureBrowser() serialized behind BrowserManager's own #mutex. Replaces (in spirit, not by cherry-pick) this branch's 2ca8527, c260b4c, and the browser.ts portion of 6d2d4e9: - #browserAttempt generation token + abandonPendingAttempt(), checked in #ensureBrowserLocked() after #initBrowser() returns. Under the new #mutex, two concurrent installs racing each other is now structurally impossible (only one attempt can ever be in flight), so the token's job narrows from "prevent a race between two installs" to "discard a connect()/launch() resolution that arrives after a tool-call timeout already abandoned it" — otherwise a stale connection could be handed to a later, unrelated call. #mutex's scope is left as-is (full ensureBrowser() call) rather than reworked for true parallel recovery; that isn't required to fix the reported bug and would touch two already-reviewed upstream concurrency tests, so it's left as a possible separate follow-up. - forget(candidate) ported directly from forgetBrowser(), including c260b4c's resource-leak fix: it actively closes/disconnects the forgotten browser instead of just dropping the reference, which also settles any CDP call still hung against it. - A push-based `disconnected` listener (#evictIfCurrent), installed in #launch()/#connect(), so a cleanly-detected disconnect is handled proactively instead of only being caught by the next call's lazy `!browser.connected` check. Upstream had neither this nor any forget()-equivalent before this change. Tests: new BrowserManager describe blocks for forget()'s three modes, push-based eviction (including a no-op check for a disconnected event firing on an already-superseded browser), and abandonment in both connect- and launch-mode. The two existing upstream close()-race tests are left untouched and still pass unmodified.
…connection Re-implemented as a fresh diff against upstream's current ToolHandler.ts (post-ChromeDevTools#2659/ChromeDevTools#2787, which predates this branch's whole timeout-wrapping fix), not a literal merge of this branch's prior diff — unrelated upstream divergences (.strict() input schema, `disabled` field, `handle` as a class-field arrow function using `using _guard = ...`) are left as-is. Replaces the ToolHandler.ts portion of this branch's 6d2d4e9, and f67b230 in full: - TOOL_CALL_TIMEOUT_MS, ToolCallTimeoutError, and #raceWithTimeout<T>() ported verbatim. Puppeteer gives no way to cancel a pending call, so a timeout only stops the handler from waiting — the underlying attempt keeps running abandoned, which is exactly why the onTimeout callbacks below exist. - getContext() is wrapped in #raceWithTimeout, calling the injected abandonPendingBrowserAttemptOnTimeout on timeout (see the BrowserManager commit) so a resolution nobody is waiting for anymore doesn't get silently installed for a later caller. - The tool.handler() + response.handle() sequence is wrapped in a single shared budget (matching f67b230's reasoning: several tools' actual CDP calls happen inside response.handle(), not tool.handler(), so both need covering by one timeout or the second phase hangs unprotected after the first one's already accounted for). On timeout, forgetBrowserOnTimeout is called with the resolved context's browser. - src/index.ts: threads BrowserManager's forget()/abandonPendingAttempt() down as bound closures into ToolHandler's two new required constructor params (`forgetBrowserOnTimeout`, `abandonPendingBrowserAttemptOnTimeout`) instead of the old free-function defaults browser.ts used to provide, since BrowserManager is now private instance state owned by McpServer rather than importable module state. #getContext() itself needs no change — it already calls this.#browserManager.ensureBrowser(). This branch's 3d9dd88 (AGENTS.md style fixes: no `!`, no hand-rolled mocks, sinon.assert over Node's assert) has nothing to port forward — this diff was written directly against those rules and upstream's current tests/mocks.ts conventions, so there was nothing to retrofit. Tests: ~23 existing `new ToolHandler(...)` call sites updated for the two new required constructor params (no-op sinon.spy() stand-ins where the test doesn't care about them). Three new regression tests ported from this branch's prior versions: a hung tool.handler() times out and forgets the browser; a hung response.handle() times out even when tool.handler() resolves fast; a hung getContext() times out and abandons the pending attempt without touching forgetBrowserOnTimeout (no resolved browser exists to forget in that case).
…ead connections proactively Ports the abandon-token / forget() / push-based disconnected-eviction mechanism from this branch's pre-rebase browser.ts onto the new BrowserManager introduced by upstream ChromeDevTools#2787 ("refactor: extract browser in a BrowserManager class"). Not a straight merge: browser.ts was deleted upstream and its module-level state / ensureBrowserConnected / ensureBrowserLaunched functions were replaced by a unified ensureBrowser() serialized behind BrowserManager's own #mutex. Replaces (in spirit, not by cherry-pick) this branch's 2ca8527, c260b4c, and the browser.ts portion of 6d2d4e9: - #browserAttempt generation token + abandonPendingAttempt(), checked in #ensureBrowserLocked() after #initBrowser() returns. Under the new #mutex, two concurrent installs racing each other is now structurally impossible (only one attempt can ever be in flight), so the token's job narrows from "prevent a race between two installs" to "discard a connect()/launch() resolution that arrives after a tool-call timeout already abandoned it" — otherwise a stale connection could be handed to a later, unrelated call. #mutex's scope is left as-is (full ensureBrowser() call) rather than reworked for true parallel recovery; that isn't required to fix the reported bug and would touch two already-reviewed upstream concurrency tests, so it's left as a possible separate follow-up. - forget(candidate) ported directly from forgetBrowser(), including c260b4c's resource-leak fix: it actively closes/disconnects the forgotten browser instead of just dropping the reference, which also settles any CDP call still hung against it. - A push-based `disconnected` listener (#evictIfCurrent), installed in #launch()/#connect(), so a cleanly-detected disconnect is handled proactively instead of only being caught by the next call's lazy `!browser.connected` check. Upstream had neither this nor any forget()-equivalent before this change. Tests: new BrowserManager describe blocks for forget()'s three modes, push-based eviction (including a no-op check for a disconnected event firing on an already-superseded browser), and abandonment in both connect- and launch-mode. The two existing upstream close()-race tests are left untouched and still pass unmodified.
…connection Re-implemented as a fresh diff against upstream's current ToolHandler.ts (post-ChromeDevTools#2659/ChromeDevTools#2787, which predates this branch's whole timeout-wrapping fix), not a literal merge of this branch's prior diff — unrelated upstream divergences (.strict() input schema, `disabled` field, `handle` as a class-field arrow function using `using _guard = ...`) are left as-is. Replaces the ToolHandler.ts portion of this branch's 6d2d4e9, and f67b230 in full: - TOOL_CALL_TIMEOUT_MS, ToolCallTimeoutError, and #raceWithTimeout<T>() ported verbatim. Puppeteer gives no way to cancel a pending call, so a timeout only stops the handler from waiting — the underlying attempt keeps running abandoned, which is exactly why the onTimeout callbacks below exist. - getContext() is wrapped in #raceWithTimeout, calling the injected abandonPendingBrowserAttemptOnTimeout on timeout (see the BrowserManager commit) so a resolution nobody is waiting for anymore doesn't get silently installed for a later caller. - The tool.handler() + response.handle() sequence is wrapped in a single shared budget (matching f67b230's reasoning: several tools' actual CDP calls happen inside response.handle(), not tool.handler(), so both need covering by one timeout or the second phase hangs unprotected after the first one's already accounted for). On timeout, forgetBrowserOnTimeout is called with the resolved context's browser. - src/index.ts: threads BrowserManager's forget()/abandonPendingAttempt() down as bound closures into ToolHandler's two new required constructor params (`forgetBrowserOnTimeout`, `abandonPendingBrowserAttemptOnTimeout`) instead of the old free-function defaults browser.ts used to provide, since BrowserManager is now private instance state owned by McpServer rather than importable module state. #getContext() itself needs no change — it already calls this.#browserManager.ensureBrowser(). This branch's 3d9dd88 (AGENTS.md style fixes: no `!`, no hand-rolled mocks, sinon.assert over Node's assert) has nothing to port forward — this diff was written directly against those rules and upstream's current tests/mocks.ts conventions, so there was nothing to retrofit. Tests: ~23 existing `new ToolHandler(...)` call sites updated for the two new required constructor params (no-op sinon.spy() stand-ins where the test doesn't care about them). Three new regression tests ported from this branch's prior versions: a hung tool.handler() times out and forgets the browser; a hung response.handle() times out even when tool.handler() resolves fast; a hung getContext() times out and abandons the pending attempt without touching forgetBrowserOnTimeout (no resolved browser exists to forget in that case).
…ead connections proactively Ports the abandon-token / forget() / push-based disconnected-eviction mechanism from this branch's pre-rebase browser.ts onto the new BrowserManager introduced by upstream ChromeDevTools#2787 ("refactor: extract browser in a BrowserManager class"). Not a straight merge: browser.ts was deleted upstream and its module-level state / ensureBrowserConnected / ensureBrowserLaunched functions were replaced by a unified ensureBrowser() serialized behind BrowserManager's own #mutex. Replaces (in spirit, not by cherry-pick) this branch's 2ca8527, c260b4c, and the browser.ts portion of 6d2d4e9: - #browserAttempt generation token + abandonPendingAttempt(), checked in #ensureBrowserLocked() after #initBrowser() returns. Under the new #mutex, two concurrent installs racing each other is now structurally impossible (only one attempt can ever be in flight), so the token's job narrows from "prevent a race between two installs" to "discard a connect()/launch() resolution that arrives after a tool-call timeout already abandoned it" — otherwise a stale connection could be handed to a later, unrelated call. #mutex's scope is left as-is (full ensureBrowser() call) rather than reworked for true parallel recovery; that isn't required to fix the reported bug and would touch two already-reviewed upstream concurrency tests, so it's left as a possible separate follow-up. - forget(candidate) ported directly from forgetBrowser(), including c260b4c's resource-leak fix: it actively closes/disconnects the forgotten browser instead of just dropping the reference, which also settles any CDP call still hung against it. - A push-based `disconnected` listener (#evictIfCurrent), installed in #launch()/#connect(), so a cleanly-detected disconnect is handled proactively instead of only being caught by the next call's lazy `!browser.connected` check. Upstream had neither this nor any forget()-equivalent before this change. Tests: new BrowserManager describe blocks for forget()'s three modes, push-based eviction (including a no-op check for a disconnected event firing on an already-superseded browser), and abandonment in both connect- and launch-mode. The two existing upstream close()-race tests are left untouched and still pass unmodified.
…connection Re-implemented as a fresh diff against upstream's current ToolHandler.ts (post-ChromeDevTools#2659/ChromeDevTools#2787, which predates this branch's whole timeout-wrapping fix), not a literal merge of this branch's prior diff — unrelated upstream divergences (.strict() input schema, `disabled` field, `handle` as a class-field arrow function using `using _guard = ...`) are left as-is. Replaces the ToolHandler.ts portion of this branch's 6d2d4e9, and f67b230 in full: - TOOL_CALL_TIMEOUT_MS, ToolCallTimeoutError, and #raceWithTimeout<T>() ported verbatim. Puppeteer gives no way to cancel a pending call, so a timeout only stops the handler from waiting — the underlying attempt keeps running abandoned, which is exactly why the onTimeout callbacks below exist. - getContext() is wrapped in #raceWithTimeout, calling the injected abandonPendingBrowserAttemptOnTimeout on timeout (see the BrowserManager commit) so a resolution nobody is waiting for anymore doesn't get silently installed for a later caller. - The tool.handler() + response.handle() sequence is wrapped in a single shared budget (matching f67b230's reasoning: several tools' actual CDP calls happen inside response.handle(), not tool.handler(), so both need covering by one timeout or the second phase hangs unprotected after the first one's already accounted for). On timeout, forgetBrowserOnTimeout is called with the resolved context's browser. - src/index.ts: threads BrowserManager's forget()/abandonPendingAttempt() down as bound closures into ToolHandler's two new required constructor params (`forgetBrowserOnTimeout`, `abandonPendingBrowserAttemptOnTimeout`) instead of the old free-function defaults browser.ts used to provide, since BrowserManager is now private instance state owned by McpServer rather than importable module state. #getContext() itself needs no change — it already calls this.#browserManager.ensureBrowser(). This branch's 3d9dd88 (AGENTS.md style fixes: no `!`, no hand-rolled mocks, sinon.assert over Node's assert) has nothing to port forward — this diff was written directly against those rules and upstream's current tests/mocks.ts conventions, so there was nothing to retrofit. Tests: ~23 existing `new ToolHandler(...)` call sites updated for the two new required constructor params (no-op sinon.spy() stand-ins where the test doesn't care about them). Three new regression tests ported from this branch's prior versions: a hung tool.handler() times out and forgets the browser; a hung response.handle() times out even when tool.handler() resolves fast; a hung getContext() times out and abandons the pending attempt without touching forgetBrowserOnTimeout (no resolved browser exists to forget in that case).
…romeDevTools#3047) Fixes ChromeDevTools#3046. Split out of ChromeDevTools#3041 at the reviewer's request. This is the target-filter half; ChromeDevTools#3041 keeps the config change. `BrowserManager#connect()`, used for `--browserUrl`, `--wsEndpoint` and `--autoConnect`, built Puppeteer's target filter with `makeTargetFilter()` and no argument. So Puppeteer dropped every `chrome-extension://` target at connect time, and `list_pages` never showed extension pages or service workers when attached, even with `--categoryExtensions`. `#launch()` already passes the flag. This passes it the same way in `#connect()`. The omission dates from ChromeDevTools#1922, whose attach call site didn't pass the flag (see ChromeDevTools#1171 and ChromeDevTools#1173). ChromeDevTools#2787 carried it into `BrowserManager`. ## Changes - `src/BrowserManager.ts`: read `categoryExtensions` from the server args in `#connect()` and pass it to `makeTargetFilter()`. - `tests/browser.test.ts`: two tests that connect with `browserUrl` and check the `targetFilter` handed to `puppeteer.connect`. A `chrome-extension://` target is kept only when `categoryExtensions` is set. The `true` case fails without the `BrowserManager` change. With the flag off, behaviour is unchanged: `undefined` falls back to `makeTargetFilter`'s `false` default. ## Note on reachability On `main`, `--categoryExtensions` with an attach flag is currently rejected at startup (ChromeDevTools#2989, lifted in ChromeDevTools#3041). So this path can't be reached from the command line on `main` until ChromeDevTools#3041 lands. The unit tests reach it directly. Landing this first means ChromeDevTools#3041 doesn't expose an attach mode with hidden extension pages. ## Testing - `npm run gen` (no changes) and `npm run check-format`: clean. - `node scripts/test.js tests/browser.test.ts tests/cli.test.ts`: all pass. - Manual, on Windows with Chrome 154.0.8037.98, a tab open on an unpacked MV3 extension's page: the same change applied on top of 1.10.1, started with `--browserUrl http://127.0.0.1:<port> --categoryExtensions=true`. `list_pages` lists the tab under `## Extension Pages`. Unpatched 1.10.1 and 1.9.0 list no extension pages. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Nicholas Roscino <[email protected]>
No description provided.