Skip to content

refactor: extract browser in a BrowserManager class - #2787

Merged
Lightning00Blade merged 1 commit into
mainfrom
refactor-browser-manager
Sep 22, 2026
Merged

Lightning00Blade merged 1 commit into
mainfrom
refactor-browser-manager

Conversation

@Lightning00Blade

Copy link
Copy Markdown
Collaborator

No description provided.

@Lightning00Blade
Lightning00Blade marked this pull request as ready for review September 21, 2026 16:18
Comment thread src/config/browser-options.ts Resolved

@OrKoN OrKoN left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 / #closingPromise coordination from Commit 2 with #mutex = new Mutex() and #closingCount.
  • Unintended behaviors:
    1. Queued ensureBrowser() calls bypass #closingCount > 0 and return a browser that is about to be closed:
      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;
      }
      Suppose Call 1 (ensureBrowser()) is awaiting #initBrowser(), Call 2 (ensureBrowser()) queues on #mutex, and then Call 3 (close()) increments #closingCount to 1 and queues on #mutex behind Call 2:
      • Call 1 finishes #launch(), sets this.#browser = browser, checks this.#closingCount > 0, and throws 'Browser was closed while initializing.'.
      • Call 2 acquires #mutex before Call 3 (close()). Call 2 checks if (this.#browser?.connected) — which is true because Call 3 hasn't acquired the mutex yet! — and returns this.#browser without checking this.#closingCount > 0.
      • Immediately afterward, Call 3 (close()) acquires #mutex and closes this.#browser while Call 2 is actively using it.
    2. ensureBrowser() rejects before browser.close() has actually executed:
      When close() is called mid-launch, close() increments #closingCount and blocks on #mutex.acquire(). ensureBrowser() throws 'Browser was closed while initializing.' while still holding #mutex—meaning at the time ensureBrowser() rejects, close() has not yet run and the Chrome process is still alive.

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;
      }
  • Unintended behavior:
    1. Because this.#browserManager.close() now runs before this.#context?.dispose(), McpContext and ServiceWorkerConsoleCollector still have their targetdestroyed listeners attached to browser while Chrome is closing all targets, triggering unnecessary per-target teardown handlers during shutdown.
    2. When this.#context?.dispose() finally runs, the browser connection/pipe is already closed, causing devtoolsUniverse?.session.detach() in McpPage.dispose() and this.#session?.detach() in ServiceWorkerSubscriber.unsubscribe() to send CDP commands over a dead connection and log spurious 'Failed to detach DevTools session' errors.

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: false to experimentalDevtools in src/config/mcp-options.ts to avoid ?? false in TypeScript.
  • Unintended behavior:
    In src/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 --experimentalDevtools was omitted by the user, args.experimentalDevtools was undefined. computeFlagUsage logged experimental_devtools_present: false and left experimental_devtools as undefined (matching other experimental flags like experimentalVision, experimentalScreencast, experimentalIncludeAllPages).
    • After: Because default: false is now in mcpOptions, Yargs populates args.experimentalDevtools = false on every run. computeFlagUsage now sets experimental_devtools_present to undefined and logs experimental_devtools: false on every server startup even when the user never passed the flag.

