@myrialabs/clopen 0.4.20 → 0.4.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/bootstrap.ts +39 -0
  5. package/backend/chat/stream-manager.ts +15 -0
  6. package/backend/database/migrations/065_add_session_reasoning_effort.ts +28 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/session-queries.ts +10 -0
  9. package/backend/engine/README.md +11 -8
  10. package/backend/engine/adapters/claude/models.ts +46 -23
  11. package/backend/engine/adapters/claude/stream.ts +18 -4
  12. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  13. package/backend/engine/adapters/codex/models.ts +19 -2
  14. package/backend/engine/adapters/codex/stream.ts +10 -3
  15. package/backend/engine/adapters/copilot/models.ts +20 -1
  16. package/backend/engine/adapters/copilot/stream.ts +11 -1
  17. package/backend/engine/adapters/cursor/models.ts +27 -3
  18. package/backend/engine/adapters/cursor/stream.ts +23 -3
  19. package/backend/engine/adapters/pi/models.ts +20 -2
  20. package/backend/engine/adapters/pi/stream.ts +6 -3
  21. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  22. package/backend/engine/bootstrap-default-engine.ts +18 -5
  23. package/backend/engine/docs/adapter-contract.md +66 -2
  24. package/backend/engine/docs/adding-an-engine.md +46 -7
  25. package/backend/engine/docs/frontend-and-chat.md +80 -17
  26. package/backend/engine/docs/lessons-learned.md +126 -7
  27. package/backend/engine/docs/quick-reference.md +12 -3
  28. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  29. package/backend/engine/docs/websocket-routes.md +54 -15
  30. package/backend/engine/install-runner.ts +4 -4
  31. package/backend/engine/resolve-model.ts +87 -0
  32. package/backend/engine/structured-helpers.test.ts +64 -0
  33. package/backend/engine/structured-helpers.ts +105 -13
  34. package/backend/engine/types.ts +6 -0
  35. package/backend/index.ts +6 -9
  36. package/backend/mcp/README.md +32 -11
  37. package/backend/mcp/internal/config.ts +3 -20
  38. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  39. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  40. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  41. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  42. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  43. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  44. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  45. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
  46. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
  47. package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
  48. package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
  49. package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
  50. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  51. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  52. package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
  53. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  54. package/backend/preview/browser/browser-console-manager.ts +310 -156
  55. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  56. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  57. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  58. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  59. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  60. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  61. package/backend/preview/browser/browser-pool.ts +83 -9
  62. package/backend/preview/browser/browser-preview-service.ts +432 -53
  63. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  64. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  65. package/backend/preview/browser/capture-profile.ts +213 -0
  66. package/backend/preview/browser/element-locator.ts +357 -0
  67. package/backend/preview/browser/frame-targeting.ts +92 -0
  68. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  69. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  70. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  71. package/backend/preview/browser/types.ts +397 -37
  72. package/backend/utils/cli.ts +1 -1
  73. package/backend/utils/path-enrich.ts +2 -2
  74. package/backend/ws/README.md +1 -1
  75. package/backend/ws/artifacts/generate.ts +2 -1
  76. package/backend/ws/chat/stream.ts +38 -2
  77. package/backend/ws/engine/codex/accounts.ts +1 -1
  78. package/backend/ws/engine/codex/status.ts +1 -1
  79. package/backend/ws/git/branch-name.ts +11 -5
  80. package/backend/ws/git/commit-message.ts +11 -5
  81. package/backend/ws/index.ts +3 -3
  82. package/backend/ws/preview/browser/host.ts +95 -0
  83. package/backend/ws/preview/browser/interact.ts +204 -10
  84. package/backend/ws/preview/browser/native-ui.ts +31 -1
  85. package/backend/ws/preview/browser/tab-info.ts +10 -1
  86. package/backend/ws/preview/browser/tab.ts +43 -0
  87. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  88. package/backend/ws/preview/index.ts +58 -1
  89. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  90. package/backend/ws/stack/index.ts +16 -0
  91. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  92. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  93. package/backend/ws/system/device-info.ts +290 -0
  94. package/backend/ws/system/index.ts +2 -0
  95. package/backend/ws/system/operations.ts +7 -0
  96. package/backend/ws/user/crud.ts +6 -3
  97. package/dist/assets/{index-BqBxKeAv.js → index-DH_GO0Lf.js} +1 -1
  98. package/dist/assets/{index-DdrcY5TE.js → index-igSQ3JaM.js} +1 -1
  99. package/dist/assets/main-BD3-qPfT.css +1 -0
  100. package/dist/assets/main-D-d8SFfW.js +616 -0
  101. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +2 -1
  104. package/shared/constants/engines.ts +23 -0
  105. package/shared/types/database/schema.ts +1 -0
  106. package/shared/types/stores/settings.ts +12 -0
  107. package/shared/types/unified/engine.ts +33 -0
  108. package/shared/types/unified/index.ts +2 -0
  109. package/shared/types/unified/message.ts +6 -0
  110. package/shared/types/unified/stream.ts +6 -0
  111. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  112. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  113. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  114. package/backend/ws/system-tools/index.ts +0 -16
  115. package/dist/assets/main-BBxAj17T.js +0 -582
  116. package/dist/assets/main-Cry3pLcl.css +0 -1
@@ -1,25 +1,99 @@
1
+ /**
2
+ * Browser Interaction Handler
3
+ *
4
+ * Executes agent-driven input against a tab: mouse, keyboard, touch and the
5
+ * few gestures that cannot be expressed as either (native drag, file upload,
6
+ * <select>).
7
+ *
8
+ * Two rules shape everything here:
9
+ *
10
+ * 1. Drive real input, not the DOM. Clicks go through CDP mouse events at a
11
+ * point, so a page cannot tell an agent apart from a person — and handlers
12
+ * the page installed on the real event are the ones that run. The DOM is
13
+ * touched only where no input event exists (reading values, <select>,
14
+ * uploads).
15
+ * 2. Report every action. A batch that stops halfway must say so, and say
16
+ * where, or the agent will happily plan its next step on top of a state
17
+ * that never happened.
18
+ */
19
+
1
20
  import { EventEmitter } from 'events';
2
- import type { Page, KeyInput } from 'puppeteer';
3
- import type { BrowserAutonomousAction, BrowserTab } from './types';
21
+ import type { CDPSession, ElementHandle, KeyInput, Page } from 'puppeteer';
22
+ import type {
23
+ BrowserActionResult,
24
+ BrowserActionTarget,
25
+ BrowserAutonomousAction,
26
+ BrowserTab
27
+ } from './types';
4
28
  import { debug } from '$shared/utils/logger';
5
29
  import { sleep } from '$shared/utils/async';
6
30
  import { browserMcpControl } from './browser-mcp-control';
