chrome-devtools-mcp 1.10.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +72 -20
  2. package/build/src/BrowserManager.js +155 -27
  3. package/build/src/McpContext.js +598 -200
  4. package/build/src/McpPage.js +513 -131
  5. package/build/src/McpResponse.js +291 -116
  6. package/build/src/McpWorker.js +66 -0
  7. package/build/src/SlimMcpResponse.js +5 -1
  8. package/build/src/TextSnapshot.js +40 -20
  9. package/build/src/ToolHandler.js +306 -147
  10. package/build/src/bin/chrome-devtools-mcp-main.js +13 -10
  11. package/build/src/bin/chrome-devtools-mcp.js +1 -1
  12. package/build/src/bin/chrome-devtools.js +34 -44
  13. package/build/src/collectors/PageCollector.js +13 -9
  14. package/build/src/collectors/ServiceWorkerCollector.js +20 -13
  15. package/build/src/collectors/constants.js +7 -0
  16. package/build/src/config/ConfigLocator.js +70 -0
  17. package/build/src/config/ConfigParser.js +159 -0
  18. package/build/src/config/ConfigWatcher.js +94 -0
  19. package/build/src/config/ServerConfig.js +251 -0
  20. package/build/src/config/browser-options.js +15 -17
  21. package/build/src/config/category-options.js +15 -30
  22. package/build/src/config/cli-commands.js +165 -5
  23. package/build/src/config/cli-options.js +441 -58
  24. package/build/src/config/mcp-options.js +212 -264
  25. package/build/src/config/puppeteer-options.js +67 -0
  26. package/build/src/config/tool-options.js +60 -0
  27. package/build/src/daemon/client.js +84 -44
  28. package/build/src/daemon/daemon.js +59 -45
  29. package/build/src/daemon/utils.js +46 -12
  30. package/build/src/devtools/DevToolsCommentBridge.js +71 -11
  31. package/build/src/devtools/DevtoolsUtils.js +52 -15
  32. package/build/src/devtools/McpHostBindingAdapter.js +0 -1
  33. package/build/src/formatters/CommentFormatter.js +4 -13
  34. package/build/src/formatters/ConsoleFormatter.js +29 -2
  35. package/build/src/formatters/CssFormatter.js +3 -2
  36. package/build/src/formatters/HeapSnapshotFormatter.js +111 -57
  37. package/build/src/formatters/IssueFormatter.js +33 -32
  38. package/build/src/formatters/NetworkFormatter.js +62 -22
  39. package/build/src/formatters/RemoteObjectFormatter.js +231 -0
  40. package/build/src/formatters/SnapshotFormatter.js +44 -7
  41. package/build/src/index.js +285 -88
  42. package/build/src/processors/ChunkedTraceParser.js +11 -11
  43. package/build/src/processors/HeapSnapshotManager.js +455 -156
  44. package/build/src/processors/PerformanceTrace.js +9 -9
  45. package/build/src/telemetry/ClearcutLogger.js +1 -1
  46. package/build/src/telemetry/transformation.js +7 -11
  47. package/build/src/telemetry/watchdog/main.js +1 -1
  48. package/build/src/third_party/THIRD_PARTY_NOTICES +399 -689
  49. package/build/src/third_party/bundled-packages.json +7 -8
  50. package/build/src/third_party/cli.js +9239 -0
  51. package/build/src/third_party/devtools-formatter-worker.js +4299 -2517
  52. package/build/src/third_party/devtools-heap-snapshot-worker.js +1298 -22
  53. package/build/src/third_party/index.js +132003 -146852
  54. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantRead.md +0 -1
  55. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantReadOptOut.md +5 -0
  56. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSet.md +0 -1
  57. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSetOptOut.md +5 -0
  58. package/build/src/third_party/issue-descriptions/deprecation.md +1 -1
  59. package/build/src/third_party/issue-descriptions/genericGeolocationPromptWithoutUserGesture.md +5 -0
  60. package/build/src/third_party/issue-descriptions/sriValidationFailedIntegrityMismatch.md +2 -0
  61. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +54576 -52174
  62. package/build/src/tools/ToolDefinition.js +102 -12
  63. package/build/src/tools/comments.js +62 -4
  64. package/build/src/tools/console.js +6 -4
  65. package/build/src/tools/css.js +5 -2
  66. package/build/src/tools/emulation.js +22 -8
  67. package/build/src/tools/extensions.js +5 -0
  68. package/build/src/tools/input.js +29 -9
  69. package/build/src/tools/lighthouse.js +136 -12
  70. package/build/src/tools/memory.js +166 -59
  71. package/build/src/tools/network.js +5 -4
  72. package/build/src/tools/pages.js +52 -7
  73. package/build/src/tools/performance.js +28 -7
  74. package/build/src/tools/pwa.js +7 -0
  75. package/build/src/tools/screencast.js +74 -33
  76. package/build/src/tools/screenshot.js +52 -21
  77. package/build/src/tools/script.js +125 -40
  78. package/build/src/tools/slim/tools.js +27 -13
  79. package/build/src/tools/snapshot.js +13 -3
  80. package/build/src/tools/thirdPartyDeveloper.js +9 -5
  81. package/build/src/tools/tools.js +35 -22
  82. package/build/src/tools/webmcp.js +11 -6
  83. package/build/src/types.js +11 -0
  84. package/build/src/utils/TaskRunner.js +136 -0
  85. package/build/src/utils/WaitForHelper.js +15 -2
  86. package/build/src/utils/bytes.js +2 -12
  87. package/build/src/utils/check-for-updates.js +2 -2
  88. package/build/src/utils/disclaimers.js +27 -0
  89. package/build/src/utils/errorHandling.js +20 -0
  90. package/build/src/utils/keyboard.js +14 -2
  91. package/build/src/utils/logger.js +84 -5
  92. package/build/src/utils/resourceType.js +27 -0
  93. package/build/src/utils/text.js +44 -0
  94. package/build/src/utils/timeout.js +14 -0
  95. package/build/src/utils/url.js +140 -3
  96. package/build/src/version.js +1 -1
  97. package/package.json +16 -11
  98. package/skills/a11y-debugging/SKILL.md +7 -12
  99. package/skills/chrome-devtools/SKILL.md +2 -2
  100. package/skills/chrome-devtools-cli/SKILL.md +18 -15
  101. package/skills/cookie-debugging/SKILL.md +8 -5
  102. package/skills/debug-optimize-lcp/SKILL.md +1 -1
  103. package/skills/troubleshooting/SKILL.md +5 -6
