Skip to content

Commit d6599aa

Browse files
bryanchen-dCopilot
andcommitted
Browser tools: report a dialog that an input action opens after the action resolved
A click can resolve before the page runs its handlers, for example before an onclick calls alert(). The tool then reported the click without the dialog, and the agent's next action failed because a dialog was open. After an action run for a tool, wait for one evaluation per frame, capped at 1 s, while still racing the dialog opening, so a dialog the input opened is reported with the action. Evaluations wait for pending dialogs, so the dialog wins that race. Fixes #350285 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 1f8d8b2 commit d6599aa

3 files changed

Lines changed: 111 additions & 2 deletions

File tree

‎src/vs/platform/browserView/node/playwrightService.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ class PlaywrightSession extends Disposable {
495495
if (!tab) {
496496
throw new Error('Failed to execute function against page');
497497
}
498-
return tab.safeRunAgainstPage(async () => callback(page));
498+
return tab.safeRunAgainstPage(async () => callback(page), { reportTriggeredDialogs: true });
499499
}
500500

501501
private async _runWithDeferral(pageId: string, callback: (page: Page) => Promise<unknown>, timeoutMs: number, existingDeferredId?: string, logCtx?: IExecutionLogContext): Promise<IInvokeFunctionResult> {

‎src/vs/platform/browserView/node/playwrightTab.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ import { IPlaywrightActionScope } from './playwrightService.js';
1414

1515
type IAiAriaSnapshotOptions = NonNullable<Parameters<playwright.Locator['ariaSnapshot']>[0]> & { _track?: string };
1616

17+
/** How long an action waits at most for the frames to process its input, see `waitForTriggeredDialogs`. */
18+
const triggeredDialogWaitMs = 1000;
19+
1720
declare module 'playwright-core' {
1821
interface Page {
1922
// We defined this here to be able to use the unofficial `_track` option
@@ -159,8 +162,11 @@ export class PlaywrightTab {
159162
*
160163
* Also allows for interactions to be handled differently when triggered by agents.
161164
* E.g. file dialogs should appear when the user triggers one, but not when the agent does.
165+
*
166+
* With `reportTriggeredDialogs`, a dialog that the action's input opens is reported even when the action
167+
* itself resolves first, see {@link waitForTriggeredDialogs}.
162168
*/
163-
async safeRunAgainstPage<T>(action: (page: playwright.Page, token: CancellationToken) => Promise<T>): Promise<T> {
169+
async safeRunAgainstPage<T>(action: (page: playwright.Page, token: CancellationToken) => Promise<T>, options?: { readonly reportTriggeredDialogs?: boolean }): Promise<T> {
164170
if (this._dialog) {
165171
throw new Error(`Cannot perform action while a dialog is open`);
166172
}
@@ -186,6 +192,9 @@ export class PlaywrightTab {
186192
try {
187193
this.actionScope.activeCalls++;
188194
result = await this.runAndWaitForCompletion((token) => action(this.page, token), token);
195+
if (options?.reportTriggeredDialogs) {
196+
await this.waitForTriggeredDialogs(token);
197+
}
189198
actionDidComplete = true;
190199
} finally {
191200
this.page.off('filechooser', handleFileChooser);
@@ -249,6 +258,31 @@ export class PlaywrightTab {
249258
return page.ariaSnapshot(options);
250259
}
251260

261+
/**
262+
* Waits until every frame has processed the input that an action sent, so that a dialog the input opened
263+
* is reported with the action rather than after it.
264+
*
265+
* An action can resolve before the page runs its input's handlers, for example before a click's `onclick`
266+
* calls `alert()`. A dialog then only opens once the action has already been reported as complete. One
267+
* evaluation per frame runs after that input. While a dialog is open or pending, evaluations wait for it
268+
* (the dialog barrier in the browser view debugger), so the caller's race against the dialog opening sees
269+
* it first. Actions that open no dialog pay one parallel round trip per frame. The wait is capped, so a
270+
* frame that never answers doesn't hold the action.
271+
*/
272+
private async waitForTriggeredDialogs(token: CancellationToken): Promise<void> {
273+
const frames = Promise.all(this.page.frames().map(frame => frame.evaluate(() => undefined).catch(() => undefined)));
274+
const deadline = timeout(triggeredDialogWaitMs);
275+
// A dialog that opens wins the caller's race and cancels the action, which ends this wait too.
276+
const cancellation = token.onCancellationRequested(() => deadline.cancel());
277+
try {
278+
await raceCancellablePromises<unknown>([frames, deadline]);
279+
} catch {
280+
// Cancelled
281+
} finally {
282+
cancellation.dispose();
283+
}
284+
}
285+
252286
private async runAndWaitForCompletion<T>(callback: (token: CancellationToken) => Promise<T>, token = CancellationToken.None): Promise<T> {
253287
const requests: playwright.Request[] = [];
254288

‎src/vs/platform/browserView/test/node/playwrightTab.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,4 +90,79 @@ suite('PlaywrightTab', () => {
9090
summary: networkFilterService.formatError(URI.parse(url)),
9191
})));
9292
});
93+
94+
test('reports a dialog that an action opens after the action itself resolved', async () => {
95+
const configService = new TestConfigurationService();
96+
configService.setUserConfiguration(AgentNetworkDomainSettingId.NetworkFilter, false);
97+
const networkFilterService = disposables.add(new AgentNetworkFilterService(configService));
98+
// Like a click whose `onclick` calls `alert()` only once the page processes the input: the dialog opens
99+
// when the frame is next asked to evaluate, after the action has resolved.
100+
const page = new DialogPage('http://127.0.0.1:3000/');
101+
const tab = new PlaywrightTab(page, { activeCalls: 0 }, networkFilterService);
102+
103+
const withoutWait = await tab.safeRunAgainstPage(async () => 'clicked');
104+
const withWait = await tab.safeRunAgainstPage(async () => 'clicked', { reportTriggeredDialogs: true }).catch(error => error.name);
105+
106+
assert.deepStrictEqual({
107+
withoutWait,
108+
withWait,
109+
dialogReported: (await tab.getSummary()).includes('Active alert dialog: "Alert"'),
110+
}, {
111+
withoutWait: 'clicked',
112+
withWait: 'DialogInterruptedError',
113+
dialogReported: true,
114+
});
115+
});
116+
117+
test('an action that opens no dialog waits for one evaluation per frame', async () => {
118+
const configService = new TestConfigurationService();
119+
configService.setUserConfiguration(AgentNetworkDomainSettingId.NetworkFilter, false);
120+
const networkFilterService = disposables.add(new AgentNetworkFilterService(configService));
121+
const page = new DialogPage('http://127.0.0.1:3000/', false);
122+
const tab = new PlaywrightTab(page, { activeCalls: 0 }, networkFilterService);
123+
124+
const result = await tab.safeRunAgainstPage(async () => 'clicked', { reportTriggeredDialogs: true });
125+
126+
assert.deepStrictEqual({ result, evaluations: page.evaluations, summary: (await tab.getSummary()).includes('Active ') }, {
127+
result: 'clicked',
128+
evaluations: 2,
129+
summary: false,
130+
});
131+
});
93132
});
133+
134+
/** A page with two frames whose first evaluation opens an alert, if `opensDialog`. */
135+
class DialogPage extends TestPage {
136+
private dialogListener: ((dialog: never) => void) | undefined;
137+
evaluations = 0;
138+
139+
constructor(url: string, private opensDialog = true) {
140+
super(url);
141+
}
142+
143+
override on(event?: string, listener?: (dialog: never) => void): this {
144+
if (event === 'dialog') {
145+
this.dialogListener = listener;
146+
}
147+
return this;
148+
}
149+
150+
override waitForFunction() {
151+
return new Promise<never>(() => { });
152+
}
153+
154+
override frames() {
155+
const frame = {
156+
evaluate: async () => {
157+
this.evaluations++;
158+
if (this.opensDialog) {
159+
this.opensDialog = false;
160+
this.dialogListener?.({ type: () => 'alert', message: () => 'Alert' } as never);
161+
return new Promise<never>(() => { });
162+
}
163+
return undefined;
164+
},
165+
};
166+
return [frame, frame] as unknown as ReturnType<PlaywrightPage['frames']>;
167+
}
168+
}

0 commit comments

Comments
 (0)