31
+ import { isNativeDraggable, resolveHandle, resolveTarget } from './element-locator';
32
+
33
+ /** Modifier aliases an agent (or a model trained on other tools) might use. */
34
+ const MODIFIER_ALIASES: Record<string, 'Control' | 'Shift' | 'Alt' | 'Meta'> = {
35
+ ctrl: 'Control',
36
+ control: 'Control',
37
+ shift: 'Shift',
38
+ alt: 'Alt',
39
+ option: 'Alt',
40
+ meta: 'Meta',
41
+ cmd: 'Meta',
42
+ command: 'Meta',
43
+ super: 'Meta',
44
+ win: 'Meta'
45
+ };
46
+
47
+ export interface AutonomousRunOutcome {
48
+ results: BrowserActionResult[];
49
+ /** True when the run stopped early because the tab or the stream went away. */
50
+ aborted: boolean;
51
+ }
7
52
 
8
53
  export class BrowserInteractionHandler extends EventEmitter {
9
54
  // Track cursor positions per session
10
- private sessionCursorPositions: Map<string, {x: number, y: number}> = new Map();
55
+ private sessionCursorPositions: Map<string, { x: number; y: number }> = new Map();
11
56
 
12
57
  constructor() {
13
58
  super();
14
59
  }
15
60
 
61
+ // ========================================================================
62
+ // Cursor telemetry
63
+ // ========================================================================
64
+
65
+ /**
66
+ * Publish where the agent's pointer is.
67
+ *
68
+ * `pressed` is what makes a drag legible on screen: without it the overlay
69
+ * cursor glides across the page with no indication the button is down, and
70
+ * a drag looks identical to a move.
71
+ */
72
+ private publishCursor(sessionId: string, x: number, y: number, pressed = false) {
73
+ this.updateCursorPosition(sessionId, x, y);
74
+ browserMcpControl.emitCursorPosition(sessionId, x, y, pressed);
75
+ }
76
+
77
+ private publishClick(sessionId: string, x: number, y: number, button: 'left' | 'right' | 'middle' = 'left') {
78
+ browserMcpControl.emitCursorClick(sessionId, x, y, button);
79
+ }
80
+
16
81
  // MCP-optimized mouse movement with smooth curves and ease-out easing
17
- private async mcpMouseMove(page: Page, fromX: number, fromY: number, toX: number, toY: number, steps: number = 8) {
82
+ private async mcpMouseMove(
83
+ page: Page,
84
+ fromX: number,
85
+ fromY: number,
86
+ toX: number,
87
+ toY: number,
88
+ steps: number = 8,
89
+ opts: { pressed?: boolean; totalMs?: number } = {}
90
+ ) {
18
91
  const controlPointX = fromX + (toX - fromX) * 0.5 + (Math.random() - 0.5) * 50;
19
92
  const controlPointY = fromY + (toY - fromY) * 0.5 + (Math.random() - 0.5) * 50;
20
93
 
21
94
  // Get session for emitting cursor position
22
95
  const sessionId = (page as any).__sessionId;
96
+ const perStepDelay = opts.totalMs ? Math.max(0, opts.totalMs / Math.max(1, steps)) : null;
23
97
 
24
98
  for (let i = 0; i <= steps; i++) {
25
99
  const t = i / steps;
@@ -34,23 +108,10 @@ export class BrowserInteractionHandler extends EventEmitter {
34
108
  await page.mouse.move(x, y);
35
109
 
36
110
  // Emit cursor position for visual tracking
37
- if (sessionId) {
38
- this.updateCursorPosition(sessionId, x, y);
39
-
40
- // Emit to WebSocket for frontend virtual cursor
41
- browserMcpControl.emitCursorPosition(sessionId, x, y);
42
-
43
- this.emit('cursor-position', {
44
- sessionId,
45
- x,
46
- y,
47
- timestamp: Date.now()
48
- });
49
- }
111
+ if (sessionId) this.publishCursor(sessionId, x, y, opts.pressed);
50
112
 
51
113
  // Smooth delay between movements (15-25ms) for MCP automation
52
- const moveDelay = 15 + Math.random() * 10;
53
- await sleep(moveDelay);
114
+ await sleep(perStepDelay ?? 15 + Math.random() * 10);
54
115
  }
55
116
  }
56
117
 
@@ -67,7 +128,7 @@ export class BrowserInteractionHandler extends EventEmitter {
67
128
  }
68
129
 
69
130
  // Get current mouse position from session tracking
70
- private getCurrentMousePosition(sessionId: string): {x: number, y: number} {
131
+ private getCurrentMousePosition(sessionId: string): { x: number; y: number } {
71
132
  const stored = this.sessionCursorPositions.get(sessionId);
72
133
  if (stored) {
73
134
  return stored;
@@ -92,330 +153,840 @@ export class BrowserInteractionHandler extends EventEmitter {
92
153
 
93
154
  // Clear all session cursors (when cleaning up all sessions)
94
155
  public clearAllSessionCursors() {
95
- const sessionCount = this.sessionCursorPositions.size;
96
156
  this.sessionCursorPositions.clear();
97
157
  }
98
158
 
159
+ // ========================================================================
160
+ // Helpers
161
+ // ========================================================================
162
+
163
+ /**
164
+ * Where should this action land?
165
+ *
166
+ * `target` (selector/text/coords) wins; bare x/y is the shorthand kept for
167
+ * coordinates read off a screenshot.
168
+ */
169
+ private async pointFor(
170
+ page: Page,
171
+ action: BrowserAutonomousAction,
172
+ target?: BrowserActionTarget
173
+ ): Promise<{ x: number; y: number; described: string }> {
174
+ const resolved = target ?? action.target ??
175
+ (typeof action.x === 'number' && typeof action.y === 'number'
176
+ ? { x: action.x, y: action.y }
177
+ : action.selector
178
+ ? { selector: action.selector }
179
+ : undefined);
180
+
181
+ return resolveTarget(page, resolved, { scrollIntoView: !action.noScroll });
182
+ }
183
+
184
+ /** Move the pointer to a point, animating so the overlay cursor tracks it. */
185
+ private async glideTo(
186
+ sessionId: string,
187
+ page: Page,
188
+ to: { x: number; y: number },
189
+ opts: { steps?: number; pressed?: boolean; totalMs?: number } = {}
190
+ ) {
191
+ const from = this.getCurrentMousePosition(sessionId);
192
+
193
+ // Already there. Animating anyway would still cost the full duration, and
194
+ // a batch that works one control repeatedly pays that on every action.
195
+ // Never skipped while the button is held: a drag needs its real moves.
196
+ if (!opts.pressed && Math.abs(from.x - to.x) < 2 && Math.abs(from.y - to.y) < 2) {
197
+ await page.mouse.move(to.x, to.y);
198
+ this.publishCursor(sessionId, to.x, to.y);
199
+ return;
200
+ }
201
+
202
+ await this.mcpMouseMove(page, from.x, from.y, to.x, to.y, opts.steps ?? 8, {
203
+ pressed: opts.pressed,
204
+ totalMs: opts.totalMs
205
+ });
206
+ this.publishCursor(sessionId, to.x, to.y, opts.pressed);
207
+ }
208
+
209
+ /**
210
+ * Walk the *overlay* pointer to a point, dispatching no real input.
211
+ *
212
+ * Half the actions never touch the mouse — keyboard chords, `focus`,
213
+ * `select_option`, touch gestures, reads — which left them with nothing on
214
+ * screen: the page changed and no cursor explained why. Driving the real
215
+ * pointer there instead would be worse than silent, because hovering is an
216
+ * input the agent never asked for: it opens menus, arms tooltips, and for a
217
+ * read it can change the very value being read.
218
+ */
219
+ private async glideOverlay(sessionId: string, to: { x: number; y: number }, steps = 6) {
220
+ const from = this.getCurrentMousePosition(sessionId);
221
+
222
+ if (Math.abs(from.x - to.x) < 2 && Math.abs(from.y - to.y) < 2) {
223
+ this.publishCursor(sessionId, to.x, to.y);
224
+ return;
225
+ }
226
+
227
+ for (let i = 1; i <= steps; i++) {
228
+ // Same ease-out as the real glide, so the two read as one pointer.
229
+ const t = 1 - Math.pow(1 - i / steps, 3);
230
+ this.publishCursor(
231
+ sessionId,
232
+ Math.round(from.x + (to.x - from.x) * t),
233
+ Math.round(from.y + (to.y - from.y) * t)
234
+ );
235
+ await sleep(16);
236
+ }
237
+
238
+ this.publishCursor(sessionId, to.x, to.y);
239
+ }
240
+
241
+ /**
242
+ * Point the overlay at whatever an action is about to act on.
243
+ *
244
+ * Resolution failure is swallowed: this is telemetry, and the action itself
245
+ * is about to resolve the same target and report the real error.
246
+ */
247
+ private async showTarget(
248
+ sessionId: string,
249
+ page: Page,
250
+ action: BrowserAutonomousAction,
251
+ target: BrowserActionTarget | undefined,
252
+ opts: { pulse?: boolean } = {}
253
+ ) {
254
+ if (!target) return;
255
+
256
+ try {
257
+ const point = await resolveTarget(page, target, { scrollIntoView: !action.noScroll });
258
+ await this.glideOverlay(sessionId, point);
259
+ if (opts.pulse) this.publishClick(sessionId, point.x, point.y);
260
+ } catch {
261
+ // Nothing to point at — the action's own resolve will say why.
262
+ }
263
+ }
264
+
265
+ /**
266
+ * The same, for an element the action has already resolved. Preferred where
267
+ * a handle is at hand: re-resolving the target would sweep every frame a
268
+ * second time purely to draw a cursor.
269
+ */
270
+ private async showHandle(
271
+ sessionId: string,
272
+ handle: ElementHandle<Element>,
273
+ opts: { pulse?: boolean } = {}
274
+ ) {
275
+ const box = await handle.boundingBox().catch(() => null);
276
+ if (!box) return;
277
+
278
+ const point = {
279
+ x: Math.round(box.x + box.width / 2),
280
+ y: Math.round(box.y + box.height / 2)
281
+ };
282
+
283
+ await this.glideOverlay(sessionId, point);
284
+ if (opts.pulse) this.publishClick(sessionId, point.x, point.y);
285
+ }
286
+
287
+ /**
288
+ * Where the keyboard is aimed, in page coordinates.
289
+ *
290
+ * Keystrokes carry no coordinates, so the focused field is the only honest
291
+ * answer to "where is this going" — and without it typing is the one gesture
292
+ * that changes the page with the pointer parked somewhere unrelated.
293
+ */
294
+ private async focusedPoint(page: Page): Promise<{ x: number; y: number } | null> {
295
+ try {
296
+ return await page.evaluate(() => {
297
+ let element: Element | null = document.activeElement;
298
+
299
+ // A shadow root keeps its own activeElement; the outer document only
300
+ // names the host, whose box is the whole component rather than the
301
+ // field inside it.
302
+ while (element && (element as HTMLElement).shadowRoot?.activeElement) {
303
+ element = (element as HTMLElement).shadowRoot!.activeElement;
304
+ }
305
+
306
+ if (!element || element === document.body || element === document.documentElement) return null;
307
+
308
+ const rect = element.getBoundingClientRect();
309
+ if (rect.width === 0 || rect.height === 0) return null;
310
+ // Scrolled out of sight — pointing off-viewport would draw the cursor
311
+ // outside the frame entirely.
312
+ if (rect.bottom < 0 || rect.right < 0 || rect.top > innerHeight || rect.left > innerWidth) return null;
313
+
314
+ return {
315
+ x: Math.round(rect.left + rect.width / 2),
316
+ y: Math.round(rect.top + rect.height / 2)
317
+ };
318
+ });
319
+ } catch {
320
+ return null;
321
+ }
322
+ }
323
+
324
+ /** Point the overlay at the focused field, for gestures that are pure keyboard. */
325
+ private async showFocused(sessionId: string, page: Page, opts: { pulse?: boolean } = {}) {
326
+ const point = await this.focusedPoint(page);
327
+ if (!point) {
328
+ // Nothing focused: keep the pointer asserted where it is, so the run
329
+ // never goes dark mid-batch.
330
+ const parked = this.getCurrentMousePosition(sessionId);
331
+ this.publishCursor(sessionId, parked.x, parked.y);
332
+ return;
333
+ }
334
+
335
+ await this.glideOverlay(sessionId, point);
336
+ if (opts.pulse) this.publishClick(sessionId, point.x, point.y);
337
+ }
338
+
339
+ /** "Control+Shift+K" → modifiers to hold plus the key to press. */
340
+ private parseChord(chord: string): { modifiers: Array<'Control' | 'Shift' | 'Alt' | 'Meta'>; key: string } {
341
+ const parts = chord.split('+').map((p) => p.trim()).filter(Boolean);
342
+ const modifiers: Array<'Control' | 'Shift' | 'Alt' | 'Meta'> = [];
343
+ let key = '';
344
+
345
+ for (const part of parts) {
346
+ const modifier = MODIFIER_ALIASES[part.toLowerCase()];
347
+ if (modifier) {
348
+ if (!modifiers.includes(modifier)) modifiers.push(modifier);
349
+ } else {
350
+ key = part;
351
+ }
352
+ }
353
+
354
+ return { modifiers, key };
355
+ }
356
+
357
+ /**
358
+ * Touch has to be turned on before it can be dispatched: without emulation
359
+ * the renderer drops touch events and the page's own feature detection
360
+ * (`'ontouchstart' in window`) reports false, so mobile-only handlers never
361
+ * even get installed.
362
+ */
363
+ private async withTouch<T>(page: Page, fn: (client: CDPSession) => Promise<T>): Promise<T> {
364
+ const client = await page.createCDPSession();
365
+ try {
366
+ await client.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 2 });
367
+ return await fn(client);
368
+ } finally {
369
+ await client.send('Emulation.setTouchEmulationEnabled', { enabled: false }).catch(() => {});
370
+ await client.detach().catch(() => {});
371
+ }
372
+ }
373
+
374
+ // ========================================================================
375
+ // Batch execution
376
+ // ========================================================================
377
+
99
378
  async performAutonomousActions(
100
379
  sessionId: string,
101
380
  session: BrowserTab,
102
381
  actions: BrowserAutonomousAction[],
103
382
  isValidSession: () => boolean
104
- ) {
105
- let currentMousePos = this.getCurrentMousePosition(sessionId);
106
- const results: any[] = [];
383
+ ): Promise<AutonomousRunOutcome> {
384
+ const results: BrowserActionResult[] = [];
385
+ const page = session.page;
107
386
 
108
387
  // Store session ID on page for cursor tracking
109
- (session.page as any).__sessionId = sessionId;
388
+ (page as any).__sessionId = sessionId;
389
+
390
+ // Show the pointer before the first gesture, parked where the last batch
391
+ // left it. Otherwise the only cursor events in a run are the ones a glide
392
+ // emits, so a batch that opens with a keystroke or a scroll moves the page
393
+ // with nothing on screen to attribute it to.
394
+ const parked = this.getCurrentMousePosition(sessionId);
395
+ this.publishCursor(sessionId, parked.x, parked.y);
110
396
 
111
397
  for (let i = 0; i < actions.length; i++) {
112
398
  // Check if session is still valid before each action
113
399
  if (!isValidSession()) {
114
400
  debug.warn('preview', `⚠️ Session ${sessionId} is no longer valid, stopping autonomous actions at ${i + 1}/${actions.length}`);
115
- return;
401
+ return { results, aborted: true };
116
402
  }
117
403
 
118
404
  const action = actions[i];
119
405
 
120
406
  try {
121
- switch (action.type) {
122
- case 'wait':
123
- await sleep(action.delay || 1000);
124
- break;
125
-
126
- case 'move':
127
- if (action.x !== undefined && action.y !== undefined) {
128
- // Always use MCP-optimized movement
129
- await this.mcpMouseMove(
130
- session.page,
131
- currentMousePos.x,
132
- currentMousePos.y,
133
- action.x,
134
- action.y,
135
- action.steps || 8
136
- );
137
- currentMousePos = { x: action.x, y: action.y };
138
- this.updateCursorPosition(sessionId, action.x, action.y);
139
-
140
- // Emit to WebSocket for frontend virtual cursor
141
- browserMcpControl.emitCursorPosition(sessionId, action.x, action.y);
142
-
143
- this.emit('cursor-position', {
144
- sessionId: session.id,
145
- x: action.x,
146
- y: action.y,
147
- timestamp: Date.now()
148
- });
149
- }
150
- break;
151
-
152
- case 'type': {
153
- // Clear existing input first if specified (default: true for MCP autonomous)
154
- const shouldClear = action.clearFirst !== false; // default true
155
-
156
- if (shouldClear && action.text) {
157
- // Select all text first (Ctrl+A), then type will overwrite
158
- await session.page.keyboard.down('Control');
159
- await session.page.keyboard.press('KeyA');
160
- await session.page.keyboard.up('Control');
161
- await sleep(30); // Fast delay for MCP automation
162
- }
407
+ const outcome = await this.runAction(sessionId, session, action);
408
+ results.push({
409
+ action: action.type,
410
+ ok: true,
411
+ detail: outcome.detail,
412
+ data: outcome.data,
413
+ selector: outcome.selector,
414
+ attribute: outcome.attribute,
415
+ timestamp: Date.now()
416
+ });
417
+ } catch (error) {
418
+ const message = (error as Error)?.message || 'Unknown error';
419
+ debug.error('preview', `❌ Error performing action ${action.type}:`, error);
163
420
 
164
- // Native keyboard: type text OR press single key
165
- if (action.text) {
166
- // Always use MCP-optimized typing
167
- await this.mcpType(session.page, action.text, action.delay || 30);
168
- } else if (action.key) {
169
- await session.page.keyboard.press(action.key as KeyInput);
170
- }
171
- break;
421
+ results.push({ action: action.type, ok: false, error: message, timestamp: Date.now() });
422
+
423
+ // A closed page cannot recover, and every later action would fail
424
+ // with the same message — stop and let the caller report it.
425
+ if (
426
+ message.includes('Target page, context or browser has been closed') ||
427
+ message.includes('Browser has been closed') ||
428
+ message.includes('Page has been closed')
429
+ ) {
430
+ debug.warn('preview', `⚠️ Browser/page closed during action ${i + 1}/${actions.length}, stopping autonomous actions`);
431
+ return { results, aborted: true };
432
+ }
433
+ }
434
+
435
+ // Fast delay between actions for MCP automation (50-100ms)
436
+ if (action.type !== 'wait') {
437
+ await sleep(50 + Math.random() * 50);
438
+ }
439
+ }
440
+
441
+ // Emit test completed event to hide virtual cursor
442
+ this.emit('test-completed', {
443
+ sessionId: session.id,
444
+ timestamp: Date.now(),
445
+ // Part of the wire contract for this event; without it the payload
446
+ // fails the shape the client is typed against.
447
+ source: 'mcp'
448
+ });
449
+
450
+ return { results, aborted: false };
451
+ }
452
+
453
+ /**
454
+ * Run one action.
455
+ *
456
+ * Returns a one-line description for the report, plus whatever the action
457
+ * read back. Failure is signalled by throwing — every caller path then
458
+ * records it identically.
459
+ */
460
+ private async runAction(
461
+ sessionId: string,
462
+ session: BrowserTab,
463
+ action: BrowserAutonomousAction
464
+ ): Promise<{ detail: string; data?: unknown; selector?: string; attribute?: string }> {
465
+ if (action.type === 'extract_data') {
466
+ const identifier = action.selector ?? action.target?.selector;
467
+ if (!identifier) throw new Error('extract_data needs a selector');
468
+
469
+ // Overlay only, and no pulse: a read is not a click, and driving the
470
+ // real pointer over the element could fire the hover handlers that
471
+ // change what is about to be read.
472
+ await this.showTarget(sessionId, session.page, action, { selector: identifier });
473
+
474
+ const extracted = await this.extractData(session.page, identifier, action.attribute, action.all);
475
+ if (extracted.error) throw new Error(extracted.error);
476
+
477
+ return {
478
+ detail: `extracted from "${extracted.selector ?? identifier}"`,
479
+ data: extracted.data,
480
+ selector: extracted.selector ?? identifier,
481
+ attribute: extracted.attribute
482
+ };
483
+ }
484
+
485
+ return { detail: await this.runGesture(sessionId, session, action) };
486
+ }
487
+
488
+ /** The gesture itself. Returns a one-line description for the report. */
489
+ private async runGesture(
490
+ sessionId: string,
491
+ session: BrowserTab,
492
+ action: BrowserAutonomousAction
493
+ ): Promise<string> {
494
+ const page = session.page;
495
+
496
+ switch (action.type) {
497
+ case 'wait': {
498
+ const ms = action.delay ?? 1000;
499
+ // A wait has nowhere to point, but it is often the longest step in a
500
+ // batch — re-asserting the parked pointer keeps the overlay alive
501
+ // rather than letting the run appear to have stopped.
502
+ const parked = this.getCurrentMousePosition(sessionId);
503
+ this.publishCursor(sessionId, parked.x, parked.y);
504
+ await sleep(ms);
505
+ return `waited ${ms}ms`;
506
+ }
507
+
508
+ case 'move': {
509
+ const point = await this.pointFor(page, action);
510
+ await this.glideTo(sessionId, page, point, { steps: action.steps ?? 8 });
511
+ if (action.dwellMs) await sleep(action.dwellMs);
512
+ return `moved to ${point.described}`;
513
+ }
514
+
515
+ case 'click': {
516
+ const point = await this.pointFor(page, action);
517
+ const button = action.button ?? 'left';
518
+ const clickCount = action.clickCount ?? 1;
519
+
520
+ await this.glideTo(sessionId, page, point, { steps: 8 });
521
+ await sleep(30);
522
+ this.publishClick(sessionId, point.x, point.y, button);
523
+
524
+ // Native mouse click with slight variance for MCP automation
525
+ const finalX = point.x + (Math.random() - 0.5) * 2;
526
+ const finalY = point.y + (Math.random() - 0.5) * 2;
527
+ await page.mouse.click(finalX, finalY, { button, count: clickCount });
528
+
529
+ const label = clickCount > 1 ? `${clickCount}× click` : 'click';
530
+ return `${label} (${button}) at ${point.described}`;
531
+ }
532
+
533
+ case 'long_press': {
534
+ const point = await this.pointFor(page, action);
535
+ const holdMs = action.holdMs ?? 700;
536
+
537
+ await this.glideTo(sessionId, page, point, { steps: 8 });
538
+ this.publishClick(sessionId, point.x, point.y, action.button ?? 'left');
539
+ await page.mouse.down({ button: action.button ?? 'left' });
540
+ this.publishCursor(sessionId, point.x, point.y, true);
541
+ await sleep(holdMs);
542
+ await page.mouse.up({ button: action.button ?? 'left' });
543
+ this.publishCursor(sessionId, point.x, point.y, false);
544
+
545
+ return `long press ${holdMs}ms at ${point.described}`;
546
+ }
547
+
548
+ case 'drag': {
549
+ const fromTarget = action.from ?? action.target;
550
+ const toTarget = action.to;
551
+ if (!fromTarget || !toTarget) throw new Error('drag needs both `from` and `to`');
552
+
553
+ const mode = action.mode ?? ((await isNativeDraggable(page, fromTarget)) ? 'native' : 'pointer');
554
+ const from = await resolveTarget(page, fromTarget, { scrollIntoView: !action.noScroll });
555
+ const to = await resolveTarget(page, toTarget, { scrollIntoView: !action.noScroll });
556
+
557
+ if (mode === 'native') {
558
+ // HTML5 drag-and-drop never sees plain mouse events — the browser
559
+ // synthesises dragstart/dragover/drop itself, and only when drag
560
+ // interception is on can CDP drive that protocol.
561
+ await page.setDragInterception(true);
562
+ try {
563
+ await this.glideTo(sessionId, page, from, { steps: 6 });
564
+ this.publishCursor(sessionId, from.x, from.y, true);
565
+
566
+ const payload = await page.mouse.drag({ x: from.x, y: from.y }, { x: to.x, y: to.y });
567
+ await this.glideTo(sessionId, page, to, { steps: action.steps ?? 12, pressed: true, totalMs: action.durationMs });
568
+ await page.mouse.dragEnter({ x: to.x, y: to.y }, payload);
569
+ await page.mouse.dragOver({ x: to.x, y: to.y }, payload);
570
+ await page.mouse.drop({ x: to.x, y: to.y }, payload);
571
+ await page.mouse.up();
572
+ } finally {
573
+ await page.setDragInterception(false).catch(() => {});
574
+ this.publishCursor(sessionId, to.x, to.y, false);
172
575
  }
576
+ return `native drag ${from.described} → ${to.described}`;
577
+ }
173
578
 
174
- case 'click': {
175
- // Native mouse click at coordinates
176
- if (action.x === undefined || action.y === undefined) break;
177
-
178
- const button = action.click || 'left';
179
-
180
- // Move mouse to target position with MCP-optimized movement
181
- await this.mcpMouseMove(
182
- session.page,
183
- currentMousePos.x,
184
- currentMousePos.y,
185
- action.x,
186
- action.y,
187
- 8
188
- );
189
-
190
- currentMousePos = { x: action.x, y: action.y };
191
- this.updateCursorPosition(sessionId, action.x, action.y);
192
-
193
- // Emit cursor position to WebSocket for frontend virtual cursor
194
- browserMcpControl.emitCursorPosition(sessionId, action.x, action.y);
195
-
196
- this.emit('cursor-position', {
197
- sessionId: session.id,
198
- x: action.x,
199
- y: action.y,
200
- timestamp: Date.now()
201
- });
579
+ await this.glideTo(sessionId, page, from, { steps: 6 });
580
+ await page.mouse.down({ button: action.button ?? 'left' });
581
+ this.publishCursor(sessionId, from.x, from.y, true);
582
+ // A pause after pressing is what most JS drag implementations wait
583
+ // for before they consider the gesture started.
584
+ await sleep(action.holdMs ?? 120);
585
+ await this.glideTo(sessionId, page, to, {
586
+ steps: action.steps ?? 16,
587
+ pressed: true,
588
+ totalMs: action.durationMs
589
+ });
590
+ await sleep(80);
591
+ await page.mouse.up({ button: action.button ?? 'left' });
592
+ this.publishCursor(sessionId, to.x, to.y, false);
202
593
 
203
- await sleep(30);
594
+ return `drag ${from.described} → ${to.described}`;
595
+ }
204
596
 
205
- // Emit click event to WebSocket for frontend virtual cursor
206
- browserMcpControl.emitCursorClick(sessionId, action.x, action.y);
597
+ case 'scroll': {
598
+ // Position over the intended scroll container first — the wheel
599
+ // event applies to whatever is under the pointer, not to the page.
600
+ let described = 'page';
601
+ if (action.target || (typeof action.x === 'number' && typeof action.y === 'number')) {
602
+ const point = await this.pointFor(page, action);
603
+ await this.glideTo(sessionId, page, point, { steps: 4 });
604
+ await sleep(50);
605
+ described = point.described;
606
+ } else {
607
+ // A page scroll applies wherever the pointer already is, so that
608
+ // is what the overlay should be showing while the page moves.
609
+ const parked = this.getCurrentMousePosition(sessionId);
610
+ this.publishCursor(sessionId, parked.x, parked.y);
611
+ }
207
612
 
208
- this.emit('cursor-click', {
209
- sessionId: session.id,
210
- x: action.x,
211
- y: action.y,
212
- timestamp: Date.now()
213
- });
613
+ const deltaX = action.deltaX ?? 0;
614
+ const deltaY = action.deltaY ?? 0;
214
615
 
215
- // Native mouse click with slight variance for MCP automation
216
- const finalX = action.x + (Math.random() - 0.5) * 2;
217
- const finalY = action.y + (Math.random() - 0.5) * 2;
218
- await session.page.mouse.click(finalX, finalY, { button });
219
- break;
616
+ if (action.smooth) {
617
+ const steps = 5;
618
+ for (let s = 0; s < steps; s++) {
619
+ await page.mouse.wheel({ deltaX: deltaX / steps, deltaY: deltaY / steps });
620
+ await sleep(50);
220
621
  }
622
+ } else {
623
+ await page.mouse.wheel({ deltaX, deltaY });
624
+ }
221
625
 
222
- case 'scroll':
223
- // Move cursor to target area first if coordinates provided
224
- // This ensures scroll happens in the correct scrollable container (like human behavior)
225
- if (action.x !== undefined && action.y !== undefined) {
226
- await session.page.mouse.move(action.x, action.y, { steps: 1 });
227
- currentMousePos = { x: action.x, y: action.y };
228
- this.updateCursorPosition(sessionId, action.x, action.y);
229
-
230
- // Emit cursor position for visual tracking
231
- browserMcpControl.emitCursorPosition(sessionId, action.x, action.y);
232
- this.emit('cursor-position', {
233
- sessionId: session.id,
234
- x: action.x,
235
- y: action.y,
236
- timestamp: Date.now()
237
- });
238
-
239
- await sleep(50); // Small delay after positioning
240
- }
626
+ return `scroll (${deltaX}, ${deltaY}) at ${described}`;
627
+ }
241
628
 
242
- // Perform scroll using deltaX/deltaY
243
- if (action.deltaX !== undefined || action.deltaY !== undefined) {
244
- if (action.smooth) {
245
- const steps = 5;
246
- const stepX = (action.deltaX || 0) / steps;
247
- const stepY = (action.deltaY || 0) / steps;
248
-
249
- for (let s = 0; s < steps; s++) {
250
- await session.page.mouse.wheel({ deltaX: stepX, deltaY: stepY });
251
- await sleep(50);
252
- }
253
- } else {
254
- await session.page.mouse.wheel({
255
- deltaX: action.deltaX || 0,
256
- deltaY: action.deltaY || 0
257
- });
258
- }
259
- }
260
- break;
261
-
262
- case 'extract_data': {
263
- // Extract data from DOM element - fully automatic selector and attribute detection
264
- if (!action.selector) {
265
- debug.warn('preview', `⚠️ extract_data action requires selector`);
266
- results.push({
267
- action: 'extract_data',
268
- selector: undefined,
269
- data: null,
270
- error: 'selector is required',
271
- timestamp: Date.now()
272
- });
273
- break;
274
- }
629
+ case 'type': {
630
+ // Focus a field first when one was named, so a batch does not have
631
+ // to interleave a click before every type.
632
+ if (action.target || action.selector) {
633
+ const point = await this.pointFor(page, action);
634
+ await this.glideTo(sessionId, page, point, { steps: 6 });
635
+ this.publishClick(sessionId, point.x, point.y);
636
+ await page.mouse.click(point.x, point.y);
637
+ await sleep(40);
638
+ } else {
639
+ // No target: the text goes wherever focus already is, so point at
640
+ // that instead of leaving the pointer stranded elsewhere.
641
+ await this.showFocused(sessionId, page, { pulse: true });
642
+ }
275
643
 
276
- const identifier = action.selector;
644
+ const shouldClear = action.clearFirst !== false;
645
+ if (shouldClear && action.text) {
646
+ // Select all, then typing overwrites the selection.
647
+ await page.keyboard.down('Control');
648
+ await page.keyboard.press('KeyA');
649
+ await page.keyboard.up('Control');
650
+ await sleep(30);
651
+ }
277
652
 
278
- try {
279
- // Smart extraction - try all selector patterns and all attributes automatically
280
- const result = await session.page.evaluate((id: string) => {
281
- // Try multiple selector patterns
282
- const selectors = [
283
- id, // exact (user might already include # or .)
284
- `#${id}`, // ID selector
285
- `.${id}`, // class selector
286
- `[id="${id}"]`, // attribute exact match
287
- `[id*="${id}"]`, // ID contains
288
- `[class*="${id}"]`, // class contains
289
- `[data-testid="${id}"]`, // test ID
290
- `[name="${id}"]`, // name attribute
291
- id.toLowerCase(), // lowercase tag
292
- `#${id.toLowerCase()}`, // lowercase ID
293
- `.${id.toLowerCase()}`, // lowercase class
294
- ];
295
-
296
- let element: Element | null = null;
297
- let usedSelector = '';
298
-
299
- // Try each selector until one works
300
- for (const selector of selectors) {
301
- try {
302
- element = document.querySelector(selector);
303
- if (element) {
304
- usedSelector = selector;
305
- break;
306
- }
307
- } catch (e) {
308
- // Invalid selector, skip
309
- continue;
310
- }
311
- }
312
-
313
- if (!element) {
314
- return { data: null, selector: null, attribute: null, tried: selectors.slice(0, 5) };
315
- }
316
-
317
- // Smart attribute extraction - try all common attributes and return first non-empty
318
- const extractors = [
319
- { name: 'value', fn: () => (element as HTMLInputElement).value },
320
- { name: 'textContent', fn: () => element!.textContent?.trim() },
321
- { name: 'innerText', fn: () => (element as HTMLElement).innerText?.trim() },
322
- { name: 'innerHTML', fn: () => element!.innerHTML?.trim() },
323
- ];
324
-
325
- let data = null;
326
- let usedAttribute = '';
327
-
328
- for (const extractor of extractors) {
329
- try {
330
- const extracted = extractor.fn();
331
- if (extracted && extracted.length > 0) {
332
- data = extracted;
333
- usedAttribute = extractor.name;
334
- break;
335
- }
336
- } catch (e) {
337
- // Attribute doesn't exist or failed, continue
338
- continue;
339
- }
340
- }
341
-
342
- return {
343
- data,
344
- selector: usedSelector,
345
- attribute: usedAttribute,
346
- tried: data ? [usedSelector] : selectors.slice(0, 5)
347
- };
348
- }, identifier);
349
-
350
- if (result.data !== null) {
351
- results.push({
352
- action: 'extract_data',
353
- selector: result.selector,
354
- attribute: result.attribute,
355
- data: result.data,
356
- timestamp: Date.now()
357
- });
358
- } else {
359
- results.push({
360
- action: 'extract_data',
361
- selector: identifier,
362
- attribute: null,
363
- data: null,
364
- error: `Element not found or empty. Tried selectors: ${result.tried.join(', ')}`,
365
- timestamp: Date.now()
366
- });
367
- }
368
- } catch (extractError) {
369
- debug.error('preview', `❌ Error extracting data from ${identifier}:`, extractError);
370
- results.push({
371
- action: 'extract_data',
372
- selector: identifier,
373
- attribute: null,
374
- data: null,
375
- error: (extractError as Error)?.message || 'Unknown error',
376
- timestamp: Date.now()
377
- });
378
- }
379
- break;
653
+ if (action.text) {
654
+ await this.mcpType(page, action.text, action.delay ?? 30);
655
+ return `typed ${action.text.length} char(s)`;
656
+ }
657
+ if (action.key) {
658
+ await page.keyboard.press(action.key as KeyInput);
659
+ return `pressed ${action.key}`;
660
+ }
661
+ throw new Error('type needs either `text` or `key`');
662
+ }
663
+
664
+ case 'press': {
665
+ const chord = action.keys || action.key;
666
+ if (!chord) throw new Error('press needs `keys`');
667
+
668
+ const { modifiers, key } = this.parseChord(chord);
669
+ if (!key) throw new Error(`press could not find a key in "${chord}"`);
670
+
671
+ await this.showFocused(sessionId, page, { pulse: true });
672
+
673
+ for (const modifier of modifiers) await page.keyboard.down(modifier);
674
+ try {
675
+ await page.keyboard.press(key as KeyInput);
676
+ } finally {
677
+ for (const modifier of [...modifiers].reverse()) {
678
+ await page.keyboard.up(modifier).catch(() => {});
380
679
  }
680
+ }
681
+
682
+ return `pressed ${chord}`;
683
+ }
381
684
 
382
- default:
383
- debug.warn('preview', `⚠️ Unknown action type: ${(action as any).type}`);
685
+ case 'paste': {
686
+ if (typeof action.text !== 'string') throw new Error('paste needs `text`');
687
+
688
+ await this.showFocused(sessionId, page, { pulse: true });
689
+
690
+ // Insert through CDP rather than synthesising Ctrl+V: the headless
691
+ // browser's clipboard is not the agent's, and insertText raises the
692
+ // same beforeinput/input events a real paste does.
693
+ const client = await page.createCDPSession();
694
+ try {
695
+ await client.send('Input.insertText', { text: action.text });
696
+ } finally {
697
+ await client.detach().catch(() => {});
384
698
  }
385
699
 
386
- // Fast delay between actions for MCP automation (50-100ms)
387
- const betweenActionDelay = 50 + Math.random() * 50;
700
+ return `pasted ${action.text.length} char(s)`;
701
+ }
388
702
 
389
- // Don't add delay after explicit wait actions
390
- if (action.type !== 'wait') {
391
- await sleep(betweenActionDelay);
703
+ case 'focus': {
704
+ const target = action.target ?? (action.selector ? { selector: action.selector } : undefined);
705
+ if (!target) throw new Error('focus needs a target');
706
+
707
+ const handle = await resolveHandle(page, target, { scrollIntoView: !action.noScroll });
708
+ if (!handle) throw new Error('focus found no visible element');
709
+ try {
710
+ await this.showHandle(sessionId, handle, { pulse: true });
711
+ await handle.evaluate((el) => (el as HTMLElement).focus());
712
+ } finally {
713
+ await handle.dispose().catch(() => {});
392
714
  }
393
715
 
394
- } catch (error) {
395
- debug.error('preview', `❌ Error performing action ${action.type}:`, error);
716
+ return `focused ${target.selector ?? target.text}`;
717
+ }
396
718
 
397
- // Check if error is due to closed page/browser
398
- const errorMessage = (error as Error)?.message || '';
399
- if (errorMessage.includes('Target page, context or browser has been closed') ||
400
- errorMessage.includes('Browser has been closed') ||
401
- errorMessage.includes('Page has been closed')) {
719
+ case 'clear': {
720
+ const target = action.target ?? (action.selector ? { selector: action.selector } : undefined);
721
+ if (target) {
722
+ const point = await this.pointFor(page, action, target);
723
+ await this.glideTo(sessionId, page, point, { steps: 6 });
724
+ this.publishClick(sessionId, point.x, point.y);
725
+ await page.mouse.click(point.x, point.y);
726
+ await sleep(40);
727
+ } else {
728
+ await this.showFocused(sessionId, page, { pulse: true });
729
+ }
402
730
 
403
- debug.warn('preview', `⚠️ Browser/page closed during action ${i + 1}/${actions.length}, stopping autonomous actions`);
404
- return;
731
+ await page.keyboard.down('Control');
732
+ await page.keyboard.press('KeyA');
733
+ await page.keyboard.up('Control');
734
+ await page.keyboard.press('Backspace');
735
+
736
+ return 'cleared field';
737
+ }
738
+
739
+ case 'select_option': {
740
+ const target = action.target ?? (action.selector ? { selector: action.selector } : undefined);
741
+ if (!target) throw new Error('select_option needs a target');
742
+
743
+ const handle = await resolveHandle(page, target, { scrollIntoView: !action.noScroll });
744
+ if (!handle) throw new Error('select_option found no visible <select>');
745
+
746
+ try {
747
+ // The <select> is driven through the DOM because its popup is
748
+ // browser-owned, so the pointer is the only sign anything happened.
749
+ await this.showHandle(sessionId, handle, { pulse: true });
750
+
751
+ const chosen = await handle.evaluate(
752
+ (el, value, label, index) => {
753
+ const select = el as HTMLSelectElement;
754
+ if (select.tagName !== 'SELECT') return null;
755
+
756
+ const options = Array.from(select.options);
757
+ const match =
758
+ typeof index === 'number'
759
+ ? options[index]
760
+ : value !== undefined
761
+ ? options.find((o) => o.value === value)
762
+ : options.find((o) => o.textContent?.trim() === label) ??
763
+ options.find((o) => o.textContent?.trim().toLowerCase().includes(String(label).toLowerCase()));
764
+
765
+ if (!match) return null;
766
+
767
+ select.value = match.value;
768
+ // A programmatic value assignment fires nothing; frameworks
769
+ // bind to these two events, so both have to be raised.
770
+ select.dispatchEvent(new Event('input', { bubbles: true }));
771
+ select.dispatchEvent(new Event('change', { bubbles: true }));
772
+ return { value: match.value, label: match.textContent?.trim() ?? '' };
773
+ },
774
+ action.value,
775
+ action.label,
776
+ action.index
777
+ );
778
+
779
+ if (!chosen) throw new Error('No matching <option> (or the target was not a <select>)');
780
+ return `selected "${chosen.label}" (${chosen.value})`;
781
+ } finally {
782
+ await handle.dispose().catch(() => {});
405
783
  }
784
+ }
785
+
786
+ case 'upload': {
787
+ const target = action.target ?? (action.selector ? { selector: action.selector } : undefined);
788
+ if (!target) throw new Error('upload needs a target');
789
+ if (!action.files?.length) throw new Error('upload needs `files`');
790
+
791
+ const handle = await resolveHandle(page, target, { scrollIntoView: !action.noScroll });
792
+ if (!handle) throw new Error('upload found no visible file input');
406
793
 
407
- // Continue with next action for other errors
794
+ try {
795
+ await this.showHandle(sessionId, handle, { pulse: true });
796
+ await (handle as ElementHandle<HTMLInputElement>).uploadFile(...action.files);
797
+ return `uploaded ${action.files.length} file(s)`;
798
+ } finally {
799
+ await handle.dispose().catch(() => {});
800
+ }
408
801
  }
409
- }
410
802
 
803
+ case 'tap': {
804
+ const point = await this.pointFor(page, action);
805
+ // Overlay only — a real mouse move before a touch gesture would add
806
+ // a hover the agent never asked for, on exactly the mobile layouts
807
+ // where hover and touch take different code paths.
808
+ await this.glideOverlay(sessionId, point);
809
+ await this.withTouch(page, async (client) => {
810
+ await client.send('Input.dispatchTouchEvent', {
811
+ type: 'touchStart',
812
+ touchPoints: [{ x: point.x, y: point.y, id: 1 }]
813
+ });
814
+ await sleep(action.holdMs ?? 60);
815
+ await client.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
816
+ });
817
+ this.publishClick(sessionId, point.x, point.y);
818
+ this.publishCursor(sessionId, point.x, point.y);
411
819
 
412
- // Emit test completed event to hide virtual cursor
413
- this.emit('test-completed', {
414
- sessionId: session.id,
415
- timestamp: Date.now()
416
- });
820
+ return `tap at ${point.described}`;
821
+ }
822
+
823
+ case 'swipe': {
824
+ const fromTarget = action.from ?? action.target;
825
+ const toTarget = action.to;
826
+ if (!fromTarget || !toTarget) throw new Error('swipe needs both `from` and `to`');
827
+
828
+ const from = await resolveTarget(page, fromTarget, { scrollIntoView: !action.noScroll });
829
+ const to = await resolveTarget(page, toTarget, { scrollIntoView: !action.noScroll });
830
+ const steps = action.steps ?? 12;
831
+ const totalMs = action.durationMs ?? 300;
832
+
833
+ // Walk to where the finger lands first, or the pointer teleports and
834
+ // the swipe reads as having started from nowhere.
835
+ await this.glideOverlay(sessionId, from);
836
+
837
+ await this.withTouch(page, async (client) => {
838
+ await client.send('Input.dispatchTouchEvent', {
839
+ type: 'touchStart',
840
+ touchPoints: [{ x: from.x, y: from.y, id: 1 }]
841
+ });
842
+
843
+ for (let s = 1; s <= steps; s++) {
844
+ const t = s / steps;
845
+ const x = Math.round(from.x + (to.x - from.x) * t);
846
+ const y = Math.round(from.y + (to.y - from.y) * t);
847
+ await client.send('Input.dispatchTouchEvent', {
848
+ type: 'touchMove',
849
+ touchPoints: [{ x, y, id: 1 }]
850
+ });
851
+ this.publishCursor(sessionId, x, y, true);
852
+ await sleep(totalMs / steps);
853
+ }
417
854
 
418
- return results;
855
+ await client.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
856
+ });
857
+ this.publishCursor(sessionId, to.x, to.y, false);
858
+
859
+ return `swipe ${from.described} → ${to.described}`;
860
+ }
861
+
862
+ case 'pinch': {
863
+ const centre = action.center ?? (await this.pointFor(page, action).catch(() => null)) ?? {
864
+ x: page.viewport()?.width ? page.viewport()!.width / 2 : 400,
865
+ y: page.viewport()?.height ? page.viewport()!.height / 2 : 300
866
+ };
867
+ const scale = action.scale ?? 2;
868
+ const steps = action.steps ?? 10;
869
+ const startSpread = 60;
870
+ const endSpread = Math.max(10, startSpread * scale);
871
+
872
+ await this.glideOverlay(sessionId, centre);
873
+
874
+ await this.withTouch(page, async (client) => {
875
+ const points = (spread: number) => [
876
+ { x: Math.round(centre.x - spread), y: Math.round(centre.y), id: 1 },
877
+ { x: Math.round(centre.x + spread), y: Math.round(centre.y), id: 2 }
878
+ ];
879
+
880
+ await client.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: points(startSpread) });
881
+ // Two fingers, one overlay pointer: held at the centre for the
882
+ // duration, which at least says where the gesture is anchored.
883
+ this.publishCursor(sessionId, centre.x, centre.y, true);
884
+
885
+ for (let s = 1; s <= steps; s++) {
886
+ const spread = startSpread + (endSpread - startSpread) * (s / steps);
887
+ await client.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: points(spread) });
888
+ await sleep((action.durationMs ?? 300) / steps);
889
+ }
890
+ await client.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
891
+ });
892
+ this.publishCursor(sessionId, centre.x, centre.y, false);
893
+
894
+ return `pinch ×${scale} at (${Math.round(centre.x)}, ${Math.round(centre.y)})`;
895
+ }
896
+
897
+ default:
898
+ throw new Error(`Unknown action type: ${(action as BrowserAutonomousAction).type}`);
899
+ }
419
900
  }
420
901
 
902
+ /**
903
+ * Read text or a value out of the page.
904
+ *
905
+ * The identifier is deliberately forgiving — agents pass `username`,
906
+ * `#username` and `[name="username"]` interchangeably — so every plausible
907
+ * spelling is tried before reporting a miss.
908
+ */
909
+ private async extractData(
910
+ page: Page,
911
+ identifier: string,
912
+ attribute?: string,
913
+ all?: boolean
914
+ ): Promise<{ data: unknown; selector: string | null; attribute?: string; error?: string }> {
915
+ const result = await page.evaluate(
916
+ (id: string, attr: string | undefined, wantAll: boolean | undefined) => {
917
+ const selectors = [
918
+ id,
919
+ `#${id}`,
920
+ `.${id}`,
921
+ `[id="${id}"]`,
922
+ `[id*="${id}"]`,
923
+ `[class*="${id}"]`,
924
+ `[data-testid="${id}"]`,
925
+ `[name="${id}"]`
926
+ ];
927
+
928
+ let elements: Element[] = [];
929
+ let usedSelector = '';
930
+
931
+ for (const selector of selectors) {
932
+ try {
933
+ const found = Array.from(document.querySelectorAll(selector));
934
+ if (found.length > 0) {
935
+ elements = found;
936
+ usedSelector = selector;
937
+ break;
938
+ }
939
+ } catch {
940
+ continue;
941
+ }
942
+ }
943
+
944
+ if (elements.length === 0) {
945
+ return { data: null, selector: null, attribute: null, tried: selectors.slice(0, 5) };
946
+ }
947
+
948
+ const readOne = (el: Element): { value: string | null; via: string } => {
949
+ if (attr) return { value: el.getAttribute(attr), via: attr };
950
+
951
+ const candidates: Array<{ name: string; read: () => string | undefined }> = [
952
+ { name: 'value', read: () => (el as HTMLInputElement).value },
953
+ { name: 'textContent', read: () => el.textContent?.trim() },
954
+ { name: 'innerText', read: () => (el as HTMLElement).innerText?.trim() },
955
+ { name: 'innerHTML', read: () => el.innerHTML?.trim() }
956
+ ];
957
+
958
+ for (const candidate of candidates) {
959
+ try {
960
+ const value = candidate.read();
961
+ if (value && value.length > 0) return { value, via: candidate.name };
962
+ } catch {
963
+ continue;
964
+ }
965
+ }
966
+ return { value: null, via: '' };
967
+ };
968
+
969
+ if (wantAll) {
970
+ const values = elements.map((el) => readOne(el).value).filter((v) => v !== null);
971
+ return { data: values, selector: usedSelector, attribute: attr ?? 'auto', tried: [usedSelector] };
972
+ }
973
+
974
+ const single = readOne(elements[0]);
975
+ return { data: single.value, selector: usedSelector, attribute: single.via, tried: [usedSelector] };
976
+ },
977
+ identifier,
978
+ attribute,
979
+ all
980
+ );
981
+
982
+ if (result.data === null || (Array.isArray(result.data) && result.data.length === 0)) {
983
+ return {
984
+ data: null,
985
+ selector: result.selector,
986
+ error: `Element not found or empty. Tried selectors: ${result.tried.join(', ')}`
987
+ };
988
+ }
989
+
990
+ return { data: result.data, selector: result.selector, attribute: result.attribute ?? undefined };
991
+ }
421
992
  }