Skip to content

Commit f7dd003

Browse files
authored
fix: improve error reporting when retrieving the element (#845)
Closes #839 Closes #840
1 parent 569894d commit f7dd003

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

src/McpContext.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -450,13 +450,20 @@ export class McpContext implements Context {
450450
}
451451
const node = this.#textSnapshot?.idToNode.get(uid);
452452
if (!node) {
453-
throw new Error('No such element found in the snapshot');
453+
throw new Error('No such element found in the snapshot.');
454454
}
455-
const handle = await node.elementHandle();
456-
if (!handle) {
457-
throw new Error('No such element found in the snapshot');
455+
const message = `Element with uid ${uid} no longer exists on the page.`;
456+
try {
457+
const handle = await node.elementHandle();
458+
if (!handle) {
459+
throw new Error(message);
460+
}
461+
return handle;
462+
} catch (error) {
463+
throw new Error(message, {
464+
cause: error,
465+
});
458466
}
459-
return handle;
460467
}
461468

462469
/**

src/tools/input.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* SPDX-License-Identifier: Apache-2.0
55
*/
66

7+
import {logger} from '../logger.js';
78
import type {McpContext, TextSnapshotNode} from '../McpContext.js';
89
import {zod} from '../third_party/index.js';
910
import type {ElementHandle} from '../third_party/index.js';
@@ -22,6 +23,16 @@ const includeSnapshotSchema = zod
2223
.optional()
2324
.describe('Whether to include a snapshot in the response. Default is false.');
2425

26+
function handleActionError(error: unknown, uid: string) {
27+
logger('failed to act using a locator', error);
28+
throw new Error(
29+
`Failed to interact with the element with uid ${uid}. The element did not become interactive within the configured timeout.`,
30+
{
31+
cause: error,
32+
},
33+
);
34+
}
35+
2536
export const click = defineTool({
2637
name: 'click',
2738
description: `Clicks on the provided element`,
@@ -55,6 +66,8 @@ export const click = defineTool({
5566
if (request.params.includeSnapshot) {
5667
response.includeSnapshot();
5768
}
69+
} catch (error) {
70+
handleActionError(error, uid);
5871
} finally {
5972
void handle.dispose();
6073
}
@@ -119,6 +132,8 @@ export const hover = defineTool({
119132
if (request.params.includeSnapshot) {
120133
response.includeSnapshot();
121134
}
135+
} catch (error) {
136+
handleActionError(error, uid);
122137
} finally {
123138
void handle.dispose();
124139
}
@@ -180,6 +195,8 @@ async function fillFormElement(
180195
value.length * timeoutPerChar;
181196
await handle.asLocator().setTimeout(fillTimeout).fill(value);
182197
}
198+
} catch (error) {
199+
handleActionError(error, uid);
183200
} finally {
184201
void handle.dispose();
185202
}

0 commit comments

Comments
 (0)