@capybara-hq/plugin-browser 0.1.0-rc.11 → 0.1.0-rc.13
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/.capybara-plugin/plugin.json +5 -4
- package/README.md +93 -3
- package/dist/index.mjs +417 -51
- package/package.json +2 -2
- package/ui/panel.js +304 -24
- package/ui/service/daemon.mjs +1458 -67
- package/ui/service/vendor/playwright-core/lib/coreBundle.js +30 -0
package/ui/service/daemon.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @capybara-hq/plugin-browser daemon (generated by daemon/build.ts)
|
|
2
2
|
|
|
3
|
-
// ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.
|
|
3
|
+
// ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.83/node_modules/@capybara-hq/plugin-sdk/dist/device-provider.js
|
|
4
4
|
var MAX_PATH_LENGTH = 4096;
|
|
5
5
|
var DEFAULT_SANDBOX_ROOTS = Object.freeze({
|
|
6
6
|
workspace: "/workspace",
|
|
@@ -43,7 +43,25 @@ var STOPS = /* @__PURE__ */ new Set([
|
|
|
43
43
|
"path must not contain empty segments"
|
|
44
44
|
]);
|
|
45
45
|
|
|
46
|
-
// ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.
|
|
46
|
+
// ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.83/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
|
|
47
|
+
var DEVICE_SERVICE_RESTORE_MAX_AGE_MS = 10 * 6e4;
|
|
48
|
+
function parseConversationDeleted(body) {
|
|
49
|
+
let msg;
|
|
50
|
+
try {
|
|
51
|
+
const text = typeof body === "string" ? body : new TextDecoder("utf-8", { fatal: true }).decode(body);
|
|
52
|
+
msg = JSON.parse(text);
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
if (typeof msg !== "object" || msg === null || Array.isArray(msg))
|
|
57
|
+
return null;
|
|
58
|
+
const { capybara, conversationId } = msg;
|
|
59
|
+
if (capybara !== "conversation-deleted")
|
|
60
|
+
return null;
|
|
61
|
+
if (typeof conversationId !== "string" || conversationId === "")
|
|
62
|
+
return null;
|
|
63
|
+
return { capybara: "conversation-deleted", conversationId };
|
|
64
|
+
}
|
|
47
65
|
var DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
|
|
48
66
|
var DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
|
|
49
67
|
var DEVICE_SERVICE_MACH_ENV = "CAPYBARA_SERVICE_MACH";
|
|
@@ -137,6 +155,7 @@ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSy
|
|
|
137
155
|
import { createServer } from "node:net";
|
|
138
156
|
|
|
139
157
|
// daemon/actions.ts
|
|
158
|
+
import { randomBytes } from "node:crypto";
|
|
140
159
|
import {
|
|
141
160
|
closeSync,
|
|
142
161
|
constants as fsc,
|
|
@@ -156,7 +175,38 @@ import { basename, extname, join, sep } from "node:path";
|
|
|
156
175
|
|
|
157
176
|
// daemon/protocol.ts
|
|
158
177
|
var ROLL_CHECK_REQUEST = '{"capybara":"roll-check"}';
|
|
178
|
+
var CONVERSATION_DELETED_MESSAGE = "This conversation was deleted; its browser tabs are closed.";
|
|
159
179
|
var VIEWPORT = { width: 1280, height: 800 };
|
|
180
|
+
var VIEWPORT_PROFILES = {
|
|
181
|
+
desktop: { width: VIEWPORT.width, height: VIEWPORT.height, mobile: false, scale: 1 },
|
|
182
|
+
phone: { width: 390, height: 844, mobile: true, scale: 2 }
|
|
183
|
+
};
|
|
184
|
+
var DIALOG_QUOTE_CHARS = 300;
|
|
185
|
+
function normalizeDialogText(text) {
|
|
186
|
+
return text.replace(/\r\n/g, "\n").replace(/\s+/g, " ").trim();
|
|
187
|
+
}
|
|
188
|
+
function dialogQuote(message) {
|
|
189
|
+
return clipCodePoints(normalizeDialogText(message), DIALOG_QUOTE_CHARS).trimEnd();
|
|
190
|
+
}
|
|
191
|
+
function dialogMessageMatches(given, message) {
|
|
192
|
+
return dialogQuote(given) === dialogQuote(message);
|
|
193
|
+
}
|
|
194
|
+
var AUTH_SIGN_IN_TEXT = "Signing in needs the user's credentials; call browser_handoff and ask the user to sign in.";
|
|
195
|
+
function blockedByDialogText(d) {
|
|
196
|
+
const name = d.kind === "beforeunload" ? "leave-page" : d.kind;
|
|
197
|
+
return `The page is blocked by a ${name} dialog ${d.id}: ${JSON.stringify(dialogQuote(d.message))}. Answer it with browser_dialog (dialogId ${d.id}, the message as quoted, accept or dismiss) to continue.`;
|
|
198
|
+
}
|
|
199
|
+
var REPORTED_PERMISSIONS = [
|
|
200
|
+
"notifications",
|
|
201
|
+
"clipboard-read",
|
|
202
|
+
"geolocation",
|
|
203
|
+
"camera",
|
|
204
|
+
"microphone"
|
|
205
|
+
];
|
|
206
|
+
var GRANTABLE_PERMISSIONS = [
|
|
207
|
+
"notifications",
|
|
208
|
+
"clipboard-read"
|
|
209
|
+
];
|
|
160
210
|
var SNAPSHOT_MAX_CHARS = 4e4;
|
|
161
211
|
var IDLE_STOP_MS = 15 * 6e4;
|
|
162
212
|
var TAKEOVER_GRACE_MS = 6e4;
|
|
@@ -225,6 +275,9 @@ var MAX_TABS = 10;
|
|
|
225
275
|
var MAX_TABS_PER_CONVERSATION = 6;
|
|
226
276
|
var CONVERSATION_IDLE_MS = 15 * 6e4;
|
|
227
277
|
var EVICT_MIN_IDLE_MS = 5 * 6e4;
|
|
278
|
+
var MAX_WATCHES = 16;
|
|
279
|
+
var WATCH_HEARTBEAT_MS = 10 * 6e4;
|
|
280
|
+
var WAIT_CONDITION_MAX_CHARS = 2e3;
|
|
228
281
|
var NO_CONVERSATION_MESSAGE = "the request names no conversation";
|
|
229
282
|
var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
|
|
230
283
|
var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
|
|
@@ -340,6 +393,104 @@ async function fetchIcon(cdp, url) {
|
|
|
340
393
|
return new Uint8Array(Buffer.concat(chunks));
|
|
341
394
|
}
|
|
342
395
|
|
|
396
|
+
// daemon/permissions.ts
|
|
397
|
+
var PERMISSION_REPORTS_PER_LOAD = 5;
|
|
398
|
+
function permissionInitScript(binding) {
|
|
399
|
+
return `(() => {
|
|
400
|
+
const report = globalThis[${JSON.stringify(binding)}];
|
|
401
|
+
if (typeof report !== "function") return;
|
|
402
|
+
const send = (name) => {
|
|
403
|
+
try {
|
|
404
|
+
Promise.resolve(report(name)).catch(() => {});
|
|
405
|
+
} catch {}
|
|
406
|
+
};
|
|
407
|
+
const originals = new WeakMap();
|
|
408
|
+
const nativeToString = Function.prototype.toString;
|
|
409
|
+
const toString = {
|
|
410
|
+
toString() {
|
|
411
|
+
const original = originals.get(this);
|
|
412
|
+
return nativeToString.call(original === undefined ? this : original);
|
|
413
|
+
},
|
|
414
|
+
}.toString;
|
|
415
|
+
originals.set(toString, nativeToString);
|
|
416
|
+
try {
|
|
417
|
+
Object.defineProperty(Function.prototype, "toString", {
|
|
418
|
+
value: toString,
|
|
419
|
+
writable: true,
|
|
420
|
+
configurable: true,
|
|
421
|
+
});
|
|
422
|
+
} catch {}
|
|
423
|
+
const wrap = (owner, key, make) => {
|
|
424
|
+
if (owner === null || owner === undefined) return;
|
|
425
|
+
const desc = Object.getOwnPropertyDescriptor(owner, key);
|
|
426
|
+
const original = desc === undefined ? undefined : desc.value;
|
|
427
|
+
if (typeof original !== "function") return;
|
|
428
|
+
const wrapped = make(original);
|
|
429
|
+
originals.set(wrapped, original);
|
|
430
|
+
try {
|
|
431
|
+
Object.defineProperty(wrapped, "name", { value: original.name });
|
|
432
|
+
Object.defineProperty(wrapped, "length", { value: original.length });
|
|
433
|
+
Object.defineProperty(owner, key, { ...desc, value: wrapped });
|
|
434
|
+
} catch {}
|
|
435
|
+
};
|
|
436
|
+
// observes a promise without changing it (the page still gets the very same promise)
|
|
437
|
+
const watch = (p, onValue, onError) => {
|
|
438
|
+
if (p !== null && typeof p === "object" && typeof p.then === "function")
|
|
439
|
+
p.then(onValue, onError);
|
|
440
|
+
return p;
|
|
441
|
+
};
|
|
442
|
+
if (typeof Notification === "function") {
|
|
443
|
+
wrap(Notification, "requestPermission", (original) => ({
|
|
444
|
+
requestPermission(...args) {
|
|
445
|
+
return watch(
|
|
446
|
+
original.apply(this, args),
|
|
447
|
+
(r) => {
|
|
448
|
+
if (r !== "granted") send("notifications");
|
|
449
|
+
},
|
|
450
|
+
() => {},
|
|
451
|
+
);
|
|
452
|
+
},
|
|
453
|
+
}).requestPermission);
|
|
454
|
+
}
|
|
455
|
+
const denied = (name) => (e) => {
|
|
456
|
+
if (e !== null && typeof e === "object" && e.name === "NotAllowedError") send(name);
|
|
457
|
+
};
|
|
458
|
+
if (typeof Clipboard === "function") {
|
|
459
|
+
for (const key of ["read", "readText"]) {
|
|
460
|
+
wrap(Clipboard.prototype, key, (original) => ({
|
|
461
|
+
[key](...args) {
|
|
462
|
+
return watch(original.apply(this, args), () => {}, denied("clipboard-read"));
|
|
463
|
+
},
|
|
464
|
+
})[key]);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
if (typeof Geolocation === "function") {
|
|
468
|
+
for (const key of ["getCurrentPosition", "watchPosition"]) {
|
|
469
|
+
wrap(Geolocation.prototype, key, (original) => ({
|
|
470
|
+
[key](success, error, ...rest) {
|
|
471
|
+
const onError = function (e) {
|
|
472
|
+
if (e !== null && typeof e === "object" && e.code === 1) send("geolocation");
|
|
473
|
+
if (typeof error === "function") return error.apply(this, arguments);
|
|
474
|
+
};
|
|
475
|
+
return original.call(this, success, onError, ...rest);
|
|
476
|
+
},
|
|
477
|
+
})[key]);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (typeof MediaDevices === "function") {
|
|
481
|
+
wrap(MediaDevices.prototype, "getUserMedia", (original) => ({
|
|
482
|
+
getUserMedia(constraints, ...rest) {
|
|
483
|
+
const c = constraints !== null && typeof constraints === "object" ? constraints : {};
|
|
484
|
+
return watch(original.call(this, constraints, ...rest), () => {}, (e) => {
|
|
485
|
+
if (c.video) denied("camera")(e);
|
|
486
|
+
if (c.audio) denied("microphone")(e);
|
|
487
|
+
});
|
|
488
|
+
},
|
|
489
|
+
}).getUserMedia);
|
|
490
|
+
}
|
|
491
|
+
})();`;
|
|
492
|
+
}
|
|
493
|
+
|
|
343
494
|
// daemon/snapshot.ts
|
|
344
495
|
var isNode = (line) => line.trimStart().startsWith("- ");
|
|
345
496
|
function capSnapshot(text, max = SNAPSHOT_MAX_CHARS) {
|
|
@@ -591,6 +742,32 @@ var DaemonState = class {
|
|
|
591
742
|
this.unpark(conversationId, HANDOFF_PARK, HANDOFF_PARK_KEY);
|
|
592
743
|
this.emit();
|
|
593
744
|
}
|
|
745
|
+
// ---- deleted conversations
|
|
746
|
+
/**
|
|
747
|
+
* Forgets a deleted conversation and every conversation whose tree root it is (the kernel's
|
|
748
|
+
* conversation-deleted notice): their requests' counts, pins, parks (tab parks included),
|
|
749
|
+
* handoffs, hand back notes and idle countdowns, as the idle close does and more (a deleted
|
|
750
|
+
* conversation keeps no park). Returns the conversations it forgot.
|
|
751
|
+
*/
|
|
752
|
+
forgetTree(conversationId) {
|
|
753
|
+
const gone = [];
|
|
754
|
+
for (const [id, e] of this.conversations) {
|
|
755
|
+
if (id !== conversationId && e.root !== conversationId) continue;
|
|
756
|
+
if (e.idleTimer !== void 0) this.clock.cancel(e.idleTimer);
|
|
757
|
+
e.idleTimer = void 0;
|
|
758
|
+
gone.push(id);
|
|
759
|
+
}
|
|
760
|
+
for (const id of [conversationId, ...gone]) {
|
|
761
|
+
this.conversations.delete(id);
|
|
762
|
+
this.notes.delete(id);
|
|
763
|
+
this.concerned.delete(id);
|
|
764
|
+
}
|
|
765
|
+
if (gone.length > 0) {
|
|
766
|
+
this.armIdle();
|
|
767
|
+
this.emit();
|
|
768
|
+
}
|
|
769
|
+
return gone;
|
|
770
|
+
}
|
|
594
771
|
// ---- takeover
|
|
595
772
|
/**
|
|
596
773
|
* The person takes control of the browser (every conversation's agent is refused meanwhile).
|
|
@@ -764,6 +941,288 @@ async function isVerificationPage(page, status) {
|
|
|
764
941
|
}
|
|
765
942
|
}
|
|
766
943
|
|
|
944
|
+
// daemon/viewport.ts
|
|
945
|
+
var TAP_SLOP_PX = 10;
|
|
946
|
+
var TAP_MAX_MS = 500;
|
|
947
|
+
function mobileUserAgent(desktop) {
|
|
948
|
+
const version = /(?:Headless)?Chrome\/(\d+)/.exec(desktop)?.[1] ?? "140";
|
|
949
|
+
return `Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${version}.0.0.0 Mobile Safari/537.36`;
|
|
950
|
+
}
|
|
951
|
+
var TouchTranslator = class {
|
|
952
|
+
constructor(now) {
|
|
953
|
+
this.now = now;
|
|
954
|
+
}
|
|
955
|
+
now;
|
|
956
|
+
gesture;
|
|
957
|
+
reset() {
|
|
958
|
+
this.gesture = void 0;
|
|
959
|
+
}
|
|
960
|
+
feed(kind, raw) {
|
|
961
|
+
const points = toPoints(raw);
|
|
962
|
+
const g = this.gesture;
|
|
963
|
+
if (kind === "cancel") {
|
|
964
|
+
this.gesture = void 0;
|
|
965
|
+
return [];
|
|
966
|
+
}
|
|
967
|
+
if (kind === "start") {
|
|
968
|
+
if (g !== void 0 || points.length !== 1) {
|
|
969
|
+
if (g !== void 0) g.ignored = true;
|
|
970
|
+
else this.gesture = ignoredGesture(points[0], this.now());
|
|
971
|
+
return [];
|
|
972
|
+
}
|
|
973
|
+
const p = points[0];
|
|
974
|
+
this.gesture = {
|
|
975
|
+
id: p.id,
|
|
976
|
+
start: p,
|
|
977
|
+
last: p,
|
|
978
|
+
at: this.now(),
|
|
979
|
+
panning: false,
|
|
980
|
+
ignored: false
|
|
981
|
+
};
|
|
982
|
+
return [];
|
|
983
|
+
}
|
|
984
|
+
if (g === void 0) return [];
|
|
985
|
+
if (kind === "move") {
|
|
986
|
+
const p = points.find((x) => x.id === g.id);
|
|
987
|
+
if (g.ignored || p === void 0 || points.length !== 1) return [];
|
|
988
|
+
if (!g.panning && Math.hypot(p.x - g.start.x, p.y - g.start.y) < TAP_SLOP_PX) return [];
|
|
989
|
+
g.panning = true;
|
|
990
|
+
const out = {
|
|
991
|
+
kind: "wheel",
|
|
992
|
+
x: p.x,
|
|
993
|
+
y: p.y,
|
|
994
|
+
// the content follows the finger: moving it up scrolls down
|
|
995
|
+
dx: g.last.x - p.x,
|
|
996
|
+
dy: g.last.y - p.y
|
|
997
|
+
};
|
|
998
|
+
g.last = p;
|
|
999
|
+
return out.dx === 0 && out.dy === 0 ? [] : [out];
|
|
1000
|
+
}
|
|
1001
|
+
if (points.length > 0) return [];
|
|
1002
|
+
this.gesture = void 0;
|
|
1003
|
+
if (g.ignored || g.panning || this.now() - g.at >= TAP_MAX_MS) return [];
|
|
1004
|
+
return [{ kind: "click", x: g.start.x, y: g.start.y }];
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
function ignoredGesture(p, at) {
|
|
1008
|
+
const q = p ?? { id: -1, x: 0, y: 0 };
|
|
1009
|
+
return { id: q.id, start: q, last: q, at, panning: false, ignored: true };
|
|
1010
|
+
}
|
|
1011
|
+
function toPoints(raw) {
|
|
1012
|
+
if (!Array.isArray(raw)) return [];
|
|
1013
|
+
const out = [];
|
|
1014
|
+
for (const r of raw.slice(0, 10)) {
|
|
1015
|
+
const p = r;
|
|
1016
|
+
if (typeof p !== "object" || p === null) continue;
|
|
1017
|
+
const id = Number(p.id);
|
|
1018
|
+
const x = Number(p.x);
|
|
1019
|
+
const y = Number(p.y);
|
|
1020
|
+
if (Number.isFinite(id) && Number.isFinite(x) && Number.isFinite(y)) out.push({ id, x, y });
|
|
1021
|
+
}
|
|
1022
|
+
return out;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// daemon/watches.ts
|
|
1026
|
+
var WATCH_CHECK_MS = 500;
|
|
1027
|
+
var WATCH_PARK = "watch";
|
|
1028
|
+
var NO_PARKS = { park: () => void 0, unpark: () => void 0 };
|
|
1029
|
+
function conditionLabel(c) {
|
|
1030
|
+
const cut = (s) => s.length <= 80 ? s : `${s.slice(0, 79)}\u2026`;
|
|
1031
|
+
if ("text" in c) return `text ${JSON.stringify(cut(c.text))}`;
|
|
1032
|
+
if ("ref" in c) return `element ${c.ref}`;
|
|
1033
|
+
if ("urlContains" in c) return `URL containing ${JSON.stringify(cut(c.urlContains))}`;
|
|
1034
|
+
if ("navigation" in c) return "the next navigation";
|
|
1035
|
+
return "the next download";
|
|
1036
|
+
}
|
|
1037
|
+
function parseCondition(raw) {
|
|
1038
|
+
if (typeof raw !== "object" || raw === null) return "The watch needs a condition.";
|
|
1039
|
+
const r = raw;
|
|
1040
|
+
const keys = Object.keys(r).filter((k) => r[k] !== void 0);
|
|
1041
|
+
if (keys.length !== 1) return "A watch takes exactly one condition.";
|
|
1042
|
+
const str = (v) => typeof v === "string" && v !== "" && v.length <= WAIT_CONDITION_MAX_CHARS ? v : void 0;
|
|
1043
|
+
if (str(r.text) !== void 0) return { text: r.text };
|
|
1044
|
+
if (str(r.ref) !== void 0) return { ref: r.ref };
|
|
1045
|
+
if (str(r.urlContains) !== void 0) return { urlContains: r.urlContains };
|
|
1046
|
+
if (r.navigation === true) return { navigation: true };
|
|
1047
|
+
if (r.download === true) return { download: true };
|
|
1048
|
+
return "The watch's condition is not valid.";
|
|
1049
|
+
}
|
|
1050
|
+
var Watches = class {
|
|
1051
|
+
watches = /* @__PURE__ */ new Map();
|
|
1052
|
+
clock;
|
|
1053
|
+
parks;
|
|
1054
|
+
check;
|
|
1055
|
+
onChange;
|
|
1056
|
+
disposed = false;
|
|
1057
|
+
constructor(opts) {
|
|
1058
|
+
this.clock = opts.clock;
|
|
1059
|
+
this.check = opts.check;
|
|
1060
|
+
this.parks = opts.parks ?? NO_PARKS;
|
|
1061
|
+
this.onChange = opts.onChange ?? (() => void 0);
|
|
1062
|
+
}
|
|
1063
|
+
/** How many watches the session keeps (tests). */
|
|
1064
|
+
get size() {
|
|
1065
|
+
return this.watches.size;
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* Arms a watch (idempotent per id: a known one answers its state, renewing its heartbeat).
|
|
1069
|
+
* `page` is the conversation's active tab.
|
|
1070
|
+
*/
|
|
1071
|
+
start(opts) {
|
|
1072
|
+
const known = this.watches.get(opts.id);
|
|
1073
|
+
if (known !== void 0) {
|
|
1074
|
+
known.lastPolled = this.clock.now();
|
|
1075
|
+
return this.stateOf(known);
|
|
1076
|
+
}
|
|
1077
|
+
if (this.watches.size >= MAX_WATCHES) this.evict();
|
|
1078
|
+
const now = this.clock.now();
|
|
1079
|
+
const w = {
|
|
1080
|
+
id: opts.id,
|
|
1081
|
+
conv: opts.conv,
|
|
1082
|
+
root: opts.root,
|
|
1083
|
+
tabId: opts.tabId,
|
|
1084
|
+
page: opts.page,
|
|
1085
|
+
condition: opts.condition,
|
|
1086
|
+
deadline: now + Math.max(0, opts.remainingMs),
|
|
1087
|
+
startedAt: now,
|
|
1088
|
+
lastPolled: now,
|
|
1089
|
+
latched: void 0,
|
|
1090
|
+
timer: void 0,
|
|
1091
|
+
off: () => void 0,
|
|
1092
|
+
navigated: false,
|
|
1093
|
+
checking: false
|
|
1094
|
+
};
|
|
1095
|
+
if ("navigation" in opts.condition) {
|
|
1096
|
+
const onNav = (f) => {
|
|
1097
|
+
if (f === opts.page.mainFrame()) w.navigated = true;
|
|
1098
|
+
};
|
|
1099
|
+
opts.page.on("framenavigated", onNav);
|
|
1100
|
+
w.off = () => opts.page.off("framenavigated", onNav);
|
|
1101
|
+
}
|
|
1102
|
+
this.watches.set(w.id, w);
|
|
1103
|
+
this.parks.park(w.conv, w.root, { kind: WATCH_PARK, key: w.id });
|
|
1104
|
+
this.onChange();
|
|
1105
|
+
this.schedule(w, 0);
|
|
1106
|
+
return this.stateOf(w);
|
|
1107
|
+
}
|
|
1108
|
+
/** The watch's state; a poll is its heartbeat. An unknown id is `unknown`. */
|
|
1109
|
+
poll(id) {
|
|
1110
|
+
const w = this.watches.get(id);
|
|
1111
|
+
if (w === void 0) return { state: "unknown" };
|
|
1112
|
+
w.lastPolled = this.clock.now();
|
|
1113
|
+
return this.stateOf(w);
|
|
1114
|
+
}
|
|
1115
|
+
/** The watch's state, then forgets it. */
|
|
1116
|
+
end(id) {
|
|
1117
|
+
const w = this.watches.get(id);
|
|
1118
|
+
if (w === void 0) return { state: "unknown" };
|
|
1119
|
+
const st = this.stateOf(w);
|
|
1120
|
+
this.drop(w);
|
|
1121
|
+
return st;
|
|
1122
|
+
}
|
|
1123
|
+
/** Whether the watch belongs to the conversation (watch ops of another conversation see none). */
|
|
1124
|
+
owns(id, conv) {
|
|
1125
|
+
const w = this.watches.get(id);
|
|
1126
|
+
return w === void 0 || w.conv === conv;
|
|
1127
|
+
}
|
|
1128
|
+
/** The newest pending watch of a tree (the panel's status line). */
|
|
1129
|
+
waitingOf(root) {
|
|
1130
|
+
let newest;
|
|
1131
|
+
for (const w of this.watches.values())
|
|
1132
|
+
if (w.root === root && w.latched === void 0 && (!newest || w.startedAt >= newest.startedAt))
|
|
1133
|
+
newest = w;
|
|
1134
|
+
return newest === void 0 ? void 0 : {
|
|
1135
|
+
label: conditionLabel(newest.condition),
|
|
1136
|
+
until: new Date(newest.deadline).toISOString()
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* A dialog that holds a decision (confirm, prompt) opened on a tab: its pending watches end
|
|
1141
|
+
* with reason `dialog`.
|
|
1142
|
+
*/
|
|
1143
|
+
dialog(tabId, message) {
|
|
1144
|
+
for (const w of this.watches.values())
|
|
1145
|
+
if (w.tabId === tabId && w.latched === void 0)
|
|
1146
|
+
this.latch(w, { state: "ended", reason: "dialog", detail: message.slice(0, 500) });
|
|
1147
|
+
}
|
|
1148
|
+
/** A download of the conversation was saved into the workspace: its download watches are met. */
|
|
1149
|
+
downloadSaved(conv, path) {
|
|
1150
|
+
for (const w of this.watches.values())
|
|
1151
|
+
if (w.conv === conv && w.latched === void 0 && "download" in w.condition)
|
|
1152
|
+
this.latch(w, { state: "met", detail: path });
|
|
1153
|
+
}
|
|
1154
|
+
/** A tab closed: its pending watches end with reason `tab_closed`. */
|
|
1155
|
+
tabClosed(tabId) {
|
|
1156
|
+
for (const w of this.watches.values())
|
|
1157
|
+
if (w.tabId === tabId && w.latched === void 0)
|
|
1158
|
+
this.latch(w, { state: "ended", reason: "tab_closed" });
|
|
1159
|
+
}
|
|
1160
|
+
/** Ends every watch (the session closes): their parks end, later polls are `unknown`. */
|
|
1161
|
+
dispose() {
|
|
1162
|
+
this.disposed = true;
|
|
1163
|
+
for (const w of [...this.watches.values()]) this.drop(w);
|
|
1164
|
+
}
|
|
1165
|
+
stateOf(w) {
|
|
1166
|
+
return w.latched ?? { state: "pending" };
|
|
1167
|
+
}
|
|
1168
|
+
latch(w, st) {
|
|
1169
|
+
if (w.latched !== void 0) return;
|
|
1170
|
+
w.latched = { ...st, at: new Date(this.clock.now()).toISOString() };
|
|
1171
|
+
w.off();
|
|
1172
|
+
this.onChange();
|
|
1173
|
+
}
|
|
1174
|
+
drop(w) {
|
|
1175
|
+
if (this.watches.get(w.id) !== w) return;
|
|
1176
|
+
this.watches.delete(w.id);
|
|
1177
|
+
if (w.timer !== void 0) this.clock.cancel(w.timer);
|
|
1178
|
+
w.timer = void 0;
|
|
1179
|
+
w.off();
|
|
1180
|
+
this.parks.unpark(w.conv, WATCH_PARK, w.id);
|
|
1181
|
+
this.onChange();
|
|
1182
|
+
}
|
|
1183
|
+
/** At the cap: the oldest latched watch goes, else the oldest one. */
|
|
1184
|
+
evict() {
|
|
1185
|
+
const all = [...this.watches.values()].sort((a, b) => a.startedAt - b.startedAt);
|
|
1186
|
+
const victim = all.find((w) => w.latched !== void 0) ?? all[0];
|
|
1187
|
+
if (victim !== void 0) this.drop(victim);
|
|
1188
|
+
}
|
|
1189
|
+
schedule(w, ms) {
|
|
1190
|
+
if (this.disposed) return;
|
|
1191
|
+
w.timer = this.clock.schedule(() => {
|
|
1192
|
+
w.timer = void 0;
|
|
1193
|
+
void this.tick(w);
|
|
1194
|
+
}, ms);
|
|
1195
|
+
}
|
|
1196
|
+
/** One look: the heartbeat, the deadline, the tab, then the condition. */
|
|
1197
|
+
async tick(w) {
|
|
1198
|
+
if (this.watches.get(w.id) !== w) return;
|
|
1199
|
+
const now = this.clock.now();
|
|
1200
|
+
if (now - w.lastPolled >= WATCH_HEARTBEAT_MS) {
|
|
1201
|
+
this.drop(w);
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
if (w.latched === void 0 && !w.checking) {
|
|
1205
|
+
if (w.page.isClosed()) this.latch(w, { state: "ended", reason: "tab_closed" });
|
|
1206
|
+
else if ("navigation" in w.condition) {
|
|
1207
|
+
if (w.navigated) this.latch(w, { state: "met" });
|
|
1208
|
+
} else if (!("download" in w.condition)) {
|
|
1209
|
+
w.checking = true;
|
|
1210
|
+
try {
|
|
1211
|
+
if (await this.check(w.page, w.condition)) this.latch(w, { state: "met" });
|
|
1212
|
+
} catch {
|
|
1213
|
+
} finally {
|
|
1214
|
+
w.checking = false;
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
if (w.latched === void 0 && this.clock.now() >= w.deadline)
|
|
1218
|
+
this.latch(w, { state: "ended", reason: "deadline" });
|
|
1219
|
+
}
|
|
1220
|
+
if (this.watches.get(w.id) !== w) return;
|
|
1221
|
+
const next = w.latched === void 0 ? WATCH_CHECK_MS : Math.max(0, w.lastPolled + WATCH_HEARTBEAT_MS - this.clock.now());
|
|
1222
|
+
this.schedule(w, next);
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
|
|
767
1226
|
// daemon/actions.ts
|
|
768
1227
|
var ActionError = class extends Error {
|
|
769
1228
|
constructor(code, message) {
|
|
@@ -1064,8 +1523,9 @@ async function captureFitting(cdp, opts) {
|
|
|
1064
1523
|
const content = metrics.cssContentSize;
|
|
1065
1524
|
const area = opts.fullPage ? { x: 0, y: 0, width: content.width, height: Math.min(content.height, 16384) } : { x: vv.pageX, y: vv.pageY, width: vv.clientWidth, height: vv.clientHeight };
|
|
1066
1525
|
const maxScale = Math.min(1, opts.maxScale ?? 1);
|
|
1526
|
+
const zoom = opts.fullPage === true ? 1 : vv.scale > 0 && vv.scale < 1 ? vv.scale : 1;
|
|
1067
1527
|
for (const s of SCALES) {
|
|
1068
|
-
const scale = s * maxScale;
|
|
1528
|
+
const scale = s * maxScale * zoom;
|
|
1069
1529
|
if (scale * area.width < 16) break;
|
|
1070
1530
|
for (const quality of QUALITIES) {
|
|
1071
1531
|
const shot = await cdp.send("Page.captureScreenshot", {
|
|
@@ -1172,8 +1632,49 @@ var NO_USAGE = {
|
|
|
1172
1632
|
tabParked: () => false,
|
|
1173
1633
|
tabClosed: () => void 0,
|
|
1174
1634
|
seen: () => void 0,
|
|
1175
|
-
known: () => true
|
|
1635
|
+
known: () => true,
|
|
1636
|
+
park: () => void 0,
|
|
1637
|
+
unpark: () => void 0
|
|
1176
1638
|
};
|
|
1639
|
+
var DIALOG_PARK = "dialog";
|
|
1640
|
+
var blocks = (h) => h !== void 0 && h.view.kind !== "auth";
|
|
1641
|
+
var seqOf = (h) => Number(h.view.id.slice(1));
|
|
1642
|
+
var BLOCKED_OPS = /* @__PURE__ */ new Set([
|
|
1643
|
+
"screenshot",
|
|
1644
|
+
"navigate",
|
|
1645
|
+
"click",
|
|
1646
|
+
"hover",
|
|
1647
|
+
"type",
|
|
1648
|
+
"select",
|
|
1649
|
+
"press",
|
|
1650
|
+
"scroll",
|
|
1651
|
+
"upload",
|
|
1652
|
+
"click_at",
|
|
1653
|
+
"type_at"
|
|
1654
|
+
]);
|
|
1655
|
+
var PAUSED_BY_DIALOG_MESSAGE = "A dialog on another conversation's page pauses the whole browser on this device (it runs as one process) until the user or that conversation answers it; retry later.";
|
|
1656
|
+
var DIALOG_CHANGED_MESSAGE = "The dialog changed; call browser_snapshot to see the current one.";
|
|
1657
|
+
var NO_DIALOG_MESSAGE = "No dialog is open on this tab; call browser_snapshot to see the page.";
|
|
1658
|
+
var MAX_PERMISSION_PAIRS = 50;
|
|
1659
|
+
function originOf(raw) {
|
|
1660
|
+
try {
|
|
1661
|
+
const o = new URL(raw).origin;
|
|
1662
|
+
return o === "null" ? void 0 : o;
|
|
1663
|
+
} catch {
|
|
1664
|
+
return void 0;
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
function authChallenge(header) {
|
|
1668
|
+
const scheme = /^\s*([A-Za-z0-9!#$%&'*+.^_`|~-]+)/.exec(header)?.[1] ?? "";
|
|
1669
|
+
const realm = /realm\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))/i.exec(header);
|
|
1670
|
+
return {
|
|
1671
|
+
scheme,
|
|
1672
|
+
realm: clipCodePoints(
|
|
1673
|
+
(realm?.[1] ?? realm?.[2] ?? "").replace(/\\(.)/g, "$1"),
|
|
1674
|
+
DIALOG_QUOTE_CHARS
|
|
1675
|
+
)
|
|
1676
|
+
};
|
|
1677
|
+
}
|
|
1177
1678
|
function isStartBlank(tab) {
|
|
1178
1679
|
return tab.owner === void 0 && tab.url === "about:blank";
|
|
1179
1680
|
}
|
|
@@ -1195,7 +1696,9 @@ function bareUrl(raw) {
|
|
|
1195
1696
|
}
|
|
1196
1697
|
}
|
|
1197
1698
|
function isActing(req) {
|
|
1198
|
-
if (req.op === "handoff_notice" || req.op === "handoff_clear"
|
|
1699
|
+
if (req.op === "handoff_notice" || req.op === "handoff_clear" || req.op === "dialog")
|
|
1700
|
+
return false;
|
|
1701
|
+
if (req.op === "watch_start" || req.op === "watch_poll" || req.op === "watch_end") return false;
|
|
1199
1702
|
if (req.op === "tabs") return req.action !== "list" && req.action !== "adopt";
|
|
1200
1703
|
return true;
|
|
1201
1704
|
}
|
|
@@ -1270,6 +1773,50 @@ var BrowserSession = class {
|
|
|
1270
1773
|
/** Each tab's latest agent click; `seq` grows with every click (viewers flash only new ones). */
|
|
1271
1774
|
clicks = /* @__PURE__ */ new Map();
|
|
1272
1775
|
clickSeq = 0;
|
|
1776
|
+
/** Parked long waits (browser long waits spec §6.2), bound to tabs of this session. */
|
|
1777
|
+
watches;
|
|
1778
|
+
/** Short download waits: resolved with the saved path when a download of `conv` is saved. */
|
|
1779
|
+
downloadWaiters = /* @__PURE__ */ new Set();
|
|
1780
|
+
/** The dialog each tab holds until answered (one per tab: JS dialogs are modal per page). */
|
|
1781
|
+
held = /* @__PURE__ */ new Map();
|
|
1782
|
+
dialogSeq = 0;
|
|
1783
|
+
/** Wakes a conversation's actions racing a dialog of its tabs (dialogs spec §3). */
|
|
1784
|
+
dialogWaiters = /* @__PURE__ */ new Map();
|
|
1785
|
+
/**
|
|
1786
|
+
* HTTP Basic credentials by exact origin, as the header value: typed by the person in the panel,
|
|
1787
|
+
* kept in this process's memory only, never in a reply, note, log, viewer message or file.
|
|
1788
|
+
*/
|
|
1789
|
+
credentials = /* @__PURE__ */ new Map();
|
|
1790
|
+
/** Pages whose main frame got a sign-in challenge (a 401 with WWW-Authenticate). */
|
|
1791
|
+
challenged = /* @__PURE__ */ new WeakSet();
|
|
1792
|
+
/** Requests the route signed (a 401 to one of them means the credentials are wrong). */
|
|
1793
|
+
signed = /* @__PURE__ */ new WeakSet();
|
|
1794
|
+
/** Navigations the daemon itself runs on a page (goto, history, reload): their roots are trusted. */
|
|
1795
|
+
ownNavs = /* @__PURE__ */ new WeakMap();
|
|
1796
|
+
/** The permission binding's per-daemon name (any page can call it: its payload is untrusted). */
|
|
1797
|
+
permissionBinding = `__cbPermission_${randomBytes(8).toString("hex")}`;
|
|
1798
|
+
/** Permission reports per page load (capped at PERMISSION_REPORTS_PER_LOAD). */
|
|
1799
|
+
permissionCount = /* @__PURE__ */ new WeakMap();
|
|
1800
|
+
/** Origin–permission pairs the daemon recorded (deduplicated notes; grants only for these). */
|
|
1801
|
+
permissionPairs = /* @__PURE__ */ new Set();
|
|
1802
|
+
/** The pairs recorded on each tab (a viewer grants only for pairs of its tree's tabs). */
|
|
1803
|
+
tabPermissions = /* @__PURE__ */ new Map();
|
|
1804
|
+
/** The viewport profile the person chose (desktop while the agent drives). */
|
|
1805
|
+
profile = "desktop";
|
|
1806
|
+
/** The profile the pages have now (the chosen one once applied). */
|
|
1807
|
+
applied = "desktop";
|
|
1808
|
+
/** The CDP sessions holding the phone overrides, per page (detached on restore). */
|
|
1809
|
+
profileSessions = /* @__PURE__ */ new Map();
|
|
1810
|
+
/** Every agent request waits for this (a restore to desktop after hand back). */
|
|
1811
|
+
viewportGate = Promise.resolve();
|
|
1812
|
+
mobileUa;
|
|
1813
|
+
/** The pages' own user agent (given back when the phone profile ends). */
|
|
1814
|
+
desktopUa;
|
|
1815
|
+
/** The desktop translation of a viewer's touch input (tap, pan). */
|
|
1816
|
+
touchTranslator;
|
|
1817
|
+
/** Resolves once the permission binding and init script are installed (never rejects). */
|
|
1818
|
+
ready;
|
|
1819
|
+
singleProcess;
|
|
1273
1820
|
constructor(ctx, opts) {
|
|
1274
1821
|
this.ctx = ctx;
|
|
1275
1822
|
this.proxy = opts.proxy;
|
|
@@ -1280,6 +1827,14 @@ var BrowserSession = class {
|
|
|
1280
1827
|
this.clock = opts.clock ?? systemClock;
|
|
1281
1828
|
this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
|
|
1282
1829
|
this.usage = opts.usage ?? NO_USAGE;
|
|
1830
|
+
this.watches = new Watches({
|
|
1831
|
+
clock: this.clock,
|
|
1832
|
+
check: (page, c) => this.conditionHolds(page, c),
|
|
1833
|
+
...opts.parks === void 0 ? {} : { parks: opts.parks },
|
|
1834
|
+
onChange: () => this.emit({ type: "state" })
|
|
1835
|
+
});
|
|
1836
|
+
this.singleProcess = opts.singleProcess === true;
|
|
1837
|
+
this.touchTranslator = new TouchTranslator(() => this.clock.now());
|
|
1283
1838
|
ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
|
|
1284
1839
|
ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
|
|
1285
1840
|
ctx.on("page", (p) => {
|
|
@@ -1295,6 +1850,35 @@ var BrowserSession = class {
|
|
|
1295
1850
|
});
|
|
1296
1851
|
});
|
|
1297
1852
|
for (const p of ctx.pages()) this.track(p);
|
|
1853
|
+
this.ready = Promise.all([this.installPermissionReports(), this.installAuthRoute()]).then(
|
|
1854
|
+
() => void 0
|
|
1855
|
+
);
|
|
1856
|
+
}
|
|
1857
|
+
/**
|
|
1858
|
+
* The credential route, installed for the session's lifetime (plugins#292): it signs the
|
|
1859
|
+
* requests {@link authHeaderFor} allows, and while any route exists Playwright answers every
|
|
1860
|
+
* site challenge itself, cancelling one no credentials match (the patched playwright-core,
|
|
1861
|
+
* patches/), so a page's fetch, XHR or subresource that gets a Basic challenge completes with
|
|
1862
|
+
* its 401 instead of hanging in the full build. Never fails the session.
|
|
1863
|
+
*/
|
|
1864
|
+
async installAuthRoute() {
|
|
1865
|
+
try {
|
|
1866
|
+
await this.ctx.route((u) => this.credentials.has(u.origin), this.onAuthRoute);
|
|
1867
|
+
} catch {
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* The permission report (dialogs spec §6): an init script wraps the request APIs and calls the
|
|
1872
|
+
* binding with the permission name when the page was refused. Never fails the session.
|
|
1873
|
+
*/
|
|
1874
|
+
async installPermissionReports() {
|
|
1875
|
+
try {
|
|
1876
|
+
await this.ctx.exposeBinding(this.permissionBinding, (source, name) => {
|
|
1877
|
+
this.onPermissionReport(source.page, source.frame.url(), name);
|
|
1878
|
+
});
|
|
1879
|
+
await this.ctx.addInitScript({ content: permissionInitScript(this.permissionBinding) });
|
|
1880
|
+
} catch {
|
|
1881
|
+
}
|
|
1298
1882
|
}
|
|
1299
1883
|
get context() {
|
|
1300
1884
|
return this.ctx;
|
|
@@ -1593,15 +2177,39 @@ var BrowserSession = class {
|
|
|
1593
2177
|
*/
|
|
1594
2178
|
async closeConversation(conversationId) {
|
|
1595
2179
|
const ids = this.tabsOf(conversationId).filter((id) => !this.usage.tabParked(id));
|
|
2180
|
+
await this.closeAndForget([conversationId], ids);
|
|
2181
|
+
}
|
|
2182
|
+
/**
|
|
2183
|
+
* Closes every tab of a deleted conversation and of the conversations whose tree root it is,
|
|
2184
|
+
* parked tabs included, and forgets what the session keeps for each of them (the kernel's
|
|
2185
|
+
* conversation-deleted notice). `also`: more conversations of that tree the caller knows (the
|
|
2186
|
+
* daemon state's, which may own no tab). Never touches the profile. Returns how many tabs it
|
|
2187
|
+
* closed.
|
|
2188
|
+
*/
|
|
2189
|
+
async forgetTree(conversationId, also = []) {
|
|
2190
|
+
const convs = /* @__PURE__ */ new Set([conversationId, ...also]);
|
|
2191
|
+
const ids = [];
|
|
2192
|
+
for (const [id, o] of this.owners) {
|
|
2193
|
+
if (o.owner !== conversationId && o.root !== conversationId) continue;
|
|
2194
|
+
convs.add(o.owner);
|
|
2195
|
+
if (!this.closing.has(id)) ids.push(id);
|
|
2196
|
+
}
|
|
2197
|
+
await this.closeAndForget([...convs], ids);
|
|
2198
|
+
return ids.length;
|
|
2199
|
+
}
|
|
2200
|
+
/** Closes `ids` (their owners dropped first) and forgets the session's state of `convs`. */
|
|
2201
|
+
async closeAndForget(convs, ids) {
|
|
1596
2202
|
for (const id of ids) {
|
|
1597
2203
|
this.closing.add(id);
|
|
1598
2204
|
this.owners.delete(id);
|
|
1599
2205
|
}
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
2206
|
+
for (const c of convs) {
|
|
2207
|
+
this.activeOf.delete(c);
|
|
2208
|
+
this.queues.delete(this.queueKey(c));
|
|
2209
|
+
this.unreported.delete(c);
|
|
2210
|
+
this.claiming.delete(c);
|
|
2211
|
+
this.actedSeq.delete(c);
|
|
2212
|
+
}
|
|
1605
2213
|
await Promise.all(
|
|
1606
2214
|
ids.map(
|
|
1607
2215
|
(id) => this.pages.get(id)?.close().catch(() => {
|
|
@@ -1624,6 +2232,7 @@ var BrowserSession = class {
|
|
|
1624
2232
|
const id = `t${this.nextId++}`;
|
|
1625
2233
|
this.ids.set(page, id);
|
|
1626
2234
|
this.pages.set(id, page);
|
|
2235
|
+
if (this.profile === "phone") void this.applyPhone(page);
|
|
1627
2236
|
const refresh = () => {
|
|
1628
2237
|
page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
|
|
1629
2238
|
};
|
|
@@ -1652,6 +2261,11 @@ var BrowserSession = class {
|
|
|
1652
2261
|
if (f !== page.mainFrame()) return;
|
|
1653
2262
|
this.pendingNavs.delete(page);
|
|
1654
2263
|
this.blockers.delete(id);
|
|
2264
|
+
this.permissionCount.delete(page);
|
|
2265
|
+
const auth = this.held.get(id);
|
|
2266
|
+
if (auth?.view.kind === "auth" && auth.atUrl !== docUrl(f.url()) && !f.url().startsWith("chrome-error:"))
|
|
2267
|
+
this.clearHeld(id);
|
|
2268
|
+
this.reapplyPhone(page);
|
|
1655
2269
|
refresh();
|
|
1656
2270
|
});
|
|
1657
2271
|
page.on("domcontentloaded", refresh);
|
|
@@ -1671,8 +2285,10 @@ var BrowserSession = class {
|
|
|
1671
2285
|
this.checkBlocked(page, r.url(), this.pageToOpen(page, r));
|
|
1672
2286
|
});
|
|
1673
2287
|
page.on("response", (r) => {
|
|
1674
|
-
if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
|
|
2288
|
+
if (r.request().isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
1675
2289
|
this.docStatus.set(id, r.status());
|
|
2290
|
+
if (r.status() === 401) this.onUnauthorized(page, id, r);
|
|
2291
|
+
}
|
|
1676
2292
|
if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
|
|
1677
2293
|
this.checkBlocked(page, r.url(), this.pageToOpen(page, r.request()));
|
|
1678
2294
|
}
|
|
@@ -1700,10 +2316,14 @@ var BrowserSession = class {
|
|
|
1700
2316
|
this.tabUsedAt.delete(id);
|
|
1701
2317
|
this.gainedAt.delete(id);
|
|
1702
2318
|
this.clicks.delete(id);
|
|
2319
|
+
this.clearHeld(id);
|
|
2320
|
+
this.tabPermissions.delete(id);
|
|
2321
|
+
this.profileSessions.delete(page);
|
|
1703
2322
|
const o = this.owners.get(id);
|
|
1704
2323
|
this.owners.delete(id);
|
|
1705
2324
|
if (o !== void 0) this.activeMovedOff(o.owner, id);
|
|
1706
2325
|
this.usage.tabClosed(id);
|
|
2326
|
+
this.watches.tabClosed(id);
|
|
1707
2327
|
this.emit({ type: "state" });
|
|
1708
2328
|
});
|
|
1709
2329
|
}
|
|
@@ -1737,22 +2357,491 @@ var BrowserSession = class {
|
|
|
1737
2357
|
if (!await this.evict(o.owner)) closeIt(`the browser keeps at most ${MAX_TABS} tabs`);
|
|
1738
2358
|
});
|
|
1739
2359
|
}
|
|
2360
|
+
/**
|
|
2361
|
+
* A page dialog (dialogs spec §3): an alert only informs, so it is closed at once and noted; a
|
|
2362
|
+
* confirm, prompt or beforeunload is held until answered (by the person in control or the
|
|
2363
|
+
* agent's browser_dialog) and pins its tab. A dialog of an unowned page has nobody to answer it:
|
|
2364
|
+
* it gets the safe answer (dismissed; a beforeunload accepted), as before.
|
|
2365
|
+
*/
|
|
1740
2366
|
onDialog(page, d) {
|
|
1741
2367
|
const type = d.type();
|
|
1742
|
-
|
|
2368
|
+
const id = this.tabIdOf(page);
|
|
2369
|
+
const o = this.owners.get(id);
|
|
2370
|
+
const message = clip(d.message(), MAX_DIALOG_CHARS);
|
|
2371
|
+
if (type === "alert") {
|
|
1743
2372
|
d.accept().catch(() => void 0);
|
|
2373
|
+
this.noteTo(
|
|
2374
|
+
o?.owner,
|
|
2375
|
+
`The page showed an alert: ${JSON.stringify(dialogQuote(message))} (closed).`
|
|
2376
|
+
);
|
|
2377
|
+
if (o !== void 0) this.emit({ type: "dialog", kind: "alert", message, root: o.root });
|
|
1744
2378
|
return;
|
|
1745
2379
|
}
|
|
1746
|
-
const kind = type === "confirm" || type === "prompt" ? type : "
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
this.
|
|
1752
|
-
|
|
1753
|
-
|
|
2380
|
+
const kind = type === "confirm" || type === "prompt" ? type : "beforeunload";
|
|
2381
|
+
if (o === void 0) {
|
|
2382
|
+
(kind === "beforeunload" ? d.accept() : d.dismiss()).catch(() => void 0);
|
|
2383
|
+
return;
|
|
2384
|
+
}
|
|
2385
|
+
this.clearHeld(id);
|
|
2386
|
+
const view = {
|
|
2387
|
+
id: `d${++this.dialogSeq}`,
|
|
2388
|
+
tabId: id,
|
|
2389
|
+
kind,
|
|
2390
|
+
message,
|
|
2391
|
+
...kind === "prompt" ? { defaultValue: clip(d.defaultValue(), MAX_DIALOG_CHARS) } : {}
|
|
2392
|
+
};
|
|
2393
|
+
this.held.set(id, { view, dialog: d, owner: o });
|
|
2394
|
+
this.usage.park(o.owner, o.root, { kind: DIALOG_PARK, key: view.id, tabId: id });
|
|
2395
|
+
this.watches.dialog(id, message);
|
|
2396
|
+
this.wakeDialogWaiters(o.owner);
|
|
2397
|
+
this.emit({ type: "state" });
|
|
2398
|
+
}
|
|
2399
|
+
/** Forgets the tab's held dialog (answered, its tab closed or navigated away) and its park. */
|
|
2400
|
+
clearHeld(tabId) {
|
|
2401
|
+
const h = this.held.get(tabId);
|
|
2402
|
+
if (h === void 0) return;
|
|
2403
|
+
this.held.delete(tabId);
|
|
2404
|
+
if (h.view.kind !== "auth") this.usage.unpark(h.owner.owner, DIALOG_PARK, h.view.id);
|
|
2405
|
+
this.emit({ type: "state" });
|
|
2406
|
+
}
|
|
2407
|
+
wakeDialogWaiters(conversationId) {
|
|
2408
|
+
for (const wake of [...this.dialogWaiters.get(conversationId) ?? []]) wake();
|
|
2409
|
+
}
|
|
2410
|
+
/** The held dialogs of a viewer's tree, in tab order. */
|
|
2411
|
+
dialogsOf(root) {
|
|
2412
|
+
return this.live().map(([id]) => this.held.get(id)).filter(
|
|
2413
|
+
(h) => h !== void 0 && this.owners.get(h.view.tabId)?.root === root
|
|
2414
|
+
).map((h) => h.view);
|
|
2415
|
+
}
|
|
2416
|
+
/** The pending dialog a reply of the conversation carries: its active tab's, else its newest. */
|
|
2417
|
+
dialogFor(conversationId) {
|
|
2418
|
+
const active = this.activeTabOf(conversationId);
|
|
2419
|
+
const own = active === void 0 ? void 0 : this.held.get(active);
|
|
2420
|
+
if (own !== void 0) return own.view;
|
|
2421
|
+
let best;
|
|
2422
|
+
for (const id of this.tabsOf(conversationId)) {
|
|
2423
|
+
const h = this.held.get(id);
|
|
2424
|
+
if (h !== void 0 && (best === void 0 || seqOf(h) > seqOf(best))) best = h;
|
|
2425
|
+
}
|
|
2426
|
+
return best?.view;
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* Runs `fn` and resolves early (undefined) when a dialog opens on one of the conversation's
|
|
2430
|
+
* tabs: the request that opened it replies at once and frees its queue (dialogs spec §3, R4).
|
|
2431
|
+
* The action's promise is left to settle; a failure after the dialog is noted to the
|
|
2432
|
+
* conversation (a timeout of an action held by the dialog is no news).
|
|
2433
|
+
*/
|
|
2434
|
+
async raceDialog(conversationId, op, fn) {
|
|
2435
|
+
let wake;
|
|
2436
|
+
const opened = new Promise((r) => {
|
|
2437
|
+
wake = () => r("dialog");
|
|
2438
|
+
});
|
|
2439
|
+
const waiters = this.dialogWaiters.get(conversationId) ?? /* @__PURE__ */ new Set();
|
|
2440
|
+
waiters.add(wake);
|
|
2441
|
+
this.dialogWaiters.set(conversationId, waiters);
|
|
2442
|
+
const done = fn();
|
|
2443
|
+
try {
|
|
2444
|
+
const out = await Promise.race([done, opened]);
|
|
2445
|
+
if (out !== "dialog") return out;
|
|
2446
|
+
done.catch((e) => {
|
|
2447
|
+
if (isTimeout(e)) return;
|
|
2448
|
+
const why = e instanceof ActionError ? e.message : firstLine(e);
|
|
2449
|
+
this.noteTo(conversationId, `The ${op} that opened a dialog failed afterwards: ${why}`);
|
|
2450
|
+
});
|
|
2451
|
+
return void 0;
|
|
2452
|
+
} finally {
|
|
2453
|
+
waiters.delete(wake);
|
|
2454
|
+
if (waiters.size === 0) this.dialogWaiters.delete(conversationId);
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
/**
|
|
2458
|
+
* Answers a held dialog (dialogs spec §5): for the agent (`browser_dialog`) only on its own
|
|
2459
|
+
* tabs and only when `message` matches the dialog's quote. An auth dialog takes only `dismiss`
|
|
2460
|
+
* from the agent.
|
|
2461
|
+
*/
|
|
2462
|
+
async dialogOp(req) {
|
|
2463
|
+
const conv = req.conversationId;
|
|
2464
|
+
const h = [...this.held.values()].find((x) => x.view.id === req.dialogId);
|
|
2465
|
+
if (h === void 0 || this.pageById(h.view.tabId) === void 0) {
|
|
2466
|
+
const any = this.tabsOf(conv).some((id) => this.held.has(id));
|
|
2467
|
+
throw new ActionError("failed", any ? DIALOG_CHANGED_MESSAGE : NO_DIALOG_MESSAGE);
|
|
2468
|
+
}
|
|
2469
|
+
if (this.owners.get(h.view.tabId)?.owner !== conv)
|
|
2470
|
+
throw new ActionError("failed", notYourTab(h.view.tabId));
|
|
2471
|
+
if (typeof req.message !== "string" || !dialogMessageMatches(req.message, h.view.message))
|
|
2472
|
+
throw new ActionError("failed", DIALOG_CHANGED_MESSAGE);
|
|
2473
|
+
const action = req.action === "accept" ? "accept" : "dismiss";
|
|
2474
|
+
if (h.view.kind === "auth") {
|
|
2475
|
+
if (action === "accept") throw new ActionError("failed", AUTH_SIGN_IN_TEXT);
|
|
2476
|
+
this.clearHeld(h.view.tabId);
|
|
2477
|
+
return { text: `Dismissed the sign-in request of ${h.view.origin ?? "the site"}.` };
|
|
2478
|
+
}
|
|
2479
|
+
await this.settleDialog(h, action, typeof req.text === "string" ? req.text : void 0);
|
|
2480
|
+
const name = h.view.kind === "beforeunload" ? "leave-page" : h.view.kind;
|
|
2481
|
+
return {
|
|
2482
|
+
text: `${action === "accept" ? "Accepted" : "Dismissed"} the ${name} dialog ${JSON.stringify(dialogQuote(h.view.message))}.`
|
|
2483
|
+
};
|
|
2484
|
+
}
|
|
2485
|
+
/** Accepts or dismisses a held JS dialog and forgets it. */
|
|
2486
|
+
async settleDialog(h, action, text) {
|
|
2487
|
+
this.clearHeld(h.view.tabId);
|
|
2488
|
+
const d = h.dialog;
|
|
2489
|
+
if (d === void 0) return;
|
|
2490
|
+
try {
|
|
2491
|
+
if (action === "accept")
|
|
2492
|
+
await d.accept(h.view.kind === "prompt" ? text ?? d.defaultValue() : void 0);
|
|
2493
|
+
else await d.dismiss();
|
|
2494
|
+
} catch {
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
/**
|
|
2498
|
+
* A viewer's answer to a held dialog of its tree (control is checked by the viewer). A stale id
|
|
2499
|
+
* or a dialog outside the tree changes nothing. An auth accept stores the credentials for the
|
|
2500
|
+
* dialog's origin (device-wide, memory only) and reloads the tab.
|
|
2501
|
+
*/
|
|
2502
|
+
async answerFromViewer(root, m) {
|
|
2503
|
+
const h = [...this.held.values()].find((x) => x.view.id === m.id);
|
|
2504
|
+
if (h === void 0 || this.owners.get(h.view.tabId)?.root !== root) return;
|
|
2505
|
+
const action = m.action === "accept" ? "accept" : "dismiss";
|
|
2506
|
+
if (h.view.kind !== "auth") {
|
|
2507
|
+
await this.settleDialog(h, action, typeof m.text === "string" ? m.text : void 0);
|
|
2508
|
+
return;
|
|
2509
|
+
}
|
|
2510
|
+
if (action === "dismiss") {
|
|
2511
|
+
this.clearHeld(h.view.tabId);
|
|
2512
|
+
return;
|
|
2513
|
+
}
|
|
2514
|
+
const origin = h.view.origin;
|
|
2515
|
+
if (origin === void 0 || typeof m.username !== "string" || typeof m.password !== "string")
|
|
2516
|
+
return;
|
|
2517
|
+
this.signIn(origin, m.username, m.password);
|
|
2518
|
+
for (const [id, x] of [...this.held])
|
|
2519
|
+
if (x.view.kind === "auth" && x.view.origin === origin) this.clearHeld(id);
|
|
2520
|
+
this.noteTo(h.owner.owner, `The user signed in to ${origin} (HTTP auth).`);
|
|
2521
|
+
const page = this.pageById(h.view.tabId);
|
|
2522
|
+
if (page !== void 0)
|
|
2523
|
+
await this.viewerNav(page, h.atUrl === void 0 ? { action: "reload" } : { url: h.atUrl });
|
|
2524
|
+
}
|
|
2525
|
+
// ---- HTTP Basic auth (dialogs spec §4)
|
|
2526
|
+
/**
|
|
2527
|
+
* A main-frame document answered 401: Chromium already cancelled the challenge and shows the
|
|
2528
|
+
* body. A Basic challenge becomes an auth dialog on the tab (unless a JS dialog is held there);
|
|
2529
|
+
* a 401 to a request the credentials signed means they are wrong: they are dropped. Another
|
|
2530
|
+
* scheme is noted as unsupported.
|
|
2531
|
+
*/
|
|
2532
|
+
onUnauthorized(page, id, r) {
|
|
2533
|
+
const origin = originOf(r.url());
|
|
2534
|
+
if (origin !== void 0 && this.signed.has(r.request())) this.forgetCredentials(origin);
|
|
2535
|
+
const o = this.owners.get(id);
|
|
2536
|
+
if (origin === void 0 || o === void 0) return;
|
|
2537
|
+
const header = r.headers()["www-authenticate"];
|
|
2538
|
+
if (header === void 0) return;
|
|
2539
|
+
this.challenged.add(page);
|
|
2540
|
+
const { scheme, realm } = authChallenge(header);
|
|
2541
|
+
if (scheme.toLowerCase() !== "basic") {
|
|
2542
|
+
this.noteTo(
|
|
2543
|
+
o.owner,
|
|
2544
|
+
`The site asks for ${clip(scheme, 40) || "an unknown"} sign-in, which the browser cannot do; ask the user how to continue.`
|
|
2545
|
+
);
|
|
2546
|
+
return;
|
|
2547
|
+
}
|
|
2548
|
+
if (blocks(this.held.get(id))) return;
|
|
2549
|
+
this.clearHeld(id);
|
|
2550
|
+
this.held.set(id, {
|
|
2551
|
+
view: {
|
|
2552
|
+
id: `d${++this.dialogSeq}`,
|
|
2553
|
+
tabId: id,
|
|
2554
|
+
kind: "auth",
|
|
2555
|
+
message: `HTTP sign-in for ${origin}`,
|
|
2556
|
+
origin,
|
|
2557
|
+
realm
|
|
2558
|
+
},
|
|
2559
|
+
dialog: void 0,
|
|
2560
|
+
owner: o,
|
|
2561
|
+
atUrl: docUrl(r.url())
|
|
2562
|
+
});
|
|
2563
|
+
this.emit({ type: "state" });
|
|
2564
|
+
}
|
|
2565
|
+
/**
|
|
2566
|
+
* Whether a navigation failed on a sign-in challenge the tab's page got (an auth dialog, or the
|
|
2567
|
+
* note of an unsupported scheme): the full build fails such a navigation where the headless
|
|
2568
|
+
* shell shows the 401 body; the reply names the dialog or carries the note instead.
|
|
2569
|
+
*/
|
|
2570
|
+
signInAsked(page, e) {
|
|
2571
|
+
return firstLine(e).includes("ERR_INVALID_AUTH_CREDENTIALS") && this.challenged.has(page);
|
|
2572
|
+
}
|
|
2573
|
+
/** Stores the person's credentials for exactly `origin` (memory only; the route signs). */
|
|
2574
|
+
signIn(origin, username, password) {
|
|
2575
|
+
this.credentials.set(
|
|
2576
|
+
origin,
|
|
2577
|
+
`Basic ${Buffer.from(`${username}:${password}`, "utf8").toString("base64")}`
|
|
1754
2578
|
);
|
|
1755
|
-
|
|
2579
|
+
}
|
|
2580
|
+
forgetCredentials(origin) {
|
|
2581
|
+
this.credentials.delete(origin);
|
|
2582
|
+
}
|
|
2583
|
+
onAuthRoute = async (route) => {
|
|
2584
|
+
const r = route.request();
|
|
2585
|
+
const value = this.authHeaderFor(r);
|
|
2586
|
+
if (value === void 0) {
|
|
2587
|
+
await route.fallback().catch(() => void 0);
|
|
2588
|
+
return;
|
|
2589
|
+
}
|
|
2590
|
+
this.signed.add(r);
|
|
2591
|
+
await route.fallback({ headers: { ...r.headers(), authorization: value } }).catch(() => void 0);
|
|
2592
|
+
};
|
|
2593
|
+
/**
|
|
2594
|
+
* The Authorization value a request gets, only where a browser's own page would send it: a
|
|
2595
|
+
* request to the signed-in origin from a frame whose own document has that origin inside a page
|
|
2596
|
+
* whose top-level document has it too (an iframe's navigation: its parent frame's document), or
|
|
2597
|
+
* a top-level navigation to it that this page started from that origin or that the daemon runs
|
|
2598
|
+
* (the agent's or the person's address bar, history, reload). Never a service worker's request,
|
|
2599
|
+
* a cross-site page's or embedded cross-origin frame's request (fetch, image, form post), or a
|
|
2600
|
+
* redirect into the origin. A redirect out of the origin drops the header on every later hop
|
|
2601
|
+
* (the patched playwright-core, which replays a route's headers on redirects).
|
|
2602
|
+
*/
|
|
2603
|
+
authHeaderFor(r) {
|
|
2604
|
+
const origin = originOf(r.url());
|
|
2605
|
+
const value = origin === void 0 ? void 0 : this.credentials.get(origin);
|
|
2606
|
+
if (value === void 0 || r.serviceWorker() !== null) return void 0;
|
|
2607
|
+
let frame;
|
|
2608
|
+
try {
|
|
2609
|
+
frame = r.frame();
|
|
2610
|
+
} catch {
|
|
2611
|
+
return void 0;
|
|
2612
|
+
}
|
|
2613
|
+
const page = frame.page();
|
|
2614
|
+
const top = originOf(page.mainFrame().url());
|
|
2615
|
+
let root = r;
|
|
2616
|
+
for (let f = r.redirectedFrom(); f !== null; f = f.redirectedFrom()) root = f;
|
|
2617
|
+
if (originOf(root.url()) !== origin) return void 0;
|
|
2618
|
+
if (!r.isNavigationRequest()) {
|
|
2619
|
+
return top === origin && originOf(frame.url()) === origin ? value : void 0;
|
|
2620
|
+
}
|
|
2621
|
+
if (frame !== page.mainFrame()) {
|
|
2622
|
+
const parent = frame.parentFrame();
|
|
2623
|
+
return top === origin && parent !== null && originOf(parent.url()) === origin ? value : void 0;
|
|
2624
|
+
}
|
|
2625
|
+
if (top === origin || (this.ownNavs.get(page) ?? 0) > 0) return value;
|
|
2626
|
+
return void 0;
|
|
2627
|
+
}
|
|
2628
|
+
/** Runs a navigation the daemon starts on a page (its root request is trusted for auth). */
|
|
2629
|
+
async ownNav(page, fn) {
|
|
2630
|
+
this.ownNavs.set(page, (this.ownNavs.get(page) ?? 0) + 1);
|
|
2631
|
+
try {
|
|
2632
|
+
return await fn();
|
|
2633
|
+
} finally {
|
|
2634
|
+
this.ownNavs.set(page, Math.max(0, (this.ownNavs.get(page) ?? 1) - 1));
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
// ---- permission requests (dialogs spec §6)
|
|
2638
|
+
/**
|
|
2639
|
+
* A page reported a refused permission request through the binding. Nothing in the payload is
|
|
2640
|
+
* trusted but a known permission name: the origin is the calling frame's, reports are capped per
|
|
2641
|
+
* page load and in distinct pairs, and only a pair recorded here can be granted later.
|
|
2642
|
+
*/
|
|
2643
|
+
onPermissionReport(page, frameUrl, name) {
|
|
2644
|
+
if (typeof name !== "string" || !REPORTED_PERMISSIONS.includes(name))
|
|
2645
|
+
return;
|
|
2646
|
+
const permission = name;
|
|
2647
|
+
const id = this.ids.get(page);
|
|
2648
|
+
const o = id === void 0 ? void 0 : this.owners.get(id);
|
|
2649
|
+
const origin = originOf(frameUrl);
|
|
2650
|
+
if (id === void 0 || o === void 0 || origin === void 0) return;
|
|
2651
|
+
const count = (this.permissionCount.get(page) ?? 0) + 1;
|
|
2652
|
+
this.permissionCount.set(page, count);
|
|
2653
|
+
if (count > PERMISSION_REPORTS_PER_LOAD) return;
|
|
2654
|
+
const pair = `${origin}\0${permission}`;
|
|
2655
|
+
const fresh = !this.permissionPairs.has(pair);
|
|
2656
|
+
if (fresh && this.permissionPairs.size >= MAX_PERMISSION_PAIRS) return;
|
|
2657
|
+
this.permissionPairs.add(pair);
|
|
2658
|
+
const onTab = this.tabPermissions.get(id) ?? /* @__PURE__ */ new Set();
|
|
2659
|
+
onTab.add(pair);
|
|
2660
|
+
this.tabPermissions.set(id, onTab);
|
|
2661
|
+
const grantable = GRANTABLE_PERMISSIONS.includes(permission);
|
|
2662
|
+
if (fresh)
|
|
2663
|
+
this.noteTo(
|
|
2664
|
+
o.owner,
|
|
2665
|
+
`The page asked for ${permission} permission, which was denied.${grantable ? " The user can allow it from the browser panel." : " The device's browser cannot provide it."}`
|
|
2666
|
+
);
|
|
2667
|
+
this.emit({ type: "permission", origin, permission, grantable, root: o.root });
|
|
2668
|
+
}
|
|
2669
|
+
/**
|
|
2670
|
+
* Grants a permission the person allowed in the panel, for the daemon's life (never written to
|
|
2671
|
+
* the profile): only grantable ones, only for a pair recorded on a tab of the viewer's tree.
|
|
2672
|
+
*/
|
|
2673
|
+
async grantPermission(root, origin, permission) {
|
|
2674
|
+
if (typeof origin !== "string" || typeof permission !== "string") return false;
|
|
2675
|
+
if (!GRANTABLE_PERMISSIONS.includes(permission)) return false;
|
|
2676
|
+
const pair = `${origin}\0${permission}`;
|
|
2677
|
+
const inTree = [...this.tabPermissions].some(
|
|
2678
|
+
([id, pairs]) => pairs.has(pair) && this.owners.get(id)?.root === root
|
|
2679
|
+
);
|
|
2680
|
+
if (!inTree) return false;
|
|
2681
|
+
try {
|
|
2682
|
+
await this.ctx.grantPermissions([permission], { origin });
|
|
2683
|
+
return true;
|
|
2684
|
+
} catch {
|
|
2685
|
+
return false;
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
// ---- viewport profiles and touch (dialogs spec §7)
|
|
2689
|
+
/** The viewport the pages have now (a switch counts once applied). */
|
|
2690
|
+
get viewport() {
|
|
2691
|
+
const p = VIEWPORT_PROFILES[this.applied];
|
|
2692
|
+
return { width: p.width, height: p.height, mobile: p.mobile };
|
|
2693
|
+
}
|
|
2694
|
+
/** Switches every tab (and tabs opened later) to the profile (the person's choice). */
|
|
2695
|
+
setProfile(profile) {
|
|
2696
|
+
if (profile !== "desktop" && profile !== "phone") return this.viewportGate;
|
|
2697
|
+
if (profile === this.profile) return this.viewportGate;
|
|
2698
|
+
this.profile = profile;
|
|
2699
|
+
this.touchTranslator.reset();
|
|
2700
|
+
const pages = this.live().map(([, p]) => p);
|
|
2701
|
+
const run = async () => {
|
|
2702
|
+
if (profile === "phone") await Promise.all(pages.map((p) => this.applyPhone(p)));
|
|
2703
|
+
else await this.restoreAll();
|
|
2704
|
+
if (this.profile === profile) this.applied = profile;
|
|
2705
|
+
};
|
|
2706
|
+
const next = this.viewportGate.then(run, run);
|
|
2707
|
+
this.viewportGate = next.catch(() => void 0);
|
|
2708
|
+
this.emit({ type: "state" });
|
|
2709
|
+
void this.viewportGate.then(() => this.emit({ type: "state" }));
|
|
2710
|
+
return this.viewportGate;
|
|
2711
|
+
}
|
|
2712
|
+
/**
|
|
2713
|
+
* Back to the desktop profile (hand back): every agent request of any conversation waits for
|
|
2714
|
+
* it, so the agent always acts on 1280x800.
|
|
2715
|
+
*/
|
|
2716
|
+
restoreDesktop() {
|
|
2717
|
+
return this.setProfile("desktop");
|
|
2718
|
+
}
|
|
2719
|
+
/**
|
|
2720
|
+
* The CDP session that holds a page's profile overrides (the newest of its sessions), made on
|
|
2721
|
+
* first use; `fresh` makes a new one (after a navigation, a renderer swapped in for another site
|
|
2722
|
+
* follows no session made before). Sessions are kept: a detach drops every device metric of the
|
|
2723
|
+
* page, Playwright's included, which it does not send again; the restore ends them in order.
|
|
2724
|
+
*/
|
|
2725
|
+
profileSession(page, fresh = false) {
|
|
2726
|
+
const list = this.profileSessions.get(page) ?? [];
|
|
2727
|
+
const last = list.at(-1);
|
|
2728
|
+
if (last !== void 0 && !fresh) return last;
|
|
2729
|
+
const made = (async () => {
|
|
2730
|
+
try {
|
|
2731
|
+
const cdp = await this.ctx.newCDPSession(page);
|
|
2732
|
+
this.desktopUa ??= await this.bounded(
|
|
2733
|
+
cdp.send("Runtime.evaluate", { expression: "navigator.userAgent", returnByValue: true }).then((r) => typeof r.result.value === "string" ? r.result.value : void 0),
|
|
2734
|
+
void 0
|
|
2735
|
+
);
|
|
2736
|
+
this.mobileUa ??= mobileUserAgent(this.desktopUa ?? "");
|
|
2737
|
+
return cdp;
|
|
2738
|
+
} catch {
|
|
2739
|
+
return void 0;
|
|
2740
|
+
}
|
|
2741
|
+
})();
|
|
2742
|
+
list.push(made);
|
|
2743
|
+
this.profileSessions.set(page, list);
|
|
2744
|
+
return made;
|
|
2745
|
+
}
|
|
2746
|
+
/**
|
|
2747
|
+
* Applies the phone profile to a page: Playwright's own viewport first (its emulation, which it
|
|
2748
|
+
* may send again on a navigation, then agrees on the size, and the restore is a real change for
|
|
2749
|
+
* it), then the mobile metrics, touch and user agent through the page's profile session.
|
|
2750
|
+
*/
|
|
2751
|
+
async applyPhone(page, fresh = false) {
|
|
2752
|
+
const cdp = await this.profileSession(page, fresh);
|
|
2753
|
+
if (cdp === void 0 || this.profile !== "phone" || page.isClosed()) return void 0;
|
|
2754
|
+
try {
|
|
2755
|
+
await page.setViewportSize({
|
|
2756
|
+
width: VIEWPORT_PROFILES.phone.width,
|
|
2757
|
+
height: VIEWPORT_PROFILES.phone.height
|
|
2758
|
+
});
|
|
2759
|
+
const p = VIEWPORT_PROFILES.phone;
|
|
2760
|
+
await cdp.send("Emulation.setDeviceMetricsOverride", {
|
|
2761
|
+
width: p.width,
|
|
2762
|
+
height: p.height,
|
|
2763
|
+
deviceScaleFactor: p.scale,
|
|
2764
|
+
mobile: true,
|
|
2765
|
+
screenWidth: p.width,
|
|
2766
|
+
screenHeight: p.height
|
|
2767
|
+
});
|
|
2768
|
+
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 });
|
|
2769
|
+
await cdp.send("Emulation.setUserAgentOverride", {
|
|
2770
|
+
userAgent: this.mobileUa ?? mobileUserAgent("")
|
|
2771
|
+
});
|
|
2772
|
+
return cdp;
|
|
2773
|
+
} catch {
|
|
2774
|
+
return void 0;
|
|
2775
|
+
}
|
|
2776
|
+
}
|
|
2777
|
+
/**
|
|
2778
|
+
* A page back on desktop: its older profile sessions end (each detach drops the page's
|
|
2779
|
+
* metrics), the newest sends the desktop values and the agent's user agent, and Playwright gets
|
|
2780
|
+
* its own 1280x800 again.
|
|
2781
|
+
*/
|
|
2782
|
+
async applyDesktop(page) {
|
|
2783
|
+
const list = this.profileSessions.get(page) ?? [];
|
|
2784
|
+
const sessions = await Promise.all(list);
|
|
2785
|
+
this.profileSessions.set(page, list.slice(-1));
|
|
2786
|
+
for (const old of sessions.slice(0, -1)) await old?.detach().catch(() => void 0);
|
|
2787
|
+
if (page.isClosed()) return;
|
|
2788
|
+
const cdp = sessions.at(-1);
|
|
2789
|
+
if (cdp !== void 0) {
|
|
2790
|
+
await cdp.send("Emulation.setDeviceMetricsOverride", {
|
|
2791
|
+
width: VIEWPORT.width,
|
|
2792
|
+
height: VIEWPORT.height,
|
|
2793
|
+
deviceScaleFactor: 1,
|
|
2794
|
+
mobile: false,
|
|
2795
|
+
screenWidth: VIEWPORT.width,
|
|
2796
|
+
screenHeight: VIEWPORT.height
|
|
2797
|
+
}).catch(() => void 0);
|
|
2798
|
+
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }).catch(() => void 0);
|
|
2799
|
+
if (this.desktopUa !== void 0)
|
|
2800
|
+
await cdp.send("Emulation.setUserAgentOverride", { userAgent: this.desktopUa }).catch(() => void 0);
|
|
2801
|
+
}
|
|
2802
|
+
await page.setViewportSize({ ...VIEWPORT }).catch(() => void 0);
|
|
2803
|
+
}
|
|
2804
|
+
/**
|
|
2805
|
+
* A page navigated while the phone profile is on: Playwright may send its own metrics again,
|
|
2806
|
+
* and a renderer swapped in keeps no overrides, so they go again on a fresh session (in the
|
|
2807
|
+
* profile chain: a restore waits for it).
|
|
2808
|
+
*/
|
|
2809
|
+
reapplyPhone(page) {
|
|
2810
|
+
if (this.profile !== "phone") return;
|
|
2811
|
+
const run = () => this.applyPhone(page, true).then(() => void 0);
|
|
2812
|
+
const next = this.viewportGate.then(run, run);
|
|
2813
|
+
this.viewportGate = next.catch(() => void 0);
|
|
2814
|
+
}
|
|
2815
|
+
/** Every page that got the phone profile back on desktop. */
|
|
2816
|
+
async restoreAll() {
|
|
2817
|
+
await Promise.all([...this.profileSessions.keys()].map((page) => this.applyDesktop(page)));
|
|
2818
|
+
}
|
|
2819
|
+
/**
|
|
2820
|
+
* A viewer's touch input on a page: touch events in the phone profile; in desktop a tap clicks
|
|
2821
|
+
* and a one-finger pan scrolls (anything else is ignored).
|
|
2822
|
+
*/
|
|
2823
|
+
async touch(page, kind, points) {
|
|
2824
|
+
if (this.profile === "phone") {
|
|
2825
|
+
const cdp = await this.profileSession(page);
|
|
2826
|
+
if (cdp === void 0) return;
|
|
2827
|
+
const type = kind === "start" ? "touchStart" : kind === "move" ? "touchMove" : kind === "end" ? "touchEnd" : "touchCancel";
|
|
2828
|
+
await cdp.send("Input.dispatchTouchEvent", {
|
|
2829
|
+
type,
|
|
2830
|
+
touchPoints: points.map((p) => ({ x: p.x, y: p.y, id: p.id }))
|
|
2831
|
+
}).catch(() => void 0);
|
|
2832
|
+
return;
|
|
2833
|
+
}
|
|
2834
|
+
for (const a of this.touchTranslator.feed(kind, points)) await this.runTouchAction(page, a);
|
|
2835
|
+
}
|
|
2836
|
+
async runTouchAction(page, a) {
|
|
2837
|
+
try {
|
|
2838
|
+
if (a.kind === "click") await page.mouse.click(a.x, a.y);
|
|
2839
|
+
else {
|
|
2840
|
+
await page.mouse.move(a.x, a.y);
|
|
2841
|
+
await page.mouse.wheel(a.dx, a.dy);
|
|
2842
|
+
}
|
|
2843
|
+
} catch {
|
|
2844
|
+
}
|
|
1756
2845
|
}
|
|
1757
2846
|
/**
|
|
1758
2847
|
* A device note (not about a page: the browser build that runs): the replies of the requests in
|
|
@@ -1830,6 +2919,10 @@ var BrowserSession = class {
|
|
|
1830
2919
|
}
|
|
1831
2920
|
target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
|
|
1832
2921
|
note(`Downloaded ${shown} to ${target}.`);
|
|
2922
|
+
if (owner !== void 0) {
|
|
2923
|
+
this.watches.downloadSaved(owner, target);
|
|
2924
|
+
for (const w of [...this.downloadWaiters]) if (w.conv === owner) w.resolve(target);
|
|
2925
|
+
}
|
|
1833
2926
|
} catch (e) {
|
|
1834
2927
|
note(
|
|
1835
2928
|
`The download of ${shown} was not saved: ${e instanceof ActionError ? e.message : firstLine(e)}`
|
|
@@ -2112,12 +3205,15 @@ var BrowserSession = class {
|
|
|
2112
3205
|
this.collectors.add(c);
|
|
2113
3206
|
let reply;
|
|
2114
3207
|
try {
|
|
2115
|
-
|
|
2116
|
-
const
|
|
3208
|
+
await this.viewportGate;
|
|
3209
|
+
const beside = req.op === "wait" || req.op === "watch_end" || req.op === "dialog" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
|
|
3210
|
+
this.refuseIfBlocked(req);
|
|
3211
|
+
const out = await (beside ? req.op === "wait" ? this.raceDialog(conv, req.op, () => this.exec(req)) : this.exec(req) : this.serial(conv, () => {
|
|
2117
3212
|
if (opts.takenOver?.() === true)
|
|
2118
3213
|
throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
|
|
2119
|
-
|
|
2120
|
-
|
|
3214
|
+
this.refuseIfBlocked(req);
|
|
3215
|
+
return this.raceDialog(conv, req.op, () => this.exec(req));
|
|
3216
|
+
})) ?? {};
|
|
2121
3217
|
await this.settleProbes(c);
|
|
2122
3218
|
await this.settleDownloads(c);
|
|
2123
3219
|
this.collectors.delete(c);
|
|
@@ -2126,18 +3222,21 @@ var BrowserSession = class {
|
|
|
2126
3222
|
this.tabUsedAt.set(this.tabIdOf(page), this.clock.now());
|
|
2127
3223
|
this.actedSeq.set(conv, ++this.actSeq);
|
|
2128
3224
|
}
|
|
2129
|
-
const verifying = page === void 0 || req.op === "tabs" && (req.action === "list" || req.action === "adopt") ? false : await this.checkVerification(page, this.tabIdOf(page));
|
|
3225
|
+
const verifying = page === void 0 || blocks(this.held.get(this.tabIdOf(page))) || req.op === "dialog" || req.op === "tabs" && (req.action === "list" || req.action === "adopt") ? false : await this.checkVerification(page, this.tabIdOf(page));
|
|
2130
3226
|
const text = [
|
|
2131
3227
|
...verifying ? [VERIFICATION_NOTE] : [],
|
|
2132
3228
|
...c.notes,
|
|
2133
3229
|
...out.text === void 0 ? [] : [out.text]
|
|
2134
3230
|
].join("\n");
|
|
3231
|
+
const dialog = this.dialogFor(conv);
|
|
2135
3232
|
reply = {
|
|
2136
3233
|
ok: true,
|
|
2137
3234
|
...page === void 0 ? {} : { page: await this.pageInfo(page) },
|
|
2138
3235
|
blockedHosts: blockedHostsOf(c),
|
|
2139
3236
|
...text === "" ? {} : { text },
|
|
2140
|
-
...out.image === void 0 ? {} : { image: out.image }
|
|
3237
|
+
...out.image === void 0 ? {} : { image: out.image },
|
|
3238
|
+
...out.watch === void 0 ? {} : { watch: out.watch },
|
|
3239
|
+
...dialog === void 0 ? {} : { dialog }
|
|
2141
3240
|
};
|
|
2142
3241
|
} catch (e) {
|
|
2143
3242
|
await this.settleProbes(c);
|
|
@@ -2160,6 +3259,32 @@ var BrowserSession = class {
|
|
|
2160
3259
|
this.emit({ type: "state" });
|
|
2161
3260
|
return reply;
|
|
2162
3261
|
}
|
|
3262
|
+
/**
|
|
3263
|
+
* Refuses an operation a JS dialog on the conversation's active tab blocks (`dialog_open`). In a
|
|
3264
|
+
* one-process browser any held JS dialog stops every page: every acting request is refused (the
|
|
3265
|
+
* conversation's own dialog named, another conversation's never).
|
|
3266
|
+
*/
|
|
3267
|
+
refuseIfBlocked(req) {
|
|
3268
|
+
const conv = req.conversationId;
|
|
3269
|
+
const activeHeld = this.held.get(this.activeTabOf(conv) ?? "");
|
|
3270
|
+
const harmless = req.op === "wait" || req.op === "tabs" && req.action === "switch" || req.op === "snapshot" && blocks(activeHeld);
|
|
3271
|
+
if (this.singleProcess && isActing(req) && !harmless) {
|
|
3272
|
+
const own = this.dialogFor(conv);
|
|
3273
|
+
if (own !== void 0 && own.kind !== "auth")
|
|
3274
|
+
throw new ActionError("dialog_open", blockedByDialogText(own));
|
|
3275
|
+
if ([...this.held.values()].some(blocks))
|
|
3276
|
+
throw new ActionError("failed", PAUSED_BY_DIALOG_MESSAGE);
|
|
3277
|
+
}
|
|
3278
|
+
if (!BLOCKED_OPS.has(req.op)) return;
|
|
3279
|
+
const tab = this.activeTabOf(conv);
|
|
3280
|
+
const h = tab === void 0 ? void 0 : this.held.get(tab);
|
|
3281
|
+
if (blocks(h)) throw new ActionError("dialog_open", blockedByDialogText(h.view));
|
|
3282
|
+
}
|
|
3283
|
+
/** The JS dialog that blocks a page, if any. */
|
|
3284
|
+
blockingDialog(page) {
|
|
3285
|
+
const h = this.held.get(this.tabIdOf(page));
|
|
3286
|
+
return blocks(h) ? h.view : void 0;
|
|
3287
|
+
}
|
|
2163
3288
|
/**
|
|
2164
3289
|
* Waits for the request's downloads at most `downloadWaitMs`; those still running are noted as
|
|
2165
3290
|
* in progress (their result note comes later).
|
|
@@ -2238,7 +3363,7 @@ var BrowserSession = class {
|
|
|
2238
3363
|
}
|
|
2239
3364
|
async pageInfo(page) {
|
|
2240
3365
|
const known = this.titles.get(this.tabIdOf(page)) ?? "";
|
|
2241
|
-
const title = await this.bounded(
|
|
3366
|
+
const title = this.blockingDialog(page) !== void 0 ? known : await this.bounded(
|
|
2242
3367
|
page.title().catch(() => known),
|
|
2243
3368
|
known
|
|
2244
3369
|
);
|
|
@@ -2319,9 +3444,10 @@ var BrowserSession = class {
|
|
|
2319
3444
|
const deadline = Date.now() + this.navigationTimeoutMs;
|
|
2320
3445
|
const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
|
|
2321
3446
|
try {
|
|
2322
|
-
res = await this.gotoPastNetworkChange(page, url, watch, deadline);
|
|
3447
|
+
res = await this.ownNav(page, () => this.gotoPastNetworkChange(page, url, watch, deadline));
|
|
2323
3448
|
} catch (e) {
|
|
2324
3449
|
const msg = firstLine(e);
|
|
3450
|
+
if (this.signInAsked(page, e)) return;
|
|
2325
3451
|
if (msg.includes("Download is starting")) {
|
|
2326
3452
|
await download.catch(() => void 0);
|
|
2327
3453
|
return;
|
|
@@ -2499,20 +3625,25 @@ var BrowserSession = class {
|
|
|
2499
3625
|
if (req.url !== void 0) {
|
|
2500
3626
|
await this.goto(page, normalizeUrl(req.url));
|
|
2501
3627
|
} else if (req.action === "back" || req.action === "forward") {
|
|
2502
|
-
const r = await
|
|
3628
|
+
const r = await this.ownNav(
|
|
3629
|
+
page,
|
|
3630
|
+
() => req.action === "back" ? page.goBack() : page.goForward()
|
|
3631
|
+
).catch(async (e) => {
|
|
3632
|
+
if (this.signInAsked(page, e)) return null;
|
|
3633
|
+
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
3634
|
+
throw e;
|
|
3635
|
+
});
|
|
3636
|
+
if (r === null && page.url() === "about:blank") {
|
|
3637
|
+
return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
|
|
3638
|
+
}
|
|
3639
|
+
} else if (req.action === "reload") {
|
|
3640
|
+
await this.ownNav(page, () => page.reload({ waitUntil: "domcontentloaded" })).catch(
|
|
2503
3641
|
async (e) => {
|
|
3642
|
+
if (this.signInAsked(page, e)) return null;
|
|
2504
3643
|
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
2505
3644
|
throw e;
|
|
2506
3645
|
}
|
|
2507
3646
|
);
|
|
2508
|
-
if (r === null && page.url() === "about:blank") {
|
|
2509
|
-
return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
|
|
2510
|
-
}
|
|
2511
|
-
} else if (req.action === "reload") {
|
|
2512
|
-
await page.reload({ waitUntil: "domcontentloaded" }).catch(async (e) => {
|
|
2513
|
-
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
2514
|
-
throw e;
|
|
2515
|
-
});
|
|
2516
3647
|
} else {
|
|
2517
3648
|
throw new ActionError(
|
|
2518
3649
|
"failed",
|
|
@@ -2523,8 +3654,14 @@ var BrowserSession = class {
|
|
|
2523
3654
|
}
|
|
2524
3655
|
case "tabs":
|
|
2525
3656
|
return this.tabsOp(req);
|
|
2526
|
-
case "snapshot":
|
|
2527
|
-
|
|
3657
|
+
case "snapshot": {
|
|
3658
|
+
const page = await activePage();
|
|
3659
|
+
const blocking = this.blockingDialog(page);
|
|
3660
|
+
if (blocking !== void 0) return { text: blockedByDialogText(blocking) };
|
|
3661
|
+
return { text: await takeSnapshot(page) };
|
|
3662
|
+
}
|
|
3663
|
+
case "dialog":
|
|
3664
|
+
return this.dialogOp(req);
|
|
2528
3665
|
case "click":
|
|
2529
3666
|
case "hover": {
|
|
2530
3667
|
const page = await activePage();
|
|
@@ -2588,6 +3725,8 @@ var BrowserSession = class {
|
|
|
2588
3725
|
}
|
|
2589
3726
|
case "wait":
|
|
2590
3727
|
return this.waitOp(req, this.currentPage(conv));
|
|
3728
|
+
case "watch_end":
|
|
3729
|
+
return { watch: this.watchEnd(req) };
|
|
2591
3730
|
case "screenshot": {
|
|
2592
3731
|
const page = await activePage();
|
|
2593
3732
|
const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
|
|
@@ -2708,17 +3847,79 @@ var BrowserSession = class {
|
|
|
2708
3847
|
async viewerNav(page, nav) {
|
|
2709
3848
|
try {
|
|
2710
3849
|
if (nav.url !== void 0) await this.goto(page, normalizeUrl(nav.url));
|
|
2711
|
-
else if (nav.action === "back") await page.goBack();
|
|
2712
|
-
else if (nav.action === "forward") await page.goForward();
|
|
2713
|
-
else if (nav.action === "reload") await page.reload();
|
|
3850
|
+
else if (nav.action === "back") await this.ownNav(page, () => page.goBack());
|
|
3851
|
+
else if (nav.action === "forward") await this.ownNav(page, () => page.goForward());
|
|
3852
|
+
else if (nav.action === "reload") await this.ownNav(page, () => page.reload());
|
|
2714
3853
|
} catch {
|
|
2715
3854
|
}
|
|
2716
3855
|
}
|
|
3856
|
+
/** The saved path of the conversation's next download within `ms`, else undefined. */
|
|
3857
|
+
nextDownload(conv, ms) {
|
|
3858
|
+
return new Promise((resolve) => {
|
|
3859
|
+
let timer;
|
|
3860
|
+
const w = {
|
|
3861
|
+
conv,
|
|
3862
|
+
resolve: (path) => {
|
|
3863
|
+
this.downloadWaiters.delete(w);
|
|
3864
|
+
this.clock.cancel(timer);
|
|
3865
|
+
resolve(path);
|
|
3866
|
+
}
|
|
3867
|
+
};
|
|
3868
|
+
this.downloadWaiters.add(w);
|
|
3869
|
+
timer = this.clock.schedule(() => w.resolve(void 0), ms);
|
|
3870
|
+
});
|
|
3871
|
+
}
|
|
3872
|
+
/** Whether a watch's condition holds on the page now (text, ref, URL part). */
|
|
3873
|
+
async conditionHolds(page, c) {
|
|
3874
|
+
if ("text" in c) return this.bounded(page.getByText(c.text).first().isVisible(), false);
|
|
3875
|
+
if ("ref" in c)
|
|
3876
|
+
return REF_RE.test(c.ref) && this.bounded(page.getByRef(c.ref).first().isVisible(), false);
|
|
3877
|
+
if ("urlContains" in c) return page.url().includes(c.urlContains);
|
|
3878
|
+
return false;
|
|
3879
|
+
}
|
|
3880
|
+
/**
|
|
3881
|
+
* Arms a long wait's watch on the conversation's active tab (browser long waits spec §6.2);
|
|
3882
|
+
* a conversation without a tab cannot be watched. Idempotent per watch id.
|
|
3883
|
+
*/
|
|
3884
|
+
watchStart(req) {
|
|
3885
|
+
const conv = req.conversationId;
|
|
3886
|
+
if (!this.watches.owns(req.watchId, conv)) return { state: "unknown" };
|
|
3887
|
+
const condition = parseCondition(req.condition);
|
|
3888
|
+
if (typeof condition === "string") throw new ActionError("failed", condition);
|
|
3889
|
+
if ("ref" in condition && !REF_RE.test(condition.ref))
|
|
3890
|
+
throw new ActionError(
|
|
3891
|
+
"no_such_ref",
|
|
3892
|
+
`${JSON.stringify(condition.ref)} is not an element ref; refs look like e12.`
|
|
3893
|
+
);
|
|
3894
|
+
const page = this.currentPage(conv);
|
|
3895
|
+
if (page === void 0) throw new ActionError("failed", NO_TAB_TO_WAIT_ON);
|
|
3896
|
+
const remaining = Number(req.remainingMs);
|
|
3897
|
+
return this.watches.start({
|
|
3898
|
+
id: req.watchId,
|
|
3899
|
+
conv,
|
|
3900
|
+
root: req.rootConversationId,
|
|
3901
|
+
tabId: this.tabIdOf(page),
|
|
3902
|
+
page,
|
|
3903
|
+
condition,
|
|
3904
|
+
remainingMs: Number.isFinite(remaining) ? remaining : 0
|
|
3905
|
+
});
|
|
3906
|
+
}
|
|
3907
|
+
/** A long wait's poll (its heartbeat); another conversation's watch reads as unknown. */
|
|
3908
|
+
watchPoll(req) {
|
|
3909
|
+
if (!this.watches.owns(req.watchId, req.conversationId)) return { state: "unknown" };
|
|
3910
|
+
return this.watches.poll(req.watchId);
|
|
3911
|
+
}
|
|
3912
|
+
/** Ends a long wait's watch, answering its last state. */
|
|
3913
|
+
watchEnd(req) {
|
|
3914
|
+
if (!this.watches.owns(req.watchId, req.conversationId)) return { state: "unknown" };
|
|
3915
|
+
return this.watches.end(req.watchId);
|
|
3916
|
+
}
|
|
2717
3917
|
async waitOp(req, page) {
|
|
2718
3918
|
const asked = Number(req.timeoutMs);
|
|
2719
3919
|
const timeout = Number.isFinite(asked) ? Math.max(0, Math.min(MAX_WAIT_MS, Math.floor(asked))) : DEFAULT_WAIT_MS;
|
|
3920
|
+
if (page !== void 0 && this.blockingDialog(page) !== void 0) return {};
|
|
2720
3921
|
if (page === void 0) {
|
|
2721
|
-
if (req.text !== void 0 || req.ref !== void 0 || req.navigation === true)
|
|
3922
|
+
if (req.text !== void 0 || req.ref !== void 0 || req.navigation === true || req.urlContains !== void 0 || req.download === true)
|
|
2722
3923
|
throw new ActionError("failed", NO_TAB_TO_WAIT_ON);
|
|
2723
3924
|
await new Promise((r) => this.clock.schedule(r, timeout));
|
|
2724
3925
|
return {};
|
|
@@ -2744,6 +3945,22 @@ var BrowserSession = class {
|
|
|
2744
3945
|
});
|
|
2745
3946
|
return {};
|
|
2746
3947
|
}
|
|
3948
|
+
if (req.urlContains !== void 0) {
|
|
3949
|
+
const part = req.urlContains;
|
|
3950
|
+
await page.waitForURL((u) => u.href.includes(part), { timeout, waitUntil: "commit" }).catch((e) => {
|
|
3951
|
+
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError(
|
|
3952
|
+
"timeout",
|
|
3953
|
+
`The URL did not contain ${JSON.stringify(part)} within ${timeout} ms.`
|
|
3954
|
+
) : e;
|
|
3955
|
+
});
|
|
3956
|
+
return {};
|
|
3957
|
+
}
|
|
3958
|
+
if (req.download === true) {
|
|
3959
|
+
const path = await this.nextDownload(req.conversationId, timeout);
|
|
3960
|
+
if (path === void 0)
|
|
3961
|
+
throw new ActionError("timeout", `No download finished within ${timeout} ms.`);
|
|
3962
|
+
return { text: `Waited for the download: ${path}.` };
|
|
3963
|
+
}
|
|
2747
3964
|
if (req.navigation === true) {
|
|
2748
3965
|
await page.waitForEvent("framenavigated", { predicate: (f) => f === page.mainFrame(), timeout }).catch((e) => {
|
|
2749
3966
|
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError("timeout", `No navigation within ${timeout} ms.`) : e;
|
|
@@ -2756,6 +3973,7 @@ var BrowserSession = class {
|
|
|
2756
3973
|
}
|
|
2757
3974
|
/** Closes the browser (flushes the profile). */
|
|
2758
3975
|
async close() {
|
|
3976
|
+
this.watches.dispose();
|
|
2759
3977
|
this.listeners.clear();
|
|
2760
3978
|
if (this.downloadPoll !== void 0) this.clock.cancel(this.downloadPoll);
|
|
2761
3979
|
await this.ctx.close().catch(() => void 0);
|
|
@@ -3113,7 +4331,7 @@ async function restoreCookies(ctx, stateDir) {
|
|
|
3113
4331
|
// daemon/session-file.ts
|
|
3114
4332
|
import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3115
4333
|
import { join as join4 } from "node:path";
|
|
3116
|
-
var RESTORE_MAX_AGE_MS =
|
|
4334
|
+
var RESTORE_MAX_AGE_MS = DEVICE_SERVICE_RESTORE_MAX_AGE_MS;
|
|
3117
4335
|
var SESSION_FILE_VERSION = 2;
|
|
3118
4336
|
var isId = (v) => typeof v === "string" && v !== "";
|
|
3119
4337
|
var SessionFile = class {
|
|
@@ -3203,6 +4421,27 @@ var SessionFile = class {
|
|
|
3203
4421
|
}
|
|
3204
4422
|
});
|
|
3205
4423
|
}
|
|
4424
|
+
/**
|
|
4425
|
+
* Removes a deleted conversation and the conversations whose tree root it is from the file on
|
|
4426
|
+
* disk, keeping its save time (a restore window never grows), so a later start does not restore
|
|
4427
|
+
* their tabs. Nothing to do without a file or after {@link forget}.
|
|
4428
|
+
*/
|
|
4429
|
+
dropTree(conversationId) {
|
|
4430
|
+
if (this.forgotten) return;
|
|
4431
|
+
let raw;
|
|
4432
|
+
try {
|
|
4433
|
+
raw = JSON.parse(readFileSync3(this.file, "utf8"));
|
|
4434
|
+
} catch {
|
|
4435
|
+
return;
|
|
4436
|
+
}
|
|
4437
|
+
const next = withoutTree(raw, conversationId);
|
|
4438
|
+
if (next === raw) return;
|
|
4439
|
+
try {
|
|
4440
|
+
writeFileSync3(`${this.file}.tmp`, JSON.stringify(next), { mode: 384 });
|
|
4441
|
+
renameSync2(`${this.file}.tmp`, this.file);
|
|
4442
|
+
} catch {
|
|
4443
|
+
}
|
|
4444
|
+
}
|
|
3206
4445
|
/** Removes the file and stops saving (an idle stop). */
|
|
3207
4446
|
forget() {
|
|
3208
4447
|
this.forgotten = true;
|
|
@@ -3236,6 +4475,22 @@ var SessionFile = class {
|
|
|
3236
4475
|
}
|
|
3237
4476
|
}
|
|
3238
4477
|
};
|
|
4478
|
+
function withoutTree(saved, conversationId) {
|
|
4479
|
+
const hit = (owner, root) => owner === conversationId || root === conversationId;
|
|
4480
|
+
if (!Array.isArray(saved.tabs) || !Array.isArray(saved.conversations)) return saved;
|
|
4481
|
+
const tabs = saved.tabs.filter((t) => !hit(t?.owner, t?.root));
|
|
4482
|
+
const conversations = saved.conversations.filter((c) => !hit(c?.id, c?.root));
|
|
4483
|
+
if (tabs.length === saved.tabs.length && conversations.length === saved.conversations.length)
|
|
4484
|
+
return saved;
|
|
4485
|
+
const kept = conversations.map((c) => {
|
|
4486
|
+
if (c.active === void 0) return c;
|
|
4487
|
+
const tab = saved.tabs[c.active];
|
|
4488
|
+
const at = tab === void 0 ? -1 : tabs.indexOf(tab);
|
|
4489
|
+
const { active: _active, ...rest } = c;
|
|
4490
|
+
return at < 0 ? rest : { ...rest, active: at };
|
|
4491
|
+
});
|
|
4492
|
+
return { ...saved, tabs, conversations: kept };
|
|
4493
|
+
}
|
|
3239
4494
|
|
|
3240
4495
|
// daemon/cursor.ts
|
|
3241
4496
|
var CURSOR_MAX_FRAMES = 20;
|
|
@@ -3528,6 +4783,7 @@ var FrameQuality = class {
|
|
|
3528
4783
|
|
|
3529
4784
|
// daemon/viewer.ts
|
|
3530
4785
|
var VIEWER_PING_MS = 1e3;
|
|
4786
|
+
var FIRST_FRAME_MS = 1e3;
|
|
3531
4787
|
var RESTART_MIN_MS = 500;
|
|
3532
4788
|
var ENCODE_MAX_INTERVAL_MS = 500;
|
|
3533
4789
|
var CURSOR_TIMEOUT_MS = 200;
|
|
@@ -3606,6 +4862,8 @@ var ViewerSession = class {
|
|
|
3606
4862
|
draining = false;
|
|
3607
4863
|
stateQueued = false;
|
|
3608
4864
|
lastControl = "agent";
|
|
4865
|
+
/** The viewport the screencast was started for (a profile switch restarts it). */
|
|
4866
|
+
streamedViewport = "";
|
|
3609
4867
|
constructor(opts) {
|
|
3610
4868
|
this.browser = opts.browser;
|
|
3611
4869
|
this.state = opts.state;
|
|
@@ -3696,6 +4954,34 @@ var ViewerSession = class {
|
|
|
3696
4954
|
this.queueState();
|
|
3697
4955
|
}
|
|
3698
4956
|
return;
|
|
4957
|
+
case "dialog":
|
|
4958
|
+
if (this.state.control !== "user") return;
|
|
4959
|
+
void this.browser.answerFromViewer(this.root, m).catch(() => void 0);
|
|
4960
|
+
return;
|
|
4961
|
+
case "permission":
|
|
4962
|
+
if (this.state.control !== "user" || m.allow !== true) return;
|
|
4963
|
+
void this.browser.grantPermission(this.root, m.origin, m.permission);
|
|
4964
|
+
return;
|
|
4965
|
+
case "viewport":
|
|
4966
|
+
this.input(() => this.browser.setProfile(m.profile));
|
|
4967
|
+
return;
|
|
4968
|
+
case "touch":
|
|
4969
|
+
this.input(async () => {
|
|
4970
|
+
const page = this.shownPage();
|
|
4971
|
+
if (page === void 0) return;
|
|
4972
|
+
this.concern(this.browser.tabIdOf(page));
|
|
4973
|
+
const vp = this.browser.viewport;
|
|
4974
|
+
const points = [];
|
|
4975
|
+
for (const q of Array.isArray(m.points) ? m.points.slice(0, 10) : []) {
|
|
4976
|
+
const at = point(q, vp);
|
|
4977
|
+
const id = Number(q?.id);
|
|
4978
|
+
if (at !== null && Number.isFinite(id)) points.push({ id, ...at });
|
|
4979
|
+
}
|
|
4980
|
+
const kind = m.kind;
|
|
4981
|
+
if (kind !== "start" && kind !== "move" && kind !== "end" && kind !== "cancel") return;
|
|
4982
|
+
await this.browser.touch(page, kind, points);
|
|
4983
|
+
});
|
|
4984
|
+
return;
|
|
3699
4985
|
case "tab":
|
|
3700
4986
|
if (m.action === "adopt") {
|
|
3701
4987
|
this.adopt(m.tabId);
|
|
@@ -3794,7 +5080,7 @@ var ViewerSession = class {
|
|
|
3794
5080
|
/** A pointer move: coalesced while one waits (the newest position wins), then the cursor. */
|
|
3795
5081
|
move(m) {
|
|
3796
5082
|
if (this.state.control !== "user") return;
|
|
3797
|
-
const p = point(m);
|
|
5083
|
+
const p = point(m, this.browser.viewport);
|
|
3798
5084
|
if (p === null) return;
|
|
3799
5085
|
if (this.moveSlot !== void 0) {
|
|
3800
5086
|
this.moveSlot.x = p.x;
|
|
@@ -3880,7 +5166,7 @@ var ViewerSession = class {
|
|
|
3880
5166
|
}
|
|
3881
5167
|
setSize(w, h) {
|
|
3882
5168
|
this.maxWidth = clampDim(w, VIEWPORT.width);
|
|
3883
|
-
this.maxHeight = clampDim(h, VIEWPORT.height);
|
|
5169
|
+
this.maxHeight = clampDim(h, Math.max(VIEWPORT.height, VIEWPORT_PROFILES.phone.height));
|
|
3884
5170
|
}
|
|
3885
5171
|
/** Pings the viewer every VIEWER_PING_MS (its pong measures the path, see the pacing). */
|
|
3886
5172
|
ping() {
|
|
@@ -3947,7 +5233,12 @@ var ViewerSession = class {
|
|
|
3947
5233
|
title: clip(t.title, 200),
|
|
3948
5234
|
url: clip(t.url, 200)
|
|
3949
5235
|
})),
|
|
3950
|
-
handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) }))
|
|
5236
|
+
handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) })),
|
|
5237
|
+
dialogs: m.dialogs.map((d) => ({
|
|
5238
|
+
...d,
|
|
5239
|
+
message: clip(d.message, 200),
|
|
5240
|
+
...d.defaultValue === void 0 ? {} : { defaultValue: clip(d.defaultValue, 200) }
|
|
5241
|
+
}))
|
|
3951
5242
|
};
|
|
3952
5243
|
} else if (m.t === "dialog") {
|
|
3953
5244
|
small = { ...m, message: clip(m.message, 200) };
|
|
@@ -3980,6 +5271,13 @@ var ViewerSession = class {
|
|
|
3980
5271
|
this.queueState();
|
|
3981
5272
|
} else if (e.root !== this.root) return;
|
|
3982
5273
|
else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
|
|
5274
|
+
else if (e.type === "permission")
|
|
5275
|
+
this.send({
|
|
5276
|
+
t: "permission",
|
|
5277
|
+
origin: e.origin,
|
|
5278
|
+
permission: e.permission,
|
|
5279
|
+
grantable: e.grantable
|
|
5280
|
+
});
|
|
3983
5281
|
else this.send({ t: "dialog", kind: e.kind, message: e.message });
|
|
3984
5282
|
}
|
|
3985
5283
|
/** Coalesces bursts of changes into one state message. */
|
|
@@ -4034,9 +5332,13 @@ var ViewerSession = class {
|
|
|
4034
5332
|
const tree = all.filter((t) => t.root === this.root);
|
|
4035
5333
|
this.shown = this.computeShown(tree);
|
|
4036
5334
|
this.pinShownOwner();
|
|
4037
|
-
|
|
5335
|
+
const viewport = this.browser.viewport;
|
|
5336
|
+
const vpKey = `${viewport.width}x${viewport.height}`;
|
|
5337
|
+
if (this.browser.pageById(this.shown) !== this.page || vpKey !== this.streamedViewport) {
|
|
4038
5338
|
void this.serial(async () => {
|
|
4039
|
-
|
|
5339
|
+
const key2 = `${this.browser.viewport.width}x${this.browser.viewport.height}`;
|
|
5340
|
+
if (this.browser.pageById(this.shown) === this.page && key2 === this.streamedViewport)
|
|
5341
|
+
return;
|
|
4040
5342
|
await this.detach();
|
|
4041
5343
|
await this.attach();
|
|
4042
5344
|
});
|
|
@@ -4059,6 +5361,7 @@ var ViewerSession = class {
|
|
|
4059
5361
|
tabs.sort((a, b) => (order.get(a.group) ?? 0) - (order.get(b.group) ?? 0));
|
|
4060
5362
|
const shownTab = tree.find((t) => t.id === this.shown);
|
|
4061
5363
|
const last = this.browser.lastClickOf(this.shown);
|
|
5364
|
+
const waiting = this.browser.watches.waitingOf(this.root);
|
|
4062
5365
|
this.send({
|
|
4063
5366
|
t: "state",
|
|
4064
5367
|
tabs,
|
|
@@ -4073,11 +5376,15 @@ var ViewerSession = class {
|
|
|
4073
5376
|
conversationId: h.conversationId,
|
|
4074
5377
|
message: h.message,
|
|
4075
5378
|
tabIds: this.browser.tabsOf(h.conversationId)
|
|
4076
|
-
}))
|
|
5379
|
+
})),
|
|
5380
|
+
...waiting === void 0 ? {} : { waiting: { label: waiting.label.slice(0, 200), until: waiting.until } },
|
|
5381
|
+
dialogs: this.browser.dialogsOf(this.root),
|
|
5382
|
+
viewport
|
|
4077
5383
|
});
|
|
4078
5384
|
}
|
|
4079
5385
|
get scale() {
|
|
4080
|
-
|
|
5386
|
+
const vp = this.browser.viewport;
|
|
5387
|
+
return Math.min(1, this.maxWidth / vp.width, this.maxHeight / vp.height) * this.frameQuality.shrink;
|
|
4081
5388
|
}
|
|
4082
5389
|
/** Room for the JPEG in one frame message. */
|
|
4083
5390
|
get jpegBudget() {
|
|
@@ -4087,15 +5394,20 @@ var ViewerSession = class {
|
|
|
4087
5394
|
if (this.closed) return;
|
|
4088
5395
|
const page = this.shownPage();
|
|
4089
5396
|
if (page === void 0) return;
|
|
5397
|
+
this.streamedViewport = `${this.browser.viewport.width}x${this.browser.viewport.height}`;
|
|
4090
5398
|
const cdp = await this.browser.context.newCDPSession(page);
|
|
4091
5399
|
this.page = page;
|
|
4092
5400
|
this.cdp = cdp;
|
|
4093
5401
|
cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
|
|
4094
5402
|
this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
|
|
4095
|
-
|
|
4096
|
-
|
|
4097
|
-
maxScale: this.scale
|
|
4098
|
-
|
|
5403
|
+
let timer;
|
|
5404
|
+
const first = await Promise.race([
|
|
5405
|
+
captureFitting(cdp, { maxBytes: this.jpegBudget, maxScale: this.scale }).catch(() => null),
|
|
5406
|
+
new Promise((r) => {
|
|
5407
|
+
timer = this.clock.schedule(() => r(null), FIRST_FRAME_MS);
|
|
5408
|
+
})
|
|
5409
|
+
]);
|
|
5410
|
+
this.clock.cancel(timer);
|
|
4099
5411
|
if (first !== null && this.cdp === cdp) {
|
|
4100
5412
|
this.pending = {
|
|
4101
5413
|
cdp,
|
|
@@ -4112,8 +5424,8 @@ var ViewerSession = class {
|
|
|
4112
5424
|
await cdp.send("Page.startScreencast", {
|
|
4113
5425
|
format: "jpeg",
|
|
4114
5426
|
quality: this.frameQuality.quality,
|
|
4115
|
-
maxWidth: Math.max(16, Math.floor(
|
|
4116
|
-
maxHeight: Math.max(16, Math.floor(
|
|
5427
|
+
maxWidth: Math.max(16, Math.floor(this.browser.viewport.width * this.scale)),
|
|
5428
|
+
maxHeight: Math.max(16, Math.floor(this.browser.viewport.height * this.scale)),
|
|
4117
5429
|
everyNthFrame: 1
|
|
4118
5430
|
});
|
|
4119
5431
|
}
|
|
@@ -4217,7 +5529,7 @@ var ViewerSession = class {
|
|
|
4217
5529
|
}
|
|
4218
5530
|
async mouse(m) {
|
|
4219
5531
|
const page = this.shownPage();
|
|
4220
|
-
const p = point(m);
|
|
5532
|
+
const p = point(m, this.browser.viewport);
|
|
4221
5533
|
if (p === null || page === void 0) return;
|
|
4222
5534
|
this.concern(this.browser.tabIdOf(page));
|
|
4223
5535
|
const { x, y } = p;
|
|
@@ -4263,13 +5575,13 @@ var ViewerSession = class {
|
|
|
4263
5575
|
}
|
|
4264
5576
|
};
|
|
4265
5577
|
var handoffKey = (h) => `${h.conversationId}\0${h.callId}`;
|
|
4266
|
-
function point(m) {
|
|
4267
|
-
const x = Number(m
|
|
4268
|
-
const y = Number(m
|
|
5578
|
+
function point(m, vp = VIEWPORT) {
|
|
5579
|
+
const x = Number(m?.x);
|
|
5580
|
+
const y = Number(m?.y);
|
|
4269
5581
|
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
|
|
4270
5582
|
return {
|
|
4271
|
-
x: Math.max(0, Math.min(
|
|
4272
|
-
y: Math.max(0, Math.min(
|
|
5583
|
+
x: Math.max(0, Math.min(vp.width - 1, x)),
|
|
5584
|
+
y: Math.max(0, Math.min(vp.height - 1, y))
|
|
4273
5585
|
};
|
|
4274
5586
|
}
|
|
4275
5587
|
|
|
@@ -4284,6 +5596,9 @@ var dec = new TextDecoder();
|
|
|
4284
5596
|
var REQUEST_OPS = /* @__PURE__ */ new Set([
|
|
4285
5597
|
"handoff_notice",
|
|
4286
5598
|
"handoff_clear",
|
|
5599
|
+
"watch_start",
|
|
5600
|
+
"watch_poll",
|
|
5601
|
+
"watch_end",
|
|
4287
5602
|
"navigate",
|
|
4288
5603
|
"tabs",
|
|
4289
5604
|
"snapshot",
|
|
@@ -4297,7 +5612,8 @@ var REQUEST_OPS = /* @__PURE__ */ new Set([
|
|
|
4297
5612
|
"click_at",
|
|
4298
5613
|
"type_at",
|
|
4299
5614
|
"wait",
|
|
4300
|
-
"screenshot"
|
|
5615
|
+
"screenshot",
|
|
5616
|
+
"dialog"
|
|
4301
5617
|
]);
|
|
4302
5618
|
function downloadMaxBytes(env) {
|
|
4303
5619
|
const raw = env.BROWSER_DOWNLOAD_MAX_BYTES;
|
|
@@ -4317,6 +5633,7 @@ function parse(raw) {
|
|
|
4317
5633
|
}
|
|
4318
5634
|
}
|
|
4319
5635
|
var HANDOFF_HOLDS_ROLL_MS = 30 * 6e4;
|
|
5636
|
+
var NOTICE_LAUNCH_WAIT_MS = 5e3;
|
|
4320
5637
|
function isRollCheck(body) {
|
|
4321
5638
|
return typeof body === "object" && body !== null && body.capybara === JSON.parse(ROLL_CHECK_REQUEST).capybara;
|
|
4322
5639
|
}
|
|
@@ -4350,7 +5667,7 @@ async function startDaemon(opts) {
|
|
|
4350
5667
|
mkdirSync2(opts.stateDir, { recursive: true });
|
|
4351
5668
|
let closing = false;
|
|
4352
5669
|
const sessionFile = new SessionFile(opts.stateDir, clock);
|
|
4353
|
-
|
|
5670
|
+
let saved = sessionFile.read();
|
|
4354
5671
|
let live;
|
|
4355
5672
|
const state = new DaemonState({
|
|
4356
5673
|
clock,
|
|
@@ -4421,12 +5738,19 @@ async function startDaemon(opts) {
|
|
|
4421
5738
|
proxy: plan.proxy,
|
|
4422
5739
|
clock,
|
|
4423
5740
|
usage: state,
|
|
5741
|
+
// a pending long wait's watch is its conversation's park
|
|
5742
|
+
parks: state,
|
|
5743
|
+
singleProcess: plan.build === "chromium-headless-shell",
|
|
4424
5744
|
workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
|
|
4425
5745
|
downloadsTmp: plan.downloadsTmp,
|
|
4426
5746
|
downloadMaxBytes: downloadMaxBytes(opts.env),
|
|
4427
5747
|
...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs },
|
|
4428
5748
|
...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
|
|
4429
5749
|
});
|
|
5750
|
+
await session.ready;
|
|
5751
|
+
state.onChange(() => {
|
|
5752
|
+
if (state.control === "agent") void session.restoreDesktop();
|
|
5753
|
+
});
|
|
4430
5754
|
if (plan.shippedDir !== void 0)
|
|
4431
5755
|
session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
|
|
4432
5756
|
if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
|
|
@@ -4528,6 +5852,47 @@ async function startDaemon(opts) {
|
|
|
4528
5852
|
blockedHosts: []
|
|
4529
5853
|
};
|
|
4530
5854
|
}
|
|
5855
|
+
async function watchOp(req) {
|
|
5856
|
+
if (typeof req.watchId !== "string" || req.watchId === "")
|
|
5857
|
+
return fail("The watch needs a watchId.");
|
|
5858
|
+
if (req.op === "watch_poll") {
|
|
5859
|
+
const session2 = live;
|
|
5860
|
+
return {
|
|
5861
|
+
ok: true,
|
|
5862
|
+
watch: session2 === void 0 ? { state: "unknown" } : session2.watchPoll(req),
|
|
5863
|
+
blockedHosts: []
|
|
5864
|
+
};
|
|
5865
|
+
}
|
|
5866
|
+
let session;
|
|
5867
|
+
try {
|
|
5868
|
+
session = await browser();
|
|
5869
|
+
} catch (e) {
|
|
5870
|
+
return launchFailure(e);
|
|
5871
|
+
}
|
|
5872
|
+
if (req.op === "watch_end") {
|
|
5873
|
+
const reply = await session.run(req);
|
|
5874
|
+
if (reply.ok) {
|
|
5875
|
+
const since = state.takeHandbackNote(req.conversationId);
|
|
5876
|
+
if (since !== void 0) reply.userControlledSince = since;
|
|
5877
|
+
}
|
|
5878
|
+
return reply;
|
|
5879
|
+
}
|
|
5880
|
+
let watch;
|
|
5881
|
+
try {
|
|
5882
|
+
watch = session.watchStart(req);
|
|
5883
|
+
} catch (e) {
|
|
5884
|
+
if (e instanceof ActionError)
|
|
5885
|
+
return { ok: false, error: e.code, message: e.message, blockedHosts: [] };
|
|
5886
|
+
throw e;
|
|
5887
|
+
}
|
|
5888
|
+
const page = session.currentPage(req.conversationId);
|
|
5889
|
+
return {
|
|
5890
|
+
ok: true,
|
|
5891
|
+
...page === void 0 ? {} : { page: await session.pageInfo(page) },
|
|
5892
|
+
watch,
|
|
5893
|
+
blockedHosts: []
|
|
5894
|
+
};
|
|
5895
|
+
}
|
|
4531
5896
|
const namesConversation = (raw) => {
|
|
4532
5897
|
const r = raw;
|
|
4533
5898
|
return typeof r.conversationId === "string" && r.conversationId !== "" && typeof r.rootConversationId === "string" && r.rootConversationId !== "";
|
|
@@ -4539,6 +5904,8 @@ async function startDaemon(opts) {
|
|
|
4539
5904
|
if (!namesConversation(raw)) return fail(NO_CONVERSATION_MESSAGE);
|
|
4540
5905
|
const req = raw;
|
|
4541
5906
|
const conv = req.conversationId;
|
|
5907
|
+
const deletedIn = () => deletedTree(conv) ?? deletedTree(req.rootConversationId);
|
|
5908
|
+
if (deletedIn() !== void 0) return fail(CONVERSATION_DELETED_MESSAGE);
|
|
4542
5909
|
state.requestArrived(conv, req.rootConversationId);
|
|
4543
5910
|
let reply;
|
|
4544
5911
|
try {
|
|
@@ -4547,11 +5914,15 @@ async function startDaemon(opts) {
|
|
|
4547
5914
|
reply = fail(e instanceof ActionError ? e.message : String(e));
|
|
4548
5915
|
} finally {
|
|
4549
5916
|
state.requestFinished(conv);
|
|
5917
|
+
const tree = deletedIn();
|
|
5918
|
+
if (tree !== void 0) void forgetDeleted(tree).catch(() => void 0);
|
|
4550
5919
|
}
|
|
4551
5920
|
return { ...reply, tabs: { open: live?.countOf(conv) ?? 0, max: MAX_TABS_PER_CONVERSATION } };
|
|
4552
5921
|
}
|
|
4553
5922
|
async function conversationRequest(req) {
|
|
4554
5923
|
if (req.op === "handoff_notice" || req.op === "handoff_clear") return handoffOp(req);
|
|
5924
|
+
if (req.op === "watch_start" || req.op === "watch_poll" || req.op === "watch_end")
|
|
5925
|
+
return watchOp(req);
|
|
4555
5926
|
state.dropHandoff(req.conversationId);
|
|
4556
5927
|
if (state.control === "user" && req.op !== "wait") {
|
|
4557
5928
|
return { ok: false, error: "taken_over", message: TAKEN_OVER_MESSAGE, blockedHosts: [] };
|
|
@@ -4603,7 +5974,7 @@ async function startDaemon(opts) {
|
|
|
4603
5974
|
}
|
|
4604
5975
|
if (kind === "stream" && context === void 0) {
|
|
4605
5976
|
const ctx = parseViewerContext(raw);
|
|
4606
|
-
if (ctx === null) {
|
|
5977
|
+
if (ctx === null || deletedTree(ctx.conversationId) !== void 0 || deletedTree(ctx.rootConversationId) !== void 0) {
|
|
4607
5978
|
sock.destroy();
|
|
4608
5979
|
return;
|
|
4609
5980
|
}
|
|
@@ -4647,6 +6018,11 @@ async function startDaemon(opts) {
|
|
|
4647
6018
|
if (kind === "request") {
|
|
4648
6019
|
if (handled) return;
|
|
4649
6020
|
handled = true;
|
|
6021
|
+
const deleted2 = parseConversationDeleted(raw);
|
|
6022
|
+
if (deleted2 !== null) {
|
|
6023
|
+
forgetDeleted(deleted2.conversationId).then((closed) => write(sock, { ok: true, closed })).catch((e) => write(sock, fail(e instanceof Error ? e.message : String(e)))).finally(() => sock.end());
|
|
6024
|
+
return;
|
|
6025
|
+
}
|
|
4650
6026
|
const body = parse(raw);
|
|
4651
6027
|
if (isRollCheck(body)) {
|
|
4652
6028
|
const reason = state.control === "user" ? "the person holds control of the browser" : state.handoffs().some((h) => clock.now() - h.since < HANDOFF_HOLDS_ROLL_MS) ? "a handoff to the person is pending" : void 0;
|
|
@@ -4677,6 +6053,21 @@ async function startDaemon(opts) {
|
|
|
4677
6053
|
for (const m of msgs) onMessage(m);
|
|
4678
6054
|
});
|
|
4679
6055
|
}
|
|
6056
|
+
const deleted = /* @__PURE__ */ new Map();
|
|
6057
|
+
function deletedTree(id) {
|
|
6058
|
+
const now = clock.now();
|
|
6059
|
+
for (const [c, at] of deleted) if (now - at > RESTORE_MAX_AGE_MS) deleted.delete(c);
|
|
6060
|
+
return deleted.has(id) ? id : void 0;
|
|
6061
|
+
}
|
|
6062
|
+
async function forgetDeleted(conversationId) {
|
|
6063
|
+
if (!deleted.has(conversationId)) deleted.set(conversationId, clock.now());
|
|
6064
|
+
const forgotten = state.forgetTree(conversationId);
|
|
6065
|
+
if (saved !== void 0) saved = withoutTree(saved, conversationId);
|
|
6066
|
+
sessionFile.dropTree(conversationId);
|
|
6067
|
+
const session = live ?? (current === void 0 ? void 0 : await within2(current, NOTICE_LAUNCH_WAIT_MS).catch(() => void 0));
|
|
6068
|
+
if (session === void 0) return 0;
|
|
6069
|
+
return session.forgetTree(conversationId, forgotten);
|
|
6070
|
+
}
|
|
4680
6071
|
if (existsSync2(opts.socketPath)) unlinkSync2(opts.socketPath);
|
|
4681
6072
|
const server = createServer(onConnection);
|
|
4682
6073
|
await new Promise((resolve, reject) => {
|