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
15 changes: 7 additions & 8 deletions src/McpPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/

import {DisposableStack} from './third_party/index.js';

export function replaceHtmlElementsWithUids(schema: JSONSchema7Definition) {
if (typeof schema === 'boolean') {
return;
Expand Down Expand Up @@ -225,7 +227,7 @@ export class McpPage implements ContextPage {

async getToolGroups(): Promise<ToolGroups> {
// Check if there is a `devtoolstooldiscovery` event listener
const windowHandle = await this.pptrPage.evaluateHandle(() => window);
using windowHandle = await this.pptrPage.evaluateHandle(() => window);
// @ts-expect-error internal API
const client = this.pptrPage._client();
const {listeners}: {listeners: Protocol.DOMDebugger.EventListener[]} =
Expand Down Expand Up @@ -560,17 +562,14 @@ export class McpPage implements ContextPage {
}

if (elementHandles.length) {
const oldHandles = [...this.extraHandles];
using stack = new DisposableStack();
for (const handle of elementHandles) {
stack.use(handle);
}
this.textSnapshot = await TextSnapshot.create(this, {
extraHandles: elementHandles,
});
response.includeSnapshot();

for (const handle of oldHandles) {
await handle
.dispose()
.catch(e => logger?.('Failed to dispose old handle', e));
}
}

const cdpElementIds = await Promise.all(
Expand Down
7 changes: 4 additions & 3 deletions src/TextSnapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import {DisposableStack} from './third_party/index.js';
import type {McpPage} from './McpPage.js';
import type {
Protocol,
Expand Down Expand Up @@ -221,11 +222,13 @@ export class TextSnapshot {
handle: ElementHandle,
): Promise<TextSnapshotNode | null> => {
let ancestorHandle = await handle.evaluateHandle(el => el.parentElement);
using stack = new DisposableStack();

while (ancestorHandle) {
stack.use(ancestorHandle);

const ancestorElement = ancestorHandle.asElement();
if (!ancestorElement) {
await ancestorHandle.dispose();
return null;
}

Expand All @@ -235,15 +238,13 @@ export class TextSnapshot {
.values()
.find(node => node.backendNodeId === ancestorBackendId);
if (ancestorNode) {
await ancestorHandle.dispose();
return ancestorNode;
}
}

const nextHandle = await ancestorElement.evaluateHandle(
el => el.parentElement,
);
await ancestorHandle.dispose();
ancestorHandle = nextHandle;
}
return null;
Expand Down
5 changes: 2 additions & 3 deletions src/WaitForHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export class WaitForHelper {
// Bound the setup evaluation against the stable-DOM timeout. Without this
// cap a paused renderer (e.g. an open dialog) would make evaluateHandle
// hang until protocolTimeout (default 180s) while the tool mutex is held.
const stableDomObserver = await Promise.race([
using stableDomObserver = await Promise.race([
this.#page.evaluateHandle(timeout => {
let timeoutId: ReturnType<typeof setTimeout>;
function callback() {
Expand All @@ -71,7 +71,7 @@ export class WaitForHelper {

return domObserver;
}, this.#stableDomFor),
this.timeout(this.#stableDomTimeout),
this.timeout(this.#stableDomTimeout) as Promise<undefined>,
]).catch(() => undefined);

if (!stableDomObserver) {
Expand All @@ -84,7 +84,6 @@ export class WaitForHelper {
observer.observer.disconnect();
observer.resolver.resolve();
});
await stableDomObserver.dispose();
} catch {
// Ignored cleanup errors
}
Expand Down
4 changes: 4 additions & 0 deletions src/third_party/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ export type {CdpWebWorker} from 'puppeteer-core/internal/cdp/WebWorker.js';
export type {Realm} from 'puppeteer-core/internal/api/Realm.js';
export type {JSONSchema7, JSONSchema7Definition} from 'json-schema';
export {Mutex} from 'puppeteer-core/internal/util/Mutex.js';
export {
DisposableStack,
AsyncDisposableStack,
} from 'puppeteer-core/internal/util/disposable.js';
Comment thread
OrKoN marked this conversation as resolved.
Resolved
export {
resolveDefaultUserDataDir,
detectBrowserPlatform,
Expand Down
136 changes: 56 additions & 80 deletions src/tools/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function handleActionError(error: unknown, uid: string) {
}

async function selectNativeSelectOption(handle: ElementHandle<Element>) {
const selectHandle = await handle.evaluateHandle(node => {
using selectHandle = await handle.evaluateHandle(node => {
if (!(node instanceof HTMLOptionElement)) {
return null;
}
Expand All @@ -64,26 +64,21 @@ async function selectNativeSelectOption(handle: ElementHandle<Element>) {

return select;
});
try {
const select = selectHandle.asElement() as ElementHandle<Element> | null;
if (!select) {
return false;
}

const valueHandle = await handle.getProperty('value');
try {
const value = await valueHandle.jsonValue();
if (typeof value !== 'string') {
return false;
}
await select.asLocator().fill(value);
} finally {
void valueHandle.dispose();
}
return true;
} finally {
void selectHandle.dispose();
using select = selectHandle.asElement() as ElementHandle<Element> | null;
if (!select) {
return false;
}

using valueHandle = await handle.getProperty('value');

const value = await valueHandle.jsonValue();
if (typeof value !== 'string') {
return false;
}
await select.asLocator().fill(value);

return true;
}

export const click = definePageTool({
Expand All @@ -106,7 +101,7 @@ export const click = definePageTool({
verifyFilesSchema: [],
handler: async (request, response) => {
const uid = request.params.uid;
const handle = await request.page.getElementByUid(uid);
using handle = await request.page.getElementByUid(uid);
const aXNode = request.page.getAXNodeByUid(uid);
const shouldSelectNativeOption =
!request.params.dblClick && aXNode?.role === 'option';
Expand Down Expand Up @@ -134,8 +129,6 @@ export const click = definePageTool({
}
} catch (error) {
handleActionError(error, uid);
} finally {
void handle.dispose();
}
},
});
Expand Down Expand Up @@ -194,7 +187,7 @@ export const hover = definePageTool({
verifyFilesSchema: [],
handler: async (request, response) => {
const uid = request.params.uid;
const handle = await request.page.getElementByUid(uid);
using handle = await request.page.getElementByUid(uid);
try {
const result = await request.page.waitForEventsAfterAction(async () => {
await handle.asLocator().hover();
Expand All @@ -206,8 +199,6 @@ export const hover = definePageTool({
}
} catch (error) {
handleActionError(error, uid);
} finally {
void handle.dispose();
}
},
});
Expand All @@ -225,22 +216,16 @@ async function selectOption(
for (const child of aXNode.children) {
if (child.role === 'option' && child.name === value && child.value) {
optionFound = true;
const childHandle = await child.elementHandle();
using childHandle = await child.elementHandle();
if (childHandle) {
try {
const childValueHandle = await childHandle.getProperty('value');
try {
const childValue = await childValueHandle.jsonValue();
if (childValue) {
await handle.asLocator().fill(childValue.toString());
}
} finally {
void childValueHandle.dispose();
}
break;
} finally {
void childHandle.dispose();
using childValueHandle = await childHandle.getProperty('value');

const childValue = await childValueHandle.jsonValue();
if (childValue) {
await handle.asLocator().fill(childValue.toString());
}

break;
}
}
}
Expand All @@ -259,7 +244,7 @@ async function fillFormElement(
context: McpContext,
page: ContextPage,
) {
const handle = await page.getElementByUid(uid);
using handle = await page.getElementByUid(uid);
try {
const aXNode = page.getAXNodeByUid(uid);
// We assume that combobox needs to be handled as select if it has
Expand Down Expand Up @@ -293,8 +278,6 @@ async function fillFormElement(
}
} catch (error) {
handleActionError(error, uid);
} finally {
void handle.dispose();
}
}

Expand Down Expand Up @@ -383,24 +366,20 @@ export const drag = definePageTool({
blockedByDialog: true,
verifyFilesSchema: [],
handler: async (request, response) => {
const fromHandle = await request.page.getElementByUid(
using fromHandle = await request.page.getElementByUid(
request.params.from_uid,
);
const toHandle = await request.page.getElementByUid(request.params.to_uid);
try {
const result = await request.page.waitForEventsAfterAction(async () => {
await fromHandle.drag(toHandle);
await new Promise(resolve => setTimeout(resolve, 50));
await toHandle.drop(fromHandle);
});
response.appendResponseLine(`Successfully dragged an element`);
response.attachWaitForResult(result);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
} finally {
void fromHandle.dispose();
void toHandle.dispose();
using toHandle = await request.page.getElementByUid(request.params.to_uid);

const result = await request.page.waitForEventsAfterAction(async () => {
await fromHandle.drag(toHandle);
await new Promise(resolve => setTimeout(resolve, 50));
await toHandle.drop(fromHandle);
});
response.appendResponseLine(`Successfully dragged an element`);
response.attachWaitForResult(result);
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
},
});
Expand Down Expand Up @@ -471,35 +450,32 @@ export const uploadFile = definePageTool({
verifyFilesSchema: ['filePath'],
handler: async (request, response) => {
const {uid, filePath} = request.params;
const handle = (await request.page.getElementByUid(
using handle = (await request.page.getElementByUid(
uid,
)) as ElementHandle<HTMLInputElement>;

try {
await handle.uploadFile(filePath);
} catch {
// Some sites use a proxy element to trigger file upload instead of
// a type=file element. In this case, we want to default to
// Page.waitForFileChooser() and upload the file this way.
try {
await handle.uploadFile(filePath);
const [fileChooser] = await Promise.all([
request.page.pptrPage.waitForFileChooser({timeout: 3000}),
handle.asLocator().click(),
]);
await fileChooser.accept([filePath]);
} catch {
// Some sites use a proxy element to trigger file upload instead of
// a type=file element. In this case, we want to default to
// Page.waitForFileChooser() and upload the file this way.
try {
const [fileChooser] = await Promise.all([
request.page.pptrPage.waitForFileChooser({timeout: 3000}),
handle.asLocator().click(),
]);
await fileChooser.accept([filePath]);
} catch {
throw new Error(
`Failed to upload file. The element could not accept the file directly, and clicking it did not trigger a file chooser.`,
);
}
}
if (request.params.includeSnapshot) {
response.includeSnapshot();
throw new Error(
`Failed to upload file. The element could not accept the file directly, and clicking it did not trigger a file chooser.`,
);
}
response.appendResponseLine(`File uploaded from ${filePath}.`);
} finally {
void handle.dispose();
}
if (request.params.includeSnapshot) {
response.includeSnapshot();
}
response.appendResponseLine(`File uploaded from ${filePath}.`);
},
});

Expand Down
Loading