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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,7 @@ Returns credential-redacted request/response headers and body metadata for one r
#### `browser_wait_for`
Wait for text to appear/disappear or time to pass.
- Parameters: `time` (optional), `text` (optional), `textGone` (optional)
- `time` is in seconds and capped at 30. Generated code uses the capped delay; time-only results report seconds and disclose when the requested delay exceeded the cap.

#### `browser_handle_dialog`
Handle browser dialogs (alerts, confirms, prompts).
Expand Down
18 changes: 13 additions & 5 deletions src/tools/wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import { z } from 'zod';
import { defineTool } from './tool.js';

const maxWaitSeconds = 30;

const wait = defineTool({
capability: 'core',

Expand All @@ -25,7 +27,7 @@ const wait = defineTool({
title: 'Wait for',
description: 'Wait for text to appear or disappear or a specified time to pass',
inputSchema: z.object({
time: z.number().optional().describe('The time to wait in seconds'),
time: z.number().optional().describe(`The time to wait in seconds, at most ${maxWaitSeconds}`),
text: z.string().optional().describe('The text to wait for'),
textGone: z.string().optional().describe('The text to wait for to disappear'),
}),
Expand All @@ -36,9 +38,10 @@ const wait = defineTool({
if (!params.text && !params.textGone && !params.time)
throw new Error('Either time, text or textGone must be provided');

if (params.time) {
response.addCode(`await new Promise(f => setTimeout(f, ${params.time!} * 1000));`);
await new Promise(f => setTimeout(f, Math.min(30000, params.time! * 1000)));
const time = params.time ? Math.min(maxWaitSeconds, params.time) : undefined;
if (time) {
response.addCode(`await new Promise(f => setTimeout(f, ${time} * 1000));`);
await new Promise(f => setTimeout(f, time * 1000));
}

const tab = context.currentTabOrDie();
Expand All @@ -55,7 +58,12 @@ const wait = defineTool({
await locator.waitFor({ state: 'visible' });
}

response.addResult(`Waited for ${params.text || params.textGone || params.time}`);
if (params.text || params.textGone)
response.addResult(`Waited for ${params.text || params.textGone}`);
else if (time !== params.time)
response.addResult(`Waited for ${time} seconds (requested ${params.time}, maximum is ${maxWaitSeconds})`);
else
response.addResult(`Waited for ${time} seconds`);
response.setIncludeSnapshot();
},
});
Expand Down
71 changes: 71 additions & 0 deletions tests/tools-wait.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* 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.
*/

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import waitTools from '../src/tools/wait.js';
import { Response } from '../src/response.js';
import type { Context } from '../src/context.js';

describe('browser_wait_for', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());

function setup() {
const waitFor = vi.fn().mockResolvedValue(undefined);
const getByText = vi.fn(() => ({ first: () => ({ waitFor }) }));
// SAFETY: the handler and Response only read this page stub and snapshot config.
const context = { config: { snapshot: {} }, currentTabOrDie: () => ({ page: { getByText } }) } as Context;
return { context, waitFor, response: new Response(context, 'browser_wait_for', {}) };
}

it.each([
[0.5, 0.5],
[30, 30],
[31, 30],
[70, 30],
])('reports and replays the actual delay for %s seconds', async (requested, actual) => {
const { context, response } = setup();
const done = vi.fn();
const pending = waitTools[0].handle(context, { time: requested }, response).then(done);
await vi.advanceTimersByTimeAsync(actual * 1000 - 1);
expect(done).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
await pending;
expect(response.code()).toBe(`await new Promise(f => setTimeout(f, ${actual} * 1000));`);
expect(response.result()).toBe(requested === actual
? `Waited for ${actual} seconds`
: `Waited for ${actual} seconds (requested ${requested}, maximum is 30)`);
});

it.each([undefined, 0, 70])('preserves text waits with time %s', async time => {
const { context, response, waitFor } = setup();
const pending = waitTools[0].handle(context, { time, text: 'Ready', textGone: 'Loading' }, response);
await vi.runAllTimersAsync();
await pending;
expect(waitFor.mock.calls).toEqual([[{ state: 'hidden' }], [{ state: 'visible' }]]);
expect(response.result()).toBe('Waited for Ready');
if (time)
expect(response.code()).toContain('setTimeout(f, 30 * 1000)');
else
expect(response.code()).not.toContain('setTimeout');
});

it.each([{}, { time: 0 }])('preserves missing-condition errors for %j', async params => {
const { context, response } = setup();
await expect(waitTools[0].handle(context, params, response)).rejects.toThrow('Either time, text or textGone must be provided');
expect(vi.getTimerCount()).toBe(0);
});
});
Loading