4. enableExtensions Now Passed to puppeteer.connect()

  • Where: src/BrowserManager.ts (#connect) vs. src/index.ts (previously ensureBrowserConnected)
  • What changed:
    • Before (src/index.ts): ensureBrowserConnected({...}) did not pass enableExtensions: this.#serverArgs.categoryExtensions (only ensureBrowserLaunched passed enableExtensions).
    • After (src/BrowserManager.ts): #connect() extracts categoryExtensions: enableExtensions from this.#serverArgs and passes it to BrowserManager.makeTargetFilter(enableExtensions).
  • Unintended behavior: When connecting to an existing browser (--browserUrl, --wsEndpoint, or --autoConnect) with --categoryExtensions, targetFilter now allows chrome-extension:// targets, whereas previously makeTargetFilter received undefined (false) in ensureBrowserConnected.

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 above process.stdin.on('end' | 'close', ...) and process.on('SIGTERM' | 'SIGINT' | 'SIGHUP', ...).
  • Unintended behavior:
    1. McpServer.from() is asynchronous (it awaits loadIssueDescriptions()). If stdin closes immediately or SIGTERM/SIGINT/SIGHUP arrives while McpServer.from() is still initializing, the shutdown listeners are not yet attached.
    2. In shutdown(), await closeBrowser() was replaced with await server.close(), which now also awaits this.server.close() (MCP transport teardown) and this.#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.ts held a module-scoped singleton let browser: Browser | undefined. Now each McpServer instance creates its own new BrowserManager(...).
  • Unintended behavior: If two McpServer instances are created within the same Node process without isolated: true, the second instance will no longer reuse the connected browser singleton and will instead attempt to launch a second Chrome instance using the same default profile directory (~/.cache/chrome-devtools-mcp/chrome-profile), failing with The browser is already running for ....

@Lightning00Blade

Copy link
Copy Markdown
Collaborator Author

Addressed 1, 2, 4, 5.
For 3, we already to that for other places, we want to get the setup we should resolve the telemetry earlier.
For 6, now the server requires a BrowserManager instance, so one can be re-shared if needed, but no singleton is created.

@OrKoN

OrKoN commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Remaining & Newly Introduced Issues in Latest (89611db4b)

1. [HIGH] Breaking Public API Change in createMcpServer() and McpServer.from()

  • Where: src/index.ts (McpServerOptions, McpServer.from, createMcpServer)
  • What changed in Commit 6 (89611db4b):
    export interface McpServerOptions {
      browserManager: BrowserManager;
    }
    ...
    static async from(
      serverArgs: ParsedArguments,
      options: McpServerOptions,
    ): Promise<McpServer> { ... }
    
    /**
     * Creates and initializes a Chrome DevTools MCP server instance.
     *
     * Maintained as a public API for backwards compatibility because external
     * consumers and integrations rely on `createMcpServer()`. For new code,
     * prefer using `McpServer.from(serverArgs, options)`.
     */
    export async function createMcpServer(
      serverArgs: ParsedArguments,
      options: McpServerOptions,
    ): Promise<{server: SdkMcpServer}> {
      const server = await McpServer.from(serverArgs, options);
      return {server: server.server};
    }
  • Impact:
    1. As documented in the JSDoc above createMcpServer, external consumers and integrations call createMcpServer(serverArgs) or createMcpServer(serverArgs, {logFile}) (and McpServer.from(serverArgs, {logFile})).
    2. Making options: {browserManager: BrowserManager} a required parameter and removing logFile?: fs.WriteStream from McpServerOptions is a breaking runtime and TypeScript API change: calling createMcpServer(serverArgs) without a second argument now throws TypeError: Cannot read properties of undefined (reading 'browserManager').
  • Recommendation:
    Keep browserManager and logFile optional in McpServerOptions and keep options: McpServerOptions = {} defaulted in McpServer.from and createMcpServer:
    export interface McpServerOptions {
      browserManager?: BrowserManager;
      logFile?: fs.WriteStream;
    }
    And inside McpServer's constructor:
    this.#browserManager =
      options.browserManager ?? new BrowserManager(serverArgs, options);

2. [MEDIUM] BrowserManager.#ensureBrowserLocked() Still Calls #initBrowser() Before Checking this.#closingCount > 0

  • Where: src/BrowserManager.ts (#ensureBrowserLocked, close)
  • Current code in Commit 6 (89611db4b):
    async #ensureBrowserLocked(): Promise<Browser> {
      using _guard = await this.#mutex.acquire();
      if (!this.#browser?.connected) {
        await this.#initBrowser();
      }
      if (this.#closingCount > 0 || !this.#browser) {
        await this.#closeBrowser();
        throw new Error('Browser was closed while initializing.');
      }
      return this.#browser;
    }
    
    async close(): Promise<void> {
      this.#initPromise = undefined;
      this.#closingCount++;
      using _guard = await this.#mutex.acquire();
      try {
        await this.#closeBrowser();
      } finally {
        this.#closingCount--;
      }
    }
  • Unintended behaviors:
    1. Launches Chrome when a close is already queued:
      Because close() clears this.#initPromise = undefined before acquiring #mutex, a subsequent ensureBrowser() call made while #mutex is busy will start a new #ensureBrowserLocked() call and queue on #mutex. If #closingCount > 0 when #ensureBrowserLocked() acquires #mutex (e.g., ensureBrowser() ci: re-configure ci #1 -> close() ci: re-configure ci #1 -> ensureBrowser() docs: polish readme #2 -> close() docs: polish readme #2), #ensureBrowserLocked() checks if (!this.#browser?.connected) before checking if (this.#closingCount > 0). It will launch a new Chrome process via await this.#initBrowser(), only to immediately see this.#closingCount > 0 on the next line, close the newly launched browser, and throw 'Browser was closed while initializing.'.
    2. ensureBrowser() called while close() is tearing down an active browser will relaunch Chrome instead of rejecting:
      If a browser is already running (#initPromise === undefined) and close() is called, close() increments #closingCount to 1, acquires #mutex, and awaits browser.close(). If ensureBrowser() is called while browser.close() is in flight, ensureBrowser() waits on this.#mutex.acquire(). When browser.close() completes, close() runs finally { this.#closingCount--; } (setting #closingCount back to 0) before _guard is disposed at block exit. When #mutex is released to the waiting ensureBrowser(), #closingCount is already 0, so ensureBrowser() launches a brand-new browser instead of rejecting.
  • Recommendation:
    Check if (this.#closingCount > 0) at the beginning of ensureBrowser() (or #ensureBrowserLocked() before this.#mutex.acquire() and again after acquiring #mutex before this.#initBrowser()):
    async #ensureBrowserLocked(): Promise<Browser> {
      if (this.#closingCount > 0) {
        throw new Error('Browser was closed while initializing.');
      }
      using _guard = await this.#mutex.acquire();
      if (this.#closingCount > 0) {
        throw new Error('Browser was closed while initializing.');
      }
      if (!this.#browser?.connected) {
        await this.#initBrowser();
      }
      if (this.#closingCount > 0 || !this.#browser) {
        await this.#closeBrowser();
        throw new Error('Browser was closed while initializing.');
      }
      return this.#browser;
    }

3. [LOW] Telemetry Change from default: false on experimentalDevtools Remains Unresolved

  • Where: src/config/mcp-options.ts (experimentalDevtools), tests/cli.test.ts, & src/telemetry/flagUtils.ts (computeFlagUsage)
  • What happened:
    Commit 3 added default: false to experimentalDevtools in src/config/mcp-options.ts, and Commit 5 (a265c2fcc) updated tests/cli.test.ts to include experimentalDevtools: false in the expected default parsed arguments.
  • Impact:
    In src/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;
    }
    Unlike the other experimental boolean flags (experimentalVision, experimentalScreencast, experimentalIncludeAllPages), which omit default so that computeFlagUsage reports *_present: false and *: undefined when not specified by the user, experimentalDevtools now has default: false. This causes computeFlagUsage to omit experimental_devtools_present (undefined) and always report experimental_devtools: false on every run.
  • Recommendation:
    Remove default: false from experimentalDevtools in src/config/mcp-options.ts (and revert tests/cli.test.ts), and use Boolean(this.#serverArgs.experimentalDevtools) (or this.#serverArgs.experimentalDevtools ?? false) in BrowserManager and McpServer.

Let's revert changes to the experimental_devtools defaults. Even if we happened to other flags before we do not want to spike usage for this flag and we should not make this change during refactoring. Let's file an issue to address this as a follow-up (I think it is the same issue that yargs things default values are actually set by the user).

@Lightning00Blade
Lightning00Blade added this pull request to the merge queue Sep 22, 2026
Merged via the queue into main with commit 3228f44 Sep 22, 2026
31 of 33 checks passed
@Lightning00Blade
Lightning00Blade deleted the refactor-browser-manager branch September 22, 2026 14:09
zamelee added a commit to zamelee/chrome-devtools-mcp that referenced this pull request Sep 23, 2026
…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.
pull Bot pushed a commit to oogalieboogalie/chrome-devtools-mcp that referenced this pull request Sep 23, 2026
🤖 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).
bitbay added a commit to bitbay/chrome-devtools-mcp that referenced this pull request Sep 23, 2026
…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.
bitbay added a commit to bitbay/chrome-devtools-mcp that referenced this pull request Sep 23, 2026
…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).
bitbay added a commit to bitbay/chrome-devtools-mcp that referenced this pull request Sep 28, 2026
…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.
bitbay added a commit to bitbay/chrome-devtools-mcp that referenced this pull request Sep 28, 2026
…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).
bitbay added a commit to bitbay/chrome-devtools-mcp that referenced this pull request Sep 29, 2026
…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.
bitbay added a commit to bitbay/chrome-devtools-mcp that referenced this pull request Sep 29, 2026
…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).
github-actions Bot pushed a commit to lmn451/chrome-devtools-mcp that referenced this pull request Oct 13, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants