playwright 1.58.0-alpha-2025-12-17 → 1.58.0-alpha-2025-12-19

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.
@@ -87,14 +87,15 @@ class FullConfigInternal {
87
87
  maxFailures: takeFirst(configCLIOverrides.debug ? 1 : void 0, configCLIOverrides.maxFailures, userConfig.maxFailures, 0),
88
88
  metadata: metadata ?? userConfig.metadata,
89
89
  preserveOutput: takeFirst(userConfig.preserveOutput, "always"),
90
+ projects: [],
91
+ quiet: takeFirst(configCLIOverrides.quiet, userConfig.quiet, false),
90
92
  reporter: takeFirst(configCLIOverrides.reporter, resolveReporters(userConfig.reporter, configDir), [[defaultReporter]]),
91
93
  reportSlowTests: takeFirst(userConfig.reportSlowTests, {
92
94
  max: 5,
93
95
  threshold: 3e5
94
96
  /* 5 minutes */
95
97
  }),
96
- quiet: takeFirst(configCLIOverrides.quiet, userConfig.quiet, false),
97
- projects: [],
98
+ runAgents: takeFirst(configCLIOverrides.runAgents, userConfig.runAgents, false),
98
99
  shard: takeFirst(configCLIOverrides.shard, userConfig.shard, null),
99
100
  tags: globalTags,
100
101
  updateSnapshots: takeFirst(configCLIOverrides.updateSnapshots, userConfig.updateSnapshots, "missing"),
package/lib/index.js CHANGED
@@ -111,7 +111,6 @@ const playwrightFixtures = {
111
111
  await browser.close({ reason: "Test ended." });
112
112
  }, { scope: "worker", timeout: 0 }],
113
113
  acceptDownloads: [({ contextOptions }, use) => use(contextOptions.acceptDownloads ?? true), { option: true, box: true }],
114
- agent: [({ contextOptions }, use) => use(contextOptions.agent), { option: true, box: true }],
115
114
  bypassCSP: [({ contextOptions }, use) => use(contextOptions.bypassCSP ?? false), { option: true, box: true }],
116
115
  colorScheme: [({ contextOptions }, use) => use(contextOptions.colorScheme === void 0 ? "light" : contextOptions.colorScheme), { option: true, box: true }],
117
116
  deviceScaleFactor: [({ contextOptions }, use) => use(contextOptions.deviceScaleFactor), { option: true, box: true }],
@@ -139,9 +138,9 @@ const playwrightFixtures = {
139
138
  }, { option: true, box: true }],
140
139
  serviceWorkers: [({ contextOptions }, use) => use(contextOptions.serviceWorkers ?? "allow"), { option: true, box: true }],
141
140
  contextOptions: [{}, { option: true, box: true }],
