Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/src/api/params.md
Original file line number Diff line number Diff line change
Expand Up @@ -390,10 +390,17 @@ Defaults to context-wide value specified in `agent` property.

Maximum number of agentic turns during this call, defaults to context-wide value specified in `agent` property.

## page-agent-timeout
* since: v1.58
- `timeout` <[int]>

Request timeout in milliseconds. Defaults to action timeout. Pass `0` to disable timeout.

## page-agent-call-options-v1.58
- %%-page-agent-cache-key-%%
- %%-page-agent-max-tokens-%%
- %%-page-agent-max-turns-%%
- %%-page-agent-timeout-%%

## fetch-param-url
- `url` <[string]>
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"@eslint/compat": "^1.3.2",
"@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.34.0",
"@lowire/loop": "^0.0.18",
"@lowire/loop": "^0.0.19",
"@modelcontextprotocol/sdk": "^1.17.5",
"@octokit/graphql-schema": "^15.26.0",
"@stylistic/eslint-plugin": "^5.2.3",
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-client/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5411,6 +5411,11 @@ export interface PageAgent {
* Maximum number of agentic turns during this call, defaults to context-wide value specified in `agent` property.
*/
maxTurns?: number;

/**
* Request timeout in milliseconds. Defaults to action timeout. Pass `0` to disable timeout.
*/
timeout?: number;
}): Promise<void>;

/**
Expand Down Expand Up @@ -5442,6 +5447,11 @@ export interface PageAgent {
* Maximum number of agentic turns during this call, defaults to context-wide value specified in `agent` property.
*/
maxTurns?: number;

