Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: iterate on perform (#38458)
Pavel Feldman1513578204d1
diff --git a/docs/src/api/class-browser.md b/docs/src/api/class-browser.mdindex 7867ce5c8b..878bcda040 100644--- a/docs/src/api/class-browser.md+++ b/docs/src/api/class-browser.md@@ -267,6 +267,9 @@ await browser.CloseAsync();### option: Browser.newContext.storageStatePath = %%-csharp-java-context-option-storage-state-path-%%* since: v1.9+### option: Browser.newContext.agent = %%-js-context-option-agent-%%+* since: v1.58+## async method: Browser.newPage* since: v1.8- returns: <[Page]>diff --git a/docs/src/api/class-page.md b/docs/src/api/class-page.mdindex 717cbf06cb..7d37241513 100644--- a/docs/src/api/class-page.md+++ b/docs/src/api/class-page.md@@ -2024,6 +2024,38 @@ Name of the function on the window objectCallback function which will be called in Playwright's context.+## async method: Page.extract+* since: v1.58+* langs: js+- returns: <[any]>++Extract information from the page using the agentic loop, return it in a given Zod format.++**Usage**++```js+await page.extract('List of items in the cart', z.object({+ title: z.string().describe('Item title to extract'),+ price: z.string().describe('Item price to extract'),+}).array());+```++### param: Page.extract.query+* since: v1.58+- `query` <[string]>++Task to perform using agentic loop.++### param: Page.extract.schema+* since: v1.58+- `schema` <[z.ZodSchema]>++### option: Page.extract.maxTurns+* since: v1.58+- `maxTurns` <[int]>++Maximum number of agentic steps to take while extracting the information.+## async method: Page.fill* since: v1.8* discouraged: Use locator-based [`method: Locator.fill`] instead. Read more about [locators](../locators.md).@@ -2997,6 +3029,38 @@ Whether or not to generate tagged (accessible) PDF. Defaults to `false`.Whether or not to embed the document outline into the PDF. Defaults to `false`.+## async method: Page.perform+* since: v1.58+* langs: js++Perform action using agentic loop.++**Usage**++```js+await page.perform('Click submit button');+```++### param: Page.perform.task+* since: v1.58+- `task` <[string]>++Task to perform using agentic loop.++### option: Page.perform.key+* since: v1.58+- `key` <[string]>++All the agentic actions are converted to the Playwright calls and are cached.+By default, they are cached globally with the `task` as a key. This option allows controlling the cache key explicitly.++### option: Page.perform.maxTurns+* since: v1.58+- `maxTurns` <[int]>++Maximum number of agentic steps to take while performing this action.++## async method: Page.press* since: v1.8* discouraged: Use locator-based [`method: Locator.press`] instead. Read more about [locators](../locators.md).diff --git a/docs/src/api/params.md b/docs/src/api/params.mdindex d04354f8e0..fa45a5c7ed 100644--- a/docs/src/api/params.md+++ b/docs/src/api/params.md@@ -370,6 +370,16 @@ It makes the execution of the tests non-deterministic.Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the[`option: viewport`] is set.+## js-context-option-agent+* langs: js+- `agent` <[Object]>+ - `provider` <[string]> LLM provider to use+ - `model` <[string]> Model identifier within provider+ - `cacheDir` ?<[string]> Cache folder to use/generate code for performed actions into. Cache is not used if not specified (default).+ - `cacheMode` ?<['force'|'ignore'|'auto']> Cache control, defauls to 'auto'++Agent settings for [`method: Page.perform`] and [`method: Page.extract`].+## fetch-param-url- `url` <[string]>diff --git a/docs/src/test-api/class-testoptions.md b/docs/src/test-api/class-testoptions.mdindex c285430616..f00a272332 100644--- a/docs/src/test-api/class-testoptions.md+++ b/docs/src/test-api/class-testoptions.md@@ -46,6 +46,10 @@ export default defineConfig({});```+## property: TestOptions.agent = %%-js-context-option-agent-%%+* since: v1.58++## property: TestOptions.baseURL = %%-context-option-baseURL-%%* since: v1.10diff --git a/package-lock.json b/package-lock.jsonindex bd50c98c23..1a695eb458 100644--- a/package-lock.json+++ b/package-lock.json@@ -18,7 +18,7 @@"@eslint/compat": "^1.3.2","@eslint/eslintrc": "^3.3.1","@eslint/js": "^9.34.0",- "@lowire/loop": "^0.0.4",+ "@lowire/loop": "^0.0.6","@modelcontextprotocol/sdk": "^1.17.5","@octokit/graphql-schema": "^15.26.0","@stylistic/eslint-plugin": "^5.2.3",@@ -1064,9 +1064,9 @@}},"node_modules/@lowire/loop": {- "version": "0.0.4",- "resolved": "https://registry.npmjs.org/@lowire/loop/-/loop-0.0.4.tgz",- "integrity": "sha512-MuD9BS+jDAKs6pjBmMiEHtSWEtGXYm64IwC5HjisYh3QAujSvnj3Uo+Paicuc+VrBBzIWlFKFSrZGvX5PFEzWQ==",+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/@lowire/loop/-/loop-0.0.6.tgz",+ "integrity": "sha512-mrQft4UUj4tWt8ikOvRjec88nLRt6XwEnfzyFlZggedV735OcKE5Bk0Yy2mr3QCRCVn4/aw91lugRBS9ftSSpg==","dev": true,"license": "Apache-2.0","engines": {diff --git a/package.json b/package.jsonindex ef8d2d415e..805ba4b6f3 100644--- a/package.json+++ b/package.json@@ -57,7 +57,7 @@"@eslint/compat": "^1.3.2","@eslint/eslintrc": "^3.3.1","@eslint/js": "^9.34.0",- "@lowire/loop": "^0.0.4",+ "@lowire/loop": "^0.0.6","@modelcontextprotocol/sdk": "^1.17.5","@octokit/graphql-schema": "^15.26.0","@stylistic/eslint-plugin": "^5.2.3",diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex 861d7a0f66..1f92412180 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -27,6 +27,11 @@ type ElementHandleWaitForSelectorOptionsNotHidden = ElementHandleWaitForSelectorstate?: 'visible'|'attached';};+// @ts-ignore this will be any if zod is not installed+type ZodTypeAny = import('zod').ZodTypeAny;+// @ts-ignore this will be any if zod is not installed+type ZodInfer<T extends ZodTypeAny> = import('zod').infer<T>;+/*** Page provides methods to interact with a single tab in a [Browser](https://playwright.dev/docs/api/class-browser),* or an [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One@@ -1013,6 +1018,24 @@ export interface Page {*/behavior?: 'wait'|'ignoreErrors'|'default'}): Promise<void>;++ /**+ * Extract information from the page using the agentic loop, return it in a given Zod format.+ *+ * **Usage**+ *+ * ```js+ * await page.extract('List of items in the cart', z.object({+ * title: z.string().describe('Item title to extract'),+ * price: z.string().describe('Item price to extract'),+ * }).array());+ * ```+ *+ * @param query Task to perform using agentic loop.+ * @param schema+ * @param options+ */+ extract<Schema extends ZodTypeAny>(query: string, schema: Schema): Promise<ZodInfer<Schema>>;/*** Emitted when the page closes.*/@@ -3796,6 +3819,31 @@ export interface Page {width?: string|number;}): Promise<Buffer>;+ /**+ * Perform action using agentic loop.+ *+ * **Usage**+ *+ * ```js+ * await page.perform('Click submit button');+ * ```+ *+ * @param task Task to perform using agentic loop.+ * @param options+ */+ perform(task: string, options?: {+ /**+ * All the agentic actions are converted to the Playwright calls and are cached. By default, they are cached globally+ * with the `task` as a key. This option allows controlling the cache key explicitly.+ */+ key?: string;++ /**+ * Maximum number of agentic steps to take while performing this action.+ */+ maxTurns?: number;+ }): Promise<void>;+/*** **NOTE** Use locator-based [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)* instead. Read more about [locators](https://playwright.dev/docs/locators).@@ -22033,6 +22081,32 @@ export interface BrowserContextOptions {*/acceptDownloads?: boolean;+ /**+ * Agent settings for [page.perform(task[, options])](https://playwright.dev/docs/api/class-page#page-perform) and+ * [page.extract(query, schema[, options])](https://playwright.dev/docs/api/class-page#page-extract).+ */+ agent?: {+ /**+ * LLM provider to use+ */+ provider: string;++ /**+ * Model identifier within provider+ */+ model: string;++ /**+ * Cache folder to use/generate code for performed actions into. Cache is not used if not specified (default).+ */+ cacheDir?: string;++ /**+ * Cache control, defauls to 'auto'+ */+ cacheMode?: 'force'|'ignore'|'auto';+ };+/*** When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),* [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),diff --git a/packages/playwright-core/src/client/clientInstrumentation.ts b/packages/playwright-core/src/client/clientInstrumentation.tsindex da63f59b4d..e01947d269 100644--- a/packages/playwright-core/src/client/clientInstrumentation.ts+++ b/packages/playwright-core/src/client/clientInstrumentation.ts@@ -17,6 +17,7 @@import type { BrowserContext } from './browserContext';import type { APIRequestContext } from './fetch';import type { StackFrame } from '@protocol/channels';+import type { Page } from './page';// Instrumentation can mutate the data, for example change apiName or stepId.export interface ApiCallData {@@ -35,6 +36,7 @@ export interface ClientInstrumentation {onApiCallBegin(apiCall: ApiCallData, channel: { type: string, method: string, params?: Record<string, any> }): void;onApiCallEnd(apiCall: ApiCallData): void;onWillPause(options: { keepTestTimeout: boolean }): void;+ onPage(page: Page): void;runAfterCreateBrowserContext(context: BrowserContext): Promise<void>;runAfterCreateRequestContext(context: APIRequestContext): Promise<void>;@@ -46,7 +48,7 @@ export interface ClientInstrumentationListener {onApiCallBegin?(apiCall: ApiCallData, channel: { type: string, method: string, params?: Record<string, any> }): void;onApiCallEnd?(apiCall: ApiCallData): void;onWillPause?(options: { keepTestTimeout: boolean }): void;-+ onPage?(page: Page): void;runAfterCreateBrowserContext?(context: BrowserContext): Promise<void>;runAfterCreateRequestContext?(context: APIRequestContext): Promise<void>;runBeforeCloseBrowserContext?(context: BrowserContext): Promise<void>;diff --git a/packages/playwright-core/src/client/page.ts b/packages/playwright-core/src/client/page.tsindex 62891e54bc..4618722430 100644--- a/packages/playwright-core/src/client/page.ts+++ b/packages/playwright-core/src/client/page.ts@@ -54,6 +54,7 @@ import type * as api from '../../types/types';import type { ByRoleOptions } from '../utils/isomorphic/locatorUtils';import type { URLMatch } from '../utils/isomorphic/urlMatch';import type * as channels from '@protocol/channels';+import type z from 'zod';type PDFOptions = Omit<channels.PagePdfParams, 'width' | 'height' | 'margin'> & {width?: string | number,@@ -116,6 +117,7 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pageconstructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.PageInitializer) {super(parent, type, guid, initializer);+ this._instrumentation.onPage(this);this._browserContext = parent as unknown as BrowserContext;this._timeoutSettings = new TimeoutSettings(this._platform, this._browserContext._timeoutSettings);@@ -844,6 +846,14 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pagereturn result.pdf;}+ async perform(task: string, options: { key?: string, maxTurns?: number } = {}): Promise<void> {+ throw new Error('Not implemented in playwright-core');+ }++ extract<Schema extends z.ZodTypeAny>(query: string, schema: Schema, options: { maxTurns?: number } = {}): Promise<z.infer<Schema>> {+ throw new Error('Not implemented in playwright-core');+ }+async _snapshotForAI(options: TimeoutOptions & { track?: string } = {}): Promise<{ full: string, incremental?: string }> {return await this._channel.snapshotForAI({ timeout: this._timeoutSettings.timeout(options), track: options.track });}diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.tsindex 91f26b64c6..8a438c65aa 100644--- a/packages/playwright-core/src/protocol/validator.ts+++ b/packages/playwright-core/src/protocol/validator.ts@@ -602,6 +602,12 @@ scheme.BrowserTypeLaunchPersistentContextParams = tObject({serviceWorkers: tOptional(tEnum(['allow', 'block'])),selectorEngines: tOptional(tArray(tType('SelectorEngine'))),testIdAttributeName: tOptional(tString),+ agent: tOptional(tObject({+ provider: tString,+ model: tString,+ cacheDir: tOptional(tString),+ cacheMode: tOptional(tEnum(['ignore', 'force', 'auto'])),+ })),userDataDir: tString,slowMo: tOptional(tFloat),});@@ -694,6 +700,12 @@ scheme.BrowserNewContextParams = tObject({serviceWorkers: tOptional(tEnum(['allow', 'block'])),selectorEngines: tOptional(tArray(tType('SelectorEngine'))),testIdAttributeName: tOptional(tString),+ agent: tOptional(tObject({+ provider: tString,+ model: tString,+ cacheDir: tOptional(tString),+ cacheMode: tOptional(tEnum(['ignore', 'force', 'auto'])),+ })),proxy: tOptional(tObject({server: tString,bypass: tOptional(tString),@@ -765,6 +777,12 @@ scheme.BrowserNewContextForReuseParams = tObject({serviceWorkers: tOptional(tEnum(['allow', 'block'])),selectorEngines: tOptional(tArray(tType('SelectorEngine'))),testIdAttributeName: tOptional(tString),+ agent: tOptional(tObject({+ provider: tString,+ model: tString,+ cacheDir: tOptional(tString),+ cacheMode: tOptional(tEnum(['ignore', 'force', 'auto'])),+ })),proxy: tOptional(tObject({server: tString,bypass: tOptional(tString),@@ -881,6 +899,12 @@ scheme.BrowserContextInitializer = tObject({serviceWorkers: tOptional(tEnum(['allow', 'block'])),selectorEngines: tOptional(tArray(tType('SelectorEngine'))),testIdAttributeName: tOptional(tString),+ agent: tOptional(tObject({+ provider: tString,+ model: tString,+ cacheDir: tOptional(tString),+ cacheMode: tOptional(tEnum(['ignore', 'force', 'auto'])),+ })),}),});scheme.BrowserContextBindingCallEvent = tObject({@@ -2770,6 +2794,12 @@ scheme.AndroidDeviceLaunchBrowserParams = tObject({serviceWorkers: tOptional(tEnum(['allow', 'block'])),selectorEngines: tOptional(tArray(tType('SelectorEngine'))),testIdAttributeName: tOptional(tString),+ agent: tOptional(tObject({+ provider: tString,+ model: tString,+ cacheDir: tOptional(tString),+ cacheMode: tOptional(tEnum(['ignore', 'force', 'auto'])),+ })),pkg: tOptional(tString),args: tOptional(tArray(tString)),proxy: tOptional(tObject({diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.tsindex 9edfd3a43f..c00011fbf7 100644--- a/packages/playwright-core/src/server/browserContext.ts+++ b/packages/playwright-core/src/server/browserContext.ts@@ -168,7 +168,7 @@ export abstract class BrowserContext extends SdkObject {}static reusableContextHash(params: channels.BrowserNewContextForReuseParams): string {- const paramsCopy = { ...params };+ const paramsCopy = { ...params, agent: undefined };if (paramsCopy.selectorEngines?.length === 0)delete paramsCopy.selectorEngines;diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex 861d7a0f66..1f92412180 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -27,6 +27,11 @@ type ElementHandleWaitForSelectorOptionsNotHidden = ElementHandleWaitForSelectorstate?: 'visible'|'attached';};+// @ts-ignore this will be any if zod is not installed+type ZodTypeAny = import('zod').ZodTypeAny;+// @ts-ignore this will be any if zod is not installed+type ZodInfer<T extends ZodTypeAny> = import('zod').infer<T>;+/*** Page provides methods to interact with a single tab in a [Browser](https://playwright.dev/docs/api/class-browser),* or an [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One@@ -1013,6 +1018,24 @@ export interface Page {*/behavior?: 'wait'|'ignoreErrors'|'default'}): Promise<void>;++ /**+ * Extract information from the page using the agentic loop, return it in a given Zod format.+ *+ * **Usage**+ *+ * ```js+ * await page.extract('List of items in the cart', z.object({+ * title: z.string().describe('Item title to extract'),+ * price: z.string().describe('Item price to extract'),+ * }).array());+ * ```+ *+ * @param query Task to perform using agentic loop.+ * @param schema+ * @param options+ */+ extract<Schema extends ZodTypeAny>(query: string, schema: Schema): Promise<ZodInfer<Schema>>;/*** Emitted when the page closes.*/@@ -3796,6 +3819,31 @@ export interface Page {width?: string|number;}): Promise<Buffer>;+ /**+ * Perform action using agentic loop.+ *+ * **Usage**+ *+ * ```js+ * await page.perform('Click submit button');+ * ```+ *+ * @param task Task to perform using agentic loop.+ * @param options+ */+ perform(task: string, options?: {+ /**+ * All the agentic actions are converted to the Playwright calls and are cached. By default, they are cached globally+ * with the `task` as a key. This option allows controlling the cache key explicitly.+ */+ key?: string;++ /**+ * Maximum number of agentic steps to take while performing this action.+ */+ maxTurns?: number;+ }): Promise<void>;+/*** **NOTE** Use locator-based [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)* instead. Read more about [locators](https://playwright.dev/docs/locators).@@ -22033,6 +22081,32 @@ export interface BrowserContextOptions {*/acceptDownloads?: boolean;+ /**+ * Agent settings for [page.perform(task[, options])](https://playwright.dev/docs/api/class-page#page-perform) and+ * [page.extract(query, schema[, options])](https://playwright.dev/docs/api/class-page#page-extract).+ */+ agent?: {+ /**+ * LLM provider to use+ */+ provider: string;++ /**+ * Model identifier within provider+ */+ model: string;++ /**+ * Cache folder to use/generate code for performed actions into. Cache is not used if not specified (default).+ */+ cacheDir?: string;++ /**+ * Cache control, defauls to 'auto'+ */+ cacheMode?: 'force'|'ignore'|'auto';+ };+/*** When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),* [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),diff --git a/packages/playwright/index.js b/packages/playwright/index.jsindex e263df6ab1..3c89a6329e 100644--- a/packages/playwright/index.js+++ b/packages/playwright/index.js@@ -14,4 +14,7 @@* limitations under the License.*/-module.exports = require('playwright-core');+const playwright = require('playwright-core');+const { decoratePage } = require('./lib/agents/pageDecorator');+decoratePage(playwright);+module.exports = playwright;diff --git a/packages/playwright/src/agents/pageDecorator.ts b/packages/playwright/src/agents/pageDecorator.tsnew file mode 100644index 0000000000..af65f967ee--- /dev/null+++ b/packages/playwright/src/agents/pageDecorator.ts@@ -0,0 +1,94 @@+/**+ * Copyright Microsoft Corporation. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { debug } from 'playwright-core/lib/utilsBundle';+import { Loop, zodToJsonSchema } from 'playwright-core/lib/mcpBundle';++import { identityBrowserContextFactory } from '../mcp/browser/browserContextFactory';+import { BrowserServerBackend } from '../mcp/browser/browserServerBackend';+import { defaultConfig } from '../mcp/browser/config';+import { wrapInClient } from '../mcp/sdk/server';++import type { ZodSchema } from 'zod';+import type { Playwright } from '../../../playwright-core/src/client/playwright';+import type { Page } from '../../../playwright-core/src/client/page';+import type * as lowireLoop from '@lowire/loop';++export function decoratePage(playwright: Playwright) {+ playwright._instrumentation.addListener({+ onPage: page => {+ page.perform = pagePerform.bind(null, page);+ page.extract = pageExtract.bind(null, page);+ }+ });+}++async function pagePerform(page: Page, userTask: string, options: { maxTurns?: number } = {}): Promise<void> {+ const resultSchema = {+ type: 'object',+ properties: {+ code: { type: 'string' },+ },+ required: ['code']+ };+ await perform(page, userTask, resultSchema, options);+}++async function pageExtract(page: Page, query: string, schema: ZodSchema, options: { maxTurns?: number } = {}) {+ const task = `+### Instructions+Extract the following information from the page. Do not perform any actions, just extract the information.++### Query+${query}`;+ return await perform(page, task, zodToJsonSchema(schema), options);+}++async function perform(page: Page, userTask: string, resultSchema: any, options: { maxTurns?: number } = {}): Promise<any> {+ const context = page.context();+ if (!context._options.agent)+ throw new Error(`page.perform() and page.extract() require the agent to be set on the browser context`);++ const { full } = await page._snapshotForAI();+ const backend = new BrowserServerBackend(defaultConfig, identityBrowserContextFactory(context));+ const client = await wrapInClient(backend, { name: 'Internal', version: '0.0.0' });+ const callTool: (params: { name: string, arguments: any}) => Promise<lowireLoop.ToolResult> = async params => {+ return await client.callTool(params) as lowireLoop.ToolResult;+ };++ const loop = new Loop(context._options.agent.provider as any, {+ model: context._options.agent.model,+ summarize: true,+ debug,+ callTool,+ tools: await backend.listTools(),+ ...options+ });++ const task = `${userTask}++### Page snapshot+${full}+`;++ try {+ return await loop.run(task, {+ resultSchema+ });+ } finally {+ await client.close();+ }+}diff --git a/packages/playwright/src/agents/performTask.ts b/packages/playwright/src/agents/performTask.tsdeleted file mode 100644index e95c2dc627..0000000000--- a/packages/playwright/src/agents/performTask.ts+++ /dev/null@@ -1,175 +0,0 @@-/**- * Copyright Microsoft Corporation. All rights reserved.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import fs from 'fs';-import path from 'path';--import { debug } from 'playwright-core/lib/utilsBundle';-import { z, zodToJsonSchema, Loop } from 'playwright-core/lib/mcpBundle';--import { identityBrowserContextFactory } from '../mcp/browser/browserContextFactory';-import { BrowserServerBackend } from '../mcp/browser/browserServerBackend';-import { defaultConfig } from '../mcp/browser/config';-import { wrapInClient } from '../mcp/sdk/server';--import type * as playwright from 'playwright-core';-import type * as lowireLoop from '@lowire/loop';-import type * as zod from 'zod';-import type { TestInfo } from '../../types/test';--export type PerformTaskOptions = {- provider?: 'github' | 'openai' | 'anthropic' | 'google';- model?: string;- maxTokens?: number;- reasoning?: boolean;- temperature?: number;-};--const resultSchema = z.object({- code: z.string().optional().describe(`-Generated code to perform the task using Playwright API.-Check out the <code> blocks and combine them. Should be presented in the following form:--perform(async ({ page }) => {- // generated code here.-});-`),- error: z.string().optional().describe('The error that occurred if execution failed.').optional(),-});--export async function performTask(testInfo: TestInfo, context: playwright.BrowserContext, userTask: string, options: PerformTaskOptions) {- const cacheStatus = await performTaskFromCache(testInfo, context, userTask);- if (cacheStatus === 'success')- return;-- const backend = new BrowserServerBackend(defaultConfig, identityBrowserContextFactory(context));- const client = await wrapInClient(backend, { name: 'Internal', version: '0.0.0' });- const callTool: (params: { name: string, arguments: any}) => Promise<lowireLoop.ToolResult> = async params => {- return await client.callTool(params) as lowireLoop.ToolResult;- };-- const loop = new Loop(options.provider ?? 'github', {- model: options.model ?? 'claude-sonnet-4.5',- reasoning: options.reasoning,- temperature: options.temperature,- maxTokens: options.maxTokens,- summarize: true,- debug,- callTool,- tools: await backend.listTools(),- });-- try {- const result = await loop.run<zod.infer<typeof resultSchema>>(userTask, { resultSchema: zodToJsonSchema(resultSchema) as lowireLoop.Schema });- if (result.code)- await updatePerformFile(testInfo, userTask, result.code, options);- } finally {- await client.close();- }-}--async function updatePerformFile(testInfo: TestInfo, userTask: string, taskCode: string, options: PerformTaskOptions) {- const relativeFile = path.relative(testInfo.project.testDir, testInfo.file);- const promptCacheFile = testInfo.file.replace('.spec.ts', '.cache.ts');- const testTitle = testInfo.title;-- const loop = new Loop(options.provider ?? 'github', {- model: options.model ?? 'claude-sonnet-4.5',- reasoning: options.reasoning,- temperature: options.temperature,- maxTokens: options.maxTokens,- summarize: true,- debug,- callTool: async () => ({ content: [] }),- tools: [],- });-- const resultSchema = z.object({- code: z.string().optional().describe(`-Generated code with all the perofrm routines combined or updated into the following format:--import { performCache } from '@playwright/test';--performCache({- file: 'tests/page/perform-task.spec.ts',- test: 'perform task',- task: 'Click the learn more button',- code: async ({ page }) => {- await page.getByRole('link', { name: 'Learn more' }).click();- },-});-`),- });-- const existingCode = await fs.promises.readFile(promptCacheFile, 'utf8').catch(() => '');- const task = `-- Create or update a perform file to include performCache block for the given task and code.-- Dedupe items with the same file, test, and task.-- Should produce code in the following format--import { performCache } from '@playwright/test';--performCache({- file: '<file>',- test: '<test>',- task: '<task>',- code: async ({ page }) => {- <code>- },-});--performCache({-...--## Params for the new or updated performCache block-<file-content>${existingCode}</file-content>-<file>${relativeFile}</file>-<test>${testTitle}</test>-<task>${userTask}</task>-<code>${taskCode}</code>-`;-- const result = await loop.run<zod.infer<typeof resultSchema>>(task, { resultSchema: zodToJsonSchema(resultSchema) as lowireLoop.Schema });- if (result.code)- await fs.promises.writeFile(promptCacheFile, result.code);-}--type PerformCacheEntry = {- file: string,- test: string,- task: string,- code: ({ page }: { page: playwright.Page }) => Promise<void>-};--const performCacheMap = new Map<string, PerformCacheEntry>();--export function performCache(entry: PerformCacheEntry) {- performCacheMap.set(JSON.stringify({ ...entry, code: undefined }), entry);-}--async function performTaskFromCache(testInfo: TestInfo, context: playwright.BrowserContext, userTask: string): Promise<'success' | 'cache-miss' | Error> {- const relativeFile = path.relative(testInfo.project.testDir, testInfo.file);- const key = JSON.stringify({ file: relativeFile, test: testInfo.title, task: userTask });- const entry = performCacheMap.get(key);- if (!entry)- return 'cache-miss';- try {- await entry.code({ page: context.pages()[0] });- return 'success';- } catch (error) {- return error;- }-}diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.tsindex 8868e54bc6..85c763c633 100644--- a/packages/playwright/src/index.ts+++ b/packages/playwright/src/index.ts@@ -23,7 +23,6 @@ import { setBoxedStackPrefixes, createGuid, currentZone, debugMode, jsonStringifimport { currentTestInfo } from './common/globals';import { rootTestType } from './common/testType';import { createCustomMessageHandler } from './mcp/test/browserBackend';-import { performTask } from './agents/performTask';import type { Fixtures, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, ScreenshotMode, TestInfo, TestType, VideoMode } from '../types/test';import type { ContextReuseMode } from './common/config';@@ -36,7 +35,6 @@ import type { APIRequestContext as APIRequestContextImpl } from '../../playwrighimport type { ChannelOwner } from '../../playwright-core/src/client/channelOwner';import type { Page as PageImpl } from '../../playwright-core/src/client/page';import type { BrowserContext, BrowserContextOptions, LaunchOptions, Page, Tracing } from 'playwright-core';-import type { PerformTaskOptions } from './agents/performTask';export { expect } from './matchers/expect';export const _baseTest: TestType<{}, {}> = rootTestType.test;@@ -59,7 +57,6 @@ type TestFixtures = PlaywrightTestArgs & PlaywrightTestOptions & {_combinedContextOptions: BrowserContextOptions,_setupContextOptions: void;_setupArtifacts: void;- _perform: (task: string, options?: PerformTaskOptions) => Promise<void>;_contextFactory: (options?: BrowserContextOptions) => Promise<{ context: BrowserContext, close: () => Promise<void> }>;};@@ -128,6 +125,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({}, { scope: 'worker', timeout: 0 }],acceptDownloads: [({ contextOptions }, use) => use(contextOptions.acceptDownloads ?? true), { option: true, box: true }],+ agent: [({ contextOptions }, use) => use(contextOptions.agent), { option: true, box: true }],bypassCSP: [({ contextOptions }, use) => use(contextOptions.bypassCSP ?? false), { option: true, box: true }],colorScheme: [({ contextOptions }, use) => use(contextOptions.colorScheme === undefined ? 'light' : contextOptions.colorScheme), { option: true, box: true }],deviceScaleFactor: [({ contextOptions }, use) => use(contextOptions.deviceScaleFactor), { option: true, box: true }],@@ -158,6 +156,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({_combinedContextOptions: [async ({acceptDownloads,+ agent,bypassCSP,clientCertificates,colorScheme,@@ -184,6 +183,8 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({const options: BrowserContextOptions = {};if (acceptDownloads !== undefined)options.acceptDownloads = acceptDownloads;+ if (agent !== undefined)+ options.agent = agent;if (bypassCSP !== undefined)options.bypassCSP = bypassCSP;if (colorScheme !== undefined)@@ -461,12 +462,6 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({await request.dispose();}},-- _perform: async ({ context }, use, testInfo) => {- await use(async (task: string, options?: PerformTaskOptions) => {- await performTask(testInfo, context, task, options ?? {});- });- },});type ScreenshotOption = PlaywrightWorkerOptions['screenshot'] | undefined;@@ -794,4 +789,3 @@ export const test = _baseTest.extend<TestFixtures, WorkerFixtures>(playwrightFixexport { defineConfig } from './common/configLoader';export { mergeTests } from './common/testType';export { mergeExpects } from './matchers/expect';-export { performCache } from './agents/performTask';diff --git a/packages/playwright/types/test.d.ts b/packages/playwright/types/test.d.tsindex 6691642fc1..a6471a8204 100644--- a/packages/playwright/types/test.d.ts+++ b/packages/playwright/types/test.d.ts@@ -6644,6 +6644,7 @@ export type Fixtures<T extends {} = {}, W extends {} = {}, PT extends {} = {}, P[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' }];};+type Agent = Exclude<BrowserContextOptions['agent'], undefined> | undefined;type BrowserName = 'chromium' | 'firefox' | 'webkit';type BrowserChannel = Exclude<LaunchOptions['channel'], undefined>;type ColorScheme = Exclude<BrowserContextOptions['colorScheme'], undefined>;@@ -6974,6 +6975,11 @@ export type VideoMode = 'off' | 'on' | 'retain-on-failure' | 'on-first-retry';**/export interface PlaywrightTestOptions {+ /**+ * Agent settings for [page.perform(task[, options])](https://playwright.dev/docs/api/class-page#page-perform) and+ * [page.extract(query, schema[, options])](https://playwright.dev/docs/api/class-page#page-extract).+ */+ agent: Agent;/*** Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.*diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.tsindex 9b52395916..c4e6e83261 100644--- a/packages/protocol/src/channels.d.ts+++ b/packages/protocol/src/channels.d.ts@@ -1008,6 +1008,12 @@ export type BrowserTypeLaunchPersistentContextParams = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },userDataDir: string,slowMo?: number,};@@ -1090,6 +1096,12 @@ export type BrowserTypeLaunchPersistentContextOptions = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },slowMo?: number,};export type BrowserTypeLaunchPersistentContextResult = {@@ -1211,6 +1223,12 @@ export type BrowserNewContextParams = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },proxy?: {server: string,bypass?: string,@@ -1279,6 +1297,12 @@ export type BrowserNewContextOptions = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },proxy?: {server: string,bypass?: string,@@ -1350,6 +1374,12 @@ export type BrowserNewContextForReuseParams = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },proxy?: {server: string,bypass?: string,@@ -1418,6 +1448,12 @@ export type BrowserNewContextForReuseOptions = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },proxy?: {server: string,bypass?: string,@@ -1553,6 +1589,12 @@ export type BrowserContextInitializer = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },},};export interface BrowserContextEventTarget {@@ -4836,6 +4878,12 @@ export type AndroidDeviceLaunchBrowserParams = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },pkg?: string,args?: string[],proxy?: {@@ -4902,6 +4950,12 @@ export type AndroidDeviceLaunchBrowserOptions = {serviceWorkers?: 'allow' | 'block',selectorEngines?: SelectorEngine[],testIdAttributeName?: string,+ agent?: {+ provider: string,+ model: string,+ cacheDir?: string,+ cacheMode?: 'ignore' | 'force' | 'auto',+ },pkg?: string,args?: string[],proxy?: {diff --git a/packages/protocol/src/protocol.yml b/packages/protocol/src/protocol.ymlindex a9573b1bcb..d9540743a7 100644--- a/packages/protocol/src/protocol.yml+++ b/packages/protocol/src/protocol.yml@@ -589,7 +589,18 @@ ContextOptions:type: array?items: SelectorEnginetestIdAttributeName: string?-+ agent:+ type: object?+ properties:+ provider: string+ model: string+ cacheDir: string?+ cacheMode:+ type: enum?+ literals:+ - ignore+ - force+ - autoLocalUtils:type: interfacediff --git a/tests/library/playwright.config.ts b/tests/library/playwright.config.tsindex 4fbe899cee..aa3cfb19a0 100644--- a/tests/library/playwright.config.ts+++ b/tests/library/playwright.config.ts@@ -128,6 +128,10 @@ for (const browserName of browserNames) {executablePath,},trace: trace ? 'on' : undefined,+ agent: {+ provider: 'github',+ model: 'claude-sonnet-4.5'+ }},metadata: {platform: process.platform,diff --git a/tests/page/perform-task.cache.ts b/tests/page/perform-task.cache.tsdeleted file mode 100644index e3bbc5875c..0000000000--- a/tests/page/perform-task.cache.ts+++ /dev/null@@ -1,48 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--// @ts-ignore-import { performCache } from '@playwright/test';--performCache({- file: 'perform-task.spec.ts',- test: 'perform task',- task: 'Add "Buy groceries" todo',- code: async ({ page }) => {- await page.getByRole('textbox', { name: 'What needs to be done?' }).fill('Buy groceries');- await page.keyboard.press('Enter');- },-});--performCache({- file: 'perform-task.spec.ts',- test: 'perform task',- task: 'Add "Walk the dog" todo',- code: async ({ page }) => {- await page.getByRole('textbox', { name: 'What needs to be done?' }).fill('Walk the dog');- await page.keyboard.press('Enter');- },-});--performCache({- file: 'perform-task.spec.ts',- test: 'perform task',- task: 'Add "Read a book" todo',- code: async ({ page }) => {- await page.getByRole('textbox', { name: 'What needs to be done?' }).fill('Read a book');- await page.getByRole('textbox', { name: 'What needs to be done?' }).press('Enter');- },-});diff --git a/tests/page/perform-task.spec.ts b/tests/page/perform-task.spec.tsindex f629795aa3..908477d57b 100644--- a/tests/page/perform-task.spec.ts+++ b/tests/page/perform-task.spec.ts@@ -14,13 +14,16 @@* limitations under the License.*/-import { test as it } from './pageTest';-import './perform-task.cache';+import { test } from './pageTest';+import z from 'zod';-// @ts-ignore-it('perform task', async ({ page, _perform }) => {+test.skip('perform task', async ({ page }) => {await page.goto('https://demo.playwright.dev/todomvc');- await _perform('Add "Buy groceries" todo');- await _perform('Add "Walk the dog" todo');- await _perform('Add "Read a book" todo');+ await page.perform('Add "Buy groceries" todo');+ console.log(await page.extract('List todos with their statuses', z.object({+ items: z.object({+ title: z.string(),+ completed: z.boolean()+ }).array()+ })));});diff --git a/utils/generate_types/overrides-test.d.ts b/utils/generate_types/overrides-test.d.tsindex 7b46b3402b..a314578ba5 100644--- a/utils/generate_types/overrides-test.d.ts+++ b/utils/generate_types/overrides-test.d.ts@@ -209,6 +209,7 @@ export type Fixtures<T extends {} = {}, W extends {} = {}, PT extends {} = {}, P[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' }];};+type Agent = Exclude<BrowserContextOptions['agent'], undefined> | undefined;type BrowserName = 'chromium' | 'firefox' | 'webkit';type BrowserChannel = Exclude<LaunchOptions['channel'], undefined>;type ColorScheme = Exclude<BrowserContextOptions['colorScheme'], undefined>;@@ -267,6 +268,7 @@ export type TraceMode = 'off' | 'on' | 'retain-on-failure' | 'on-first-retry' |export type VideoMode = 'off' | 'on' | 'retain-on-failure' | 'on-first-retry';export interface PlaywrightTestOptions {+ agent: Agent;acceptDownloads: boolean;bypassCSP: boolean;colorScheme: ColorScheme;diff --git a/utils/generate_types/overrides.d.ts b/utils/generate_types/overrides.d.tsindex f5dca77433..b50bb7a641 100644--- a/utils/generate_types/overrides.d.ts+++ b/utils/generate_types/overrides.d.ts@@ -26,6 +26,11 @@ type ElementHandleWaitForSelectorOptionsNotHidden = ElementHandleWaitForSelectorstate?: 'visible'|'attached';};+// @ts-ignore this will be any if zod is not installed+type ZodTypeAny = import('zod').ZodTypeAny;+// @ts-ignore this will be any if zod is not installed+type ZodInfer<T extends ZodTypeAny> = import('zod').infer<T>;+export interface Page {evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>;evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>;@@ -72,6 +77,8 @@ export interface Page {*/behavior?: 'wait'|'ignoreErrors'|'default'}): Promise<void>;++ extract<Schema extends ZodTypeAny>(query: string, schema: Schema): Promise<ZodInfer<Schema>>;}export interface Frame {