141
+ agent: [({}, use) => use(void 0), { option: true, box: true }],
142
142
  _combinedContextOptions: [async ({
143
143
  acceptDownloads,
144
- agent,
145
144
  bypassCSP,
146
145
  clientCertificates,
147
146
  colorScheme,
@@ -168,8 +167,6 @@ const playwrightFixtures = {
168
167
  const options = {};
169
168
  if (acceptDownloads !== void 0)
170
169
  options.acceptDownloads = acceptDownloads;
171
- if (agent !== void 0)
172
- options.agent = agent;
173
170
  if (bypassCSP !== void 0)
174
171
  options.bypassCSP = bypassCSP;
175
172
  if (colorScheme !== void 0)
@@ -612,19 +609,24 @@ class ArtifactsRecorder {
612
609
  }
613
610
  }
614
611
  async _cloneAgentCache(options) {
615
- if (!this._agent || this._agent.cacheMode === "ignore")
612
+ if (!this._agent)
616
613
  return;
617
- if (!this._agent.cacheFile && !this._agent.cachePathTemplate)
618
- return;
619
- const cacheFile = this._agent.cacheFile ?? this._testInfo._applyPathTemplate(this._agent.cachePathTemplate, "cache", ".json");
620
- const workerFile = await this._testInfo._cloneStorage(cacheFile);
621
- if (this._agent && workerFile)
622
- options.agent = { ...this._agent, cacheFile: workerFile };
614
+ const cachePathTemplate = this._agent.cachePathTemplate ?? "{testDir}/{testFilePath}-cache.json";
615
+ this._agentCacheFile = this._testInfo._applyPathTemplate(cachePathTemplate, "", ".json");
616
+ this._agentCacheOutFile = import_path.default.join(this._testInfo.artifactsDir(), "agent-cache-" + (0, import_utils.createGuid)() + ".json");
617
+ const cacheFile = this._testInfo.config.runAgents ? void 0 : await this._testInfo._cloneStorage(this._agentCacheFile);
618
+ options.agent = {
619
+ ...this._agent,
620
+ cacheFile,
621
+ cacheOutFile: this._agentCacheOutFile
622
+ };
623
623
  }
624
624
  async _upstreamAgentCache(context) {
625
- const agent = context._options.agent;
626
- if (this._testInfo.status === "passed" && agent?.cacheFile)
627
- await this._testInfo._upstreamStorage(agent.cacheFile);
625
+ if (!this._agentCacheFile || !this._agentCacheOutFile)
626
+ return;
627
+ if (this._testInfo.status !== "passed")
628
+ return;
629
+ await this._testInfo._upstreamStorage(this._agentCacheFile, this._agentCacheOutFile);
628
630
  }
629
631
  async didCreateRequestContext(context) {
630
632
  await this._startTraceChunkOnContextCreation(context, context._tracing);
@@ -460,6 +460,7 @@ const baseFullConfig = {
460
460
  tags: [],
461
461
  updateSnapshots: "missing",
462
462
  updateSourceMethod: "patch",
463
+ runAgents: false,
463
464
  version: "",
464
465
  workers: 0,
465
466
  webServer: null
@@ -134,7 +134,7 @@ class IsolatedContextFactory extends BaseContextFactory {
134
134
  });
135
135
  }
136
136
  async _doCreateContext(browser) {
137
- return browser.newContext(this.config.browser.contextOptions);
137
+ return browser.newContext(browserContextOptionsFromConfig(this.config));
138
138
  }
139
139
  }
140
140
  class CdpContextFactory extends BaseContextFactory {
@@ -184,7 +184,7 @@ class PersistentContextFactory {
184
184
  const launchOptions = {
185
185
  tracesDir,
186
186
  ...this.config.browser.launchOptions,
187
- ...this.config.browser.contextOptions,
187
+ ...browserContextOptionsFromConfig(this.config),
188
188
  handleSIGINT: false,
189
189
  handleSIGTERM: false,
190
190
  ignoreDefaultArgs: [
@@ -303,6 +303,16 @@ async function computeTracesDir(config, clientInfo) {
303
303
  return;
304
304
  return await (0, import_config.outputFile)(config, clientInfo, `traces`, { origin: "code", reason: "Collecting trace" });
305
305
  }
306
+ function browserContextOptionsFromConfig(config) {
307
+ const result = { ...config.browser.contextOptions };
308
+ if (config.saveVideo) {
309
+ result.recordVideo = {
310
+ dir: (0, import_config.tmpDir)(),
311
+ size: config.saveVideo
312
+ };
313
+ }
314
+ return result;
315
+ }
306
316
  // Annotate the CommonJS export names for ESM import in node:
307
317
  0 && (module.exports = {
308
318
  SharedContextFactory,
@@ -40,7 +40,8 @@ __export(config_exports, {
40
40
  resolutionParser: () => resolutionParser,
41
41
  resolveCLIConfig: () => resolveCLIConfig,
42
42
  resolveConfig: () => resolveConfig,
43
- semicolonSeparatedList: () => semicolonSeparatedList
43
+ semicolonSeparatedList: () => semicolonSeparatedList,
44
+ tmpDir: () => tmpDir
44
45
  });
45
46
  module.exports = __toCommonJS(config_exports);
46
47
  var import_fs = __toESM(require("fs"));
@@ -161,13 +162,6 @@ function configFromCLIOptions(cliOptions) {
161
162
  contextOptions.serviceWorkers = "block";
162
163
  if (cliOptions.grantPermissions)
163
164
  contextOptions.permissions = cliOptions.grantPermissions;
164
- if (cliOptions.saveVideo) {
165
- contextOptions.recordVideo = {
166
- // Videos are moved to output directory on saveAs.
167
- dir: tmpDir(),
168
- size: cliOptions.saveVideo
169
- };
170
- }
171
165
  const result = {
172
166
  browser: {
173
167
  browserName,
@@ -419,5 +413,6 @@ function sanitizeForFilePath(s) {
419
413
  resolutionParser,
420
414
  resolveCLIConfig,
421
415
  resolveConfig,
422
- semicolonSeparatedList
416
+ semicolonSeparatedList,
417
+ tmpDir
423
418
  });
@@ -154,18 +154,16 @@ class Tab extends import_events.EventEmitter {
154
154
  async navigate(url) {
155
155
  await this._initializedPromise;
156
156
  this._clearCollectedArtifacts();
157
- const downloadEvent = (0, import_utils2.callOnPageNoTrace)(this.page, (page) => page.waitForEvent("download").catch(import_log.logUnhandledError));
157
+ const { promise: downloadEvent, abort: abortDownloadEvent } = (0, import_utils2.eventWaiter)(this.page, "download", 3e3);
158
158
  try {
159
159
  await this.page.goto(url, { waitUntil: "domcontentloaded" });
160
+ abortDownloadEvent();
160
161
  } catch (_e) {
161
162
  const e = _e;
162
163
  const mightBeDownload = e.message.includes("net::ERR_ABORTED") || e.message.includes("Download is starting");
163
164
  if (!mightBeDownload)
164
165
  throw e;
165
- const download = await Promise.race([
166
- downloadEvent,
167
- new Promise((resolve) => setTimeout(resolve, 3e3))
168
- ]);
166
+ const download = await downloadEvent;
169
167
  if (!download)
170
168
  throw e;
171
169
  await new Promise((resolve) => setTimeout(resolve, 500));
@@ -20,6 +20,7 @@ var utils_exports = {};
20
20
  __export(utils_exports, {
21
21
  callOnPageNoTrace: () => callOnPageNoTrace,
22
22
  dateAsFileName: () => dateAsFileName,
23
+ eventWaiter: () => eventWaiter,
23
24
  waitForCompletion: () => waitForCompletion
24
25
  });
25
26
  module.exports = __toCommonJS(utils_exports);
@@ -65,9 +66,29 @@ function dateAsFileName(extension) {
65
66
  const date = /* @__PURE__ */ new Date();
66
67
  return `page-${date.toISOString().replace(/[:.]/g, "-")}.${extension}`;
67
68
  }
69
+ function eventWaiter(page, event, timeout) {
70
+ const disposables = [];
71
+ const eventPromise = new Promise((resolve, reject) => {
72
+ page.on(event, resolve);
73
+ disposables.push(() => page.off(event, resolve));
74
+ });
75
+ let abort;
76
+ const abortPromise = new Promise((resolve, reject) => {
77
+ abort = () => resolve(void 0);
78
+ });
79
+ const timeoutPromise = new Promise((f) => {
80
+ const timeoutId = setTimeout(() => f(void 0), timeout);
81
+ disposables.push(() => clearTimeout(timeoutId));
82
+ });
83
+ return {
84
+ promise: Promise.race([eventPromise, abortPromise, timeoutPromise]).finally(() => disposables.forEach((dispose) => dispose())),
85
+ abort
86
+ };
87
+ }
68
88
  // Annotate the CommonJS export names for ESM import in node:
69
89
  0 && (module.exports = {
70
90
  callOnPageNoTrace,
71
91
  dateAsFileName,
92
+ eventWaiter,
72
93
  waitForCompletion
73
94
  });
@@ -55,7 +55,7 @@ class ExtensionContextFactory {
55
55
  async _obtainBrowser(clientInfo, abortSignal, toolName) {
56
56
  const relay = await this._startRelay(abortSignal);
57
57
  await relay.ensureExtensionConnectionForMCPContext(clientInfo, abortSignal, toolName);
58
- return await playwright.chromium.connectOverCDP(relay.cdpEndpoint());
58
+ return await playwright.chromium.connectOverCDP(relay.cdpEndpoint(), { isLocal: true });
59
59
  }
60
60
  async _startRelay(abortSignal) {
61
61
  const httpServer = await (0, import_http.startHttpServer)({});
@@ -38,11 +38,10 @@ var mcpServer = __toESM(require("./sdk/server"));
38
38
  var import_config = require("./browser/config");
39
39
  var import_watchdog = require("./browser/watchdog");
40
40
  var import_browserContextFactory = require("./browser/browserContextFactory");
41
- var import_proxyBackend = require("./sdk/proxyBackend");
42
41
  var import_browserServerBackend = require("./browser/browserServerBackend");
43
42
  var import_extensionContextFactory = require("./extension/extensionContextFactory");
44
43
  function decorateCommand(command, version) {
45
- command.option("--allowed-hosts <hosts...>", "comma-separated list of hosts this server is allowed to serve from. Defaults to the host the server is bound to. Pass '*' to disable the host check.", import_config.commaSeparatedList).option("--allowed-origins <origins>", "semicolon-separated list of TRUSTED origins to allow the browser to request. Default is to allow all.\nImportant: *does not* serve as a security boundary and *does not* affect redirects. ", import_config.semicolonSeparatedList).option("--blocked-origins <origins>", "semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.\nImportant: *does not* serve as a security boundary and *does not* affect redirects.", import_config.semicolonSeparatedList).option("--block-service-workers", "block service workers").option("--browser <browser>", "browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.").option("--caps <caps>", "comma-separated list of additional capabilities to enable, possible values: vision, pdf.", import_config.commaSeparatedList).option("--cdp-endpoint <endpoint>", "CDP endpoint to connect to.").option("--cdp-header <headers...>", "CDP headers to send with the connect request, multiple can be specified.", import_config.headerParser).option("--config <path>", "path to the configuration file.").option("--console-level <level>", 'level of console messages to return: "error", "warning", "info", "debug". Each level includes the messages of more severe levels.', import_config.enumParser.bind(null, "--console-level", ["error", "warning", "info", "debug"])).option("--device <device>", 'device to emulate, for example: "iPhone 15"').option("--executable-path <path>", "path to the browser executable.").option("--extension", 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.').option("--grant-permissions <permissions...>", 'List of permissions to grant to the browser context, for example "geolocation", "clipboard-read", "clipboard-write".', import_config.commaSeparatedList).option("--headless", "run browser in headless mode, headed by default").option("--host <host>", "host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.").option("--ignore-https-errors", "ignore https errors").option("--init-page <path...>", "path to TypeScript file to evaluate on Playwright page object").option("--init-script <path...>", "path to JavaScript file to add as an initialization script. The script will be evaluated in every page before any of the page's scripts. Can be specified multiple times.").option("--isolated", "keep the browser profile in memory, do not save it to disk.").option("--image-responses <mode>", 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".', import_config.enumParser.bind(null, "--image-responses", ["allow", "omit"])).option("--no-sandbox", "disable the sandbox for all process types that are normally sandboxed.").option("--output-dir <path>", "path to the directory for output files.").option("--port <port>", "port to listen on for SSE transport.").option("--proxy-bypass <bypass>", 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"').option("--proxy-server <proxy>", 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"').option("--save-session", "Whether to save the Playwright MCP session into the output directory.").option("--save-trace", "Whether to save the Playwright Trace of the session into the output directory.").option("--save-video <size>", 'Whether to save the video of the session into the output directory. For example "--save-video=800x600"', import_config.resolutionParser.bind(null, "--save-video")).option("--secrets <path>", "path to a file containing secrets in the dotenv format", import_config.dotenvFileLoader).option("--shared-browser-context", "reuse the same browser context between all connected HTTP clients.").option("--snapshot-mode <mode>", 'when taking snapshots for responses, specifies the mode to use. Can be "incremental", "full", or "none". Default is incremental.').option("--storage-state <path>", "path to the storage state file for isolated sessions.").option("--test-id-attribute <attribute>", 'specify the attribute to use for test ids, defaults to "data-testid"').option("--timeout-action <timeout>", "specify action timeout in milliseconds, defaults to 5000ms", import_config.numberParser).option("--timeout-navigation <timeout>", "specify navigation timeout in milliseconds, defaults to 60000ms", import_config.numberParser).option("--user-agent <ua string>", "specify user agent string").option("--user-data-dir <path>", "path to the user data directory. If not specified, a temporary directory will be created.").option("--viewport-size <size>", 'specify browser viewport size in pixels, for example "1280x720"', import_config.resolutionParser.bind(null, "--viewport-size")).addOption(new import_utilsBundle.ProgramOption("--connect-tool", "Allow to switch between different browser connection methods.").hideHelp()).addOption(new import_utilsBundle.ProgramOption("--vision", "Legacy option, use --caps=vision instead").hideHelp()).action(async (options) => {
44
+ command.option("--allowed-hosts <hosts...>", "comma-separated list of hosts this server is allowed to serve from. Defaults to the host the server is bound to. Pass '*' to disable the host check.", import_config.commaSeparatedList).option("--allowed-origins <origins>", "semicolon-separated list of TRUSTED origins to allow the browser to request. Default is to allow all.\nImportant: *does not* serve as a security boundary and *does not* affect redirects. ", import_config.semicolonSeparatedList).option("--blocked-origins <origins>", "semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.\nImportant: *does not* serve as a security boundary and *does not* affect redirects.", import_config.semicolonSeparatedList).option("--block-service-workers", "block service workers").option("--browser <browser>", "browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.").option("--caps <caps>", "comma-separated list of additional capabilities to enable, possible values: vision, pdf.", import_config.commaSeparatedList).option("--cdp-endpoint <endpoint>", "CDP endpoint to connect to.").option("--cdp-header <headers...>", "CDP headers to send with the connect request, multiple can be specified.", import_config.headerParser).option("--config <path>", "path to the configuration file.").option("--console-level <level>", 'level of console messages to return: "error", "warning", "info", "debug". Each level includes the messages of more severe levels.', import_config.enumParser.bind(null, "--console-level", ["error", "warning", "info", "debug"])).option("--device <device>", 'device to emulate, for example: "iPhone 15"').option("--executable-path <path>", "path to the browser executable.").option("--extension", 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.').option("--grant-permissions <permissions...>", 'List of permissions to grant to the browser context, for example "geolocation", "clipboard-read", "clipboard-write".', import_config.commaSeparatedList).option("--headless", "run browser in headless mode, headed by default").option("--host <host>", "host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.").option("--ignore-https-errors", "ignore https errors").option("--init-page <path...>", "path to TypeScript file to evaluate on Playwright page object").option("--init-script <path...>", "path to JavaScript file to add as an initialization script. The script will be evaluated in every page before any of the page's scripts. Can be specified multiple times.").option("--isolated", "keep the browser profile in memory, do not save it to disk.").option("--image-responses <mode>", 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".', import_config.enumParser.bind(null, "--image-responses", ["allow", "omit"])).option("--no-sandbox", "disable the sandbox for all process types that are normally sandboxed.").option("--output-dir <path>", "path to the directory for output files.").option("--port <port>", "port to listen on for SSE transport.").option("--proxy-bypass <bypass>", 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"').option("--proxy-server <proxy>", 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"').option("--save-session", "Whether to save the Playwright MCP session into the output directory.").option("--save-trace", "Whether to save the Playwright Trace of the session into the output directory.").option("--save-video <size>", 'Whether to save the video of the session into the output directory. For example "--save-video=800x600"', import_config.resolutionParser.bind(null, "--save-video")).option("--secrets <path>", "path to a file containing secrets in the dotenv format", import_config.dotenvFileLoader).option("--shared-browser-context", "reuse the same browser context between all connected HTTP clients.").option("--snapshot-mode <mode>", 'when taking snapshots for responses, specifies the mode to use. Can be "incremental", "full", or "none". Default is incremental.').option("--storage-state <path>", "path to the storage state file for isolated sessions.").option("--test-id-attribute <attribute>", 'specify the attribute to use for test ids, defaults to "data-testid"').option("--timeout-action <timeout>", "specify action timeout in milliseconds, defaults to 5000ms", import_config.numberParser).option("--timeout-navigation <timeout>", "specify navigation timeout in milliseconds, defaults to 60000ms", import_config.numberParser).option("--user-agent <ua string>", "specify user agent string").option("--user-data-dir <path>", "path to the user data directory. If not specified, a temporary directory will be created.").option("--viewport-size <size>", 'specify browser viewport size in pixels, for example "1280x720"', import_config.resolutionParser.bind(null, "--viewport-size")).addOption(new import_utilsBundle.ProgramOption("--vision", "Legacy option, use --caps=vision instead").hideHelp()).action(async (options) => {
46
45
  (0, import_watchdog.setupExitWatchdog)();
47
46
  if (options.vision) {
48
47
  console.error("The --vision option is deprecated, use --caps=vision instead");
@@ -71,28 +70,6 @@ Please run the command below. It will install a local copy of ffmpeg and will no
71
70
  await mcpServer.start(serverBackendFactory, config.server);
72
71
  return;
73
72
  }
74
- if (options.connectTool) {
75
- const providers = [
76
- {
77
- name: "default",
78
- description: "Starts standalone browser",
79
- connect: () => mcpServer.wrapInProcess(new import_browserServerBackend.BrowserServerBackend(config, browserContextFactory))
80
- },
81
- {
82
- name: "extension",
83
- description: "Connect to a browser using the Playwright MCP extension",
84
- connect: () => mcpServer.wrapInProcess(new import_browserServerBackend.BrowserServerBackend(config, extensionContextFactory))
85
- }
86
- ];
87
- const factory2 = {
88
- name: "Playwright w/ switch",
89
- nameInConfig: "playwright-switch",
90
- version,
91
- create: () => new import_proxyBackend.ProxyBackend(providers)
92
- };
93
- await mcpServer.start(factory2, config.server);
94
- return;
95
- }
96
73
  const factory = {
97
74
  name: "Playwright",
98
75
  nameInConfig: "playwright",
@@ -16,14 +16,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
16
16
  var exports_exports = {};
17
17
  module.exports = __toCommonJS(exports_exports);
18
18
  __reExport(exports_exports, require("./inProcessTransport"), module.exports);
19
- __reExport(exports_exports, require("./proxyBackend"), module.exports);
20
19
  __reExport(exports_exports, require("./server"), module.exports);
21
20
  __reExport(exports_exports, require("./tool"), module.exports);
22
21
  __reExport(exports_exports, require("./http"), module.exports);
23
22
  // Annotate the CommonJS export names for ESM import in node:
24
23
  0 && (module.exports = {
25
24
  ...require("./inProcessTransport"),
26
- ...require("./proxyBackend"),
27
25
  ...require("./server"),
28
26
  ...require("./tool"),
29
27
  ...require("./http")
package/lib/program.js CHANGED
@@ -287,6 +287,7 @@ function overridesFromOptions(options) {
287
287
  ignoreSnapshots: options.ignoreSnapshots ? !!options.ignoreSnapshots : void 0,
288
288
  updateSnapshots: options.updateSnapshots,
289
289
  updateSourceMethod: options.updateSourceMethod,
290
+ runAgents: options.runAgents,
290
291
  workers: options.workers
291
292
  };
292
293
  if (options.browser) {
@@ -374,6 +375,7 @@ const testOptions = [
374
375
  ["--repeat-each <N>", { description: `Run each test N times (default: 1)` }],
375
376
  ["--reporter <reporter>", { description: `Reporter to use, comma-separated, can be ${import_config.builtInReporters.map((name) => `"${name}"`).join(", ")} (default: "${import_config.defaultReporter}")` }],
376
377
  ["--retries <retries>", { description: `Maximum retry count for flaky tests, zero for no retries (default: no retries)` }],
378
+ ["--run-agents", { description: `Run agents to generate the code for page.perform` }],
377
379
  ["--shard <shard>", { description: `Shard tests and execute only the selected shard, specify in the form "current/all", 1-based, for example "3/5"` }],
378
380
  ["--test-list <file>", { description: `Path to a file containing a list of tests to run. See https://playwright.dev/docs/test-cli for more details.` }],
379
381
  ["--test-list-invert <file>", { description: `Path to a file containing a list of tests to skip. See https://playwright.dev/docs/test-cli for more details.` }],
@@ -199,10 +199,10 @@ class Dispatcher {
199
199
  this._producedEnvByProjectId.set(testGroup.projectId, { ...producedEnv, ...worker.producedEnv() });
200
200
  });
201
201
  worker.onRequest("cloneStorage", async (params) => {
202
- return await import_storage.Storage.clone(params.storageFile, worker.artifactsDir());
202
+ return await import_storage.Storage.clone(params.storageFile, outputDir);
203
203
  });
204
204
  worker.onRequest("upstreamStorage", async (params) => {
205
- await import_storage.Storage.upstream(params.workerFile);
205
+ await import_storage.Storage.upstream(params.storageFile, params.storageOutFile);
206
206
  });
207
207
  return worker;
208
208
  }
@@ -35,68 +35,55 @@ var import_fs = __toESM(require("fs"));
35
35
  var import_path = __toESM(require("path"));
36
36
  var import_utils = require("playwright-core/lib/utils");
37
37
  class Storage {
38
- constructor(fileName) {
39
- this._writeChain = Promise.resolve();
40
- this._fileName = fileName;
41
- }
42
38
  static {
43
39
  this._storages = /* @__PURE__ */ new Map();
44
40
  }
45
41
  static {
46
- this._workerFiles = /* @__PURE__ */ new Map();
42
+ this._serializeQueue = Promise.resolve();
47
43
  }
48
- static async clone(storageFile, artifactsDir) {
49
- const workerFile = await this._storage(storageFile)._clone(artifactsDir);
50
- const stat = await import_fs.default.promises.stat(workerFile);
51
- const lastModified = stat.mtime.getTime();
52
- Storage._workerFiles.set(workerFile, { storageFile, lastModified });
53
- return workerFile;
44
+ static clone(storageFile, outputDir) {
45
+ return Storage._withStorage(storageFile, (storage) => storage._clone(outputDir));
54
46
  }
55
- static async upstream(workerFile) {
56
- const entry = Storage._workerFiles.get(workerFile);
57
- if (!entry)
58
- return;
59
- const { storageFile, lastModified } = entry;
60
- const stat = await import_fs.default.promises.stat(workerFile);
61
- const newLastModified = stat.mtime.getTime();
62
- if (lastModified !== newLastModified)
63
- await this._storage(storageFile)._upstream(workerFile);
64
- Storage._workerFiles.delete(workerFile);
47
+ static upstream(storageFile, storageOutFile) {
48
+ return Storage._withStorage(storageFile, (storage) => storage._upstream(storageOutFile));
65
49
  }
66
- static _storage(fileName) {
67
- if (!Storage._storages.has(fileName))
68
- Storage._storages.set(fileName, new Storage(fileName));
69
- return Storage._storages.get(fileName);
50
+ static _withStorage(fileName, runnable) {
51
+ this._serializeQueue = this._serializeQueue.then(() => {
52
+ let storage = Storage._storages.get(fileName);
53
+ if (!storage) {
54
+ storage = new Storage(fileName);
55
+ Storage._storages.set(fileName, storage);
56
+ }
57
+ return runnable(storage);
58
+ });
59
+ return this._serializeQueue;
70
60
  }
71
- async _clone(artifactsDir) {
61
+ constructor(fileName) {
62
+ this._fileName = fileName;
63
+ }
64
+ async _clone(outputDir) {
72
65
  const entries = await this._load();
73
- const workerFile = import_path.default.join(artifactsDir, `pw-storage-${(0, import_utils.createGuid)()}.json`);
74
- await import_fs.default.promises.writeFile(workerFile, JSON.stringify(entries, null, 2)).catch(() => {
66
+ if (this._lastSnapshotFileName)
67
+ return this._lastSnapshotFileName;
68
+ const snapshotFile = import_path.default.join(outputDir, `pw-storage-${(0, import_utils.createGuid)()}.json`);
69
+ await import_fs.default.promises.writeFile(snapshotFile, JSON.stringify(entries, null, 2)).catch(() => {
75
70
  });
76
- return workerFile;
71
+ this._lastSnapshotFileName = snapshotFile;
72
+ return snapshotFile;
77
73
  }
78
- async _upstream(workerFile) {
74
+ async _upstream(storageOutFile) {
79
75
  const entries = await this._load();
80
- const newEntries = await import_fs.default.promises.readFile(workerFile, "utf8").then(JSON.parse).catch(() => ({}));
81
- for (const [key, newValue] of Object.entries(newEntries)) {
82
- const existing = entries[key];
83
- if (!existing || existing.timestamp < newValue.timestamp)
84
- entries[key] = newValue;
85
- }
86
- await this._writeFile(entries);
76
+ const newEntries = await import_fs.default.promises.readFile(storageOutFile, "utf8").then(JSON.parse).catch(() => ({}));
77
+ for (const [key, newValue] of Object.entries(newEntries))
78
+ entries[key] = newValue;
79
+ this._lastSnapshotFileName = void 0;
80
+ await import_fs.default.promises.writeFile(this._fileName, JSON.stringify(entries, null, 2));
87
81
  }
88
82
  async _load() {
89
83
  if (!this._entriesPromise)
90
84
  this._entriesPromise = import_fs.default.promises.readFile(this._fileName, "utf8").then(JSON.parse).catch(() => ({}));
91
85
  return this._entriesPromise;
92
86
  }
93
- _writeFile(entries) {
94
- this._writeChain = this._writeChain.then(() => import_fs.default.promises.writeFile(this._fileName, JSON.stringify(entries, null, 2)));
95
- return this._writeChain;
96
- }
97
- async flush() {
98
- await this._writeChain;
99
- }
100
87
  }
101
88
  // Annotate the CommonJS export names for ESM import in node:
102
89
  0 && (module.exports = {
@@ -258,6 +258,7 @@ class TestRunner extends import_events.default {
258
258
  },
259
259
  ...params.updateSnapshots ? { updateSnapshots: params.updateSnapshots } : {},
260
260
  ...params.updateSourceMethod ? { updateSourceMethod: params.updateSourceMethod } : {},
261
+ ...params.runAgents ? { runAgents: params.runAgents } : {},
261
262
  ...params.workers ? { workers: params.workers } : {}
262
263
  };
263
264
  const config = await this._loadConfigOrReportError(new import_internalReporter.InternalReporter([userReporter]), overrides);
@@ -31,7 +31,8 @@ __export(testInfo_exports, {
31
31
  StepSkipError: () => StepSkipError,
32
32
  TestInfoImpl: () => TestInfoImpl,
33
33
  TestSkipError: () => TestSkipError,
34
- TestStepInfoImpl: () => TestStepInfoImpl
34
+ TestStepInfoImpl: () => TestStepInfoImpl,
35
+ emtpyTestInfoCallbacks: () => emtpyTestInfoCallbacks
35
36
  });
36
37
  module.exports = __toCommonJS(testInfo_exports);
37
38
  var import_fs = __toESM(require("fs"));
@@ -43,6 +44,17 @@ var import_testTracing = require("./testTracing");
43
44
  var import_util2 = require("./util");
44
45
  var import_transform = require("../transform/transform");
45
46
  var import_babelHighlightUtils = require("../transform/babelHighlightUtils");
47
+ const emtpyTestInfoCallbacks = {
48
+ onStepBegin: () => {
49
+ },
50
+ onStepEnd: () => {
51
+ },
52
+ onAttach: () => {
53
+ },
54
+ onTestPaused: () => Promise.reject(new Error("TestInfoImpl not initialized")),
55
+ onCloneStorage: () => Promise.reject(new Error("TestInfoImpl not initialized")),
56
+ onUpstreamStorage: () => Promise.resolve()
57
+ };
46
58
  class TestInfoImpl {
47
59
  constructor(configInternal, projectInternal, workerParams, test, retry, callbacks) {
48
60
  this._snapshotNames = { lastAnonymousSnapshotIndex: 0, lastNamedSnapshotIndex: {} };
@@ -238,7 +250,7 @@ ${(0, import_utils.stringifyStackFrames)(step.boxedStack).join("\n")}`;
238
250
  suggestedRebaseline: result.suggestedRebaseline,
239
251
  annotations: step.info.annotations
240
252
  };
241
- this._callbacks.onStepEnd?.(payload);
253
+ this._callbacks.onStepEnd(payload);
242
254
  }
243
255
  if (step.group !== "internal") {
244
256
  const errorForTrace = step.error ? { name: "", message: step.error.message || "", stack: step.error.stack } : void 0;
@@ -260,7 +272,7 @@ ${(0, import_utils.stringifyStackFrames)(step.boxedStack).join("\n")}`;
260
272
  wallTime: Date.now(),
261
273
  location: step.location
262
274
  };
263
- this._callbacks.onStepBegin?.(payload);
275
+ this._callbacks.onStepBegin(payload);
264
276
  }
265
277
  if (step.group !== "internal") {
266
278
  this._tracing.appendBeforeActionForStep({
@@ -387,7 +399,7 @@ ${(0, import_utils.stringifyStackFrames)(step.boxedStack).join("\n")}`;
387
399
  this._tracing.appendBeforeActionForStep({ stepId: stepId2, title: `Attach ${(0, import_utils.escapeWithQuotes)(attachment.name, '"')}`, category: "test.attach", stack: [] });
388
400
  this._tracing.appendAfterActionForStep(stepId2, void 0, [attachment]);
389
401
  }
390
- this._callbacks.onAttach?.({
402
+ this._callbacks.onAttach({
391
403
  testId: this.testId,
392
404
  name: attachment.name,
393
405
  contentType: attachment.contentType,
@@ -481,12 +493,14 @@ ${(0, import_utils.stringifyStackFrames)(step.boxedStack).join("\n")}`;
481
493
  setTimeout(timeout) {
482
494
  this._timeoutManager.setTimeout(timeout);
483
495
  }
484
- async _cloneStorage(cacheFileTemplate) {
485
- const storageFile = this._applyPathTemplate(cacheFileTemplate, "cache", ".json");
486
- return await this._callbacks.onCloneStorage?.({ storageFile });
496
+ async _cloneStorage(storageFile) {
497
+ return await this._callbacks.onCloneStorage({ storageFile });
498
+ }
499
+ async _upstreamStorage(storageFile, storageOutFile) {
500
+ await this._callbacks.onUpstreamStorage({ storageFile, storageOutFile });
487
501
  }
488
- async _upstreamStorage(workerFile) {
489
- await this._callbacks.onUpstreamStorage?.({ workerFile });
502
+ artifactsDir() {
503
+ return this._workerParams.artifactsDir;
490
504
  }
491
505
  }
492
506
  class TestStepInfoImpl {
@@ -538,5 +552,6 @@ const stepSymbol = Symbol("step");
538
552
  StepSkipError,
539
553
  TestInfoImpl,
540
554
  TestSkipError,
541
- TestStepInfoImpl
555
+ TestStepInfoImpl,
556
+ emtpyTestInfoCallbacks
542
557
  });
@@ -95,7 +95,7 @@ class WorkerMain extends import_process.ProcessRunner {
95
95
  if (!this._config) {
96
96
  return;
97
97
  }
98
- const fakeTestInfo = new import_testInfo.TestInfoImpl(this._config, this._project, this._params, void 0, 0, {});
98
+ const fakeTestInfo = new import_testInfo.TestInfoImpl(this._config, this._project, this._params, void 0, 0, import_testInfo.emtpyTestInfoCallbacks);
99
99
  const runnable = { type: "teardown" };
100
100
  await fakeTestInfo._runWithTimeout(runnable, () => this._loadIfNeeded()).catch(() => {
101
101
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "playwright",
3
- "version": "1.58.0-alpha-2025-12-17",
3
+ "version": "1.58.0-alpha-2025-12-19",
4
4
  "description": "A high-level API to automate web browsers",
5
5
  "repository": {
6
6
  "type": "git",
@@ -64,7 +64,7 @@
64
64
  },
65
65
  "license": "Apache-2.0",
66
66
  "dependencies": {
67
- "playwright-core": "1.58.0-alpha-2025-12-17"
67
+ "playwright-core": "1.58.0-alpha-2025-12-19"
68
68
  },
69
69
  "optionalDependencies": {
70
70
  "fsevents": "2.3.2"
package/test.mjs CHANGED
@@ -25,6 +25,7 @@ export const errors = playwright.errors;
25
25
  export const request = playwright.request;
26
26
  export const _electron = playwright._electron;
27
27
  export const _android = playwright._android;
28
+ export const _baseTest = playwright._baseTest;
28
29
  export const test = playwright.test;
29
30
  export const expect = playwright.expect;
30
31
  export const defineConfig = playwright.defineConfig;
package/types/test.d.ts CHANGED
@@ -1611,6 +1611,12 @@ interface TestConfig<TestArgs = {}, WorkerArgs = {}> {
1611
1611
  */
1612
1612
  retries?: number;
1613
1613
 
1614
+ /**
1615
+ * Run agents to generate the code for
1616
+ * [page.perform(task[, options])](https://playwright.dev/docs/api/class-page#page-perform) and similar.
1617
+ */
1618
+ runAgents?: boolean;
1619
+
1614
1620
  /**
1615
1621
  * Shard tests and execute only the selected shard. Specify in the one-based form like `{ total: 5, current: 2 }`.
1616
1622
  *
@@ -2067,6 +2073,12 @@ export interface FullConfig<TestArgs = {}, WorkerArgs = {}> {
2067
2073
  */
2068
2074
  rootDir: string;
2069
2075
 
2076
+ /**
2077
+ * Run agents to generate the code for
2078
+ * [page.perform(task[, options])](https://playwright.dev/docs/api/class-page#page-perform) and similar.
2079
+ */
2080
+ runAgents: boolean;
2081
+
2070
2082
  /**
2071
2083
  * See [testConfig.shard](https://playwright.dev/docs/api/class-testconfig#test-config-shard).
2072
2084
  */
@@ -6644,7 +6656,6 @@ export type Fixtures<T extends {} = {}, W extends {} = {}, PT extends {} = {}, P
6644
6656
  [K in Exclude<keyof T, keyof PW | keyof PT>]?: TestFixtureValue<T[K], T & W & PT & PW> | [TestFixtureValue<T[K], T & W & PT & PW>, { scope?: 'test', auto?: boolean, option?: boolean, timeout?: number | undefined, title?: string, box?: boolean | 'self' }];
6645
6657
  };
6646
6658
 
6647
- type Agent = Exclude<BrowserContextOptions['agent'], undefined> & { cachePathTemplate?: string } | undefined;
6648
6659
  type BrowserName = 'chromium' | 'firefox' | 'webkit';
6649
6660
  type BrowserChannel = Exclude<LaunchOptions['channel'], undefined>;
6650
6661
  type ColorScheme = Exclude<BrowserContextOptions['colorScheme'], undefined>;
@@ -6935,6 +6946,15 @@ export interface PlaywrightWorkerOptions {
6935
6946
  export type ScreenshotMode = 'off' | 'on' | 'only-on-failure' | 'on-first-failure';
6936
6947
  export type TraceMode = 'off' | 'on' | 'retain-on-failure' | 'on-first-retry' | 'on-all-retries' | 'retain-on-first-failure';
6937
6948
  export type VideoMode = 'off' | 'on' | 'retain-on-failure' | 'on-first-retry';
6949
+ export type Agent = {
6950
+ provider: string;
6951
+ model: string;
6952
+ cachePathTemplate?: string;
6953
+ maxTurns?: number;
6954
+ maxTokens?: number;
6955
+ runAgents?: boolean;
6956
+ secrets?: { [key: string]: string };
6957
+ };
6938
6958
 
6939
6959
  /**
6940
6960
  * Playwright Test provides many options to configure test environment,
@@ -6975,11 +6995,7 @@ export type VideoMode = 'off' | 'on' | 'retain-on-failure' | 'on-first-retry';
6975
6995
  *
6976
6996
  */
6977
6997
  export interface PlaywrightTestOptions {
6978
- /**
6979
- * Agent settings for [page.perform(task[, options])](https://playwright.dev/docs/api/class-page#page-perform) and
6980
- * [page.extract(query, schema[, options])](https://playwright.dev/docs/api/class-page#page-extract).
6981
- */
6982
- agent: Agent;
6998
+ agent: Agent | undefined;
6983
6999
  /**
6984
7000
  * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
6985
7001
  *
@@ -1,128 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var proxyBackend_exports = {};
30
- __export(proxyBackend_exports, {
31
- ProxyBackend: () => ProxyBackend
32
- });
33
- module.exports = __toCommonJS(proxyBackend_exports);
34
- var import_utilsBundle = require("playwright-core/lib/utilsBundle");
35
- var mcpBundle = __toESM(require("playwright-core/lib/mcpBundle"));
36
- const errorsDebug = (0, import_utilsBundle.debug)("pw:mcp:errors");
37
- const { z, zodToJsonSchema } = mcpBundle;
38
- class ProxyBackend {
39
- constructor(mcpProviders) {
40
- this._mcpProviders = mcpProviders;
41
- this._contextSwitchTool = this._defineContextSwitchTool();
42
- }
43
- async initialize(clientInfo) {
44
- this._clientInfo = clientInfo;
45
- }
46
- async listTools() {
47
- const currentClient = await this._ensureCurrentClient();
48
- const response = await currentClient.listTools();
49
- if (this._mcpProviders.length === 1)
50
- return response.tools;
51
- return [
52
- ...response.tools,
53
- this._contextSwitchTool
54
- ];
55
- }
56
- async callTool(name, args) {
57
- if (name === this._contextSwitchTool.name)
58
- return this._callContextSwitchTool(args);
59
- const currentClient = await this._ensureCurrentClient();
60
- return await currentClient.callTool({
61
- name,
62
- arguments: args
63
- });
64
- }
65
- serverClosed() {
66
- void this._currentClient?.close().catch(errorsDebug);
67
- }
68
- async _callContextSwitchTool(params) {
69
- try {
70
- const factory = this._mcpProviders.find((factory2) => factory2.name === params.name);
71
- if (!factory)
72
- throw new Error("Unknown connection method: " + params.name);
73
- await this._setCurrentClient(factory);
74
- return {
75
- content: [{ type: "text", text: "### Result\nSuccessfully changed connection method.\n" }]
76
- };
77
- } catch (error) {
78
- return {
79
- content: [{ type: "text", text: `### Result
80
- Error: ${error}
81
- ` }],
82
- isError: true
83
- };
84
- }
85
- }
86
- _defineContextSwitchTool() {
87
- return {
88
- name: "browser_connect",
89
- description: [
90
- "Connect to a browser using one of the available methods:",
91
- ...this._mcpProviders.map((factory) => `- "${factory.name}": ${factory.description}`)
92
- ].join("\n"),
93
- inputSchema: zodToJsonSchema(z.object({
94
- name: z.enum(this._mcpProviders.map((factory) => factory.name)).default(this._mcpProviders[0].name).describe("The method to use to connect to the browser")
95
- }), { strictUnions: true }),
96
- annotations: {
97
- title: "Connect to a browser context",
98
- readOnlyHint: true,
99
- openWorldHint: false
100
- }
101
- };
102
- }
103
- async _ensureCurrentClient() {
104
- if (this._currentClient)
105
- return this._currentClient;
106
- return await this._setCurrentClient(this._mcpProviders[0]);
107
- }
108
- async _setCurrentClient(factory) {
109
- await this._currentClient?.close();
110
- this._currentClient = void 0;
111
- const client = new mcpBundle.Client({ name: "Playwright MCP Proxy", version: "0.0.0" });
112
- client.registerCapabilities({
113
- roots: {
114
- listRoots: true
115
- }
116
- });
117
- client.setRequestHandler(mcpBundle.ListRootsRequestSchema, () => ({ roots: this._clientInfo?.roots || [] }));
118
- client.setRequestHandler(mcpBundle.PingRequestSchema, () => ({}));
119
- const transport = factory.connect();
120
- await client.connect(transport);
121
- this._currentClient = client;
122
- return client;
123
- }
124
- }
125
- // Annotate the CommonJS export names for ESM import in node:
126
- 0 && (module.exports = {
127
- ProxyBackend
128
- });