/**
* Request timeout in milliseconds. Defaults to action timeout. Pass `0` to disable timeout.
*/
timeout?: number;
}): Promise<{
usage: {
turns: number;
Expand Down
6 changes: 3 additions & 3 deletions packages/playwright-core/ThirdPartyNotices.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ THIRD-PARTY SOFTWARE NOTICES AND INFORMATION

This project incorporates components from the projects listed below. The original copyright notices and the licenses under which Microsoft received such components are set forth below. Microsoft reserves all rights not expressly granted herein, whether by implication, estoppel or otherwise.

- @lowire/loop@0.0.18 (https://github.com/pavelfeldman/lowire)
- @lowire/loop@0.0.19 (https://github.com/pavelfeldman/lowire)
- @modelcontextprotocol/sdk@1.24.2 (https://github.com/modelcontextprotocol/typescript-sdk)
- accepts@2.0.0 (https://github.com/jshttp/accepts)
- agent-base@7.1.4 (https://github.com/TooTallNate/proxy-agents)
Expand Down Expand Up @@ -135,7 +135,7 @@ This project incorporates components from the projects listed below. The origina
- zod-to-json-schema@3.25.0 (https://github.com/StefanTerdell/zod-to-json-schema)
- zod@3.25.76 (https://github.com/colinhacks/zod)

%% @lowire/loop@0.0.18 NOTICES AND INFORMATION BEGIN HERE
%% @lowire/loop@0.0.19 NOTICES AND INFORMATION BEGIN HERE
=========================================
Apache License
Version 2.0, January 2004
Expand Down Expand Up @@ -339,7 +339,7 @@ Apache License
See the License for the specific language governing permissions and
limitations under the License.
=========================================
END OF @lowire/loop@0.0.18 AND INFORMATION
END OF @lowire/loop@0.0.19 AND INFORMATION

%% @modelcontextprotocol/sdk@1.24.2 NOTICES AND INFORMATION BEGIN HERE
=========================================
Expand Down
8 changes: 4 additions & 4 deletions packages/playwright-core/bundles/mcp/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/playwright-core/bundles/mcp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.0.1",
"private": true,
"dependencies": {
"@lowire/loop": "^0.0.18",
"@lowire/loop": "^0.0.19",
"@modelcontextprotocol/sdk": "^1.24.0",
"zod": "^3.25.76",
"zod-to-json-schema": "^3.24.6"
Expand Down
3 changes: 3 additions & 0 deletions packages/playwright-core/src/protocol/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2909,6 +2909,7 @@ scheme.PageAgentPerformParams = tObject({
maxTurns: tOptional(tInt),
maxTokens: tOptional(tInt),
cacheKey: tOptional(tString),
timeout: tOptional(tInt),
});
scheme.PageAgentPerformResult = tObject({
usage: tType('AgentUsage'),
Expand All @@ -2918,6 +2919,7 @@ scheme.PageAgentExpectParams = tObject({
maxTurns: tOptional(tInt),
maxTokens: tOptional(tInt),
cacheKey: tOptional(tString),
timeout: tOptional(tInt),
});
scheme.PageAgentExpectResult = tObject({
usage: tType('AgentUsage'),
Expand All @@ -2928,6 +2930,7 @@ scheme.PageAgentExtractParams = tObject({
maxTurns: tOptional(tInt),
maxTokens: tOptional(tInt),
cacheKey: tOptional(tString),
timeout: tOptional(tInt),
});
scheme.PageAgentExtractResult = tObject({
result: tAny,
Expand Down
84 changes: 20 additions & 64 deletions packages/playwright-core/src/server/agent/actionRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import { serializeExpectedTextValues } from '../utils/expectUtils';
import { monotonicTime } from '../../utils/isomorphic/time';
import { createGuid } from '../utils/crypto';
import { parseAriaSnapshotUnsafe } from '../../utils/isomorphic/ariaSnapshot';
import { ProgressController } from '../progress';
import { yaml } from '../../utilsBundle';
import { serializeError } from '../errors';

Expand All @@ -30,27 +29,23 @@ import type { ExpectResult, Frame } from '../frames';
import type { CallMetadata } from '../instrumentation';
import type * as channels from '@protocol/channels';

export async function runAction(parentProgress: Progress, mode: 'generate' | 'run', page: Page, action: actions.Action, secrets: NameValue[]) {
const timeout = mode === 'generate' ? generateActionTimeout(action) : performActionTimeout(action);
const mt = monotonicTime();
const deadline = mt + timeout;
const minDeadline = parentProgress.deadline ? Math.min(parentProgress.deadline, deadline) : deadline;
const pc = new ProgressController();
return await pc.run(async progress => {
const frame = page.mainFrame();
const callMetadata = callMetadataForAction(frame, action);
await frame.instrumentation.onBeforeCall(frame, callMetadata, parentProgress.metadata.id);
export async function runAction(progress: Progress, mode: 'generate' | 'run', page: Page, action: actions.Action, secrets: NameValue[]) {
const parentMetadata = progress.metadata;
const frame = page.mainFrame();
const callMetadata = callMetadataForAction(progress, frame, action);
callMetadata.log = parentMetadata.log;
progress.metadata = callMetadata;

let error: Error | undefined;
const result = await innerRunAction(progress, mode, page, action, secrets).catch(e => error = e);
callMetadata.endTime = monotonicTime();
callMetadata.error = error ? serializeError(error) : undefined;
callMetadata.result = error ? undefined : result;
await frame.instrumentation.onAfterCall(frame, callMetadata);
if (error)
throw error;
return result;
}, minDeadline - mt);
await frame.instrumentation.onBeforeCall(frame, callMetadata, parentMetadata.id);
let error: Error | undefined;
const result = await innerRunAction(progress, mode, page, action, secrets).catch(e => error = e);
callMetadata.endTime = monotonicTime();
callMetadata.error = error ? serializeError(error) : undefined;
callMetadata.result = error ? undefined : result;
await frame.instrumentation.onAfterCall(frame, callMetadata);
if (error)
throw error;
return result;
}

async function innerRunAction(progress: Progress, mode: 'generate' | 'run', page: Page, action: actions.Action, secrets: NameValue[]) {
Expand Down Expand Up @@ -134,47 +129,8 @@ async function innerRunAction(progress: Progress, mode: 'generate' | 'run', page
}
}

export function generateActionTimeout(action: actions.Action): number {
switch (action.method) {
case 'navigate':
return 10000;
case 'click':
case 'drag':
case 'hover':
case 'selectOption':
case 'pressKey':
case 'pressSequentially':
case 'fill':
case 'setChecked':
return 5000;
case 'expectVisible':
case 'expectValue':
case 'expectAria':
return 1; // one shot
}
}

export function performActionTimeout(action: actions.Action): number {
switch (action.method) {
case 'navigate':
case 'click':
case 'drag':
case 'hover':
case 'selectOption':
case 'pressKey':
case 'pressSequentially':
case 'fill':
case 'setChecked':
return 0; // no timeout
case 'expectVisible':
case 'expectValue':
case 'expectAria':
return 5000; // default expect timeout.
}
}

export function traceParamsForAction(action: actions.Action): { title?: string, type: string, method: string, params: any } {
const timeout = generateActionTimeout(action);
export function traceParamsForAction(progress: Progress, action: actions.Action): { title?: string, type: string, method: string, params: any } {
const timeout = progress.timeout;
switch (action.method) {
case 'navigate': {
const params: channels.FrameGotoParams = {
Expand Down Expand Up @@ -306,7 +262,7 @@ export function traceParamsForAction(action: actions.Action): { title?: string,
}
}

function callMetadataForAction(frame: Frame, action: actions.Action): CallMetadata {
function callMetadataForAction(progress: Progress, frame: Frame, action: actions.Action): CallMetadata {
const callMetadata: CallMetadata = {
id: `call@${createGuid()}`,
objectId: frame.guid,
Expand All @@ -315,7 +271,7 @@ function callMetadataForAction(frame: Frame, action: actions.Action): CallMetada
startTime: monotonicTime(),
endTime: 0,
log: [],
...traceParamsForAction(action),
...traceParamsForAction(progress, action),
};
return callMetadata;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/server/agent/pageAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ export async function pageAgentExpect(progress: Progress, context: Context, expe
${expectation}
`;

callParams.maxTurns = callParams.maxTurns ?? 3;
await runLoop(progress, context, expectTools, task, undefined, callParams);
await updateCache(context, cacheKey);
}
Expand Down Expand Up @@ -130,7 +129,8 @@ async function runLoop(progress: Progress, context: Context, toolDefinitions: To
task.push('### Page snapshot');
task.push(full);
task.push('');
await loop.run(task.join('\n'));

await loop.run(task.join('\n'), { signal: progress.signal });

return { result: resultSchema ? reportedResult() : undefined };
}
Expand Down
8 changes: 2 additions & 6 deletions packages/playwright-core/src/server/dispatchers/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { EventEmitter } from 'events';

import { eventsHelper } from '../utils/eventsHelper';
import { ValidationError, createMetadataValidator, findValidator } from '../../protocol/validator';
import { assert, monotonicTime, rewriteErrorMessage, debugLogger } from '../../utils';
import { assert, monotonicTime, rewriteErrorMessage } from '../../utils';
import { isUnderTest } from '../utils/debug';
import { TargetClosedError, isTargetClosedError, serializeError } from '../errors';
import { createRootSdkObject, SdkObject } from '../instrumentation';
Expand Down Expand Up @@ -101,11 +101,7 @@ export class Dispatcher<Type extends SdkObject, ChannelType, ParentScopeType ext
}

async _runCommand(callMetadata: CallMetadata, method: string, validParams: any) {
const controller = new ProgressController(callMetadata, message => {
const logName = this._object.logName || 'api';
debugLogger.log(logName, message);
this._object.instrumentation.onCallLog(this._object, callMetadata, logName, message);
});
const controller = ProgressController.createForSdkObject(this._object, callMetadata);
this._activeProgressControllers.add(controller);
try {
return await controller.run(progress => (this as any)[method](validParams, progress), validParams?.timeout);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ export class PageAgentDispatcher extends Dispatcher<SdkObject, channels.PageAgen
onBeforeTurn(params: { conversation: loopTypes.Conversation }) {
const userMessage = params.conversation.messages.find(m => m.role === 'user');
self._dispatchEvent('turn', { role: 'user', message: userMessage?.content ?? '' });
return 'continue' as const;
},

onAfterTurn(params: { assistantMessage: loopTypes.AssistantMessage, totalUsage: loopTypes.Usage }) {
Expand All @@ -81,23 +80,19 @@ export class PageAgentDispatcher extends Dispatcher<SdkObject, channels.PageAgen
if (!params.assistantMessage.content.filter(c => c.type === 'tool_call').length)
self._dispatchEvent('turn', { role: 'assistant', message: `no tool calls`, usage });
self._usage = { turns: self._usage.turns + 1, inputTokens: self._usage.inputTokens + usage.inputTokens, outputTokens: self._usage.outputTokens + usage.outputTokens };
return 'continue' as const;
},

onBeforeToolCall(params: { toolCall: loopTypes.ToolCallContentPart }) {
self._dispatchEvent('turn', { role: 'assistant', message: `call tool "${params.toolCall.name}"` });
return 'continue' as const;
},

onAfterToolCall(params: { toolCall: loopTypes.ToolCallContentPart, result: loopTypes.ToolResult }) {
const suffix = params.toolCall.result?.isError ? 'failed' : 'succeeded';
self._dispatchEvent('turn', { role: 'user', message: `tool "${params.toolCall.name}" ${suffix}` });
return 'continue' as const;
},

onToolCallError(params: { toolCall: loopTypes.ToolCallContentPart, error: Error }) {
self._dispatchEvent('turn', { role: 'user', message: `tool "${params.toolCall.name}" failed: ${params.error.message}` });
return 'continue' as const;
}
};
}
Expand Down
Loading
Loading