-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathactions.ts
More file actions
2846 lines (2542 loc) · 86.3 KB
/
actions.ts
File metadata and controls
2846 lines (2542 loc) · 86.3 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as fs from 'fs';
import * as path from 'path';
import type { Page, Frame } from 'playwright-core';
import { mkdirSync } from 'node:fs';
import type { BrowserManager, ScreencastFrame } from './browser.js';
import { getAppDir } from './daemon.js';
import {
type ActionPolicy,
checkPolicy,
describeAction,
getActionCategory,
loadPolicyFile,
initPolicyReloader,
reloadPolicyIfChanged,
} from './action-policy.js';
import { requestConfirmation, getAndRemovePending } from './confirmation.js';
import { getAuthProfile, updateLastLogin } from './auth-vault.js';
import {
getSessionsDir,
readStateFile,
isValidSessionName,
isEncryptedPayload,
listStateFiles,
cleanupExpiredStates,
} from './state-utils.js';
import type {
Command,
Response,
NavigateCommand,
ClickCommand,
TypeCommand,
FillCommand,
CheckCommand,
UncheckCommand,
UploadCommand,
DoubleClickCommand,
FocusCommand,
DragCommand,
FrameCommand,
GetByRoleCommand,
GetByTextCommand,
GetByLabelCommand,
GetByPlaceholderCommand,
PressCommand,
ScreenshotCommand,
EvaluateCommand,
WaitCommand,
ScrollCommand,
SelectCommand,
HoverCommand,
ContentCommand,
TabNewCommand,
TabSwitchCommand,
TabCloseCommand,
WindowNewCommand,
CookiesSetCommand,
StorageGetCommand,
StorageSetCommand,
StorageClearCommand,
DialogCommand,
PdfCommand,
RouteCommand,
RequestsCommand,
DownloadCommand,
GeolocationCommand,
PermissionsCommand,
ViewportCommand,
DeviceCommand,
GetAttributeCommand,
GetTextCommand,
IsVisibleCommand,
IsEnabledCommand,
IsCheckedCommand,
CountCommand,
BoundingBoxCommand,
StylesCommand,
TraceStartCommand,
TraceStopCommand,
ProfilerStartCommand,
ProfilerStopCommand,
HarStopCommand,
StorageStateSaveCommand,
StateListCommand,
StateClearCommand,
StateShowCommand,
StateCleanCommand,
StateRenameCommand,
ConsoleCommand,
ErrorsCommand,
KeyboardCommand,
WheelCommand,
TapCommand,
ClipboardCommand,
HighlightCommand,
ClearCommand,
SelectAllCommand,
InnerTextCommand,
InnerHtmlCommand,
InputValueCommand,
SetValueCommand,
DispatchEventCommand,
AddScriptCommand,
AddStyleCommand,
EmulateMediaCommand,
OfflineCommand,
HeadersCommand,
GetByAltTextCommand,
GetByTitleCommand,
GetByTestIdCommand,
NthCommand,
WaitForUrlCommand,
WaitForLoadStateCommand,
SetContentCommand,
TimezoneCommand,
LocaleCommand,
HttpCredentialsCommand,
MouseMoveCommand,
MouseDownCommand,
MouseUpCommand,
WaitForFunctionCommand,
ScrollIntoViewCommand,
AddInitScriptCommand,
KeyDownCommand,
KeyUpCommand,
InsertTextCommand,
MultiSelectCommand,
WaitForDownloadCommand,
ResponseBodyCommand,
ScreencastStartCommand,
ScreencastStopCommand,
InputMouseCommand,
InputKeyboardCommand,
InputTouchCommand,
RecordingStartCommand,
RecordingStopCommand,
RecordingRestartCommand,
DiffSnapshotCommand,
DiffScreenshotCommand,
DiffUrlCommand,
AuthLoginCommand,
ConfirmCommand,
DenyCommand,
Annotation,
NavigateData,
ScreenshotData,
EvaluateData,
DiffSnapshotData,
DiffScreenshotData,
DiffUrlData,
ContentData,
TabListData,
TabNewData,
TabSwitchData,
TabCloseData,
ScreencastStartData,
ScreencastStopData,
RecordingStartData,
RecordingStopData,
RecordingRestartData,
InputEventData,
StylesData,
} from './types.js';
import { successResponse, errorResponse, parseCommand } from './protocol.js';
import { diffSnapshots, diffScreenshots } from './diff.js';
import { getEnhancedSnapshot } from './snapshot.js';
// Callback for screencast frames - will be set by the daemon when streaming is active
let screencastFrameCallback: ((frame: ScreencastFrame) => void) | null = null;
/**
* Set the callback for screencast frames
* This is called by the daemon to set up frame streaming
*/
export function setScreencastFrameCallback(
callback: ((frame: ScreencastFrame) => void) | null
): void {
screencastFrameCallback = callback;
}
// Snapshot response type
interface SnapshotData {
snapshot: string;
refs?: Record<string, { role: string; name?: string }>;
}
/**
* Convert Playwright errors to AI-friendly messages
* @internal Exported for testing
*/
export function toAIFriendlyError(error: unknown, selector: string): Error {
const message = error instanceof Error ? error.message : String(error);
// Handle strict mode violation (multiple elements match)
if (message.includes('strict mode violation')) {
// Extract count if available
const countMatch = message.match(/resolved to (\d+) elements/);
const count = countMatch ? countMatch[1] : 'multiple';
return new Error(
`Selector "${selector}" matched ${count} elements. ` +
`Run 'snapshot' to get updated refs, or use a more specific CSS selector.`
);
}
// Handle element not interactable (must be checked BEFORE timeout case)
// This includes cases where an overlay/modal blocks the element
if (message.includes('intercepts pointer events')) {
return new Error(
`Element "${selector}" is blocked by another element (likely a modal or overlay). ` +
`Try dismissing any modals/cookie banners first.`
);
}
// Handle element not visible
if (message.includes('not visible') && !message.includes('Timeout')) {
return new Error(
`Element "${selector}" is not visible. ` +
`Try scrolling it into view or check if it's hidden.`
);
}
// Handle general timeout (element exists but action couldn't complete)
if (message.includes('Timeout') && message.includes('exceeded')) {
return new Error(
`Action on "${selector}" timed out. The element may be blocked, still loading, or not interactable. ` +
`Run 'snapshot' to check the current page state.`
);
}
// Handle element not found (timeout waiting for element)
if (
message.includes('waiting for') &&
(message.includes('to be visible') || message.includes('Timeout'))
) {
return new Error(
`Element "${selector}" not found or not visible. ` +
`Run 'snapshot' to see current page elements.`
);
}
// Return original error for unknown cases
return error instanceof Error ? error : new Error(message);
}
let actionPolicy: ActionPolicy | null = null;
let confirmCategories = new Set<string>();
export function initActionPolicy(): void {
const policyPath = process.env.AGENT_BROWSER_ACTION_POLICY;
if (policyPath) {
try {
actionPolicy = loadPolicyFile(policyPath);
initPolicyReloader(policyPath, actionPolicy);
} catch (err) {
console.error(
`[ERROR] Failed to load action policy from ${policyPath}: ${err instanceof Error ? err.message : err}`
);
process.exit(1);
}
}
const confirmActionsEnv = process.env.AGENT_BROWSER_CONFIRM_ACTIONS;
if (confirmActionsEnv) {
confirmCategories = new Set(
confirmActionsEnv
.split(',')
.map((c) => c.trim().toLowerCase())
.filter((c) => c.length > 0)
);
}
}
/**
* Execute a command and return a response
*/
export async function executeCommand(command: Command, browser: BrowserManager): Promise<Response> {
try {
// Handle confirm/deny actions (bypass policy check)
if (command.action === 'confirm') {
return await handleConfirm(command, browser);
}
if (command.action === 'deny') {
return handleDeny(command);
}
// Hot-reload policy file if it changed on disk
actionPolicy = reloadPolicyIfChanged();
// Policy enforcement
const decision = checkPolicy(command.action, actionPolicy, confirmCategories);
if (decision === 'deny') {
const category = getActionCategory(command.action);
return errorResponse(command.id, `Action denied by policy: '${category}' is not allowed`);
}
if (decision === 'confirm') {
const category = getActionCategory(command.action);
const description = describeAction(
command.action,
command as unknown as Record<string, unknown>
);
const { confirmationId } = requestConfirmation(
command.action,
category,
description,
command as unknown as Record<string, unknown>
);
return successResponse(command.id, {
confirmation_required: true,
action: command.action,
category,
description,
confirmation_id: confirmationId,
});
}
return await dispatchAction(command, browser);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return errorResponse(command.id, message);
}
}
/**
* Dispatch a command to its handler after policy checks have passed.
*/
async function dispatchAction(command: Command, browser: BrowserManager): Promise<Response> {
switch (command.action) {
case 'launch':
return await handleLaunch(command, browser);
case 'navigate':
return await handleNavigate(command, browser);
case 'click':
return await handleClick(command, browser);
case 'type':
return await handleType(command, browser);
case 'fill':
return await handleFill(command, browser);
case 'check':
return await handleCheck(command, browser);
case 'uncheck':
return await handleUncheck(command, browser);
case 'upload':
return await handleUpload(command, browser);
case 'dblclick':
return await handleDoubleClick(command, browser);
case 'focus':
return await handleFocus(command, browser);
case 'drag':
return await handleDrag(command, browser);
case 'frame':
return await handleFrame(command, browser);
case 'mainframe':
return await handleMainFrame(command, browser);
case 'getbyrole':
return await handleGetByRole(command, browser);
case 'getbytext':
return await handleGetByText(command, browser);
case 'getbylabel':
return await handleGetByLabel(command, browser);
case 'getbyplaceholder':
return await handleGetByPlaceholder(command, browser);
case 'press':
return await handlePress(command, browser);
case 'screenshot':
return await handleScreenshot(command, browser);
case 'snapshot':
return await handleSnapshot(command, browser);
case 'evaluate':
return await handleEvaluate(command, browser);
case 'wait':
return await handleWait(command, browser);
case 'scroll':
return await handleScroll(command, browser);
case 'select':
return await handleSelect(command, browser);
case 'hover':
return await handleHover(command, browser);
case 'content':
return await handleContent(command, browser);
case 'close':
return await handleClose(command, browser);
case 'tab_new':
return await handleTabNew(command, browser);
case 'tab_list':
return await handleTabList(command, browser);
case 'tab_switch':
return await handleTabSwitch(command, browser);
case 'tab_close':
return await handleTabClose(command, browser);
case 'window_new':
return await handleWindowNew(command, browser);
case 'cookies_get':
return await handleCookiesGet(command, browser);
case 'cookies_set':
return await handleCookiesSet(command, browser);
case 'cookies_clear':
return await handleCookiesClear(command, browser);
case 'storage_get':
return await handleStorageGet(command, browser);
case 'storage_set':
return await handleStorageSet(command, browser);
case 'storage_clear':
return await handleStorageClear(command, browser);
case 'dialog':
return await handleDialog(command, browser);
case 'pdf':
return await handlePdf(command, browser);
case 'route':
return await handleRoute(command, browser);
case 'unroute':
return await handleUnroute(command, browser);
case 'requests':
return await handleRequests(command, browser);
case 'download':
return await handleDownload(command, browser);
case 'geolocation':
return await handleGeolocation(command, browser);
case 'permissions':
return await handlePermissions(command, browser);
case 'viewport':
return await handleViewport(command, browser);
case 'useragent':
return await handleUserAgent(command, browser);
case 'device':
return await handleDevice(command, browser);
case 'back':
return await handleBack(command, browser);
case 'forward':
return await handleForward(command, browser);
case 'reload':
return await handleReload(command, browser);
case 'url':
return await handleUrl(command, browser);
case 'title':
return await handleTitle(command, browser);
case 'getattribute':
return await handleGetAttribute(command, browser);
case 'gettext':
return await handleGetText(command, browser);
case 'isvisible':
return await handleIsVisible(command, browser);
case 'isenabled':
return await handleIsEnabled(command, browser);
case 'ischecked':
return await handleIsChecked(command, browser);
case 'count':
return await handleCount(command, browser);
case 'boundingbox':
return await handleBoundingBox(command, browser);
case 'styles':
return await handleStyles(command, browser);
case 'video_start':
return await handleVideoStart(command, browser);
case 'video_stop':
return await handleVideoStop(command, browser);
case 'trace_start':
return await handleTraceStart(command, browser);
case 'trace_stop':
return await handleTraceStop(command, browser);
case 'profiler_start':
return await handleProfilerStart(command, browser);
case 'profiler_stop':
return await handleProfilerStop(command, browser);
case 'har_start':
return await handleHarStart(command, browser);
case 'har_stop':
return await handleHarStop(command, browser);
case 'state_save':
return await handleStateSave(command, browser);
case 'state_load':
return await handleStateLoad(command, browser);
case 'state_list':
return await handleStateList(command);
case 'state_clear':
return await handleStateClear(command);
case 'state_show':
return await handleStateShow(command);
case 'state_clean':
return await handleStateClean(command);
case 'state_rename':
return await handleStateRename(command);
case 'console':
return await handleConsole(command, browser);
case 'errors':
return await handleErrors(command, browser);
case 'keyboard':
return await handleKeyboard(command, browser);
case 'wheel':
return await handleWheel(command, browser);
case 'tap':
return await handleTap(command, browser);
case 'clipboard':
return await handleClipboard(command, browser);
case 'highlight':
return await handleHighlight(command, browser);
case 'clear':
return await handleClear(command, browser);
case 'selectall':
return await handleSelectAll(command, browser);
case 'innertext':
return await handleInnerText(command, browser);
case 'innerhtml':
return await handleInnerHtml(command, browser);
case 'inputvalue':
return await handleInputValue(command, browser);
case 'setvalue':
return await handleSetValue(command, browser);
case 'dispatch':
return await handleDispatch(command, browser);
case 'evalhandle':
return await handleEvalHandle(command, browser);
case 'expose':
return await handleExpose(command, browser);
case 'addscript':
return await handleAddScript(command, browser);
case 'addstyle':
return await handleAddStyle(command, browser);
case 'emulatemedia':
return await handleEmulateMedia(command, browser);
case 'offline':
return await handleOffline(command, browser);
case 'headers':
return await handleHeaders(command, browser);
case 'pause':
return await handlePause(command, browser);
case 'getbyalttext':
return await handleGetByAltText(command, browser);
case 'getbytitle':
return await handleGetByTitle(command, browser);
case 'getbytestid':
return await handleGetByTestId(command, browser);
case 'nth':
return await handleNth(command, browser);
case 'waitforurl':
return await handleWaitForUrl(command, browser);
case 'waitforloadstate':
return await handleWaitForLoadState(command, browser);
case 'setcontent':
return await handleSetContent(command, browser);
case 'timezone':
return await handleTimezone(command, browser);
case 'locale':
return await handleLocale(command, browser);
case 'credentials':
return await handleCredentials(command, browser);
case 'mousemove':
return await handleMouseMove(command, browser);
case 'mousedown':
return await handleMouseDown(command, browser);
case 'mouseup':
return await handleMouseUp(command, browser);
case 'bringtofront':
return await handleBringToFront(command, browser);
case 'waitforfunction':
return await handleWaitForFunction(command, browser);
case 'scrollintoview':
return await handleScrollIntoView(command, browser);
case 'addinitscript':
return await handleAddInitScript(command, browser);
case 'keydown':
return await handleKeyDown(command, browser);
case 'keyup':
return await handleKeyUp(command, browser);
case 'inserttext':
return await handleInsertText(command, browser);
case 'multiselect':
return await handleMultiSelect(command, browser);
case 'waitfordownload':
return await handleWaitForDownload(command, browser);
case 'responsebody':
return await handleResponseBody(command, browser);
case 'screencast_start':
return await handleScreencastStart(command, browser);
case 'screencast_stop':
return await handleScreencastStop(command, browser);
case 'input_mouse':
return await handleInputMouse(command, browser);
case 'input_keyboard':
return await handleInputKeyboard(command, browser);
case 'input_touch':
return await handleInputTouch(command, browser);
case 'recording_start':
return await handleRecordingStart(command, browser);
case 'recording_stop':
return await handleRecordingStop(command, browser);
case 'recording_restart':
return await handleRecordingRestart(command, browser);
case 'diff_snapshot':
return await handleDiffSnapshot(command, browser);
case 'diff_screenshot':
return await handleDiffScreenshot(command, browser);
case 'diff_url':
return await handleDiffUrl(command, browser);
case 'auth_login':
return await handleAuthLogin(command, browser);
default: {
// TypeScript narrows to never here, but we handle it for safety
const unknownCommand = command as { id: string; action: string };
return errorResponse(unknownCommand.id, `Unknown action: ${unknownCommand.action}`);
}
}
}
async function handleLaunch(
command: Command & { action: 'launch' },
browser: BrowserManager
): Promise<Response> {
if (command.engine === 'lightpanda') {
return errorResponse(command.id, 'Lightpanda engine requires --native mode');
}
await browser.launch(command);
return successResponse(command.id, { launched: true });
}
async function handleNavigate(
command: NavigateCommand,
browser: BrowserManager
): Promise<Response<NavigateData>> {
browser.checkDomainAllowed(command.url);
const page = browser.getPage();
// If headers are provided, set up scoped headers for this origin
if (command.headers && Object.keys(command.headers).length > 0) {
await browser.setScopedHeaders(command.url, command.headers);
}
await page.goto(command.url, {
waitUntil: command.waitUntil ?? 'load',
});
return successResponse(command.id, {
url: page.url(),
title: await page.title(),
});
}
async function handleClick(command: ClickCommand, browser: BrowserManager): Promise<Response> {
// Support both refs (@e1) and regular selectors
const locator = browser.getLocator(command.selector);
try {
// If --new-tab flag is set, get the href and open in a new tab
if (command.newTab) {
const fullUrl = await locator.evaluate((el) => {
const href = el.getAttribute('href');
// URL and document.baseURI are available in the browser context
return href
? new (globalThis as any).URL(href, (globalThis as any).document.baseURI).toString()
: '';
});
if (!fullUrl) {
throw new Error(
`Element '${command.selector}' does not have an href attribute. --new-tab only works on links.`
);
}
await browser.newTab();
const newPage = browser.getPage();
await newPage.goto(fullUrl);
return successResponse(command.id, {
clicked: true,
newTab: true,
url: fullUrl,
});
}
await locator.click({
button: command.button,
clickCount: command.clickCount,
delay: command.delay,
});
} catch (error) {
throw toAIFriendlyError(error, command.selector);
}
return successResponse(command.id, { clicked: true });
}
async function handleType(command: TypeCommand, browser: BrowserManager): Promise<Response> {
const locator = browser.getLocator(command.selector);
try {
if (command.clear) {
await locator.fill('');
}
await locator.pressSequentially(command.text, {
delay: command.delay,
});
} catch (error) {
throw toAIFriendlyError(error, command.selector);
}
return successResponse(command.id, { typed: true });
}
async function handlePress(command: PressCommand, browser: BrowserManager): Promise<Response> {
const page = browser.getPage();
if (command.selector) {
await page.press(command.selector, command.key);
} else {
await page.keyboard.press(command.key);
}
return successResponse(command.id, { pressed: true });
}
const ANNOTATION_OVERLAY_ID = '__agent_browser_annotations__';
async function removeAnnotationOverlay(page: Page): Promise<void> {
await page
.evaluate(
`(() => { const el = document.getElementById(${JSON.stringify(ANNOTATION_OVERLAY_ID)}); if (el) el.remove(); })()`
)
.catch(() => {});
}
async function handleScreenshot(
command: ScreenshotCommand,
browser: BrowserManager
): Promise<Response<ScreenshotData>> {
const page = browser.getPage();
const options: Parameters<Page['screenshot']>[0] = {
fullPage: command.fullPage,
type: command.format ?? 'png',
};
if (command.format === 'jpeg' && command.quality !== undefined) {
options.quality = command.quality;
}
let target: Page | ReturnType<Page['locator']> = page;
if (command.selector) {
target = browser.getLocator(command.selector);
}
let overlayInjected = false;
try {
let savePath = command.path;
if (!savePath) {
const ext = command.format === 'jpeg' ? 'jpg' : 'png';
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const random = Math.random().toString(36).substring(2, 8);
const filename = `screenshot-${timestamp}-${random}.${ext}`;
const screenshotDir = path.join(getAppDir(), 'tmp', 'screenshots');
mkdirSync(screenshotDir, { recursive: true });
savePath = path.join(screenshotDir, filename);
}
let annotations: Annotation[] | undefined;
if (command.annotate) {
const { refs } = await browser.getSnapshot({ interactive: true });
const entries = Object.entries(refs);
const results = await Promise.all(
entries.map(async ([ref, data]): Promise<Annotation | null> => {
try {
const locator = browser.getLocatorFromRef(ref);
if (!locator) return null;
const box = await locator.boundingBox();
if (!box || box.width === 0 || box.height === 0) return null;
const num = parseInt(ref.replace('e', ''), 10);
return {
ref,
number: num,
role: data.role,
name: data.name || undefined,
box: {
x: Math.round(box.x),
y: Math.round(box.y),
width: Math.round(box.width),
height: Math.round(box.height),
},
};
} catch {
return null;
}
})
);
// When a selector is provided the screenshot is cropped to that element,
// so filter to annotations that overlap the target and shift coordinates.
let targetBox: { x: number; y: number; width: number; height: number } | null = null;
if (command.selector) {
const raw = await browser.getLocator(command.selector).boundingBox();
if (raw) {
targetBox = {
x: Math.round(raw.x),
y: Math.round(raw.y),
width: Math.round(raw.width),
height: Math.round(raw.height),
};
}
}
const filtered = results.filter((a): a is Annotation => a !== null);
// Filter by selector overlap if needed, but keep viewport-relative coords
// for overlay positioning. Coordinate shifting happens later for metadata only.
let overlayItems: Annotation[];
if (targetBox) {
const tb = targetBox;
overlayItems = filtered
.filter((a) => {
const ax2 = a.box.x + a.box.width;
const ay2 = a.box.y + a.box.height;
const bx2 = tb.x + tb.width;
const by2 = tb.y + tb.height;
return a.box.x < bx2 && ax2 > tb.x && a.box.y < by2 && ay2 > tb.y;
})
.sort((a, b) => a.number - b.number);
} else {
overlayItems = filtered.sort((a, b) => a.number - b.number);
}
if (overlayItems.length > 0) {
const overlayData = overlayItems.map((a) => ({
number: a.number,
x: a.box.x,
y: a.box.y,
width: a.box.width,
height: a.box.height,
}));
// Uses position:absolute with document-relative coords so labels render
// correctly for both viewport and fullPage screenshots, and when the
// screenshot is scoped to a selector element.
await page.evaluate(`(() => {
var items = ${JSON.stringify(overlayData)};
var id = ${JSON.stringify(ANNOTATION_OVERLAY_ID)};
var sx = window.scrollX || 0;
var sy = window.scrollY || 0;
var c = document.createElement('div');
c.id = id;
c.style.cssText = 'position:absolute;top:0;left:0;width:0;height:0;pointer-events:none;z-index:2147483647;';
for (var i = 0; i < items.length; i++) {
var it = items[i];
var dx = it.x + sx;
var dy = it.y + sy;
var b = document.createElement('div');
b.style.cssText = 'position:absolute;left:' + dx + 'px;top:' + dy + 'px;width:' + it.width + 'px;height:' + it.height + 'px;border:2px solid rgba(255,0,0,0.8);box-sizing:border-box;pointer-events:none;';
var l = document.createElement('div');
l.textContent = String(it.number);
var labelTop = dy < 14 ? '2px' : '-14px';
l.style.cssText = 'position:absolute;top:' + labelTop + ';left:-2px;background:rgba(255,0,0,0.9);color:#fff;font:bold 11px/14px monospace;padding:0 4px;border-radius:2px;white-space:nowrap;';
b.appendChild(l);
c.appendChild(b);
}
document.documentElement.appendChild(c);
})()`);
overlayInjected = true;
}
// Build returned annotation metadata with image-relative coordinates.
// Selector: shift to target-element-relative.
// fullPage: convert to document-relative (matching fullPage image origin).
// Default: viewport-relative (unchanged).
if (targetBox) {
const tb = targetBox;
annotations = overlayItems.map((a) => ({
...a,
box: {
x: a.box.x - tb.x,
y: a.box.y - tb.y,
width: a.box.width,
height: a.box.height,
},
}));
} else if (command.fullPage) {
const scroll = (await page.evaluate(
`({x: window.scrollX || 0, y: window.scrollY || 0})`
)) as { x: number; y: number };
annotations = overlayItems.map((a) => ({
...a,
box: {
x: a.box.x + scroll.x,
y: a.box.y + scroll.y,
width: a.box.width,
height: a.box.height,
},
}));
} else {
annotations = overlayItems;
}
}
await target.screenshot({ ...options, path: savePath });
if (overlayInjected) {
await removeAnnotationOverlay(page);
}
return successResponse(command.id, {
path: savePath,
...(annotations && annotations.length > 0 ? { annotations } : {}),
});
} catch (error) {
if (overlayInjected) {
await removeAnnotationOverlay(page);
}
if (command.selector) {
throw toAIFriendlyError(error, command.selector);
}
throw error;
}
}
async function handleSnapshot(
command: Command & {
action: 'snapshot';
interactive?: boolean;
cursor?: boolean;
maxDepth?: number;
compact?: boolean;
selector?: string;
},
browser: BrowserManager
): Promise<Response<SnapshotData>> {
// Use enhanced snapshot with refs and optional filtering
const { tree, refs } = await browser.getSnapshot({
interactive: command.interactive,
cursor: command.cursor,
maxDepth: command.maxDepth,
compact: command.compact,
selector: command.selector,
});
// Simplify refs for output (just role and name)
const simpleRefs: Record<string, { role: string; name: string }> = {};
for (const [ref, data] of Object.entries(refs)) {
simpleRefs[ref] = { role: data.role, name: data.name };
}
const page = browser.getPage();
return successResponse(command.id, {
snapshot: tree || 'Empty page',
refs: Object.keys(simpleRefs).length > 0 ? simpleRefs : undefined,
origin: page.url(),
});
}
async function handleEvaluate(
command: EvaluateCommand,
browser: BrowserManager
): Promise<Response<EvaluateData>> {
const page = browser.getPage();
// Evaluate the script directly as a string expression
const result = await page.evaluate(command.script);
return successResponse(command.id, { result, origin: page.url() });
}
async function handleWait(command: WaitCommand, browser: BrowserManager): Promise<Response> {
const page = browser.getPage();
if (command.selector) {
await page.waitForSelector(command.selector, {
state: command.state ?? 'visible',
timeout: command.timeout,
});
} else if (command.timeout) {
await page.waitForTimeout(command.timeout);
} else {
// Default: wait for load state
await page.waitForLoadState('load');
}
return successResponse(command.id, { waited: true });
}
async function handleScroll(command: ScrollCommand, browser: BrowserManager): Promise<Response> {
const page = browser.getPage();
let deltaX = command.x ?? 0;
let deltaY = command.y ?? 0;
const hasExplicitDelta = command.x !== undefined || command.y !== undefined;
if (command.direction) {
const amount = command.amount ?? 100;
switch (command.direction) {
case 'up':
deltaY = -amount;
break;
case 'down':
deltaY = amount;
break;
case 'left':
deltaX = -amount;
break;
case 'right':
deltaX = amount;
break;
}