package/README.md CHANGED
@@ -3,12 +3,12 @@
3
3
  [![npm chrome-devtools-mcp package](https://img.shields.io/npm/v/chrome-devtools-mcp.svg)](https://npmjs.org/package/chrome-devtools-mcp)
4
4
 
5
5
  Chrome DevTools for agents (`chrome-devtools-mcp`) lets your coding agent (such as Antigravity, Claude, Cursor or Copilot)
6
- control and inspect a live Chrome browser. It acts as a Model-Context-Protocol
7
- (MCP) server, giving your AI coding assistant access to the full power of
8
- Chrome DevTools for reliable automation, in-depth debugging, and performance analysis.
9
- A [CLI][cli] is also provided for use without MCP.
6
+ control and inspect a live Chrome browser. It is available as a
7
+ Model-Context-Protocol (MCP) server and as a [CLI][cli]. Both give your AI
8
+ coding assistant access to the full power of Chrome DevTools for reliable
9
+ automation, in-depth debugging, and performance analysis.
10
10
 
11
- [Tool reference][tool-reference] | [Changelog][changelog] | [Contributing][contributing] | [Troubleshooting][troubleshooting] | [Design Principles][design-principles]
11
+ [Tool reference][tool-reference] | [CLI][cli] | [Skills][skills] | [Changelog][changelog] | [Contributing][contributing] | [Troubleshooting][troubleshooting] | [Design Principles][design-principles]
12
12
 
13
13
  ## Key features
14
14
 
@@ -83,21 +83,6 @@ Add the following config to your MCP client:
83
83
  > [!NOTE]
84
84
  > Using `chrome-devtools-mcp@latest` ensures that your MCP client will always use the latest version of the Chrome DevTools MCP server.
85
85
 
86
- If you are interested in doing only basic browser tasks, use the `--slim` mode:
87
-
88
- ```json
89
- {
90
- "mcpServers": {
91
- "chrome-devtools": {
92
- "command": "npx",
93
- "args": ["-y", "chrome-devtools-mcp@latest", "--slim", "--headless"]
94
- }
95
- }
96
- }
97
- ```
98
-
99
- See [Slim tool reference][slim-tool-reference].
100
-
101
86
  ### MCP Client configuration
102
87
 
103
88
  For setup instructions specific to your editor or agent (e.g. Antigravity, Claude Code, Cursor, VS Code), please see our [Client Configurations Guide][client-configurations-guide].
@@ -115,6 +100,70 @@ Your MCP client should open the browser and record a performance trace.
115
100
  > [!NOTE]
116
101
  > The MCP server will start the browser automatically once the MCP client uses a tool that requires a running browser instance. Connecting to the Chrome DevTools MCP server on its own will not automatically start the browser.
117
102
 
103
+ ## CLI
104
+
105
+ The package also includes the `chrome-devtools` CLI. Use it to control the browser from your terminal without MCP:
106
+
107
+ ```sh
108
+ npm i chrome-devtools-mcp@latest -g
109
+ chrome-devtools navigate_page 1 --url "https://developers.chrome.com"
110
+ chrome-devtools take_screenshot 1 --filePath screenshot.png
111
+ chrome-devtools stop
112
+ ```
113
+
114
+ See the [CLI guide][cli] for all commands and options.
115
+
116
+ ## Skills
117
+
118
+ The package includes [skills](./skills) that teach your agent how to use Chrome DevTools:
119
+
120
+ | Skill | Use it to |
121
+ | --------------------------------------------------------- | ----------------------------------------------- |
122
+ | [`chrome-devtools`](./skills/chrome-devtools) | Debug and automate pages with the MCP tools. |
123
+ | [`chrome-devtools-cli`](./skills/chrome-devtools-cli) | Run the CLI and write shell scripts with it. |
124
+ | [`a11y-debugging`](./skills/a11y-debugging) | Audit and fix accessibility issues. |
125
+ | [`cookie-debugging`](./skills/cookie-debugging) | Debug cookies, sessions, and authentication. |
126
+ | [`debug-optimize-lcp`](./skills/debug-optimize-lcp) | Debug and improve Largest Contentful Paint. |
127
+ | [`memory-leak-debugging`](./skills/memory-leak-debugging) | Find and fix memory leaks. |
128
+ | [`troubleshooting`](./skills/troubleshooting) | Fix connection problems between MCP and Chrome. |
129
+
130
+ ### Install skills as a plugin
131
+
132
+ A plugin installs the MCP server and all skills, including the CLI skill:
133
+
134
+ - **Claude Code:** Run `/plugin marketplace add ChromeDevTools/chrome-devtools-mcp`, then `/plugin install chrome-devtools-mcp@chrome-devtools-plugins`.
135
+ - **Copilot / VS Code:** Run **Chat: Install Plugin From Source** and enter `ChromeDevTools/chrome-devtools-mcp`.
136
+ - **Gemini CLI:** Run `gemini extensions install --auto-update https://github.com/ChromeDevTools/chrome-devtools-mcp`.
137
+
138
+ See the [Client Configurations Guide][client-configurations-guide] for more information.
139
+
140
+ ### Install skills manually
141
+
142
+ If your agent does not support plugins, copy the skill folders into the skills directory of your agent. The npm package contains the skills:
143
+
144
+ ```sh
145
+ npm i chrome-devtools-mcp@latest -g
146
+ # Example for Claude Code. Use the skills directory of your agent.
147
+ mkdir -p ~/.claude/skills
148
+ cp -R "$(npm root -g)/chrome-devtools-mcp/skills/chrome-devtools-cli" ~/.claude/skills/
149
+ ```
150
+
151
+ > [!IMPORTANT]
152
+ > The `chrome-devtools-cli` skill requires the CLI. Install the package globally before you use the skill.
153
+
154
+ ### Keep skills up to date
155
+
156
+ Skills describe the tools of a specific version. Update the skills each time you update the MCP server or the CLI. Outdated skills can tell your agent to use tools or parameters that changed.
157
+
158
+ - **Plugins:** Use the update command of the plugin manager of your agent. The Gemini CLI command above enables automatic updates with `--auto-update`.
159
+ - **Manual installs:** Update the package, then copy the skill folders again:
160
+
161
+ ```sh
162
+ npm i chrome-devtools-mcp@latest -g
163
+ mkdir -p ~/.claude/skills
164
+ cp -R "$(npm root -g)/chrome-devtools-mcp/skills/chrome-devtools-cli" ~/.claude/skills/
165
+ ```
166
+
118
167
  ## Tools
119
168
 
120
169
  If you run into any issues, checkout our [troubleshooting guide][troubleshooting].
@@ -124,6 +173,8 @@ See the full [Tool Reference][tool-reference] for a complete list of all support
124
173
 
125
174
  Find the complete list of server parameters (e.g., `--headless`, `--isolated`, `--slim`) and how to configure WebSocket connections in the [Configuration Guide][configuration-guide].
126
175
 
176
+ For basic browser tasks only, the `--slim` flag exposes a reduced set of tools. See the [Slim tool reference][slim-tool-reference].
177
+
127
178
  ## Advanced Usage
128
179
 
129
180
  For advanced features such as handling concurrent sessions, persistent user data directories, connecting to a running Chrome instance instead of starting a new one, or debugging on Android, see our [Advanced Usage Guide][advanced-usage-guide].
@@ -141,6 +192,7 @@ For a reference implementation, see the [Gemini CLI browser agent documentation]
141
192
  [configuration-guide]: ./docs/configuration.md
142
193
  [contributing]: ./CONTRIBUTING.md
143
194
  [design-principles]: ./docs/design-principles.md
195
+ [skills]: #skills
144
196
  [slim-tool-reference]: ./docs/slim-tool-reference.md
145
197
  [tool-reference]: ./docs/tool-reference.md
146
198
  [troubleshooting]: ./docs/troubleshooting.md
@@ -60,19 +60,27 @@ import { execSync } from 'node:child_process';
60
60
  import fs from 'node:fs';
61
61
  import os from 'node:os';
62
62
  import path from 'node:path';
63
- import { Mutex, puppeteer } from './third_party/index.js';
64
- import { logger, puppeteerLogger } from './utils/logger.js';
63
+ import { Mutex, puppeteer, } from './third_party/index.js';
64
+ import { logger, puppeteerLogger, redactConnectOptionsForLogging, } from './utils/logger.js';
65
65
  import { isAllowedUrl } from './utils/url.js';
66
+ /**
67
+ * Identity token for an in-flight connect/launch attempt. Instances carry no
68
+ * data and are never inspected structurally — only ever compared by
69
+ * reference (`!==`) — see BrowserManager#abandonPendingAttempt().
70
+ */
71
+ class BrowserAttempt {
72
+ }
66
73
  export class BrowserManager {
67
74
  #browser;
68
75
  #browserMode;
69
76
  #initPromise;
70
77
  #mutex = new Mutex();
71
78
  #closingCount = 0;
72
- #serverArgs;
79
+ #config;
73
80
  #options;
74
- constructor(serverArgs, options = {}) {
75
- this.#serverArgs = serverArgs;
81
+ #browserAttempt = new BrowserAttempt();
82
+ constructor(config, options = {}) {
83
+ this.#config = config;
76
84
  this.#options = options;
77
85
  }
78
86
  static makeTargetFilter(enableExtensions = false) {
@@ -148,16 +156,33 @@ export class BrowserManager {
148
156
  if (this.#closingCount > 0) {
149
157
  throw new Error('Browser was closed while initializing.');
150
158
  }
151
- const _guard = __addDisposableResource(env_1, await this.#mutex.acquire(), false);
159
+ // Captured before acquiring #mutex, not after: a caller queued here can
160
+ // have its own timeout fire (abandonPendingAttempt()) while it's still
161
+ // waiting for the lock. Capturing only after acquiring it would let such
162
+ // a call silently adopt the freshly-rotated token as its own baseline
163
+ // once the lock frees up, defeating the abandonment check entirely.
164
+ const attempt = this.#browserAttempt;
165
+ const guard = __addDisposableResource(env_1, await this.#mutex.acquire(), false);
152
166
  if (this.#closingCount > 0) {
153
167
  throw new Error('Browser was closed while initializing.');
154
168
  }
169
+ if (this.#browserAttempt !== attempt) {
170
+ // Abandoned while queued for the lock — #browser was never touched by
171
+ // this call, so bail immediately without #closeBrowser(), which could
172
+ // otherwise tear down a different, still-current attempt's browser.
173
+ throw new Error('Connection attempt was abandoned before it completed.');
174
+ }
155
175
  if (!this.#browser?.connected) {
156
176
  await this.#initBrowser();
157
177
  }
158
- if (this.#closingCount > 0 || !this.#browser) {
178
+ if (this.#closingCount > 0 ||
179
+ this.#browserAttempt !== attempt ||
180
+ !this.#browser) {
181
+ const reason = this.#closingCount > 0
182
+ ? 'Browser was closed while initializing.'
183
+ : 'Connection attempt was abandoned before it completed.';
159
184
  await this.#closeBrowser();
160
- throw new Error('Browser was closed while initializing.');
185
+ throw new Error(reason);
161
186
  }
162
187
  return this.#browser;
163
188
  }
@@ -169,27 +194,51 @@ export class BrowserManager {
169
194
  __disposeResources(env_1);
170
195
  }
171
196
  }
197
+ /**
198
+ * Signals that whoever was waiting on the in-flight ensureBrowser() call
199
+ * has given up (e.g. a tool-call timeout). There's no way to cancel a
200
+ * pending connect()/launch(), so this doesn't stop it — it rotates the
201
+ * token to a fresh value and clears #initPromise, so a late-resolving
202
+ * attempt gets discarded by #ensureBrowserLocked() instead of silently
203
+ * installed for a caller who already walked away.
204
+ *
205
+ * Also forgets the cached #browser, if any. This only ever fires from a
206
+ * getContext()-level timeout, which covers both ensureBrowser() and the
207
+ * McpContext initialization built on it — if ensureBrowser() already
208
+ * resolved and it's that later step hanging (e.g. a dead CDP transport),
209
+ * the token rotation alone does nothing, since #browser is already
210
+ * cached. Safe to forget unconditionally here: a tool call that already
211
+ * received a Browser keeps using it, so forgetting the cached value only
212
+ * makes the next ensureBrowser() reconnect.
213
+ */
214
+ abandonPendingAttempt() {
215
+ this.#browserAttempt = new BrowserAttempt();
216
+ this.#initPromise = undefined;
217
+ this.#forgetCurrentBrowser();
218
+ }
172
219
  async #initBrowser() {
173
- if (this.#serverArgs.browserUrl ||
174
- this.#serverArgs.wsEndpoint ||
175
- this.#serverArgs.autoConnect) {
220
+ if (this.#config.resolved.browserUrl ||
221
+ this.#config.resolved.wsEndpoint ||
222
+ this.#config.resolved.autoConnect) {
176
223
  return await this.#connect();
177
224
  }
178
225
  return await this.#launch();
179
226
  }
180
227
  async #launch() {
181
- const { channel, executablePath, headless, isolated = false, categoryExtensions: enableExtensions, viaCli, viewport, acceptInsecureCerts, experimentalDevtools: devtools = false, blockedUrlPattern: blocklist, allowedUrlPattern: allowlist, ignoreDefaultChromeArg, proxyServer, } = this.#serverArgs;
228
+ const { channel, executablePath, headless, isolated = false, categoryExtensions: enableExtensions, viaCli, viewport, acceptInsecureCerts, experimentalDevtools: devtools = false, blockedUrlPattern: blocklist, allowedUrlPattern: allowlist, ignoreDefaultChromeArg, proxyServer, } = this.#config.resolved;
182
229
  const profileDirName = channel && channel !== 'stable'
183
230
  ? `chrome-profile-${channel}`
184
231
  : 'chrome-profile';
185
- let userDataDir = this.#serverArgs.userDataDir;
232
+ let userDataDir = this.#config.resolved.userDataDir;
186
233
  if (!isolated && !userDataDir) {
187
234
  userDataDir = path.join(os.homedir(), '.cache', viaCli ? 'chrome-devtools-mcp-cli' : 'chrome-devtools-mcp', profileDirName);
188
235
  await fs.promises.mkdir(userDataDir, {
189
236
  recursive: true,
190
237
  });
191
238
  }
192
- const args = [...(this.#serverArgs.chromeArg ?? [])];
239
+ const args = [
240
+ ...(this.#config.resolved.chromeArg ?? []),
241
+ ];
193
242
  if (proxyServer) {
194
243
  args.push(`--proxy-server=${proxyServer}`);
195
244
  }
@@ -227,6 +276,12 @@ export class BrowserManager {
227
276
  blocklist,
228
277
  allowlist,
229
278
  logger: puppeteerLogger,
279
+ // The entry points own signal handling and call close(), which
280
+ // closes the browser gracefully. Puppeteer's handlers would SIGKILL
281
+ // Chrome synchronously on the same signal and win the race.
282
+ handleSIGINT: false,
283
+ handleSIGTERM: false,
284
+ handleSIGHUP: false,
230
285
  });
231
286
  if (this.#options.logFile) {
232
287
  // FIXME: we are probably subscribing too late to catch startup logs. We
@@ -243,7 +298,9 @@ export class BrowserManager {
243
298
  }
244
299
  this.#browserMode = 'launched';
245
300
  this.#browser = browser;
246
- return browser;
301
+ const launched = browser;
302
+ launched.once('disconnected', () => this.#evictIfCurrent(launched));
303
+ return launched;
247
304
  }
248
305
  catch (error) {
249
306
  await browser?.close().catch(() => {
@@ -266,30 +323,37 @@ export class BrowserManager {
266
323
  }
267
324
  }
268
325
  async #connect() {
269
- const { browserUrl: browserURL, wsEndpoint, wsHeaders, autoConnect: isAutoConnect, userDataDir, blockedUrlPattern: blocklist, allowedUrlPattern: allowlist, } = this.#serverArgs;
326
+ const { browserUrl: browserURL, wsEndpoint, wsHeaders, autoConnect: isAutoConnect, userDataDir, blockedUrlPattern: blocklist, allowedUrlPattern: allowlist, categoryExtensions: enableExtensions, } = this.#config.resolved;
270
327
  // Important: only pass channel, if autoConnect is true.
271
- const channel = isAutoConnect ? this.#serverArgs.channel : undefined;
328
+ const channel = isAutoConnect ? this.#config.resolved.channel : undefined;
272
329
  const connectOptions = {
273
- targetFilter: _a.makeTargetFilter(),
330
+ targetFilter: _a.makeTargetFilter(enableExtensions),
274
331
  defaultViewport: null,
275
332
  handleDevToolsAsPage: true,
276
333
  blocklist,
277
334
  allowlist,
278
335
  logger: puppeteerLogger,
336
+ // Detects a transport that died without a close frame (e.g. an adb
337
+ // port-forward torn down mid-call). Puppeteer pings the socket
338
+ // periodically and terminates it on a missed pong, which rejects the
339
+ // in-flight CDP calls and fires `disconnected` so #evictIfCurrent()
340
+ // drops the stale handle. Without this, such a call would hang until
341
+ // protocolTimeout inside the context queue.
342
+ wsOptions: {
343
+ keepAlive: true,
344
+ headers: wsHeaders,
345
+ },
279
346
  };
280
347
  let autoConnect = false;
281
348
  if (wsEndpoint) {
282
349
  connectOptions.browserWSEndpoint = wsEndpoint;
283
- if (wsHeaders) {
284
- connectOptions.headers = wsHeaders;
285
- }
286
350
  }
287
351
  else if (browserURL) {
288
352
  connectOptions.browserURL = browserURL;
289
353
  }
290
354
  else if (channel || userDataDir) {
355
+ autoConnect = true;
291
356
  if (userDataDir) {
292
- autoConnect = true;
293
357
  // TODO: re-expose this logic via Puppeteer.
294
358
  const portPath = path.join(userDataDir, 'DevToolsActivePort');
295
359
  try {
@@ -329,12 +393,13 @@ export class BrowserManager {
329
393
  else {
330
394
  throw new Error('Either browserURL, wsEndpoint, channel or userDataDir must be provided');
331
395
  }
332
- logger?.('Connecting Puppeteer to ', JSON.stringify(connectOptions));
396
+ logger?.('Connecting Puppeteer to ', JSON.stringify(redactConnectOptionsForLogging(connectOptions)));
333
397
  try {
334
398
  const connected = await puppeteer.connect(connectOptions);
335
399
  logger?.('Connected Puppeteer');
336
400
  this.#browserMode = 'connected';
337
401
  this.#browser = connected;
402
+ connected.once('disconnected', () => this.#evictIfCurrent(connected));
338
403
  return connected;
339
404
  }
340
405
  catch (err) {
@@ -343,6 +408,71 @@ export class BrowserManager {
343
408
  });
344
409
  }
345
410
  }
411
+ /**
412
+ * Drops the cached browser handle so the next ensureBrowser() call
413
+ * establishes a fresh connection. Only called from abandonPendingAttempt()
414
+ * when a getContext()-level timeout fires after ensureBrowser() already
415
+ * resolved, which means the handle looks connected but its CDP
416
+ * initialization is hanging.
417
+ *
418
+ * Also tears the browser down in the background: closes it if it was
419
+ * launched (so the Chrome subprocess doesn't leak), or disconnects if it
420
+ * was only connected to (so the transport and its listeners don't leak).
421
+ * Puppeteer's connection disposal rejects any in-flight CDP call, so a hung
422
+ * call settles instead of leaking forever.
423
+ */
424
+ #forgetCurrentBrowser() {
425
+ const browser = this.#browser;
426
+ if (!browser) {
427
+ return;
428
+ }
429
+ const mode = this.#browserMode;
430
+ this.#browser = undefined;
431
+ this.#browserMode = undefined;
432
+ if (mode === 'launched') {
433
+ void this.#closeLaunchedBrowser(browser);
434
+ }
435
+ else {
436
+ void browser.disconnect().catch(err => {
437
+ logger?.('Failed to disconnect forgotten browser', err);
438
+ });
439
+ }
440
+ }
441
+ /**
442
+ * Handles a `disconnected` event fired by a browser we hold: clears the
443
+ * cached handle if it's still the current one, so the next ensureBrowser()
444
+ * call reconnects proactively rather than only discovering the staleness
445
+ * lazily on the next call's `!this.#browser?.connected` check. No teardown
446
+ * here — the browser is already disconnected/closed, that's why this
447
+ * fired. The identity guard makes a `disconnected` that fires late on an
448
+ * already-superseded browser a safe no-op.
449
+ */
450
+ #evictIfCurrent(candidate) {
451
+ if (this.#browser !== candidate) {
452
+ return;
453
+ }
454
+ this.#browser = undefined;
455
+ this.#browserMode = undefined;
456
+ }
457
+ async #closeLaunchedBrowser(browser) {
458
+ let timer;
459
+ try {
460
+ await Promise.race([
461
+ browser.close(),
462
+ new Promise((_, reject) => {
463
+ timer = setTimeout(() => reject(new Error('Timed out closing browser')), 5_000);
464
+ timer.unref?.();
465
+ }),
466
+ ]);
467
+ }
468
+ catch (err) {
469
+ logger?.('Failed to close browser', err);
470
+ browser.process()?.kill('SIGKILL');
471
+ }
472
+ finally {
473
+ clearTimeout(timer);
474
+ }
475
+ }
346
476
  async #closeBrowser() {
347
477
  const browser = this.#browser;
348
478
  const mode = this.#browserMode;
@@ -352,9 +482,7 @@ export class BrowserManager {
352
482
  return;
353
483
  }
354
484
  if (mode === 'launched') {
355
- await browser.close().catch(err => {
356
- logger?.('Failed to close browser', err);
357
- });
485
+ await this.#closeLaunchedBrowser(browser);
358
486
  return;
359
487
  }
360
488
  await browser.disconnect().catch(err => {
@@ -372,7 +500,7 @@ export class BrowserManager {
372
500
  try {
373
501
  this.#initPromise = undefined;
374
502
  this.#closingCount++;
375
- const _guard = __addDisposableResource(env_2, await this.#mutex.acquire(), false);
503
+ const guard = __addDisposableResource(env_2, await this.#mutex.acquire(), false);
376
504
  try {
377
505
  await this.#closeBrowser();
378
506
  }