@mlola/backend-playwright 0.2.11 → 0.5.0
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.
- package/dist/backend.d.ts +1 -0
- package/dist/backend.d.ts.map +1 -1
- package/dist/backend.js +384 -85
- package/dist/backend.js.map +1 -1
- package/dist/snapshot-script.d.ts +5 -0
- package/dist/snapshot-script.d.ts.map +1 -1
- package/dist/snapshot-script.js +93 -15
- package/dist/snapshot-script.js.map +1 -1
- package/package.json +3 -3
package/dist/backend.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { callWebMcpTool } from "./snapshot-script.js";
|
|
2
|
-
import { webMcpCapability } from "@mlola/browser-backend";
|
|
2
|
+
import { DeadlineExceededError, webMcpCapability, withDeadline } from "@mlola/browser-backend";
|
|
3
3
|
/**
|
|
4
4
|
* Playwright browser backend (PRD §9.2, §9.3, §48).
|
|
5
5
|
*
|
|
@@ -11,7 +11,7 @@ import { mkdirSync, readFileSync } from "node:fs";
|
|
|
11
11
|
import { basename, join } from "node:path";
|
|
12
12
|
import { chromium, } from "playwright-core";
|
|
13
13
|
import { DEFAULT_BROWSER_CONFIG, RuntimeError, newSnapshotId, newTabId, } from "@mlola/browser-protocol";
|
|
14
|
-
import { collectSnapshot, probeDocument, validateTarget } from "./snapshot-script.js";
|
|
14
|
+
import { collectSnapshot, probeDocument, validateTarget, } from "./snapshot-script.js";
|
|
15
15
|
import { pageFn } from "./page-fn.js";
|
|
16
16
|
const CAPABILITIES = {
|
|
17
17
|
observe: true,
|
|
@@ -37,6 +37,41 @@ const CAPABILITIES = {
|
|
|
37
37
|
clipboard: false,
|
|
38
38
|
};
|
|
39
39
|
const MAX_DIAGNOSTICS = 40;
|
|
40
|
+
/** A hung tab or browser must not keep cleanup (and the run) from finishing. */
|
|
41
|
+
/**
|
|
42
|
+
* Fields masked in screenshots. Mirrors the snapshot's secret rule
|
|
43
|
+
* (snapshot-script.ts, SECRET_HINT) as closely as selectors allow: type,
|
|
44
|
+
* autocomplete, and name/id/label/placeholder hints, Indonesian included.
|
|
45
|
+
*/
|
|
46
|
+
const SECRET_FIELD_SELECTOR = [
|
|
47
|
+
'input[type="password" i]',
|
|
48
|
+
'input[autocomplete*="password" i]',
|
|
49
|
+
'input[autocomplete="one-time-code" i]',
|
|
50
|
+
'input[autocomplete^="cc-" i]',
|
|
51
|
+
...["pass", "otp", "cvv", "cvc", "card", "pin", "sandi"].flatMap((hint) => [
|
|
52
|
+
`input[name*="${hint}" i]`,
|
|
53
|
+
`input[id*="${hint}" i]`,
|
|
54
|
+
]),
|
|
55
|
+
].join(", ");
|
|
56
|
+
const SECRET_LABEL = /\b(password|passcode|otp|one[\s-]?time(?:\s+code)?|mfa|2fa|security\s+code|cvv2?|card\s*number|credit\s*card|kata\s+sandi|sandi|rahasia|pin|verifikasi)\b/i;
|
|
57
|
+
export const SCREENSHOT_MASK_COLOR = "#FF00FF";
|
|
58
|
+
const CLOSE_DEADLINE_MS = 5000;
|
|
59
|
+
/** Navigation races are retried after this pause, growing per attempt. */
|
|
60
|
+
const OBSERVE_RETRY_BASE_MS = 120;
|
|
61
|
+
/** A retry with less time left than this cannot read a page; it reports the navigation instead. */
|
|
62
|
+
const MIN_OBSERVE_ATTEMPT_MS = 250;
|
|
63
|
+
/** Auxiliary page round-trips (titles, history, probes) are cheap or skipped. */
|
|
64
|
+
const AUX_DEADLINE_MS = 1500;
|
|
65
|
+
/** Child frames observed per page, and the node budget they share. */
|
|
66
|
+
const MAX_FRAMES = 8;
|
|
67
|
+
const MAX_FRAME_NODES = 200;
|
|
68
|
+
const FRAME_TEXT_CHARS = 600;
|
|
69
|
+
/**
|
|
70
|
+
* Id range per child-frame document (the main document counts from 1), wide
|
|
71
|
+
* enough that a long-lived, re-rendering main document never reaches it.
|
|
72
|
+
*/
|
|
73
|
+
const FRAME_ID_STRIDE = 1_000_000_000;
|
|
74
|
+
const NAVIGATION_RACE = /execution context was destroyed|cannot find context with specified id|frame was detached|navigating frame was detached|most likely because of a navigation/i;
|
|
40
75
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
41
76
|
export class PlaywrightBackend {
|
|
42
77
|
name = "playwright";
|
|
@@ -47,8 +82,17 @@ export class PlaywrightBackend {
|
|
|
47
82
|
#pages = [];
|
|
48
83
|
#activeTab;
|
|
49
84
|
#cdp = new Map();
|
|
85
|
+
/** The latest observation's nodes; `frame` is set for nodes inside a child frame. */
|
|
50
86
|
#nodeIndex = new Map();
|
|
51
|
-
#
|
|
87
|
+
#observeSeq = 0;
|
|
88
|
+
/** Per child-frame document: navigation token and the node id range of its bridge. */
|
|
89
|
+
#frameDocs = new WeakMap();
|
|
90
|
+
#frameDocCounter = 0;
|
|
91
|
+
/**
|
|
92
|
+
* Open native dialogs, per tab: a confirm() in a background tab blocks that
|
|
93
|
+
* tab only, and must neither block nor be answered by work on the active one.
|
|
94
|
+
*/
|
|
95
|
+
#dialogs = new Map();
|
|
52
96
|
#dialogWaiters = new Set();
|
|
53
97
|
#dialogDiagnostics = [];
|
|
54
98
|
#pendingFileChooser;
|
|
@@ -62,9 +106,17 @@ export class PlaywrightBackend {
|
|
|
62
106
|
#screenshotsDir = "";
|
|
63
107
|
#closeDiagnostics = [];
|
|
64
108
|
#humanHandler;
|
|
109
|
+
/** Why the browser is gone, when it went away without stopSession. */
|
|
110
|
+
#crashed;
|
|
111
|
+
#stopping = false;
|
|
112
|
+
/** Increments per session, so a late event from a previous browser is ignored. */
|
|
113
|
+
#sessionSeq = 0;
|
|
65
114
|
/* ─────────────────────────────── session ──────────────────────────────── */
|
|
66
115
|
async startSession(input) {
|
|
67
116
|
this.#config = { ...DEFAULT_BROWSER_CONFIG, ...input.browser };
|
|
117
|
+
this.#crashed = undefined;
|
|
118
|
+
this.#stopping = false;
|
|
119
|
+
const sessionSeq = ++this.#sessionSeq;
|
|
68
120
|
this.#artifactsDir = input.artifactsDir;
|
|
69
121
|
this.#screenshotsDir = input.screenshotsDir ?? join(input.artifactsDir, "screenshots");
|
|
70
122
|
mkdirSync(this.#artifactsDir, { recursive: true });
|
|
@@ -89,6 +141,15 @@ export class PlaywrightBackend {
|
|
|
89
141
|
const context = this.#context;
|
|
90
142
|
if (!context)
|
|
91
143
|
throw new RuntimeError("INTERNAL", "failed to create a browser context");
|
|
144
|
+
// Without this, a killed or crashed browser surfaces as an opaque error from
|
|
145
|
+
// whatever call happens next, and the recovery ladder keeps re-observing a
|
|
146
|
+
// browser that no longer exists.
|
|
147
|
+
const markGone = (reason) => {
|
|
148
|
+
if (sessionSeq === this.#sessionSeq && !this.#stopping)
|
|
149
|
+
this.#crashed ??= reason;
|
|
150
|
+
};
|
|
151
|
+
this.#browser?.on("disconnected", () => markGone("the browser disconnected (closed or crashed)"));
|
|
152
|
+
context.on("close", () => markGone("the browser context was closed"));
|
|
92
153
|
context.on("page", (page) => {
|
|
93
154
|
this.#registerPage(page, "agent_created", true);
|
|
94
155
|
});
|
|
@@ -141,8 +202,12 @@ export class PlaywrightBackend {
|
|
|
141
202
|
}
|
|
142
203
|
}
|
|
143
204
|
#launchOptions() {
|
|
205
|
+
const handleSignals = this.#config.handleSignals ?? true;
|
|
144
206
|
return {
|
|
145
207
|
headless: this.#config.headless ?? false,
|
|
208
|
+
handleSIGINT: handleSignals,
|
|
209
|
+
handleSIGTERM: handleSignals,
|
|
210
|
+
handleSIGHUP: handleSignals,
|
|
146
211
|
...(this.#config.executablePath ? { executablePath: this.#config.executablePath } : {}),
|
|
147
212
|
...(this.#config.slowMoMs ? { slowMo: this.#config.slowMoMs } : {}),
|
|
148
213
|
args: ["--no-first-run", "--no-default-browser-check"],
|
|
@@ -169,10 +234,17 @@ export class PlaywrightBackend {
|
|
|
169
234
|
};
|
|
170
235
|
this.#pages.push(state);
|
|
171
236
|
page.on("framenavigated", (frame) => {
|
|
172
|
-
if (frame
|
|
173
|
-
|
|
174
|
-
this.#
|
|
237
|
+
if (frame !== page.mainFrame()) {
|
|
238
|
+
// A new document in a child frame: its old node ids mean nothing now.
|
|
239
|
+
this.#frameDocs.delete(frame);
|
|
240
|
+
return;
|
|
175
241
|
}
|
|
242
|
+
state.token = `p${++this.#navCounter}`;
|
|
243
|
+
this.#dialogs.delete(page);
|
|
244
|
+
// The index describes the active tab's last observation; a background
|
|
245
|
+
// tab navigating says nothing about it.
|
|
246
|
+
if (state.tabId === this.#activeTab)
|
|
247
|
+
this.#nodeIndex.clear();
|
|
176
248
|
});
|
|
177
249
|
page.on("dialog", (dialog) => {
|
|
178
250
|
if (dialog.type() === "alert") {
|
|
@@ -185,9 +257,9 @@ export class PlaywrightBackend {
|
|
|
185
257
|
});
|
|
186
258
|
return;
|
|
187
259
|
}
|
|
188
|
-
this.#
|
|
260
|
+
this.#dialogs.set(page, dialog);
|
|
189
261
|
for (const notify of this.#dialogWaiters)
|
|
190
|
-
notify();
|
|
262
|
+
notify(page);
|
|
191
263
|
});
|
|
192
264
|
page.on("console", (msg) => {
|
|
193
265
|
if (msg.type() !== "error" && msg.type() !== "warning")
|
|
@@ -213,7 +285,11 @@ export class PlaywrightBackend {
|
|
|
213
285
|
page.on("filechooser", (chooser) => {
|
|
214
286
|
this.#pendingFileChooser = chooser;
|
|
215
287
|
});
|
|
288
|
+
page.on("crash", () => {
|
|
289
|
+
state.crashed = true;
|
|
290
|
+
});
|
|
216
291
|
page.on("close", () => {
|
|
292
|
+
this.#dialogs.delete(page);
|
|
217
293
|
this.#pages = this.#pages.filter((p) => p.page !== page);
|
|
218
294
|
if (this.#activeTab === state.tabId)
|
|
219
295
|
this.#activeTab = this.#pages[0]?.tabId;
|
|
@@ -226,14 +302,15 @@ export class PlaywrightBackend {
|
|
|
226
302
|
list.shift();
|
|
227
303
|
}
|
|
228
304
|
async stopSession(_sessionId) {
|
|
305
|
+
this.#stopping = true;
|
|
229
306
|
const closedTabs = [];
|
|
230
307
|
const errors = [...this.#closeDiagnostics];
|
|
231
308
|
const returned = [];
|
|
232
309
|
// A modal dialog blocks the page; release it so tabs can actually close.
|
|
233
|
-
|
|
234
|
-
await
|
|
235
|
-
this.#pendingDialog = undefined;
|
|
310
|
+
for (const dialog of this.#dialogs.values()) {
|
|
311
|
+
await withDeadline(dialog.dismiss(), AUX_DEADLINE_MS, "dialog dismiss").catch(() => undefined);
|
|
236
312
|
}
|
|
313
|
+
this.#dialogs.clear();
|
|
237
314
|
const context = this.#context;
|
|
238
315
|
const browser = this.#browser;
|
|
239
316
|
this.#context = undefined;
|
|
@@ -247,24 +324,25 @@ export class PlaywrightBackend {
|
|
|
247
324
|
continue;
|
|
248
325
|
}
|
|
249
326
|
try {
|
|
250
|
-
await state.page.close({ runBeforeUnload: false });
|
|
327
|
+
await withDeadline(state.page.close({ runBeforeUnload: false }), CLOSE_DEADLINE_MS, `close ${state.tabId}`);
|
|
251
328
|
closedTabs.push(state.tabId);
|
|
252
329
|
}
|
|
253
330
|
catch (err) {
|
|
254
331
|
errors.push(`failed to close ${state.tabId}: ${String(err)}`);
|
|
255
332
|
}
|
|
256
333
|
}
|
|
257
|
-
await context.close().catch((err) => errors.push(`context close: ${String(err)}`));
|
|
334
|
+
await withDeadline(context.close(), CLOSE_DEADLINE_MS, "context close").catch((err) => errors.push(`context close: ${String(err)}`));
|
|
335
|
+
}
|
|
336
|
+
if (browser) {
|
|
337
|
+
await withDeadline(browser.close(), CLOSE_DEADLINE_MS, "browser close").catch((err) => errors.push(`browser close: ${String(err)}`));
|
|
258
338
|
}
|
|
259
|
-
if (browser)
|
|
260
|
-
await browser.close().catch((err) => errors.push(`browser close: ${String(err)}`));
|
|
261
339
|
}
|
|
262
340
|
finally {
|
|
263
341
|
this.#pages = [];
|
|
264
342
|
this.#activeTab = undefined;
|
|
265
343
|
this.#cdp.clear();
|
|
266
344
|
this.#nodeIndex.clear();
|
|
267
|
-
this.#
|
|
345
|
+
this.#dialogs.clear();
|
|
268
346
|
this.#pendingFileChooser = undefined;
|
|
269
347
|
this.#downloads = [];
|
|
270
348
|
}
|
|
@@ -282,56 +360,215 @@ export class PlaywrightBackend {
|
|
|
282
360
|
/* ────────────────────────────── observation ───────────────────────────── */
|
|
283
361
|
async observe(sessionId) {
|
|
284
362
|
void sessionId;
|
|
285
|
-
const
|
|
286
|
-
const
|
|
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
|
-
|
|
363
|
+
const budgetMs = this.#config.observeTimeoutMs ?? 10_000;
|
|
364
|
+
const deadline = Date.now() + budgetMs;
|
|
365
|
+
// A caller may abandon this observation at its own deadline and start
|
|
366
|
+
// another; only the newest observation may replace the node index.
|
|
367
|
+
const seq = ++this.#observeSeq;
|
|
368
|
+
let lastRace;
|
|
369
|
+
// A document that navigates while it is being read (client-side redirects,
|
|
370
|
+
// SSO hops, reloads) destroys the execution context mid-evaluate. That is
|
|
371
|
+
// the page moving on, not a failure: wait for the next document and read
|
|
372
|
+
// that one, within the observation deadline.
|
|
373
|
+
for (let attempt = 1;; attempt += 1) {
|
|
374
|
+
const state = this.#requireActive();
|
|
375
|
+
const dialog = this.#dialogs.get(state.page);
|
|
376
|
+
if (dialog)
|
|
377
|
+
return this.#dialogSnapshot(state, dialog);
|
|
378
|
+
// Waiting for the next document used up the budget: the page kept
|
|
379
|
+
// navigating, which is not the same as a page that stopped answering.
|
|
380
|
+
if (lastRace !== undefined && deadline - Date.now() < MIN_OBSERVE_ATTEMPT_MS) {
|
|
381
|
+
throw new RuntimeError("PAGE_MUTATED", `the page kept navigating for ${budgetMs}ms: ${lastRace}`, {
|
|
382
|
+
retryable: true,
|
|
383
|
+
evidence: { attempts: attempt - 1 },
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
try {
|
|
387
|
+
const collected = await withDeadline(state.page.evaluate(pageFn(collectSnapshot), {
|
|
388
|
+
generation: this.#generation + 1,
|
|
389
|
+
token: state.token,
|
|
390
|
+
maxNodes: 900,
|
|
391
|
+
maxText: 2400,
|
|
392
|
+
}), deadline - Date.now(), "observation");
|
|
393
|
+
const frames = await this.#collectFrames(state, collected.nodes.length, deadline);
|
|
394
|
+
return await this.#snapshotFrom(state, collected, frames, seq === this.#observeSeq);
|
|
395
|
+
}
|
|
396
|
+
catch (err) {
|
|
397
|
+
this.#throwIfCrashed(state);
|
|
398
|
+
if (err instanceof DeadlineExceededError) {
|
|
399
|
+
throw new RuntimeError("PAGE_UNRESPONSIVE", `the page did not answer an observation within ${budgetMs}ms`, {
|
|
400
|
+
cause: err,
|
|
401
|
+
evidence: { attempts: attempt },
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
405
|
+
const raced = NAVIGATION_RACE.test(message) || state.page.isClosed();
|
|
406
|
+
const pause = Math.min(OBSERVE_RETRY_BASE_MS * attempt, 600);
|
|
407
|
+
if (raced && Date.now() + pause < deadline) {
|
|
408
|
+
lastRace = message.split("\n")[0];
|
|
409
|
+
await sleep(pause);
|
|
410
|
+
await withDeadline(state.page.waitForLoadState("domcontentloaded"), Math.max(1, Math.min(2000, deadline - Date.now())), "load").catch(() => undefined);
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
throw new RuntimeError("PAGE_MUTATED", `observation failed: ${message}`, {
|
|
414
|
+
cause: err,
|
|
415
|
+
retryable: true,
|
|
416
|
+
evidence: { attempts: attempt },
|
|
417
|
+
});
|
|
418
|
+
}
|
|
327
419
|
}
|
|
328
|
-
|
|
329
|
-
|
|
420
|
+
}
|
|
421
|
+
#dialogSnapshot(state, dialog) {
|
|
422
|
+
const page = state.page;
|
|
423
|
+
const message = dialog.message().slice(0, 300);
|
|
424
|
+
const tabs = this.#tabInfosWithoutTitles();
|
|
425
|
+
return {
|
|
426
|
+
snapshotId: newSnapshotId(),
|
|
427
|
+
generation: ++this.#generation,
|
|
428
|
+
capturedAt: Date.now(),
|
|
429
|
+
pageToken: state.token,
|
|
430
|
+
url: page.url(),
|
|
431
|
+
title: "",
|
|
432
|
+
readyState: "complete",
|
|
433
|
+
textSummary: "",
|
|
434
|
+
injectedTexts: [],
|
|
435
|
+
nodes: [],
|
|
436
|
+
viewport: { width: 0, height: 0, scrollX: 0, scrollY: 0, documentWidth: 0, documentHeight: 0 },
|
|
437
|
+
tabs,
|
|
438
|
+
activeTabId: state.tabId,
|
|
439
|
+
blockingUi: {
|
|
440
|
+
kind: dialog.type() === "confirm"
|
|
441
|
+
? "confirm"
|
|
442
|
+
: dialog.type() === "prompt"
|
|
443
|
+
? "prompt"
|
|
444
|
+
: dialog.type() === "beforeunload"
|
|
445
|
+
? "beforeunload"
|
|
446
|
+
: "alert",
|
|
447
|
+
text: message,
|
|
448
|
+
nodeIndexes: [],
|
|
449
|
+
provenance: "browser_runtime",
|
|
450
|
+
},
|
|
451
|
+
fingerprint: `dialog:${dialog.type()}:${message.length}`,
|
|
452
|
+
history: { canGoBack: false, canGoForward: false },
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Same-origin child frames (embedded forms, statements, help widgets): each is
|
|
457
|
+
* read with the same page function and merged into the page's observation,
|
|
458
|
+
* with geometry translated into the top viewport. Cross-origin frames are not
|
|
459
|
+
* read; a frame that is mid-navigation or unreadable is skipped, never fatal.
|
|
460
|
+
*/
|
|
461
|
+
async #collectFrames(state, mainNodes, deadline) {
|
|
462
|
+
const page = state.page;
|
|
463
|
+
const topOrigin = originOf(page.url());
|
|
464
|
+
const budget = Math.min(MAX_FRAME_NODES, Math.max(0, 900 - mainNodes));
|
|
465
|
+
if (budget === 0)
|
|
466
|
+
return [];
|
|
467
|
+
const frames = page
|
|
468
|
+
.frames()
|
|
469
|
+
.filter((frame) => frame !== page.mainFrame() && !frame.isDetached())
|
|
470
|
+
.filter((frame) => {
|
|
471
|
+
const url = frame.url();
|
|
472
|
+
return url.startsWith("about:") || (topOrigin !== undefined && originOf(url) === topOrigin);
|
|
473
|
+
})
|
|
474
|
+
.slice(0, MAX_FRAMES);
|
|
475
|
+
const out = [];
|
|
476
|
+
const offsets = new Map();
|
|
477
|
+
const offsetOf = async (frame) => {
|
|
478
|
+
if (offsets.has(frame))
|
|
479
|
+
return offsets.get(frame);
|
|
480
|
+
let result;
|
|
481
|
+
try {
|
|
482
|
+
const parent = frame.parentFrame();
|
|
483
|
+
const element = await withDeadline(frame.frameElement(), AUX_DEADLINE_MS, "frame element");
|
|
484
|
+
const box = await withDeadline(element.evaluate(pageFn((el) => {
|
|
485
|
+
const r = el.getBoundingClientRect();
|
|
486
|
+
const style = getComputedStyle(el);
|
|
487
|
+
const hidden = style.visibility === "hidden" || style.display === "none";
|
|
488
|
+
return {
|
|
489
|
+
x: r.left + el.clientLeft + parseFloat(style.paddingLeft || "0"),
|
|
490
|
+
y: r.top + el.clientTop + parseFloat(style.paddingTop || "0"),
|
|
491
|
+
width: hidden ? 0 : el.clientWidth,
|
|
492
|
+
height: hidden ? 0 : el.clientHeight,
|
|
493
|
+
};
|
|
494
|
+
})), AUX_DEADLINE_MS, "frame box");
|
|
495
|
+
const parentOffset = parent && parent !== page.mainFrame() ? await offsetOf(parent) : { x: 0, y: 0, width: 1, height: 1 };
|
|
496
|
+
if (parentOffset && box.width > 0 && box.height > 0) {
|
|
497
|
+
result = { x: Math.round(box.x + parentOffset.x), y: Math.round(box.y + parentOffset.y), width: box.width, height: box.height };
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
catch {
|
|
501
|
+
result = undefined;
|
|
502
|
+
}
|
|
503
|
+
offsets.set(frame, result);
|
|
504
|
+
return result;
|
|
505
|
+
};
|
|
506
|
+
let remaining = budget;
|
|
507
|
+
for (const frame of frames) {
|
|
508
|
+
if (remaining <= 0 || Date.now() >= deadline)
|
|
509
|
+
break;
|
|
510
|
+
const offset = await offsetOf(frame);
|
|
511
|
+
if (!offset)
|
|
512
|
+
continue; // hidden, zero-sized or gone
|
|
513
|
+
let doc = this.#frameDocs.get(frame);
|
|
514
|
+
if (!doc) {
|
|
515
|
+
doc = { token: `f${++this.#frameDocCounter}`, idBase: this.#frameDocCounter * FRAME_ID_STRIDE };
|
|
516
|
+
this.#frameDocs.set(frame, doc);
|
|
517
|
+
}
|
|
518
|
+
try {
|
|
519
|
+
const collected = await withDeadline(frame.evaluate(pageFn(collectSnapshot), {
|
|
520
|
+
generation: this.#generation + 1,
|
|
521
|
+
token: doc.token,
|
|
522
|
+
maxNodes: remaining,
|
|
523
|
+
maxText: FRAME_TEXT_CHARS,
|
|
524
|
+
idBase: doc.idBase,
|
|
525
|
+
}), Math.max(1, Math.min(deadline - Date.now(), 3000)), "frame observation");
|
|
526
|
+
remaining -= collected.nodes.length;
|
|
527
|
+
out.push({ frame, token: doc.token, offset, collected });
|
|
528
|
+
}
|
|
529
|
+
catch {
|
|
530
|
+
// Mid-navigation, detached or busy: the frame is skipped this time.
|
|
531
|
+
}
|
|
330
532
|
}
|
|
533
|
+
return out;
|
|
534
|
+
}
|
|
535
|
+
async #snapshotFrom(state, collected, frames, current) {
|
|
536
|
+
const page = state.page;
|
|
331
537
|
this.#generation += 1;
|
|
332
|
-
|
|
538
|
+
// An abandoned observation still builds its snapshot (nobody reads it), but
|
|
539
|
+
// must not overwrite the index the newer observation's decision relies on.
|
|
540
|
+
const index = current ? this.#nodeIndex : new Map();
|
|
541
|
+
index.clear();
|
|
333
542
|
for (const node of collected.nodes) {
|
|
334
|
-
|
|
543
|
+
index.set(node.nodeId, { tag: node.tag, role: node.role, token: state.token });
|
|
544
|
+
}
|
|
545
|
+
const viewportWidth = collected.viewport.width;
|
|
546
|
+
const viewportHeight = collected.viewport.height;
|
|
547
|
+
let nextIndex = collected.nodes.length;
|
|
548
|
+
for (const { frame, token, offset, collected: inner } of frames) {
|
|
549
|
+
for (const node of inner.nodes) {
|
|
550
|
+
index.set(node.nodeId, { tag: node.tag, role: node.role, token: state.token, frame, frameToken: token });
|
|
551
|
+
node.index = ++nextIndex;
|
|
552
|
+
if (node.geometry) {
|
|
553
|
+
const g = node.geometry;
|
|
554
|
+
// Clipped by the frame's own box, then placed in the top viewport.
|
|
555
|
+
const insideFrame = g.x + g.width > 0 && g.y + g.height > 0 && g.x < offset.width && g.y < offset.height;
|
|
556
|
+
node.geometry = { ...g, x: g.x + offset.x, y: g.y + offset.y };
|
|
557
|
+
const top = node.geometry;
|
|
558
|
+
const onScreen = top.x + top.width > 0 && top.y + top.height > 0 && top.x < viewportWidth && top.y < viewportHeight;
|
|
559
|
+
node.flags = { ...node.flags, offscreen: node.flags.offscreen || !insideFrame || !onScreen };
|
|
560
|
+
if (node.documentRect) {
|
|
561
|
+
node.documentRect = { ...node.documentRect, x: top.x + collected.viewport.scrollX, y: top.y + collected.viewport.scrollY };
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
collected.nodes.push(node);
|
|
565
|
+
}
|
|
566
|
+
const text = inner.textSummary.trim();
|
|
567
|
+
if (text.length > 0) {
|
|
568
|
+
collected.textSummary = `${collected.textSummary} [frame] ${text}`.slice(0, collected.textSummary.length + FRAME_TEXT_CHARS + 9);
|
|
569
|
+
}
|
|
570
|
+
collected.injectedTexts.push(...inner.injectedTexts.slice(0, 4));
|
|
571
|
+
collected.fingerprint = `${collected.fingerprint}+${inner.fingerprint}`;
|
|
335
572
|
}
|
|
336
573
|
const history = await this.#history(page);
|
|
337
574
|
const tabs = await this.#tabInfos();
|
|
@@ -394,8 +631,8 @@ export class PlaywrightBackend {
|
|
|
394
631
|
}
|
|
395
632
|
async #history(page) {
|
|
396
633
|
try {
|
|
397
|
-
const cdp = await this.#cdpSession(page);
|
|
398
|
-
const result = (await cdp.send("Page.getNavigationHistory"));
|
|
634
|
+
const cdp = await withDeadline(this.#cdpSession(page), AUX_DEADLINE_MS, "cdp session");
|
|
635
|
+
const result = (await withDeadline(cdp.send("Page.getNavigationHistory"), AUX_DEADLINE_MS, "history"));
|
|
399
636
|
return {
|
|
400
637
|
canGoBack: result.currentIndex > 0,
|
|
401
638
|
canGoForward: result.currentIndex < result.entries.length - 1,
|
|
@@ -418,24 +655,27 @@ export class PlaywrightBackend {
|
|
|
418
655
|
return session;
|
|
419
656
|
}
|
|
420
657
|
async #tabInfos() {
|
|
421
|
-
|
|
422
|
-
|
|
658
|
+
// In parallel: one busy background tab costs one deadline, not one per tab.
|
|
659
|
+
return Promise.all(this.#pages.map(async (state) => {
|
|
423
660
|
let title = "";
|
|
424
661
|
try {
|
|
425
|
-
|
|
662
|
+
// A tab with an open dialog cannot answer until the dialog is resolved.
|
|
663
|
+
title =
|
|
664
|
+
state.page.isClosed() || this.#dialogs.has(state.page)
|
|
665
|
+
? ""
|
|
666
|
+
: await withDeadline(state.page.title(), AUX_DEADLINE_MS, "title");
|
|
426
667
|
}
|
|
427
668
|
catch {
|
|
428
669
|
title = "";
|
|
429
670
|
}
|
|
430
|
-
|
|
671
|
+
return {
|
|
431
672
|
id: state.tabId,
|
|
432
673
|
title: title.slice(0, 200),
|
|
433
674
|
url: state.page.isClosed() ? "" : state.page.url(),
|
|
434
675
|
active: state.tabId === this.#activeTab,
|
|
435
676
|
ownership: state.ownership,
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
return infos;
|
|
677
|
+
};
|
|
678
|
+
}));
|
|
439
679
|
}
|
|
440
680
|
/** Tab list that never round-trips to a page (safe while a dialog blocks). */
|
|
441
681
|
#tabInfosWithoutTitles() {
|
|
@@ -450,7 +690,7 @@ export class PlaywrightBackend {
|
|
|
450
690
|
/* ─────────────────────────────── preflight ────────────────────────────── */
|
|
451
691
|
async preflight(_sessionId, action) {
|
|
452
692
|
const state = this.#requireActive();
|
|
453
|
-
if (this.#
|
|
693
|
+
if (this.#dialogs.has(state.page)) {
|
|
454
694
|
if (action.op === "ACCEPT_DIALOG" || action.op === "DISMISS_DIALOG" || action.op === "WAIT") {
|
|
455
695
|
return { ok: true };
|
|
456
696
|
}
|
|
@@ -479,7 +719,14 @@ export class PlaywrightBackend {
|
|
|
479
719
|
}
|
|
480
720
|
const needsEditable = action.op === "TYPE_TEXT";
|
|
481
721
|
const requireHitTarget = action.op === "CLICK" || action.op === "DOWNLOAD" || action.op === "OPEN_TAB";
|
|
482
|
-
|
|
722
|
+
if (evidence.frame) {
|
|
723
|
+
const current = this.#frameDocs.get(evidence.frame);
|
|
724
|
+
if (evidence.frame.isDetached() || current?.token !== evidence.frameToken) {
|
|
725
|
+
return { ok: false, code: "STALE_DECISION", detail: "the frame holding the target changed since the observation" };
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
const scope = evidence.frame ?? state.page;
|
|
729
|
+
const result = await withDeadline(scope.evaluate(pageFn(validateTarget), {
|
|
483
730
|
nodeId: ref.nodeId,
|
|
484
731
|
pageToken: state.token,
|
|
485
732
|
expectedToken: ref.pageToken,
|
|
@@ -489,6 +736,18 @@ export class PlaywrightBackend {
|
|
|
489
736
|
...(action.op === "SELECT" ? { optionValue: action.option.value, optionIndex: action.option.index } : {}),
|
|
490
737
|
...(needsEditable ? { editableOnly: true } : {}),
|
|
491
738
|
...(requireHitTarget ? { requireHitTarget: true } : {}),
|
|
739
|
+
}), this.#config.actionTimeoutMs ?? 10_000, "preflight").catch((err) => {
|
|
740
|
+
this.#throwIfCrashed(state);
|
|
741
|
+
if (err instanceof DeadlineExceededError) {
|
|
742
|
+
return { ok: false, code: "PAGE_UNRESPONSIVE", detail: err.message };
|
|
743
|
+
}
|
|
744
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
745
|
+
// The document changed under the decision: the target belongs to a page
|
|
746
|
+
// that no longer exists, which is exactly what STALE_DECISION means.
|
|
747
|
+
if (NAVIGATION_RACE.test(message)) {
|
|
748
|
+
return { ok: false, code: "STALE_DECISION", detail: "the page navigated before the action could run" };
|
|
749
|
+
}
|
|
750
|
+
throw err;
|
|
492
751
|
});
|
|
493
752
|
if (!result.ok) {
|
|
494
753
|
return {
|
|
@@ -527,7 +786,8 @@ export class PlaywrightBackend {
|
|
|
527
786
|
: ref;
|
|
528
787
|
return el ?? null;
|
|
529
788
|
});
|
|
530
|
-
const
|
|
789
|
+
const scope = this.#nodeIndex.get(nodeId)?.frame ?? page;
|
|
790
|
+
const handle = await withDeadline(scope.evaluateHandle(resolver, nodeId), timeout, "target lookup");
|
|
531
791
|
const element = handle.asElement();
|
|
532
792
|
if (!element)
|
|
533
793
|
throw new RuntimeError("DETACHED_TARGET", "the target element is gone");
|
|
@@ -539,12 +799,15 @@ export class PlaywrightBackend {
|
|
|
539
799
|
* until the dialog is resolved (PRD §37).
|
|
540
800
|
*/
|
|
541
801
|
const act = async (operation) => {
|
|
542
|
-
if (this.#
|
|
802
|
+
if (this.#dialogs.has(page))
|
|
543
803
|
return "dialog";
|
|
544
804
|
const promise = operation();
|
|
545
805
|
let notify;
|
|
546
806
|
const signal = new Promise((resolve) => {
|
|
547
|
-
notify = () =>
|
|
807
|
+
notify = (from) => {
|
|
808
|
+
if (from === page)
|
|
809
|
+
resolve("dialog");
|
|
810
|
+
};
|
|
548
811
|
});
|
|
549
812
|
this.#dialogWaiters.add(notify);
|
|
550
813
|
try {
|
|
@@ -580,7 +843,7 @@ export class PlaywrightBackend {
|
|
|
580
843
|
if (pressed === "dialog")
|
|
581
844
|
detail = "submit opened a dialog";
|
|
582
845
|
}
|
|
583
|
-
if (!this.#
|
|
846
|
+
if (!this.#dialogs.has(page))
|
|
584
847
|
await this.#settle(page, true);
|
|
585
848
|
detail ??= `typed ${action.text.length} char(s)`;
|
|
586
849
|
break;
|
|
@@ -737,14 +1000,14 @@ export class PlaywrightBackend {
|
|
|
737
1000
|
}
|
|
738
1001
|
case "ACCEPT_DIALOG":
|
|
739
1002
|
case "DISMISS_DIALOG": {
|
|
740
|
-
const dialog = this.#
|
|
1003
|
+
const dialog = this.#dialogs.get(page);
|
|
741
1004
|
if (!dialog)
|
|
742
1005
|
throw new RuntimeError("STALE_DECISION", "no dialog is open");
|
|
743
1006
|
if (action.op === "ACCEPT_DIALOG")
|
|
744
1007
|
await dialog.accept();
|
|
745
1008
|
else
|
|
746
1009
|
await dialog.dismiss();
|
|
747
|
-
this.#
|
|
1010
|
+
this.#dialogs.delete(page);
|
|
748
1011
|
effect = "dialog_closed";
|
|
749
1012
|
detail = `dialog ${action.op === "ACCEPT_DIALOG" ? "accepted" : "dismissed"}`;
|
|
750
1013
|
break;
|
|
@@ -754,7 +1017,8 @@ export class PlaywrightBackend {
|
|
|
754
1017
|
}
|
|
755
1018
|
// Bounded settle + effect probe (PRD §26). While a native dialog is open the
|
|
756
1019
|
// renderer is blocked, so page round-trips must be skipped.
|
|
757
|
-
const
|
|
1020
|
+
const openDialog = this.#dialogs.get(page);
|
|
1021
|
+
const dialogOpen = openDialog !== undefined;
|
|
758
1022
|
if (!dialogOpen)
|
|
759
1023
|
await this.#settle(page, action.op === "TYPE_TEXT");
|
|
760
1024
|
const after = dialogOpen ? undefined : await this.#probe(page).catch(() => undefined);
|
|
@@ -780,9 +1044,9 @@ export class PlaywrightBackend {
|
|
|
780
1044
|
if (newest && newest.tabId !== state.tabId)
|
|
781
1045
|
newTabId = newest.tabId;
|
|
782
1046
|
}
|
|
783
|
-
if (
|
|
1047
|
+
if (openDialog && effect === "none") {
|
|
784
1048
|
effect = "dialog_opened";
|
|
785
|
-
dialog = { kind:
|
|
1049
|
+
dialog = { kind: openDialog.type(), text: openDialog.message().slice(0, 200) };
|
|
786
1050
|
}
|
|
787
1051
|
// Downloads started by this action: wait for completion and hand the file over.
|
|
788
1052
|
let downloadedFile;
|
|
@@ -868,7 +1132,17 @@ export class PlaywrightBackend {
|
|
|
868
1132
|
const state = this.#requireActive();
|
|
869
1133
|
const safeReason = reason.replace(/[^a-z0-9-]+/gi, "-").slice(0, 40);
|
|
870
1134
|
const path = join(this.#screenshotsDir, `${Date.now()}-${safeReason}.png`);
|
|
871
|
-
|
|
1135
|
+
// Screenshots are evidence that outlives the run, so secret fields are
|
|
1136
|
+
// painted over: a value a person typed during takeover must not end up in
|
|
1137
|
+
// a PNG next to the trace.
|
|
1138
|
+
const page = state.page;
|
|
1139
|
+
await page.screenshot({
|
|
1140
|
+
path,
|
|
1141
|
+
fullPage: false,
|
|
1142
|
+
timeout: this.#config.actionTimeoutMs ?? 10_000,
|
|
1143
|
+
mask: [page.locator(SECRET_FIELD_SELECTOR), page.getByLabel(SECRET_LABEL), page.getByPlaceholder(SECRET_LABEL)],
|
|
1144
|
+
maskColor: SCREENSHOT_MASK_COLOR,
|
|
1145
|
+
});
|
|
872
1146
|
const size = state.page.viewportSize() ?? { width: 0, height: 0 };
|
|
873
1147
|
return { path, width: size.width, height: size.height };
|
|
874
1148
|
}
|
|
@@ -879,7 +1153,7 @@ export class PlaywrightBackend {
|
|
|
879
1153
|
*/
|
|
880
1154
|
async callTool(_sessionId, toolId, args) {
|
|
881
1155
|
const state = this.#requireActive();
|
|
882
|
-
const outcome = await state.page.evaluate(pageFn(callWebMcpTool), { toolId, args });
|
|
1156
|
+
const outcome = await withDeadline(state.page.evaluate(pageFn(callWebMcpTool), { toolId, args }), this.#config.actionTimeoutMs ?? 10_000, `tool ${toolId}`).catch((err) => ({ ok: false, error: err instanceof Error ? err.message : String(err) }));
|
|
883
1157
|
if (!outcome.ok) {
|
|
884
1158
|
// Conservative: a tool call that failed for any reason may still have had an
|
|
885
1159
|
// effect, so the executor must re-observe before deciding to retry (§11).
|
|
@@ -889,13 +1163,29 @@ export class PlaywrightBackend {
|
|
|
889
1163
|
}
|
|
890
1164
|
/* ──────────────────────────────── helpers ─────────────────────────────── */
|
|
891
1165
|
#requireActive() {
|
|
1166
|
+
if (this.#crashed)
|
|
1167
|
+
throw new RuntimeError("BROWSER_CRASHED", this.#crashed, { retryable: false });
|
|
892
1168
|
const state = this.#pages.find((p) => p.tabId === this.#activeTab) ?? this.#pages[0];
|
|
893
1169
|
if (!state)
|
|
894
1170
|
throw new RuntimeError("INTERNAL", "no active browser tab");
|
|
1171
|
+
this.#throwIfCrashed(state);
|
|
895
1172
|
return state;
|
|
896
1173
|
}
|
|
1174
|
+
#throwIfCrashed(state) {
|
|
1175
|
+
if (this.#crashed)
|
|
1176
|
+
throw new RuntimeError("BROWSER_CRASHED", this.#crashed, { retryable: false });
|
|
1177
|
+
if (state.crashed) {
|
|
1178
|
+
throw new RuntimeError("BROWSER_CRASHED", `the renderer of ${state.tabId} crashed (out of memory or a browser bug)`, {
|
|
1179
|
+
retryable: false,
|
|
1180
|
+
evidence: { tabId: state.tabId, url: state.page.url() },
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
897
1184
|
async #probe(page) {
|
|
898
|
-
|
|
1185
|
+
// A modal dialog blocks the renderer; the probe would only wait out its deadline.
|
|
1186
|
+
if (this.#dialogs.has(page))
|
|
1187
|
+
return undefined;
|
|
1188
|
+
return withDeadline(page.evaluate(pageFn(probeDocument)), AUX_DEADLINE_MS, "probe").catch(() => undefined);
|
|
899
1189
|
}
|
|
900
1190
|
async #settle(page, waitForOptions) {
|
|
901
1191
|
const settleMs = this.#config.settleMs ?? 250;
|
|
@@ -978,4 +1268,13 @@ export class PlaywrightBackend {
|
|
|
978
1268
|
}
|
|
979
1269
|
}
|
|
980
1270
|
export const createPlaywrightBackend = () => new PlaywrightBackend();
|
|
1271
|
+
const originOf = (url) => {
|
|
1272
|
+
try {
|
|
1273
|
+
const origin = new URL(url).origin;
|
|
1274
|
+
return origin === "null" ? undefined : origin;
|
|
1275
|
+
}
|
|
1276
|
+
catch {
|
|
1277
|
+
return undefined;
|
|
1278
|
+
}
|
|
1279
|
+
};
|
|
981
1280
|
//# sourceMappingURL=backend.js.map
|