Chrome DevTools for coding agents
fix(wait_for): find text in dynamically attached iframes (#3210)
Robert McConnell5f8488840191
diff --git a/src/McpPage.ts b/src/McpPage.tsindex eea0e4fd..573e8b4a 100644--- a/src/McpPage.ts+++ b/src/McpPage.ts@@ -22,6 +22,7 @@ import {PredefinedNetworkConditions,type Dialog,type ElementHandle,+ type Frame,type Viewport,type WebMCPTool,type Protocol,@@ -1358,27 +1359,74 @@ export class McpPage implements ContextPage {options: {timeout?: number; visible?: boolean} = {},): Promise<Element> {const {timeout, visible} = options;- const frames = this.pptrPage.frames();-- let locator = this.#locatorClass.race(- frames.flatMap(frame =>- text.flatMap(value => {- const locators = [- frame.locator(`aria/${value}`),- frame.locator(`text/${value}`),- ];- return visible- ? locators.map(locator => locator.setVisibility('visible'))- : locators;- }),- ),- );+ const page = this.pptrPage;+ const initialFrames = page.frames();+ const observedFrames = new Set(initialFrames);+ const controller = new AbortController();++ const locatorForFrames = (frames: Frame[]): Locator<Element> =>+ this.#locatorClass.race(+ frames.flatMap(frame =>+ text.flatMap(value => {+ const locators = [+ frame.locator(`aria/${value}`),+ frame.locator(`text/${value}`),+ ];+ return visible+ ? locators.map(locator => locator.setVisibility('visible'))+ : locators;+ }),+ ),+ );+ let initialLocator = locatorForFrames(initialFrames);if (timeout) {- locator = locator.setTimeout(timeout);+ initialLocator = initialLocator.setTimeout(timeout);}- return locator.wait();+ return new Promise<Element>((resolve, reject) => {+ let settled = false;+ const cleanup = (): boolean => {+ if (settled) {+ return false;+ }+ settled = true;+ page.off('frameattached', onFrameAttached);+ controller.abort();+ return true;+ };+ const finish = (element: Element): void => {+ if (cleanup()) {+ resolve(element);+ }+ };+ const fail = (error: unknown): void => {+ if (cleanup()) {+ reject(error);+ }+ };+ const onFrameAttached = (frame: Frame): void => {+ if (observedFrames.has(frame)) {+ return;+ }+ observedFrames.add(frame);+ // The initial locator race does not include frames added later.+ // Watch each new frame until the initial race resolves or times out.+ // A timeout of 0 disables the frame timer; controller.abort() stops it.+ void locatorForFrames([frame])+ .setTimeout(0)+ .wait({signal: controller.signal})+ .then(finish, error => {+ if (controller.signal.aborted) {+ return;+ }+ logger?.('Failed to wait for text in an attached frame', error);+ });+ };++ page.on('frameattached', onFrameAttached);+ void initialLocator.wait({signal: controller.signal}).then(finish, fail);+ });}/**diff --git a/src/third_party/index.ts b/src/third_party/index.tsindex 40d95f69..6dee7b17 100644--- a/src/third_party/index.ts+++ b/src/third_party/index.ts@@ -53,6 +53,7 @@ export {ConsoleMessage,Dialog,ElementHandle,+ Frame,Locator,PredefinedNetworkConditions,KnownDevices,diff --git a/tests/McpPage.test.ts b/tests/McpPage.test.tsindex b546077c..2d38bb52 100644--- a/tests/McpPage.test.ts+++ b/tests/McpPage.test.ts@@ -12,7 +12,12 @@ import sinon from 'sinon';import type {ReadonlyServerConfig} from '../src/config/ServerConfig.js';import type {TargetUniverse} from '../src/devtools/DevtoolsUtils.js';import {McpPage, replaceHtmlElementsWithUids} from '../src/McpPage.js';-import {DevTools, Locator, ScreenRecorder} from '../src/third_party/index.js';+import {+ DevTools,+ Frame,+ Locator,+ ScreenRecorder,+} from '../src/third_party/index.js';import type {JSONSchema7Definition} from '../src/third_party/index.js';import {TextSnapshot} from '../src/TextSnapshot.js';import type {TextSnapshotNode} from '../src/types.js';@@ -1220,6 +1225,86 @@ describe('McpPage', () => {);});});++ it('finds text in an iframe attached while waiting', async () => {+ await withMcpContext(async (_response, context) => {+ const mcpPage = context.getSelectedMcpPage();+ const page = mcpPage.pptrPage;+ await page.setContent('<main>Waiting for the frame</main>');++ const listenersBefore = page.listenerCount('frameattached');+ const waitPromise = mcpPage.waitForTextOnPage(+ ['Arrived in a late iframe'],+ {timeout: 1500},+ );+ await page.evaluate(() => {+ const frame = document.createElement('iframe');+ frame.srcdoc = '<p>Arrived in a late iframe</p>';+ document.body.appendChild(frame);+ });++ const element = await waitPromise;+ assert.ok(element);+ assert.strictEqual(+ page.listenerCount('frameattached'),+ listenersBefore,+ );+ });+ });++ it('cleans the frame listener after a timed out wait', async () => {+ await withMcpContext(async (_response, context) => {+ const mcpPage = context.getSelectedMcpPage();+ const page = mcpPage.pptrPage;+ await page.setContent('<main>No matching text</main>');++ const listenersBefore = page.listenerCount('frameattached');+ await assert.rejects(+ mcpPage.waitForTextOnPage(['Text that never appears'], {+ timeout: 250,+ }),+ );+ assert.strictEqual(+ page.listenerCount('frameattached'),+ listenersBefore,+ );+ });+ });++ it('applies visible matching to frames attached while waiting', async () => {+ const {mcpPage, pptrPage} = await createMcpPage();+ pptrPage.frames.returns([]);+ const initialRace = Locator.race([]);+ sinon.stub(initialRace, 'wait').returns(new Promise(() => {}));+ const lateRace = Locator.race([]);+ const lateRaceSetTimeout = sinon+ .stub(lateRace, 'setTimeout')+ .returns(lateRace);+ sinon.stub(lateRace, 'wait').resolves();+ const race = sinon.stub(Locator, 'race');+ race.onFirstCall().returns(initialRace);+ race.onSecondCall().returns(lateRace);+ const frameLocator = sinon.createStubInstance<Locator<Element>>(Locator);+ frameLocator.setVisibility.returns(frameLocator);+ const lateFrame = sinon.createStubInstance(Frame);+ lateFrame.locator.returns(frameLocator);++ const waitPromise = mcpPage.waitForTextOnPage(['Saved'], {visible: true});+ pptrPage.emit('frameattached', lateFrame);+ await waitPromise;++ sinon.assert.calledWithExactly(lateFrame.locator.firstCall, 'aria/Saved');+ sinon.assert.calledWithExactly(+ lateFrame.locator.secondCall,+ 'text/Saved',+ );+ sinon.assert.calledTwice(frameLocator.setVisibility);+ sinon.assert.alwaysCalledWithExactly(+ frameLocator.setVisibility,+ 'visible',+ );+ sinon.assert.calledOnceWithExactly(lateRaceSetTimeout, 0);+ });});describe('DevToolsCommentBridge lifecycle', () => {