-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathactHandlerUtils.ts
More file actions
488 lines (446 loc) · 12.9 KB
/
Copy pathactHandlerUtils.ts
File metadata and controls
488 lines (446 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import { Page, Locator } from "patchright";
import { PlaywrightCommandException } from "../../../types/playwright";
import { StagehandPage } from "../../StagehandPage";
import { getNodeFromXpath } from "@/lib/dom/utils";
import { Logger } from "../../../types/log";
import { MethodHandlerContext } from "@/types/act";
import { StagehandClickError } from "@/types/stagehandErrors";
/**
* A mapping of playwright methods that may be chosen by the LLM to their
* implementation.
*/
export const methodHandlerMap: Record<
string,
(ctx: MethodHandlerContext) => Promise<void>
> = {
scrollIntoView: scrollElementIntoView,
scrollTo: scrollElementToPercentage,
scroll: scrollElementToPercentage,
"mouse.wheel": scrollElementToPercentage,
fill: fillOrType,
type: fillOrType,
press: pressKey,
click: clickElement,
nextChunk: scrollToNextChunk,
prevChunk: scrollToPreviousChunk,
};
export async function scrollToNextChunk(ctx: MethodHandlerContext) {
const { stagehandPage, xpath, logger } = ctx;
logger({
category: "action",
message: "scrolling to next chunk",
level: 2,
auxiliary: {
xpath: { value: xpath, type: "string" },
},
});
try {
await stagehandPage.page.evaluate(
({ xpath }) => {
const elementNode = getNodeFromXpath(xpath);
if (!elementNode || elementNode.nodeType !== Node.ELEMENT_NODE) {
console.warn(`Could not locate element to scroll by its height.`);
return Promise.resolve();
}
const element = elementNode as HTMLElement;
const tagName = element.tagName.toLowerCase();
let height: number;
if (tagName === "html" || tagName === "body") {
height = window.visualViewport.height;
window.scrollBy({
top: height,
left: 0,
behavior: "smooth",
});
const scrollingEl =
document.scrollingElement || document.documentElement;
return window.waitForElementScrollEnd(scrollingEl as HTMLElement);
} else {
height = element.getBoundingClientRect().height;
element.scrollBy({
top: height,
left: 0,
behavior: "smooth",
});
return window.waitForElementScrollEnd(element);
}
},
{ xpath },
);
} catch (e) {
logger({
category: "action",
message: "error scrolling to next chunk",
level: 1,
auxiliary: {
error: { value: e.message, type: "string" },
trace: { value: e.stack, type: "string" },
xpath: { value: xpath, type: "string" },
},
});
throw new PlaywrightCommandException(e.message);
}
}
export async function scrollToPreviousChunk(ctx: MethodHandlerContext) {
const { stagehandPage, xpath, logger } = ctx;
logger({
category: "action",
message: "scrolling to previous chunk",
level: 2,
auxiliary: {
xpath: { value: xpath, type: "string" },
},
});
try {
await stagehandPage.page.evaluate(
({ xpath }) => {
const elementNode = getNodeFromXpath(xpath);
if (!elementNode || elementNode.nodeType !== Node.ELEMENT_NODE) {
console.warn(`Could not locate element to scroll by its height.`);
return Promise.resolve();
}
const element = elementNode as HTMLElement;
const tagName = element.tagName.toLowerCase();
let height: number;
if (tagName === "html" || tagName === "body") {
height = window.visualViewport.height;
window.scrollBy({
top: -height,
left: 0,
behavior: "smooth",
});
const scrollingEl =
document.scrollingElement || document.documentElement;
return window.waitForElementScrollEnd(scrollingEl as HTMLElement);
} else {
height = element.getBoundingClientRect().height;
element.scrollBy({
top: -height,
left: 0,
behavior: "smooth",
});
return window.waitForElementScrollEnd(element);
}
},
{ xpath },
);
} catch (e) {
logger({
category: "action",
message: "error scrolling to previous chunk",
level: 1,
auxiliary: {
error: { value: e.message, type: "string" },
trace: { value: e.stack, type: "string" },
xpath: { value: xpath, type: "string" },
},
});
throw new PlaywrightCommandException(e.message);
}
}
export async function scrollElementIntoView(ctx: MethodHandlerContext) {
const { locator, xpath, logger } = ctx;
logger({
category: "action",
message: "scrolling element into view",
level: 2,
auxiliary: {
xpath: { value: xpath, type: "string" },
},
});
try {
await locator.evaluate((element: HTMLElement) => {
element.scrollIntoView({ behavior: "smooth", block: "center" });
});
} catch (e) {
logger({
category: "action",
message: "error scrolling element into view",
level: 1,
auxiliary: {
error: { value: e.message, type: "string" },
trace: { value: e.stack, type: "string" },
xpath: { value: xpath, type: "string" },
},
});
throw new PlaywrightCommandException(e.message);
}
}
export async function scrollElementToPercentage(ctx: MethodHandlerContext) {
const { args, stagehandPage, xpath, logger } = ctx;
logger({
category: "action",
message: "scrolling element vertically to specified percentage",
level: 2,
auxiliary: {
xpath: { value: xpath, type: "string" },
coordinate: { value: JSON.stringify(args), type: "string" },
},
});
try {
const [yArg = "0%"] = args as string[];
await stagehandPage.page.evaluate(
({ xpath, yArg }) => {
function parsePercent(val: string): number {
const cleaned = val.trim().replace("%", "");
const num = parseFloat(cleaned);
return Number.isNaN(num) ? 0 : Math.max(0, Math.min(num, 100));
}
const elementNode = getNodeFromXpath(xpath);
if (!elementNode || elementNode.nodeType !== Node.ELEMENT_NODE) {
console.warn(`Could not locate element to scroll on.`);
return;
}
const element = elementNode as HTMLElement;
const yPct = parsePercent(yArg);
if (element.tagName.toLowerCase() === "html") {
const scrollHeight = document.body.scrollHeight;
const viewportHeight = window.innerHeight;
const scrollTop = (scrollHeight - viewportHeight) * (yPct / 100);
window.scrollTo({
top: scrollTop,
left: window.scrollX,
behavior: "smooth",
});
} else {
const scrollHeight = element.scrollHeight;
const clientHeight = element.clientHeight;
const scrollTop = (scrollHeight - clientHeight) * (yPct / 100);
element.scrollTo({
top: scrollTop,
left: element.scrollLeft,
behavior: "smooth",
});
}
},
{ xpath, yArg },
);
} catch (e) {
logger({
category: "action",
message: "error scrolling element vertically to percentage",
level: 1,
auxiliary: {
error: { value: e.message, type: "string" },
trace: { value: e.stack, type: "string" },
xpath: { value: xpath, type: "string" },
args: { value: JSON.stringify(args), type: "object" },
},
});
throw new PlaywrightCommandException(e.message);
}
}
export async function fillOrType(ctx: MethodHandlerContext) {
const { locator, xpath, args, logger } = ctx;
try {
await locator.fill("", { force: true });
const text = args[0]?.toString() || "";
await locator.fill(text, { force: true });
} catch (e) {
logger({
category: "action",
message: "error filling element",
level: 1,
auxiliary: {
error: { value: e.message, type: "string" },
trace: { value: e.stack, type: "string" },
xpath: { value: xpath, type: "string" },
},
});
throw new PlaywrightCommandException(e.message);
}
}
export async function pressKey(ctx: MethodHandlerContext) {
const {
locator,
xpath,
args,
logger,
stagehandPage,
initialUrl,
domSettleTimeoutMs,
} = ctx;
try {
const key = args[0]?.toString() ?? "";
await locator.page().keyboard.press(key);
await handlePossiblePageNavigation(
"press",
xpath,
initialUrl,
stagehandPage,
logger,
domSettleTimeoutMs,
);
} catch (e) {
logger({
category: "action",
message: "error pressing key",
level: 1,
auxiliary: {
error: { value: e.message, type: "string" },
trace: { value: e.stack, type: "string" },
key: { value: args[0]?.toString() ?? "unknown", type: "string" },
},
});
throw new PlaywrightCommandException(e.message);
}
}
export async function clickElement(ctx: MethodHandlerContext) {
const {
locator,
xpath,
args,
logger,
stagehandPage,
initialUrl,
domSettleTimeoutMs,
} = ctx;
logger({
category: "action",
message: "page URL before click",
level: 2,
auxiliary: {
url: {
value: stagehandPage.page.url(),
type: "string",
},
},
});
try {
await locator.evaluate((el) => {
(el as HTMLElement).click();
});
} catch (e) {
logger({
category: "action",
message: "error performing click",
level: 1,
auxiliary: {
error: { value: e.message, type: "string" },
trace: { value: e.stack, type: "string" },
xpath: { value: xpath, type: "string" },
method: { value: "click", type: "string" },
args: { value: JSON.stringify(args), type: "object" },
},
});
throw new StagehandClickError(xpath, e.message);
}
await handlePossiblePageNavigation(
"click",
xpath,
initialUrl,
stagehandPage,
logger,
domSettleTimeoutMs,
);
}
/**
* Fallback method: if method is not in our map but *is* a valid Playwright locator method.
*/
export async function fallbackLocatorMethod(ctx: MethodHandlerContext) {
const { locator, xpath, method, args, logger } = ctx;
logger({
category: "action",
message: "page URL before action",
level: 2,
auxiliary: {
url: { value: locator.page().url(), type: "string" },
},
});
try {
await (
locator[method as keyof Locator] as unknown as (
...a: string[]
) => Promise<void>
)(...args.map((arg) => arg?.toString() || ""));
} catch (e) {
logger({
category: "action",
message: "error performing method",
level: 1,
auxiliary: {
error: { value: e.message, type: "string" },
trace: { value: e.stack, type: "string" },
xpath: { value: xpath, type: "string" },
method: { value: method, type: "string" },
args: { value: JSON.stringify(args), type: "object" },
},
});
throw new PlaywrightCommandException(e.message);
}
}
async function handlePossiblePageNavigation(
actionDescription: string,
xpath: string,
initialUrl: string,
stagehandPage: StagehandPage,
logger: Logger,
domSettleTimeoutMs?: number,
): Promise<void> {
logger({
category: "action",
message: `${actionDescription}, checking for page navigation`,
level: 1,
auxiliary: {
xpath: { value: xpath, type: "string" },
},
});
const newOpenedTab = await Promise.race([
new Promise<Page | null>((resolve) => {
stagehandPage.context.once("page", (page) => resolve(page));
setTimeout(() => resolve(null), 1500);
}),
]);
logger({
category: "action",
message: `${actionDescription} complete`,
level: 1,
auxiliary: {
newOpenedTab: {
value: newOpenedTab ? "opened a new tab" : "no new tabs opened",
type: "string",
},
},
});
if (newOpenedTab) {
logger({
category: "action",
message: "new page detected (new tab) with URL",
level: 1,
auxiliary: {
url: { value: newOpenedTab.url(), type: "string" },
},
});
await newOpenedTab.close();
await stagehandPage.page.goto(newOpenedTab.url());
await stagehandPage.page.waitForLoadState("domcontentloaded");
}
try {
await stagehandPage._waitForSettledDom(domSettleTimeoutMs);
} catch (e) {
logger({
category: "action",
message: "wait for settled DOM timeout hit",
level: 1,
auxiliary: {
trace: { value: e.stack, type: "string" },
message: { value: e.message, type: "string" },
},
});
}
logger({
category: "action",
message: "finished waiting for (possible) page navigation",
level: 1,
});
if (stagehandPage.page.url() !== initialUrl) {
logger({
category: "action",
message: "new page detected with URL",
level: 1,
auxiliary: {
url: { value: stagehandPage.page.url(), type: "string" },
},
});
}
}