Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(mcp): allow combining time, text and textGone in browser_wait_for (#43011)

Dmitry Gozmanc0ecb0bb347d
diff --git a/packages/playwright-core/src/tools/backend/wait.ts b/packages/playwright-core/src/tools/backend/wait.ts
index 95ba71d1be..fc87a46483 100644
--- a/packages/playwright-core/src/tools/backend/wait.ts
+++ b/packages/playwright-core/src/tools/backend/wait.ts
@@ -25,9 +25,9 @@ const wait = defineTool({
schema: {
name: 'browser_wait_for',
title: 'Wait for',
- description: 'Wait for text to appear or disappear or a specified time to pass',
+ description: 'Wait for text to appear or disappear or a specified time to pass. When both text and textGone are provided, waits for the first one to happen',
inputSchema: z.object({
- time: z.number().optional().describe(`The time to wait in seconds, at most ${maxWaitSeconds}`),
+ time: z.number().optional().describe(`The time to wait in seconds, at most ${maxWaitSeconds}. When combined with text or textGone, serves as a timeout for them instead of the default action timeout`),
text: z.string().optional().describe('The text to wait for'),
textGone: z.string().optional().describe('The text to wait for to disappear'),
}),
@@ -38,32 +38,36 @@ const wait = defineTool({
if (!params.text && !params.textGone && !params.time)
throw new Error('Either time, text or textGone must be provided');
+ const tab = context.currentTabOrDie();
const time = params.time ? Math.min(maxWaitSeconds, params.time) : undefined;
- if (time) {
+
+ if (params.text || params.textGone) {
+ const timeoutOptions = time ? { timeout: time * 1000 } : tab.actionTimeoutOptions;
+ const waitForText = async (text: string, state: 'visible' | 'hidden') => {
+ await tab.page.getByText(text).first().waitFor({ state, ...timeoutOptions });
+ return {
+ code: `await page.getByText(${JSON.stringify(text)}).first().waitFor({ state: '${state}' });`,
+ result: `Waited for ${text}`,
+ };
+ };
+ const waits = [
+ params.text ? waitForText(params.text, 'visible') : undefined,
+ params.textGone ? waitForText(params.textGone, 'hidden') : undefined,
+ ].filter(wait => !!wait);
+ // The wait that lost the race will eventually fail, do not report it.
+ for (const wait of waits)
+ wait.catch(() => {});
+ const outcome = await Promise.race(waits);
+ response.addCode(outcome.code);
+ response.addTextResult(outcome.result);
+ } else if (time) {
response.addCode(`await new Promise(f => setTimeout(f, ${time} * 1000));`);
await new Promise(f => setTimeout(f, time * 1000));
+ if (time !== params.time)
+ response.addTextResult(`Waited for ${time} seconds (requested ${params.time}, maximum is ${maxWaitSeconds})`);
+ else
+ response.addTextResult(`Waited for ${time} seconds`);
}
-
- const tab = context.currentTabOrDie();
- const locator = params.text ? tab.page.getByText(params.text).first() : undefined;
- const goneLocator = params.textGone ? tab.page.getByText(params.textGone).first() : undefined;
-
- if (goneLocator) {
- response.addCode(`await page.getByText(${JSON.stringify(params.textGone)}).first().waitFor({ state: 'hidden' });`);
- await goneLocator.waitFor({ state: 'hidden', ...tab.actionTimeoutOptions });
- }
-
- if (locator) {
- response.addCode(`await page.getByText(${JSON.stringify(params.text)}).first().waitFor({ state: 'visible' });`);
- await locator.waitFor({ state: 'visible', ...tab.actionTimeoutOptions });
- }
-
- if (params.text || params.textGone)
- response.addTextResult(`Waited for ${params.text || params.textGone}`);
- else if (time !== params.time)
- response.addTextResult(`Waited for ${time} seconds (requested ${params.time}, maximum is ${maxWaitSeconds})`);
- else
- response.addTextResult(`Waited for ${time} seconds`);
response.setIncludeSnapshot();
},
});
diff --git a/tests/mcp/wait.spec.ts b/tests/mcp/wait.spec.ts
index a179486807..8eb7144e9f 100644
--- a/tests/mcp/wait.spec.ts
+++ b/tests/mcp/wait.spec.ts
@@ -134,3 +134,69 @@ test('browser_wait_for(time) reports capped time', async ({ client, server }) =>
code: `await new Promise(f => setTimeout(f, 30 * 1000));`,
});
});
+
+test('browser_wait_for(time, text) uses time as a timeout', async ({ startClient, server }) => {
+ const { client } = await startClient({ args: [`--timeout-action=500`] });
+ server.setContent('/', `
+ <body>
+ <div>Loading</div>
+ <script>
+ setTimeout(() => document.querySelector('div').textContent = 'Text to appear', 2000);
+ </script>
+ </body>
+ `, 'text/html');
+
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.PREFIX },
+ });
+
+ expect(await client.callTool({
+ name: 'browser_wait_for',
+ arguments: { text: 'Text to appear', time: 20 },
+ })).toHaveResponse({
+ result: `Waited for Text to appear`,
+ code: `await page.getByText("Text to appear").first().waitFor({ state: 'visible' });`,
+ });
+});
+
+test('browser_wait_for(time, text) fails when time passes', async ({ client, server }) => {
+ server.setContent('/', `<body><div>Hello World</div></body>`, 'text/html');
+
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.PREFIX },
+ });
+
+ expect(await client.callTool({
+ name: 'browser_wait_for',
+ arguments: { text: 'This text will never appear', time: 1 },
+ })).toHaveResponse({
+ error: expect.stringContaining(`Timeout 1000ms exceeded.`),
+ isError: true,
+ });
+});
+
+test('browser_wait_for(text, textGone) waits for the first one', async ({ client, server }) => {
+ server.setContent('/', `
+ <body>
+ <div>Text to disappear</div>
+ <script>
+ setTimeout(() => document.querySelector('div').textContent = 'Something else', 1000);
+ </script>
+ </body>
+ `, 'text/html');
+
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.PREFIX },
+ });
+
+ expect(await client.callTool({
+ name: 'browser_wait_for',
+ arguments: { text: 'This text will never appear', textGone: 'Text to disappear' },
+ })).toHaveResponse({
+ result: `Waited for Text to disappear`,
+ code: `await page.getByText("Text to disappear").first().waitFor({ state: 'hidden' });`,
+ });
+});