@capybara-hq/plugin-browser 0.1.0-rc.11 → 0.1.0-rc.12
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 +87 -3
- package/dist/index.mjs +417 -51
- package/package.json +2 -2
- package/ui/panel.js +304 -24
- package/ui/service/daemon.mjs +1445 -67
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,52 @@ 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
|
+
/** Whether the credential route is installed (only while credentials exist). */
|
|
1791
|
+
authRouted = false;
|
|
1792
|
+
/** Pages whose main frame got a sign-in challenge (a 401 with WWW-Authenticate). */
|
|
1793
|
+
challenged = /* @__PURE__ */ new WeakSet();
|
|
1794
|
+
/** Requests the route signed (a 401 to one of them means the credentials are wrong). */
|
|
1795
|
+
signed = /* @__PURE__ */ new WeakSet();
|
|
1796
|
+
/** Navigations the daemon itself runs on a page (goto, history, reload): their roots are trusted. */
|
|
1797
|
+
ownNavs = /* @__PURE__ */ new WeakMap();
|
|
1798
|
+
/** The permission binding's per-daemon name (any page can call it: its payload is untrusted). */
|
|
1799
|
+
permissionBinding = `__cbPermission_${randomBytes(8).toString("hex")}`;
|
|
1800
|
+
/** Permission reports per page load (capped at PERMISSION_REPORTS_PER_LOAD). */
|
|
1801
|
+
permissionCount = /* @__PURE__ */ new WeakMap();
|
|
1802
|
+
/** Origin–permission pairs the daemon recorded (deduplicated notes; grants only for these). */
|
|
1803
|
+
permissionPairs = /* @__PURE__ */ new Set();
|
|
1804
|
+
/** The pairs recorded on each tab (a viewer grants only for pairs of its tree's tabs). */
|
|
1805
|
+
tabPermissions = /* @__PURE__ */ new Map();
|
|
1806
|
+
/** The viewport profile the person chose (desktop while the agent drives). */
|
|
1807
|
+
profile = "desktop";
|
|
1808
|
+
/** The profile the pages have now (the chosen one once applied). */
|
|
1809
|
+
applied = "desktop";
|
|
1810
|
+
/** The CDP sessions holding the phone overrides, per page (detached on restore). */
|
|
1811
|
+
profileSessions = /* @__PURE__ */ new Map();
|
|
1812
|
+
/** Every agent request waits for this (a restore to desktop after hand back). */
|
|
1813
|
+
viewportGate = Promise.resolve();
|
|
1814
|
+
mobileUa;
|
|
1815
|
+
/** The pages' own user agent (given back when the phone profile ends). */
|
|
1816
|
+
desktopUa;
|
|
1817
|
+
/** The desktop translation of a viewer's touch input (tap, pan). */
|
|
1818
|
+
touchTranslator;
|
|
1819
|
+
/** Resolves once the permission binding and init script are installed (never rejects). */
|
|
1820
|
+
ready;
|
|
1821
|
+
singleProcess;
|
|
1273
1822
|
constructor(ctx, opts) {
|
|
1274
1823
|
this.ctx = ctx;
|
|
1275
1824
|
this.proxy = opts.proxy;
|
|
@@ -1280,6 +1829,14 @@ var BrowserSession = class {
|
|
|
1280
1829
|
this.clock = opts.clock ?? systemClock;
|
|
1281
1830
|
this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
|
|
1282
1831
|
this.usage = opts.usage ?? NO_USAGE;
|
|
1832
|
+
this.watches = new Watches({
|
|
1833
|
+
clock: this.clock,
|
|
1834
|
+
check: (page, c) => this.conditionHolds(page, c),
|
|
1835
|
+
...opts.parks === void 0 ? {} : { parks: opts.parks },
|
|
1836
|
+
onChange: () => this.emit({ type: "state" })
|
|
1837
|
+
});
|
|
1838
|
+
this.singleProcess = opts.singleProcess === true;
|
|
1839
|
+
this.touchTranslator = new TouchTranslator(() => this.clock.now());
|
|
1283
1840
|
ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
|
|
1284
1841
|
ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
|
|
1285
1842
|
ctx.on("page", (p) => {
|
|
@@ -1295,6 +1852,20 @@ var BrowserSession = class {
|
|
|
1295
1852
|
});
|
|
1296
1853
|
});
|
|
1297
1854
|
for (const p of ctx.pages()) this.track(p);
|
|
1855
|
+
this.ready = this.installPermissionReports();
|
|
1856
|
+
}
|
|
1857
|
+
/**
|
|
1858
|
+
* The permission report (dialogs spec §6): an init script wraps the request APIs and calls the
|
|
1859
|
+
* binding with the permission name when the page was refused. Never fails the session.
|
|
1860
|
+
*/
|
|
1861
|
+
async installPermissionReports() {
|
|
1862
|
+
try {
|
|
1863
|
+
await this.ctx.exposeBinding(this.permissionBinding, (source, name) => {
|
|
1864
|
+
this.onPermissionReport(source.page, source.frame.url(), name);
|
|
1865
|
+
});
|
|
1866
|
+
await this.ctx.addInitScript({ content: permissionInitScript(this.permissionBinding) });
|
|
1867
|
+
} catch {
|
|
1868
|
+
}
|
|
1298
1869
|
}
|
|
1299
1870
|
get context() {
|
|
1300
1871
|
return this.ctx;
|
|
@@ -1593,15 +2164,39 @@ var BrowserSession = class {
|
|
|
1593
2164
|
*/
|
|
1594
2165
|
async closeConversation(conversationId) {
|
|
1595
2166
|
const ids = this.tabsOf(conversationId).filter((id) => !this.usage.tabParked(id));
|
|
2167
|
+
await this.closeAndForget([conversationId], ids);
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* Closes every tab of a deleted conversation and of the conversations whose tree root it is,
|
|
2171
|
+
* parked tabs included, and forgets what the session keeps for each of them (the kernel's
|
|
2172
|
+
* conversation-deleted notice). `also`: more conversations of that tree the caller knows (the
|
|
2173
|
+
* daemon state's, which may own no tab). Never touches the profile. Returns how many tabs it
|
|
2174
|
+
* closed.
|
|
2175
|
+
*/
|
|
2176
|
+
async forgetTree(conversationId, also = []) {
|
|
2177
|
+
const convs = /* @__PURE__ */ new Set([conversationId, ...also]);
|
|
2178
|
+
const ids = [];
|
|
2179
|
+
for (const [id, o] of this.owners) {
|
|
2180
|
+
if (o.owner !== conversationId && o.root !== conversationId) continue;
|
|
2181
|
+
convs.add(o.owner);
|
|
2182
|
+
if (!this.closing.has(id)) ids.push(id);
|
|
2183
|
+
}
|
|
2184
|
+
await this.closeAndForget([...convs], ids);
|
|
2185
|
+
return ids.length;
|
|
2186
|
+
}
|
|
2187
|
+
/** Closes `ids` (their owners dropped first) and forgets the session's state of `convs`. */
|
|
2188
|
+
async closeAndForget(convs, ids) {
|
|
1596
2189
|
for (const id of ids) {
|
|
1597
2190
|
this.closing.add(id);
|
|
1598
2191
|
this.owners.delete(id);
|
|
1599
2192
|
}
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
2193
|
+
for (const c of convs) {
|
|
2194
|
+
this.activeOf.delete(c);
|
|
2195
|
+
this.queues.delete(this.queueKey(c));
|
|
2196
|
+
this.unreported.delete(c);
|
|
2197
|
+
this.claiming.delete(c);
|
|
2198
|
+
this.actedSeq.delete(c);
|
|
2199
|
+
}
|
|
1605
2200
|
await Promise.all(
|
|
1606
2201
|
ids.map(
|
|
1607
2202
|
(id) => this.pages.get(id)?.close().catch(() => {
|
|
@@ -1624,6 +2219,7 @@ var BrowserSession = class {
|
|
|
1624
2219
|
const id = `t${this.nextId++}`;
|
|
1625
2220
|
this.ids.set(page, id);
|
|
1626
2221
|
this.pages.set(id, page);
|
|
2222
|
+
if (this.profile === "phone") void this.applyPhone(page);
|
|
1627
2223
|
const refresh = () => {
|
|
1628
2224
|
page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
|
|
1629
2225
|
};
|
|
@@ -1652,6 +2248,11 @@ var BrowserSession = class {
|
|
|
1652
2248
|
if (f !== page.mainFrame()) return;
|
|
1653
2249
|
this.pendingNavs.delete(page);
|
|
1654
2250
|
this.blockers.delete(id);
|
|
2251
|
+
this.permissionCount.delete(page);
|
|
2252
|
+
const auth = this.held.get(id);
|
|
2253
|
+
if (auth?.view.kind === "auth" && auth.atUrl !== docUrl(f.url()) && !f.url().startsWith("chrome-error:"))
|
|
2254
|
+
this.clearHeld(id);
|
|
2255
|
+
this.reapplyPhone(page);
|
|
1655
2256
|
refresh();
|
|
1656
2257
|
});
|
|
1657
2258
|
page.on("domcontentloaded", refresh);
|
|
@@ -1671,8 +2272,10 @@ var BrowserSession = class {
|
|
|
1671
2272
|
this.checkBlocked(page, r.url(), this.pageToOpen(page, r));
|
|
1672
2273
|
});
|
|
1673
2274
|
page.on("response", (r) => {
|
|
1674
|
-
if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
|
|
2275
|
+
if (r.request().isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
1675
2276
|
this.docStatus.set(id, r.status());
|
|
2277
|
+
if (r.status() === 401) this.onUnauthorized(page, id, r);
|
|
2278
|
+
}
|
|
1676
2279
|
if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
|
|
1677
2280
|
this.checkBlocked(page, r.url(), this.pageToOpen(page, r.request()));
|
|
1678
2281
|
}
|
|
@@ -1700,10 +2303,14 @@ var BrowserSession = class {
|
|
|
1700
2303
|
this.tabUsedAt.delete(id);
|
|
1701
2304
|
this.gainedAt.delete(id);
|
|
1702
2305
|
this.clicks.delete(id);
|
|
2306
|
+
this.clearHeld(id);
|
|
2307
|
+
this.tabPermissions.delete(id);
|
|
2308
|
+
this.profileSessions.delete(page);
|
|
1703
2309
|
const o = this.owners.get(id);
|
|
1704
2310
|
this.owners.delete(id);
|
|
1705
2311
|
if (o !== void 0) this.activeMovedOff(o.owner, id);
|
|
1706
2312
|
this.usage.tabClosed(id);
|
|
2313
|
+
this.watches.tabClosed(id);
|
|
1707
2314
|
this.emit({ type: "state" });
|
|
1708
2315
|
});
|
|
1709
2316
|
}
|
|
@@ -1737,22 +2344,491 @@ var BrowserSession = class {
|
|
|
1737
2344
|
if (!await this.evict(o.owner)) closeIt(`the browser keeps at most ${MAX_TABS} tabs`);
|
|
1738
2345
|
});
|
|
1739
2346
|
}
|
|
2347
|
+
/**
|
|
2348
|
+
* A page dialog (dialogs spec §3): an alert only informs, so it is closed at once and noted; a
|
|
2349
|
+
* confirm, prompt or beforeunload is held until answered (by the person in control or the
|
|
2350
|
+
* agent's browser_dialog) and pins its tab. A dialog of an unowned page has nobody to answer it:
|
|
2351
|
+
* it gets the safe answer (dismissed; a beforeunload accepted), as before.
|
|
2352
|
+
*/
|
|
1740
2353
|
onDialog(page, d) {
|
|
1741
2354
|
const type = d.type();
|
|
1742
|
-
|
|
2355
|
+
const id = this.tabIdOf(page);
|
|
2356
|
+
const o = this.owners.get(id);
|
|
2357
|
+
const message = clip(d.message(), MAX_DIALOG_CHARS);
|
|
2358
|
+
if (type === "alert") {
|
|
1743
2359
|
d.accept().catch(() => void 0);
|
|
2360
|
+
this.noteTo(
|
|
2361
|
+
o?.owner,
|
|
2362
|
+
`The page showed an alert: ${JSON.stringify(dialogQuote(message))} (closed).`
|
|
2363
|
+
);
|
|
2364
|
+
if (o !== void 0) this.emit({ type: "dialog", kind: "alert", message, root: o.root });
|
|
1744
2365
|
return;
|
|
1745
2366
|
}
|
|
1746
|
-
const kind = type === "confirm" || type === "prompt" ? type : "
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
this.
|
|
1752
|
-
|
|
1753
|
-
|
|
2367
|
+
const kind = type === "confirm" || type === "prompt" ? type : "beforeunload";
|
|
2368
|
+
if (o === void 0) {
|
|
2369
|
+
(kind === "beforeunload" ? d.accept() : d.dismiss()).catch(() => void 0);
|
|
2370
|
+
return;
|
|
2371
|
+
}
|
|
2372
|
+
this.clearHeld(id);
|
|
2373
|
+
const view = {
|
|
2374
|
+
id: `d${++this.dialogSeq}`,
|
|
2375
|
+
tabId: id,
|
|
2376
|
+
kind,
|
|
2377
|
+
message,
|
|
2378
|
+
...kind === "prompt" ? { defaultValue: clip(d.defaultValue(), MAX_DIALOG_CHARS) } : {}
|
|
2379
|
+
};
|
|
2380
|
+
this.held.set(id, { view, dialog: d, owner: o });
|
|
2381
|
+
this.usage.park(o.owner, o.root, { kind: DIALOG_PARK, key: view.id, tabId: id });
|
|
2382
|
+
this.watches.dialog(id, message);
|
|
2383
|
+
this.wakeDialogWaiters(o.owner);
|
|
2384
|
+
this.emit({ type: "state" });
|
|
2385
|
+
}
|
|
2386
|
+
/** Forgets the tab's held dialog (answered, its tab closed or navigated away) and its park. */
|
|
2387
|
+
clearHeld(tabId) {
|
|
2388
|
+
const h = this.held.get(tabId);
|
|
2389
|
+
if (h === void 0) return;
|
|
2390
|
+
this.held.delete(tabId);
|
|
2391
|
+
if (h.view.kind !== "auth") this.usage.unpark(h.owner.owner, DIALOG_PARK, h.view.id);
|
|
2392
|
+
this.emit({ type: "state" });
|
|
2393
|
+
}
|
|
2394
|
+
wakeDialogWaiters(conversationId) {
|
|
2395
|
+
for (const wake of [...this.dialogWaiters.get(conversationId) ?? []]) wake();
|
|
2396
|
+
}
|
|
2397
|
+
/** The held dialogs of a viewer's tree, in tab order. */
|
|
2398
|
+
dialogsOf(root) {
|
|
2399
|
+
return this.live().map(([id]) => this.held.get(id)).filter(
|
|
2400
|
+
(h) => h !== void 0 && this.owners.get(h.view.tabId)?.root === root
|
|
2401
|
+
).map((h) => h.view);
|
|
2402
|
+
}
|
|
2403
|
+
/** The pending dialog a reply of the conversation carries: its active tab's, else its newest. */
|
|
2404
|
+
dialogFor(conversationId) {
|
|
2405
|
+
const active = this.activeTabOf(conversationId);
|
|
2406
|
+
const own = active === void 0 ? void 0 : this.held.get(active);
|
|
2407
|
+
if (own !== void 0) return own.view;
|
|
2408
|
+
let best;
|
|
2409
|
+
for (const id of this.tabsOf(conversationId)) {
|
|
2410
|
+
const h = this.held.get(id);
|
|
2411
|
+
if (h !== void 0 && (best === void 0 || seqOf(h) > seqOf(best))) best = h;
|
|
2412
|
+
}
|
|
2413
|
+
return best?.view;
|
|
2414
|
+
}
|
|
2415
|
+
/**
|
|
2416
|
+
* Runs `fn` and resolves early (undefined) when a dialog opens on one of the conversation's
|
|
2417
|
+
* tabs: the request that opened it replies at once and frees its queue (dialogs spec §3, R4).
|
|
2418
|
+
* The action's promise is left to settle; a failure after the dialog is noted to the
|
|
2419
|
+
* conversation (a timeout of an action held by the dialog is no news).
|
|
2420
|
+
*/
|
|
2421
|
+
async raceDialog(conversationId, op, fn) {
|
|
2422
|
+
let wake;
|
|
2423
|
+
const opened = new Promise((r) => {
|
|
2424
|
+
wake = () => r("dialog");
|
|
2425
|
+
});
|
|
2426
|
+
const waiters = this.dialogWaiters.get(conversationId) ?? /* @__PURE__ */ new Set();
|
|
2427
|
+
waiters.add(wake);
|
|
2428
|
+
this.dialogWaiters.set(conversationId, waiters);
|
|
2429
|
+
const done = fn();
|
|
2430
|
+
try {
|
|
2431
|
+
const out = await Promise.race([done, opened]);
|
|
2432
|
+
if (out !== "dialog") return out;
|
|
2433
|
+
done.catch((e) => {
|
|
2434
|
+
if (isTimeout(e)) return;
|
|
2435
|
+
const why = e instanceof ActionError ? e.message : firstLine(e);
|
|
2436
|
+
this.noteTo(conversationId, `The ${op} that opened a dialog failed afterwards: ${why}`);
|
|
2437
|
+
});
|
|
2438
|
+
return void 0;
|
|
2439
|
+
} finally {
|
|
2440
|
+
waiters.delete(wake);
|
|
2441
|
+
if (waiters.size === 0) this.dialogWaiters.delete(conversationId);
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
/**
|
|
2445
|
+
* Answers a held dialog (dialogs spec §5): for the agent (`browser_dialog`) only on its own
|
|
2446
|
+
* tabs and only when `message` matches the dialog's quote. An auth dialog takes only `dismiss`
|
|
2447
|
+
* from the agent.
|
|
2448
|
+
*/
|
|
2449
|
+
async dialogOp(req) {
|
|
2450
|
+
const conv = req.conversationId;
|
|
2451
|
+
const h = [...this.held.values()].find((x) => x.view.id === req.dialogId);
|
|
2452
|
+
if (h === void 0 || this.pageById(h.view.tabId) === void 0) {
|
|
2453
|
+
const any = this.tabsOf(conv).some((id) => this.held.has(id));
|
|
2454
|
+
throw new ActionError("failed", any ? DIALOG_CHANGED_MESSAGE : NO_DIALOG_MESSAGE);
|
|
2455
|
+
}
|
|
2456
|
+
if (this.owners.get(h.view.tabId)?.owner !== conv)
|
|
2457
|
+
throw new ActionError("failed", notYourTab(h.view.tabId));
|
|
2458
|
+
if (typeof req.message !== "string" || !dialogMessageMatches(req.message, h.view.message))
|
|
2459
|
+
throw new ActionError("failed", DIALOG_CHANGED_MESSAGE);
|
|
2460
|
+
const action = req.action === "accept" ? "accept" : "dismiss";
|
|
2461
|
+
if (h.view.kind === "auth") {
|
|
2462
|
+
if (action === "accept") throw new ActionError("failed", AUTH_SIGN_IN_TEXT);
|
|
2463
|
+
this.clearHeld(h.view.tabId);
|
|
2464
|
+
return { text: `Dismissed the sign-in request of ${h.view.origin ?? "the site"}.` };
|
|
2465
|
+
}
|
|
2466
|
+
await this.settleDialog(h, action, typeof req.text === "string" ? req.text : void 0);
|
|
2467
|
+
const name = h.view.kind === "beforeunload" ? "leave-page" : h.view.kind;
|
|
2468
|
+
return {
|
|
2469
|
+
text: `${action === "accept" ? "Accepted" : "Dismissed"} the ${name} dialog ${JSON.stringify(dialogQuote(h.view.message))}.`
|
|
2470
|
+
};
|
|
2471
|
+
}
|
|
2472
|
+
/** Accepts or dismisses a held JS dialog and forgets it. */
|
|
2473
|
+
async settleDialog(h, action, text) {
|
|
2474
|
+
this.clearHeld(h.view.tabId);
|
|
2475
|
+
const d = h.dialog;
|
|
2476
|
+
if (d === void 0) return;
|
|
2477
|
+
try {
|
|
2478
|
+
if (action === "accept")
|
|
2479
|
+
await d.accept(h.view.kind === "prompt" ? text ?? d.defaultValue() : void 0);
|
|
2480
|
+
else await d.dismiss();
|
|
2481
|
+
} catch {
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
/**
|
|
2485
|
+
* A viewer's answer to a held dialog of its tree (control is checked by the viewer). A stale id
|
|
2486
|
+
* or a dialog outside the tree changes nothing. An auth accept stores the credentials for the
|
|
2487
|
+
* dialog's origin (device-wide, memory only) and reloads the tab.
|
|
2488
|
+
*/
|
|
2489
|
+
async answerFromViewer(root, m) {
|
|
2490
|
+
const h = [...this.held.values()].find((x) => x.view.id === m.id);
|
|
2491
|
+
if (h === void 0 || this.owners.get(h.view.tabId)?.root !== root) return;
|
|
2492
|
+
const action = m.action === "accept" ? "accept" : "dismiss";
|
|
2493
|
+
if (h.view.kind !== "auth") {
|
|
2494
|
+
await this.settleDialog(h, action, typeof m.text === "string" ? m.text : void 0);
|
|
2495
|
+
return;
|
|
2496
|
+
}
|
|
2497
|
+
if (action === "dismiss") {
|
|
2498
|
+
this.clearHeld(h.view.tabId);
|
|
2499
|
+
return;
|
|
2500
|
+
}
|
|
2501
|
+
const origin = h.view.origin;
|
|
2502
|
+
if (origin === void 0 || typeof m.username !== "string" || typeof m.password !== "string")
|
|
2503
|
+
return;
|
|
2504
|
+
await this.signIn(origin, m.username, m.password);
|
|
2505
|
+
for (const [id, x] of [...this.held])
|
|
2506
|
+
if (x.view.kind === "auth" && x.view.origin === origin) this.clearHeld(id);
|
|
2507
|
+
this.noteTo(h.owner.owner, `The user signed in to ${origin} (HTTP auth).`);
|
|
2508
|
+
const page = this.pageById(h.view.tabId);
|
|
2509
|
+
if (page !== void 0)
|
|
2510
|
+
await this.viewerNav(page, h.atUrl === void 0 ? { action: "reload" } : { url: h.atUrl });
|
|
2511
|
+
}
|
|
2512
|
+
// ---- HTTP Basic auth (dialogs spec §4)
|
|
2513
|
+
/**
|
|
2514
|
+
* A main-frame document answered 401: Chromium already cancelled the challenge and shows the
|
|
2515
|
+
* body. A Basic challenge becomes an auth dialog on the tab (unless a JS dialog is held there);
|
|
2516
|
+
* a 401 to a request the credentials signed means they are wrong: they are dropped. Another
|
|
2517
|
+
* scheme is noted as unsupported.
|
|
2518
|
+
*/
|
|
2519
|
+
onUnauthorized(page, id, r) {
|
|
2520
|
+
const origin = originOf(r.url());
|
|
2521
|
+
if (origin !== void 0 && this.signed.has(r.request())) this.forgetCredentials(origin);
|
|
2522
|
+
const o = this.owners.get(id);
|
|
2523
|
+
if (origin === void 0 || o === void 0) return;
|
|
2524
|
+
const header = r.headers()["www-authenticate"];
|
|
2525
|
+
if (header === void 0) return;
|
|
2526
|
+
this.challenged.add(page);
|
|
2527
|
+
const { scheme, realm } = authChallenge(header);
|
|
2528
|
+
if (scheme.toLowerCase() !== "basic") {
|
|
2529
|
+
this.noteTo(
|
|
2530
|
+
o.owner,
|
|
2531
|
+
`The site asks for ${clip(scheme, 40) || "an unknown"} sign-in, which the browser cannot do; ask the user how to continue.`
|
|
2532
|
+
);
|
|
2533
|
+
return;
|
|
2534
|
+
}
|
|
2535
|
+
if (blocks(this.held.get(id))) return;
|
|
2536
|
+
this.clearHeld(id);
|
|
2537
|
+
this.held.set(id, {
|
|
2538
|
+
view: {
|
|
2539
|
+
id: `d${++this.dialogSeq}`,
|
|
2540
|
+
tabId: id,
|
|
2541
|
+
kind: "auth",
|
|
2542
|
+
message: `HTTP sign-in for ${origin}`,
|
|
2543
|
+
origin,
|
|
2544
|
+
realm
|
|
2545
|
+
},
|
|
2546
|
+
dialog: void 0,
|
|
2547
|
+
owner: o,
|
|
2548
|
+
atUrl: docUrl(r.url())
|
|
2549
|
+
});
|
|
2550
|
+
this.emit({ type: "state" });
|
|
2551
|
+
}
|
|
2552
|
+
/**
|
|
2553
|
+
* Whether a navigation failed on a sign-in challenge the tab's page got (an auth dialog, or the
|
|
2554
|
+
* note of an unsupported scheme): the full build fails such a navigation where the headless
|
|
2555
|
+
* shell shows the 401 body; the reply names the dialog or carries the note instead.
|
|
2556
|
+
*/
|
|
2557
|
+
signInAsked(page, e) {
|
|
2558
|
+
return firstLine(e).includes("ERR_INVALID_AUTH_CREDENTIALS") && this.challenged.has(page);
|
|
2559
|
+
}
|
|
2560
|
+
/** Stores the person's credentials for exactly `origin` and routes them (memory only). */
|
|
2561
|
+
async signIn(origin, username, password) {
|
|
2562
|
+
this.credentials.set(
|
|
2563
|
+
origin,
|
|
2564
|
+
`Basic ${Buffer.from(`${username}:${password}`, "utf8").toString("base64")}`
|
|
2565
|
+
);
|
|
2566
|
+
if (this.authRouted) return;
|
|
2567
|
+
this.authRouted = true;
|
|
2568
|
+
await this.ctx.route((u) => this.credentials.has(u.origin), this.onAuthRoute).catch(() => {
|
|
2569
|
+
this.authRouted = false;
|
|
2570
|
+
});
|
|
2571
|
+
}
|
|
2572
|
+
forgetCredentials(origin) {
|
|
2573
|
+
if (!this.credentials.delete(origin) || this.credentials.size > 0 || !this.authRouted) return;
|
|
2574
|
+
this.authRouted = false;
|
|
2575
|
+
void this.ctx.unroute(() => true, this.onAuthRoute).catch(() => void 0);
|
|
2576
|
+
}
|
|
2577
|
+
onAuthRoute = async (route) => {
|
|
2578
|
+
const r = route.request();
|
|
2579
|
+
const value = this.authHeaderFor(r);
|
|
2580
|
+
if (value === void 0) {
|
|
2581
|
+
await route.fallback().catch(() => void 0);
|
|
2582
|
+
return;
|
|
2583
|
+
}
|
|
2584
|
+
this.signed.add(r);
|
|
2585
|
+
await route.fallback({ headers: { ...r.headers(), authorization: value } }).catch(() => void 0);
|
|
2586
|
+
};
|
|
2587
|
+
/**
|
|
2588
|
+
* The Authorization value a request gets, only where a browser's own page would send it: a
|
|
2589
|
+
* request to the signed-in origin from a page whose top-level document has that origin, or a
|
|
2590
|
+
* top-level navigation to it that this page started from that origin or that the daemon runs
|
|
2591
|
+
* (the agent's or the person's address bar, history, reload). Never a service worker's request,
|
|
2592
|
+
* a cross-site page's request (fetch, image, form post) or a redirect into the origin.
|
|
2593
|
+
*/
|
|
2594
|
+
authHeaderFor(r) {
|
|
2595
|
+
const origin = originOf(r.url());
|
|
2596
|
+
const value = origin === void 0 ? void 0 : this.credentials.get(origin);
|
|
2597
|
+
if (value === void 0 || r.serviceWorker() !== null) return void 0;
|
|
2598
|
+
let frame;
|
|
2599
|
+
try {
|
|
2600
|
+
frame = r.frame();
|
|
2601
|
+
} catch {
|
|
2602
|
+
return void 0;
|
|
2603
|
+
}
|
|
2604
|
+
const page = frame.page();
|
|
2605
|
+
const top = originOf(page.mainFrame().url());
|
|
2606
|
+
if (!(r.isNavigationRequest() && frame === page.mainFrame())) {
|
|
2607
|
+
return top === origin ? value : void 0;
|
|
2608
|
+
}
|
|
2609
|
+
let root = r;
|
|
2610
|
+
for (let f = r.redirectedFrom(); f !== null; f = f.redirectedFrom()) root = f;
|
|
2611
|
+
if (originOf(root.url()) !== origin) return void 0;
|
|
2612
|
+
if (top === origin || (this.ownNavs.get(page) ?? 0) > 0) return value;
|
|
2613
|
+
return void 0;
|
|
2614
|
+
}
|
|
2615
|
+
/** Runs a navigation the daemon starts on a page (its root request is trusted for auth). */
|
|
2616
|
+
async ownNav(page, fn) {
|
|
2617
|
+
this.ownNavs.set(page, (this.ownNavs.get(page) ?? 0) + 1);
|
|
2618
|
+
try {
|
|
2619
|
+
return await fn();
|
|
2620
|
+
} finally {
|
|
2621
|
+
this.ownNavs.set(page, Math.max(0, (this.ownNavs.get(page) ?? 1) - 1));
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
// ---- permission requests (dialogs spec §6)
|
|
2625
|
+
/**
|
|
2626
|
+
* A page reported a refused permission request through the binding. Nothing in the payload is
|
|
2627
|
+
* trusted but a known permission name: the origin is the calling frame's, reports are capped per
|
|
2628
|
+
* page load and in distinct pairs, and only a pair recorded here can be granted later.
|
|
2629
|
+
*/
|
|
2630
|
+
onPermissionReport(page, frameUrl, name) {
|
|
2631
|
+
if (typeof name !== "string" || !REPORTED_PERMISSIONS.includes(name))
|
|
2632
|
+
return;
|
|
2633
|
+
const permission = name;
|
|
2634
|
+
const id = this.ids.get(page);
|
|
2635
|
+
const o = id === void 0 ? void 0 : this.owners.get(id);
|
|
2636
|
+
const origin = originOf(frameUrl);
|
|
2637
|
+
if (id === void 0 || o === void 0 || origin === void 0) return;
|
|
2638
|
+
const count = (this.permissionCount.get(page) ?? 0) + 1;
|
|
2639
|
+
this.permissionCount.set(page, count);
|
|
2640
|
+
if (count > PERMISSION_REPORTS_PER_LOAD) return;
|
|
2641
|
+
const pair = `${origin}\0${permission}`;
|
|
2642
|
+
const fresh = !this.permissionPairs.has(pair);
|
|
2643
|
+
if (fresh && this.permissionPairs.size >= MAX_PERMISSION_PAIRS) return;
|
|
2644
|
+
this.permissionPairs.add(pair);
|
|
2645
|
+
const onTab = this.tabPermissions.get(id) ?? /* @__PURE__ */ new Set();
|
|
2646
|
+
onTab.add(pair);
|
|
2647
|
+
this.tabPermissions.set(id, onTab);
|
|
2648
|
+
const grantable = GRANTABLE_PERMISSIONS.includes(permission);
|
|
2649
|
+
if (fresh)
|
|
2650
|
+
this.noteTo(
|
|
2651
|
+
o.owner,
|
|
2652
|
+
`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."}`
|
|
2653
|
+
);
|
|
2654
|
+
this.emit({ type: "permission", origin, permission, grantable, root: o.root });
|
|
2655
|
+
}
|
|
2656
|
+
/**
|
|
2657
|
+
* Grants a permission the person allowed in the panel, for the daemon's life (never written to
|
|
2658
|
+
* the profile): only grantable ones, only for a pair recorded on a tab of the viewer's tree.
|
|
2659
|
+
*/
|
|
2660
|
+
async grantPermission(root, origin, permission) {
|
|
2661
|
+
if (typeof origin !== "string" || typeof permission !== "string") return false;
|
|
2662
|
+
if (!GRANTABLE_PERMISSIONS.includes(permission)) return false;
|
|
2663
|
+
const pair = `${origin}\0${permission}`;
|
|
2664
|
+
const inTree = [...this.tabPermissions].some(
|
|
2665
|
+
([id, pairs]) => pairs.has(pair) && this.owners.get(id)?.root === root
|
|
1754
2666
|
);
|
|
1755
|
-
if (
|
|
2667
|
+
if (!inTree) return false;
|
|
2668
|
+
try {
|
|
2669
|
+
await this.ctx.grantPermissions([permission], { origin });
|
|
2670
|
+
return true;
|
|
2671
|
+
} catch {
|
|
2672
|
+
return false;
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
// ---- viewport profiles and touch (dialogs spec §7)
|
|
2676
|
+
/** The viewport the pages have now (a switch counts once applied). */
|
|
2677
|
+
get viewport() {
|
|
2678
|
+
const p = VIEWPORT_PROFILES[this.applied];
|
|
2679
|
+
return { width: p.width, height: p.height, mobile: p.mobile };
|
|
2680
|
+
}
|
|
2681
|
+
/** Switches every tab (and tabs opened later) to the profile (the person's choice). */
|
|
2682
|
+
setProfile(profile) {
|
|
2683
|
+
if (profile !== "desktop" && profile !== "phone") return this.viewportGate;
|
|
2684
|
+
if (profile === this.profile) return this.viewportGate;
|
|
2685
|
+
this.profile = profile;
|
|
2686
|
+
this.touchTranslator.reset();
|
|
2687
|
+
const pages = this.live().map(([, p]) => p);
|
|
2688
|
+
const run = async () => {
|
|
2689
|
+
if (profile === "phone") await Promise.all(pages.map((p) => this.applyPhone(p)));
|
|
2690
|
+
else await this.restoreAll();
|
|
2691
|
+
if (this.profile === profile) this.applied = profile;
|
|
2692
|
+
};
|
|
2693
|
+
const next = this.viewportGate.then(run, run);
|
|
2694
|
+
this.viewportGate = next.catch(() => void 0);
|
|
2695
|
+
this.emit({ type: "state" });
|
|
2696
|
+
void this.viewportGate.then(() => this.emit({ type: "state" }));
|
|
2697
|
+
return this.viewportGate;
|
|
2698
|
+
}
|
|
2699
|
+
/**
|
|
2700
|
+
* Back to the desktop profile (hand back): every agent request of any conversation waits for
|
|
2701
|
+
* it, so the agent always acts on 1280x800.
|
|
2702
|
+
*/
|
|
2703
|
+
restoreDesktop() {
|
|
2704
|
+
return this.setProfile("desktop");
|
|
2705
|
+
}
|
|
2706
|
+
/**
|
|
2707
|
+
* The CDP session that holds a page's profile overrides (the newest of its sessions), made on
|
|
2708
|
+
* first use; `fresh` makes a new one (after a navigation, a renderer swapped in for another site
|
|
2709
|
+
* follows no session made before). Sessions are kept: a detach drops every device metric of the
|
|
2710
|
+
* page, Playwright's included, which it does not send again; the restore ends them in order.
|
|
2711
|
+
*/
|
|
2712
|
+
profileSession(page, fresh = false) {
|
|
2713
|
+
const list = this.profileSessions.get(page) ?? [];
|
|
2714
|
+
const last = list.at(-1);
|
|
2715
|
+
if (last !== void 0 && !fresh) return last;
|
|
2716
|
+
const made = (async () => {
|
|
2717
|
+
try {
|
|
2718
|
+
const cdp = await this.ctx.newCDPSession(page);
|
|
2719
|
+
this.desktopUa ??= await this.bounded(
|
|
2720
|
+
cdp.send("Runtime.evaluate", { expression: "navigator.userAgent", returnByValue: true }).then((r) => typeof r.result.value === "string" ? r.result.value : void 0),
|
|
2721
|
+
void 0
|
|
2722
|
+
);
|
|
2723
|
+
this.mobileUa ??= mobileUserAgent(this.desktopUa ?? "");
|
|
2724
|
+
return cdp;
|
|
2725
|
+
} catch {
|
|
2726
|
+
return void 0;
|
|
2727
|
+
}
|
|
2728
|
+
})();
|
|
2729
|
+
list.push(made);
|
|
2730
|
+
this.profileSessions.set(page, list);
|
|
2731
|
+
return made;
|
|
2732
|
+
}
|
|
2733
|
+
/**
|
|
2734
|
+
* Applies the phone profile to a page: Playwright's own viewport first (its emulation, which it
|
|
2735
|
+
* may send again on a navigation, then agrees on the size, and the restore is a real change for
|
|
2736
|
+
* it), then the mobile metrics, touch and user agent through the page's profile session.
|
|
2737
|
+
*/
|
|
2738
|
+
async applyPhone(page, fresh = false) {
|
|
2739
|
+
const cdp = await this.profileSession(page, fresh);
|
|
2740
|
+
if (cdp === void 0 || this.profile !== "phone" || page.isClosed()) return void 0;
|
|
2741
|
+
try {
|
|
2742
|
+
await page.setViewportSize({
|
|
2743
|
+
width: VIEWPORT_PROFILES.phone.width,
|
|
2744
|
+
height: VIEWPORT_PROFILES.phone.height
|
|
2745
|
+
});
|
|
2746
|
+
const p = VIEWPORT_PROFILES.phone;
|
|
2747
|
+
await cdp.send("Emulation.setDeviceMetricsOverride", {
|
|
2748
|
+
width: p.width,
|
|
2749
|
+
height: p.height,
|
|
2750
|
+
deviceScaleFactor: p.scale,
|
|
2751
|
+
mobile: true,
|
|
2752
|
+
screenWidth: p.width,
|
|
2753
|
+
screenHeight: p.height
|
|
2754
|
+
});
|
|
2755
|
+
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 });
|
|
2756
|
+
await cdp.send("Emulation.setUserAgentOverride", {
|
|
2757
|
+
userAgent: this.mobileUa ?? mobileUserAgent("")
|
|
2758
|
+
});
|
|
2759
|
+
return cdp;
|
|
2760
|
+
} catch {
|
|
2761
|
+
return void 0;
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
/**
|
|
2765
|
+
* A page back on desktop: its older profile sessions end (each detach drops the page's
|
|
2766
|
+
* metrics), the newest sends the desktop values and the agent's user agent, and Playwright gets
|
|
2767
|
+
* its own 1280x800 again.
|
|
2768
|
+
*/
|
|
2769
|
+
async applyDesktop(page) {
|
|
2770
|
+
const list = this.profileSessions.get(page) ?? [];
|
|
2771
|
+
const sessions = await Promise.all(list);
|
|
2772
|
+
this.profileSessions.set(page, list.slice(-1));
|
|
2773
|
+
for (const old of sessions.slice(0, -1)) await old?.detach().catch(() => void 0);
|
|
2774
|
+
if (page.isClosed()) return;
|
|
2775
|
+
const cdp = sessions.at(-1);
|
|
2776
|
+
if (cdp !== void 0) {
|
|
2777
|
+
await cdp.send("Emulation.setDeviceMetricsOverride", {
|
|
2778
|
+
width: VIEWPORT.width,
|
|
2779
|
+
height: VIEWPORT.height,
|
|
2780
|
+
deviceScaleFactor: 1,
|
|
2781
|
+
mobile: false,
|
|
2782
|
+
screenWidth: VIEWPORT.width,
|
|
2783
|
+
screenHeight: VIEWPORT.height
|
|
2784
|
+
}).catch(() => void 0);
|
|
2785
|
+
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }).catch(() => void 0);
|
|
2786
|
+
if (this.desktopUa !== void 0)
|
|
2787
|
+
await cdp.send("Emulation.setUserAgentOverride", { userAgent: this.desktopUa }).catch(() => void 0);
|
|
2788
|
+
}
|
|
2789
|
+
await page.setViewportSize({ ...VIEWPORT }).catch(() => void 0);
|
|
2790
|
+
}
|
|
2791
|
+
/**
|
|
2792
|
+
* A page navigated while the phone profile is on: Playwright may send its own metrics again,
|
|
2793
|
+
* and a renderer swapped in keeps no overrides, so they go again on a fresh session (in the
|
|
2794
|
+
* profile chain: a restore waits for it).
|
|
2795
|
+
*/
|
|
2796
|
+
reapplyPhone(page) {
|
|
2797
|
+
if (this.profile !== "phone") return;
|
|
2798
|
+
const run = () => this.applyPhone(page, true).then(() => void 0);
|
|
2799
|
+
const next = this.viewportGate.then(run, run);
|
|
2800
|
+
this.viewportGate = next.catch(() => void 0);
|
|
2801
|
+
}
|
|
2802
|
+
/** Every page that got the phone profile back on desktop. */
|
|
2803
|
+
async restoreAll() {
|
|
2804
|
+
await Promise.all([...this.profileSessions.keys()].map((page) => this.applyDesktop(page)));
|
|
2805
|
+
}
|
|
2806
|
+
/**
|
|
2807
|
+
* A viewer's touch input on a page: touch events in the phone profile; in desktop a tap clicks
|
|
2808
|
+
* and a one-finger pan scrolls (anything else is ignored).
|
|
2809
|
+
*/
|
|
2810
|
+
async touch(page, kind, points) {
|
|
2811
|
+
if (this.profile === "phone") {
|
|
2812
|
+
const cdp = await this.profileSession(page);
|
|
2813
|
+
if (cdp === void 0) return;
|
|
2814
|
+
const type = kind === "start" ? "touchStart" : kind === "move" ? "touchMove" : kind === "end" ? "touchEnd" : "touchCancel";
|
|
2815
|
+
await cdp.send("Input.dispatchTouchEvent", {
|
|
2816
|
+
type,
|
|
2817
|
+
touchPoints: points.map((p) => ({ x: p.x, y: p.y, id: p.id }))
|
|
2818
|
+
}).catch(() => void 0);
|
|
2819
|
+
return;
|
|
2820
|
+
}
|
|
2821
|
+
for (const a of this.touchTranslator.feed(kind, points)) await this.runTouchAction(page, a);
|
|
2822
|
+
}
|
|
2823
|
+
async runTouchAction(page, a) {
|
|
2824
|
+
try {
|
|
2825
|
+
if (a.kind === "click") await page.mouse.click(a.x, a.y);
|
|
2826
|
+
else {
|
|
2827
|
+
await page.mouse.move(a.x, a.y);
|
|
2828
|
+
await page.mouse.wheel(a.dx, a.dy);
|
|
2829
|
+
}
|
|
2830
|
+
} catch {
|
|
2831
|
+
}
|
|
1756
2832
|
}
|
|
1757
2833
|
/**
|
|
1758
2834
|
* A device note (not about a page: the browser build that runs): the replies of the requests in
|
|
@@ -1830,6 +2906,10 @@ var BrowserSession = class {
|
|
|
1830
2906
|
}
|
|
1831
2907
|
target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
|
|
1832
2908
|
note(`Downloaded ${shown} to ${target}.`);
|
|
2909
|
+
if (owner !== void 0) {
|
|
2910
|
+
this.watches.downloadSaved(owner, target);
|
|
2911
|
+
for (const w of [...this.downloadWaiters]) if (w.conv === owner) w.resolve(target);
|
|
2912
|
+
}
|
|
1833
2913
|
} catch (e) {
|
|
1834
2914
|
note(
|
|
1835
2915
|
`The download of ${shown} was not saved: ${e instanceof ActionError ? e.message : firstLine(e)}`
|
|
@@ -2112,12 +3192,15 @@ var BrowserSession = class {
|
|
|
2112
3192
|
this.collectors.add(c);
|
|
2113
3193
|
let reply;
|
|
2114
3194
|
try {
|
|
2115
|
-
|
|
2116
|
-
const
|
|
3195
|
+
await this.viewportGate;
|
|
3196
|
+
const beside = req.op === "wait" || req.op === "watch_end" || req.op === "dialog" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
|
|
3197
|
+
this.refuseIfBlocked(req);
|
|
3198
|
+
const out = await (beside ? req.op === "wait" ? this.raceDialog(conv, req.op, () => this.exec(req)) : this.exec(req) : this.serial(conv, () => {
|
|
2117
3199
|
if (opts.takenOver?.() === true)
|
|
2118
3200
|
throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
|
|
2119
|
-
|
|
2120
|
-
|
|
3201
|
+
this.refuseIfBlocked(req);
|
|
3202
|
+
return this.raceDialog(conv, req.op, () => this.exec(req));
|
|
3203
|
+
})) ?? {};
|
|
2121
3204
|
await this.settleProbes(c);
|
|
2122
3205
|
await this.settleDownloads(c);
|
|
2123
3206
|
this.collectors.delete(c);
|
|
@@ -2126,18 +3209,21 @@ var BrowserSession = class {
|
|
|
2126
3209
|
this.tabUsedAt.set(this.tabIdOf(page), this.clock.now());
|
|
2127
3210
|
this.actedSeq.set(conv, ++this.actSeq);
|
|
2128
3211
|
}
|
|
2129
|
-
const verifying = page === void 0 || req.op === "tabs" && (req.action === "list" || req.action === "adopt") ? false : await this.checkVerification(page, this.tabIdOf(page));
|
|
3212
|
+
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
3213
|
const text = [
|
|
2131
3214
|
...verifying ? [VERIFICATION_NOTE] : [],
|
|
2132
3215
|
...c.notes,
|
|
2133
3216
|
...out.text === void 0 ? [] : [out.text]
|
|
2134
3217
|
].join("\n");
|
|
3218
|
+
const dialog = this.dialogFor(conv);
|
|
2135
3219
|
reply = {
|
|
2136
3220
|
ok: true,
|
|
2137
3221
|
...page === void 0 ? {} : { page: await this.pageInfo(page) },
|
|
2138
3222
|
blockedHosts: blockedHostsOf(c),
|
|
2139
3223
|
...text === "" ? {} : { text },
|
|
2140
|
-
...out.image === void 0 ? {} : { image: out.image }
|
|
3224
|
+
...out.image === void 0 ? {} : { image: out.image },
|
|
3225
|
+
...out.watch === void 0 ? {} : { watch: out.watch },
|
|
3226
|
+
...dialog === void 0 ? {} : { dialog }
|
|
2141
3227
|
};
|
|
2142
3228
|
} catch (e) {
|
|
2143
3229
|
await this.settleProbes(c);
|
|
@@ -2160,6 +3246,32 @@ var BrowserSession = class {
|
|
|
2160
3246
|
this.emit({ type: "state" });
|
|
2161
3247
|
return reply;
|
|
2162
3248
|
}
|
|
3249
|
+
/**
|
|
3250
|
+
* Refuses an operation a JS dialog on the conversation's active tab blocks (`dialog_open`). In a
|
|
3251
|
+
* one-process browser any held JS dialog stops every page: every acting request is refused (the
|
|
3252
|
+
* conversation's own dialog named, another conversation's never).
|
|
3253
|
+
*/
|
|
3254
|
+
refuseIfBlocked(req) {
|
|
3255
|
+
const conv = req.conversationId;
|
|
3256
|
+
const activeHeld = this.held.get(this.activeTabOf(conv) ?? "");
|
|
3257
|
+
const harmless = req.op === "wait" || req.op === "tabs" && req.action === "switch" || req.op === "snapshot" && blocks(activeHeld);
|
|
3258
|
+
if (this.singleProcess && isActing(req) && !harmless) {
|
|
3259
|
+
const own = this.dialogFor(conv);
|
|
3260
|
+
if (own !== void 0 && own.kind !== "auth")
|
|
3261
|
+
throw new ActionError("dialog_open", blockedByDialogText(own));
|
|
3262
|
+
if ([...this.held.values()].some(blocks))
|
|
3263
|
+
throw new ActionError("failed", PAUSED_BY_DIALOG_MESSAGE);
|
|
3264
|
+
}
|
|
3265
|
+
if (!BLOCKED_OPS.has(req.op)) return;
|
|
3266
|
+
const tab = this.activeTabOf(conv);
|
|
3267
|
+
const h = tab === void 0 ? void 0 : this.held.get(tab);
|
|
3268
|
+
if (blocks(h)) throw new ActionError("dialog_open", blockedByDialogText(h.view));
|
|
3269
|
+
}
|
|
3270
|
+
/** The JS dialog that blocks a page, if any. */
|
|
3271
|
+
blockingDialog(page) {
|
|
3272
|
+
const h = this.held.get(this.tabIdOf(page));
|
|
3273
|
+
return blocks(h) ? h.view : void 0;
|
|
3274
|
+
}
|
|
2163
3275
|
/**
|
|
2164
3276
|
* Waits for the request's downloads at most `downloadWaitMs`; those still running are noted as
|
|
2165
3277
|
* in progress (their result note comes later).
|
|
@@ -2238,7 +3350,7 @@ var BrowserSession = class {
|
|
|
2238
3350
|
}
|
|
2239
3351
|
async pageInfo(page) {
|
|
2240
3352
|
const known = this.titles.get(this.tabIdOf(page)) ?? "";
|
|
2241
|
-
const title = await this.bounded(
|
|
3353
|
+
const title = this.blockingDialog(page) !== void 0 ? known : await this.bounded(
|
|
2242
3354
|
page.title().catch(() => known),
|
|
2243
3355
|
known
|
|
2244
3356
|
);
|
|
@@ -2319,9 +3431,10 @@ var BrowserSession = class {
|
|
|
2319
3431
|
const deadline = Date.now() + this.navigationTimeoutMs;
|
|
2320
3432
|
const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
|
|
2321
3433
|
try {
|
|
2322
|
-
res = await this.gotoPastNetworkChange(page, url, watch, deadline);
|
|
3434
|
+
res = await this.ownNav(page, () => this.gotoPastNetworkChange(page, url, watch, deadline));
|
|
2323
3435
|
} catch (e) {
|
|
2324
3436
|
const msg = firstLine(e);
|
|
3437
|
+
if (this.signInAsked(page, e)) return;
|
|
2325
3438
|
if (msg.includes("Download is starting")) {
|
|
2326
3439
|
await download.catch(() => void 0);
|
|
2327
3440
|
return;
|
|
@@ -2499,20 +3612,25 @@ var BrowserSession = class {
|
|
|
2499
3612
|
if (req.url !== void 0) {
|
|
2500
3613
|
await this.goto(page, normalizeUrl(req.url));
|
|
2501
3614
|
} else if (req.action === "back" || req.action === "forward") {
|
|
2502
|
-
const r = await
|
|
3615
|
+
const r = await this.ownNav(
|
|
3616
|
+
page,
|
|
3617
|
+
() => req.action === "back" ? page.goBack() : page.goForward()
|
|
3618
|
+
).catch(async (e) => {
|
|
3619
|
+
if (this.signInAsked(page, e)) return null;
|
|
3620
|
+
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
3621
|
+
throw e;
|
|
3622
|
+
});
|
|
3623
|
+
if (r === null && page.url() === "about:blank") {
|
|
3624
|
+
return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
|
|
3625
|
+
}
|
|
3626
|
+
} else if (req.action === "reload") {
|
|
3627
|
+
await this.ownNav(page, () => page.reload({ waitUntil: "domcontentloaded" })).catch(
|
|
2503
3628
|
async (e) => {
|
|
3629
|
+
if (this.signInAsked(page, e)) return null;
|
|
2504
3630
|
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
2505
3631
|
throw e;
|
|
2506
3632
|
}
|
|
2507
3633
|
);
|
|
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
3634
|
} else {
|
|
2517
3635
|
throw new ActionError(
|
|
2518
3636
|
"failed",
|
|
@@ -2523,8 +3641,14 @@ var BrowserSession = class {
|
|
|
2523
3641
|
}
|
|
2524
3642
|
case "tabs":
|
|
2525
3643
|
return this.tabsOp(req);
|
|
2526
|
-
case "snapshot":
|
|
2527
|
-
|
|
3644
|
+
case "snapshot": {
|
|
3645
|
+
const page = await activePage();
|
|
3646
|
+
const blocking = this.blockingDialog(page);
|
|
3647
|
+
if (blocking !== void 0) return { text: blockedByDialogText(blocking) };
|
|
3648
|
+
return { text: await takeSnapshot(page) };
|
|
3649
|
+
}
|
|
3650
|
+
case "dialog":
|
|
3651
|
+
return this.dialogOp(req);
|
|
2528
3652
|
case "click":
|
|
2529
3653
|
case "hover": {
|
|
2530
3654
|
const page = await activePage();
|
|
@@ -2588,6 +3712,8 @@ var BrowserSession = class {
|
|
|
2588
3712
|
}
|
|
2589
3713
|
case "wait":
|
|
2590
3714
|
return this.waitOp(req, this.currentPage(conv));
|
|
3715
|
+
case "watch_end":
|
|
3716
|
+
return { watch: this.watchEnd(req) };
|
|
2591
3717
|
case "screenshot": {
|
|
2592
3718
|
const page = await activePage();
|
|
2593
3719
|
const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
|
|
@@ -2708,17 +3834,79 @@ var BrowserSession = class {
|
|
|
2708
3834
|
async viewerNav(page, nav) {
|
|
2709
3835
|
try {
|
|
2710
3836
|
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();
|
|
3837
|
+
else if (nav.action === "back") await this.ownNav(page, () => page.goBack());
|
|
3838
|
+
else if (nav.action === "forward") await this.ownNav(page, () => page.goForward());
|
|
3839
|
+
else if (nav.action === "reload") await this.ownNav(page, () => page.reload());
|
|
2714
3840
|
} catch {
|
|
2715
3841
|
}
|
|
2716
3842
|
}
|
|
3843
|
+
/** The saved path of the conversation's next download within `ms`, else undefined. */
|
|
3844
|
+
nextDownload(conv, ms) {
|
|
3845
|
+
return new Promise((resolve) => {
|
|
3846
|
+
let timer;
|
|
3847
|
+
const w = {
|
|
3848
|
+
conv,
|
|
3849
|
+
resolve: (path) => {
|
|
3850
|
+
this.downloadWaiters.delete(w);
|
|
3851
|
+
this.clock.cancel(timer);
|
|
3852
|
+
resolve(path);
|
|
3853
|
+
}
|
|
3854
|
+
};
|
|
3855
|
+
this.downloadWaiters.add(w);
|
|
3856
|
+
timer = this.clock.schedule(() => w.resolve(void 0), ms);
|
|
3857
|
+
});
|
|
3858
|
+
}
|
|
3859
|
+
/** Whether a watch's condition holds on the page now (text, ref, URL part). */
|
|
3860
|
+
async conditionHolds(page, c) {
|
|
3861
|
+
if ("text" in c) return this.bounded(page.getByText(c.text).first().isVisible(), false);
|
|
3862
|
+
if ("ref" in c)
|
|
3863
|
+
return REF_RE.test(c.ref) && this.bounded(page.getByRef(c.ref).first().isVisible(), false);
|
|
3864
|
+
if ("urlContains" in c) return page.url().includes(c.urlContains);
|
|
3865
|
+
return false;
|
|
3866
|
+
}
|
|
3867
|
+
/**
|
|
3868
|
+
* Arms a long wait's watch on the conversation's active tab (browser long waits spec §6.2);
|
|
3869
|
+
* a conversation without a tab cannot be watched. Idempotent per watch id.
|
|
3870
|
+
*/
|
|
3871
|
+
watchStart(req) {
|
|
3872
|
+
const conv = req.conversationId;
|
|
3873
|
+
if (!this.watches.owns(req.watchId, conv)) return { state: "unknown" };
|
|
3874
|
+
const condition = parseCondition(req.condition);
|
|
3875
|
+
if (typeof condition === "string") throw new ActionError("failed", condition);
|
|
3876
|
+
if ("ref" in condition && !REF_RE.test(condition.ref))
|
|
3877
|
+
throw new ActionError(
|
|
3878
|
+
"no_such_ref",
|
|
3879
|
+
`${JSON.stringify(condition.ref)} is not an element ref; refs look like e12.`
|
|
3880
|
+
);
|
|
3881
|
+
const page = this.currentPage(conv);
|
|
3882
|
+
if (page === void 0) throw new ActionError("failed", NO_TAB_TO_WAIT_ON);
|
|
3883
|
+
const remaining = Number(req.remainingMs);
|
|
3884
|
+
return this.watches.start({
|
|
3885
|
+
id: req.watchId,
|
|
3886
|
+
conv,
|
|
3887
|
+
root: req.rootConversationId,
|
|
3888
|
+
tabId: this.tabIdOf(page),
|
|
3889
|
+
page,
|
|
3890
|
+
condition,
|
|
3891
|
+
remainingMs: Number.isFinite(remaining) ? remaining : 0
|
|
3892
|
+
});
|
|
3893
|
+
}
|
|
3894
|
+
/** A long wait's poll (its heartbeat); another conversation's watch reads as unknown. */
|
|
3895
|
+
watchPoll(req) {
|
|
3896
|
+
if (!this.watches.owns(req.watchId, req.conversationId)) return { state: "unknown" };
|
|
3897
|
+
return this.watches.poll(req.watchId);
|
|
3898
|
+
}
|
|
3899
|
+
/** Ends a long wait's watch, answering its last state. */
|
|
3900
|
+
watchEnd(req) {
|
|
3901
|
+
if (!this.watches.owns(req.watchId, req.conversationId)) return { state: "unknown" };
|
|
3902
|
+
return this.watches.end(req.watchId);
|
|
3903
|
+
}
|
|
2717
3904
|
async waitOp(req, page) {
|
|
2718
3905
|
const asked = Number(req.timeoutMs);
|
|
2719
3906
|
const timeout = Number.isFinite(asked) ? Math.max(0, Math.min(MAX_WAIT_MS, Math.floor(asked))) : DEFAULT_WAIT_MS;
|
|
3907
|
+
if (page !== void 0 && this.blockingDialog(page) !== void 0) return {};
|
|
2720
3908
|
if (page === void 0) {
|
|
2721
|
-
if (req.text !== void 0 || req.ref !== void 0 || req.navigation === true)
|
|
3909
|
+
if (req.text !== void 0 || req.ref !== void 0 || req.navigation === true || req.urlContains !== void 0 || req.download === true)
|
|
2722
3910
|
throw new ActionError("failed", NO_TAB_TO_WAIT_ON);
|
|
2723
3911
|
await new Promise((r) => this.clock.schedule(r, timeout));
|
|
2724
3912
|
return {};
|
|
@@ -2744,6 +3932,22 @@ var BrowserSession = class {
|
|
|
2744
3932
|
});
|
|
2745
3933
|
return {};
|
|
2746
3934
|
}
|
|
3935
|
+
if (req.urlContains !== void 0) {
|
|
3936
|
+
const part = req.urlContains;
|
|
3937
|
+
await page.waitForURL((u) => u.href.includes(part), { timeout, waitUntil: "commit" }).catch((e) => {
|
|
3938
|
+
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError(
|
|
3939
|
+
"timeout",
|
|
3940
|
+
`The URL did not contain ${JSON.stringify(part)} within ${timeout} ms.`
|
|
3941
|
+
) : e;
|
|
3942
|
+
});
|
|
3943
|
+
return {};
|
|
3944
|
+
}
|
|
3945
|
+
if (req.download === true) {
|
|
3946
|
+
const path = await this.nextDownload(req.conversationId, timeout);
|
|
3947
|
+
if (path === void 0)
|
|
3948
|
+
throw new ActionError("timeout", `No download finished within ${timeout} ms.`);
|
|
3949
|
+
return { text: `Waited for the download: ${path}.` };
|
|
3950
|
+
}
|
|
2747
3951
|
if (req.navigation === true) {
|
|
2748
3952
|
await page.waitForEvent("framenavigated", { predicate: (f) => f === page.mainFrame(), timeout }).catch((e) => {
|
|
2749
3953
|
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError("timeout", `No navigation within ${timeout} ms.`) : e;
|
|
@@ -2756,6 +3960,7 @@ var BrowserSession = class {
|
|
|
2756
3960
|
}
|
|
2757
3961
|
/** Closes the browser (flushes the profile). */
|
|
2758
3962
|
async close() {
|
|
3963
|
+
this.watches.dispose();
|
|
2759
3964
|
this.listeners.clear();
|
|
2760
3965
|
if (this.downloadPoll !== void 0) this.clock.cancel(this.downloadPoll);
|
|
2761
3966
|
await this.ctx.close().catch(() => void 0);
|
|
@@ -3113,7 +4318,7 @@ async function restoreCookies(ctx, stateDir) {
|
|
|
3113
4318
|
// daemon/session-file.ts
|
|
3114
4319
|
import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3115
4320
|
import { join as join4 } from "node:path";
|
|
3116
|
-
var RESTORE_MAX_AGE_MS =
|
|
4321
|
+
var RESTORE_MAX_AGE_MS = DEVICE_SERVICE_RESTORE_MAX_AGE_MS;
|
|
3117
4322
|
var SESSION_FILE_VERSION = 2;
|
|
3118
4323
|
var isId = (v) => typeof v === "string" && v !== "";
|
|
3119
4324
|
var SessionFile = class {
|
|
@@ -3203,6 +4408,27 @@ var SessionFile = class {
|
|
|
3203
4408
|
}
|
|
3204
4409
|
});
|
|
3205
4410
|
}
|
|
4411
|
+
/**
|
|
4412
|
+
* Removes a deleted conversation and the conversations whose tree root it is from the file on
|
|
4413
|
+
* disk, keeping its save time (a restore window never grows), so a later start does not restore
|
|
4414
|
+
* their tabs. Nothing to do without a file or after {@link forget}.
|
|
4415
|
+
*/
|
|
4416
|
+
dropTree(conversationId) {
|
|
4417
|
+
if (this.forgotten) return;
|
|
4418
|
+
let raw;
|
|
4419
|
+
try {
|
|
4420
|
+
raw = JSON.parse(readFileSync3(this.file, "utf8"));
|
|
4421
|
+
} catch {
|
|
4422
|
+
return;
|
|
4423
|
+
}
|
|
4424
|
+
const next = withoutTree(raw, conversationId);
|
|
4425
|
+
if (next === raw) return;
|
|
4426
|
+
try {
|
|
4427
|
+
writeFileSync3(`${this.file}.tmp`, JSON.stringify(next), { mode: 384 });
|
|
4428
|
+
renameSync2(`${this.file}.tmp`, this.file);
|
|
4429
|
+
} catch {
|
|
4430
|
+
}
|
|
4431
|
+
}
|
|
3206
4432
|
/** Removes the file and stops saving (an idle stop). */
|
|
3207
4433
|
forget() {
|
|
3208
4434
|
this.forgotten = true;
|
|
@@ -3236,6 +4462,22 @@ var SessionFile = class {
|
|
|
3236
4462
|
}
|
|
3237
4463
|
}
|
|
3238
4464
|
};
|
|
4465
|
+
function withoutTree(saved, conversationId) {
|
|
4466
|
+
const hit = (owner, root) => owner === conversationId || root === conversationId;
|
|
4467
|
+
if (!Array.isArray(saved.tabs) || !Array.isArray(saved.conversations)) return saved;
|
|
4468
|
+
const tabs = saved.tabs.filter((t) => !hit(t?.owner, t?.root));
|
|
4469
|
+
const conversations = saved.conversations.filter((c) => !hit(c?.id, c?.root));
|
|
4470
|
+
if (tabs.length === saved.tabs.length && conversations.length === saved.conversations.length)
|
|
4471
|
+
return saved;
|
|
4472
|
+
const kept = conversations.map((c) => {
|
|
4473
|
+
if (c.active === void 0) return c;
|
|
4474
|
+
const tab = saved.tabs[c.active];
|
|
4475
|
+
const at = tab === void 0 ? -1 : tabs.indexOf(tab);
|
|
4476
|
+
const { active: _active, ...rest } = c;
|
|
4477
|
+
return at < 0 ? rest : { ...rest, active: at };
|
|
4478
|
+
});
|
|
4479
|
+
return { ...saved, tabs, conversations: kept };
|
|
4480
|
+
}
|
|
3239
4481
|
|
|
3240
4482
|
// daemon/cursor.ts
|
|
3241
4483
|
var CURSOR_MAX_FRAMES = 20;
|
|
@@ -3528,6 +4770,7 @@ var FrameQuality = class {
|
|
|
3528
4770
|
|
|
3529
4771
|
// daemon/viewer.ts
|
|
3530
4772
|
var VIEWER_PING_MS = 1e3;
|
|
4773
|
+
var FIRST_FRAME_MS = 1e3;
|
|
3531
4774
|
var RESTART_MIN_MS = 500;
|
|
3532
4775
|
var ENCODE_MAX_INTERVAL_MS = 500;
|
|
3533
4776
|
var CURSOR_TIMEOUT_MS = 200;
|
|
@@ -3606,6 +4849,8 @@ var ViewerSession = class {
|
|
|
3606
4849
|
draining = false;
|
|
3607
4850
|
stateQueued = false;
|
|
3608
4851
|
lastControl = "agent";
|
|
4852
|
+
/** The viewport the screencast was started for (a profile switch restarts it). */
|
|
4853
|
+
streamedViewport = "";
|
|
3609
4854
|
constructor(opts) {
|
|
3610
4855
|
this.browser = opts.browser;
|
|
3611
4856
|
this.state = opts.state;
|
|
@@ -3696,6 +4941,34 @@ var ViewerSession = class {
|
|
|
3696
4941
|
this.queueState();
|
|
3697
4942
|
}
|
|
3698
4943
|
return;
|
|
4944
|
+
case "dialog":
|
|
4945
|
+
if (this.state.control !== "user") return;
|
|
4946
|
+
void this.browser.answerFromViewer(this.root, m).catch(() => void 0);
|
|
4947
|
+
return;
|
|
4948
|
+
case "permission":
|
|
4949
|
+
if (this.state.control !== "user" || m.allow !== true) return;
|
|
4950
|
+
void this.browser.grantPermission(this.root, m.origin, m.permission);
|
|
4951
|
+
return;
|
|
4952
|
+
case "viewport":
|
|
4953
|
+
this.input(() => this.browser.setProfile(m.profile));
|
|
4954
|
+
return;
|
|
4955
|
+
case "touch":
|
|
4956
|
+
this.input(async () => {
|
|
4957
|
+
const page = this.shownPage();
|
|
4958
|
+
if (page === void 0) return;
|
|
4959
|
+
this.concern(this.browser.tabIdOf(page));
|
|
4960
|
+
const vp = this.browser.viewport;
|
|
4961
|
+
const points = [];
|
|
4962
|
+
for (const q of Array.isArray(m.points) ? m.points.slice(0, 10) : []) {
|
|
4963
|
+
const at = point(q, vp);
|
|
4964
|
+
const id = Number(q?.id);
|
|
4965
|
+
if (at !== null && Number.isFinite(id)) points.push({ id, ...at });
|
|
4966
|
+
}
|
|
4967
|
+
const kind = m.kind;
|
|
4968
|
+
if (kind !== "start" && kind !== "move" && kind !== "end" && kind !== "cancel") return;
|
|
4969
|
+
await this.browser.touch(page, kind, points);
|
|
4970
|
+
});
|
|
4971
|
+
return;
|
|
3699
4972
|
case "tab":
|
|
3700
4973
|
if (m.action === "adopt") {
|
|
3701
4974
|
this.adopt(m.tabId);
|
|
@@ -3794,7 +5067,7 @@ var ViewerSession = class {
|
|
|
3794
5067
|
/** A pointer move: coalesced while one waits (the newest position wins), then the cursor. */
|
|
3795
5068
|
move(m) {
|
|
3796
5069
|
if (this.state.control !== "user") return;
|
|
3797
|
-
const p = point(m);
|
|
5070
|
+
const p = point(m, this.browser.viewport);
|
|
3798
5071
|
if (p === null) return;
|
|
3799
5072
|
if (this.moveSlot !== void 0) {
|
|
3800
5073
|
this.moveSlot.x = p.x;
|
|
@@ -3880,7 +5153,7 @@ var ViewerSession = class {
|
|
|
3880
5153
|
}
|
|
3881
5154
|
setSize(w, h) {
|
|
3882
5155
|
this.maxWidth = clampDim(w, VIEWPORT.width);
|
|
3883
|
-
this.maxHeight = clampDim(h, VIEWPORT.height);
|
|
5156
|
+
this.maxHeight = clampDim(h, Math.max(VIEWPORT.height, VIEWPORT_PROFILES.phone.height));
|
|
3884
5157
|
}
|
|
3885
5158
|
/** Pings the viewer every VIEWER_PING_MS (its pong measures the path, see the pacing). */
|
|
3886
5159
|
ping() {
|
|
@@ -3947,7 +5220,12 @@ var ViewerSession = class {
|
|
|
3947
5220
|
title: clip(t.title, 200),
|
|
3948
5221
|
url: clip(t.url, 200)
|
|
3949
5222
|
})),
|
|
3950
|
-
handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) }))
|
|
5223
|
+
handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) })),
|
|
5224
|
+
dialogs: m.dialogs.map((d) => ({
|
|
5225
|
+
...d,
|
|
5226
|
+
message: clip(d.message, 200),
|
|
5227
|
+
...d.defaultValue === void 0 ? {} : { defaultValue: clip(d.defaultValue, 200) }
|
|
5228
|
+
}))
|
|
3951
5229
|
};
|
|
3952
5230
|
} else if (m.t === "dialog") {
|
|
3953
5231
|
small = { ...m, message: clip(m.message, 200) };
|
|
@@ -3980,6 +5258,13 @@ var ViewerSession = class {
|
|
|
3980
5258
|
this.queueState();
|
|
3981
5259
|
} else if (e.root !== this.root) return;
|
|
3982
5260
|
else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
|
|
5261
|
+
else if (e.type === "permission")
|
|
5262
|
+
this.send({
|
|
5263
|
+
t: "permission",
|
|
5264
|
+
origin: e.origin,
|
|
5265
|
+
permission: e.permission,
|
|
5266
|
+
grantable: e.grantable
|
|
5267
|
+
});
|
|
3983
5268
|
else this.send({ t: "dialog", kind: e.kind, message: e.message });
|
|
3984
5269
|
}
|
|
3985
5270
|
/** Coalesces bursts of changes into one state message. */
|
|
@@ -4034,9 +5319,13 @@ var ViewerSession = class {
|
|
|
4034
5319
|
const tree = all.filter((t) => t.root === this.root);
|
|
4035
5320
|
this.shown = this.computeShown(tree);
|
|
4036
5321
|
this.pinShownOwner();
|
|
4037
|
-
|
|
5322
|
+
const viewport = this.browser.viewport;
|
|
5323
|
+
const vpKey = `${viewport.width}x${viewport.height}`;
|
|
5324
|
+
if (this.browser.pageById(this.shown) !== this.page || vpKey !== this.streamedViewport) {
|
|
4038
5325
|
void this.serial(async () => {
|
|
4039
|
-
|
|
5326
|
+
const key2 = `${this.browser.viewport.width}x${this.browser.viewport.height}`;
|
|
5327
|
+
if (this.browser.pageById(this.shown) === this.page && key2 === this.streamedViewport)
|
|
5328
|
+
return;
|
|
4040
5329
|
await this.detach();
|
|
4041
5330
|
await this.attach();
|
|
4042
5331
|
});
|
|
@@ -4059,6 +5348,7 @@ var ViewerSession = class {
|
|
|
4059
5348
|
tabs.sort((a, b) => (order.get(a.group) ?? 0) - (order.get(b.group) ?? 0));
|
|
4060
5349
|
const shownTab = tree.find((t) => t.id === this.shown);
|
|
4061
5350
|
const last = this.browser.lastClickOf(this.shown);
|
|
5351
|
+
const waiting = this.browser.watches.waitingOf(this.root);
|
|
4062
5352
|
this.send({
|
|
4063
5353
|
t: "state",
|
|
4064
5354
|
tabs,
|
|
@@ -4073,11 +5363,15 @@ var ViewerSession = class {
|
|
|
4073
5363
|
conversationId: h.conversationId,
|
|
4074
5364
|
message: h.message,
|
|
4075
5365
|
tabIds: this.browser.tabsOf(h.conversationId)
|
|
4076
|
-
}))
|
|
5366
|
+
})),
|
|
5367
|
+
...waiting === void 0 ? {} : { waiting: { label: waiting.label.slice(0, 200), until: waiting.until } },
|
|
5368
|
+
dialogs: this.browser.dialogsOf(this.root),
|
|
5369
|
+
viewport
|
|
4077
5370
|
});
|
|
4078
5371
|
}
|
|
4079
5372
|
get scale() {
|
|
4080
|
-
|
|
5373
|
+
const vp = this.browser.viewport;
|
|
5374
|
+
return Math.min(1, this.maxWidth / vp.width, this.maxHeight / vp.height) * this.frameQuality.shrink;
|
|
4081
5375
|
}
|
|
4082
5376
|
/** Room for the JPEG in one frame message. */
|
|
4083
5377
|
get jpegBudget() {
|
|
@@ -4087,15 +5381,20 @@ var ViewerSession = class {
|
|
|
4087
5381
|
if (this.closed) return;
|
|
4088
5382
|
const page = this.shownPage();
|
|
4089
5383
|
if (page === void 0) return;
|
|
5384
|
+
this.streamedViewport = `${this.browser.viewport.width}x${this.browser.viewport.height}`;
|
|
4090
5385
|
const cdp = await this.browser.context.newCDPSession(page);
|
|
4091
5386
|
this.page = page;
|
|
4092
5387
|
this.cdp = cdp;
|
|
4093
5388
|
cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
|
|
4094
5389
|
this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
|
|
4095
|
-
|
|
4096
|
-
|
|
4097
|
-
maxScale: this.scale
|
|
4098
|
-
|
|
5390
|
+
let timer;
|
|
5391
|
+
const first = await Promise.race([
|
|
5392
|
+
captureFitting(cdp, { maxBytes: this.jpegBudget, maxScale: this.scale }).catch(() => null),
|
|
5393
|
+
new Promise((r) => {
|
|
5394
|
+
timer = this.clock.schedule(() => r(null), FIRST_FRAME_MS);
|
|
5395
|
+
})
|
|
5396
|
+
]);
|
|
5397
|
+
this.clock.cancel(timer);
|
|
4099
5398
|
if (first !== null && this.cdp === cdp) {
|
|
4100
5399
|
this.pending = {
|
|
4101
5400
|
cdp,
|
|
@@ -4112,8 +5411,8 @@ var ViewerSession = class {
|
|
|
4112
5411
|
await cdp.send("Page.startScreencast", {
|
|
4113
5412
|
format: "jpeg",
|
|
4114
5413
|
quality: this.frameQuality.quality,
|
|
4115
|
-
maxWidth: Math.max(16, Math.floor(
|
|
4116
|
-
maxHeight: Math.max(16, Math.floor(
|
|
5414
|
+
maxWidth: Math.max(16, Math.floor(this.browser.viewport.width * this.scale)),
|
|
5415
|
+
maxHeight: Math.max(16, Math.floor(this.browser.viewport.height * this.scale)),
|
|
4117
5416
|
everyNthFrame: 1
|
|
4118
5417
|
});
|
|
4119
5418
|
}
|
|
@@ -4217,7 +5516,7 @@ var ViewerSession = class {
|
|
|
4217
5516
|
}
|
|
4218
5517
|
async mouse(m) {
|
|
4219
5518
|
const page = this.shownPage();
|
|
4220
|
-
const p = point(m);
|
|
5519
|
+
const p = point(m, this.browser.viewport);
|
|
4221
5520
|
if (p === null || page === void 0) return;
|
|
4222
5521
|
this.concern(this.browser.tabIdOf(page));
|
|
4223
5522
|
const { x, y } = p;
|
|
@@ -4263,13 +5562,13 @@ var ViewerSession = class {
|
|
|
4263
5562
|
}
|
|
4264
5563
|
};
|
|
4265
5564
|
var handoffKey = (h) => `${h.conversationId}\0${h.callId}`;
|
|
4266
|
-
function point(m) {
|
|
4267
|
-
const x = Number(m
|
|
4268
|
-
const y = Number(m
|
|
5565
|
+
function point(m, vp = VIEWPORT) {
|
|
5566
|
+
const x = Number(m?.x);
|
|
5567
|
+
const y = Number(m?.y);
|
|
4269
5568
|
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
|
|
4270
5569
|
return {
|
|
4271
|
-
x: Math.max(0, Math.min(
|
|
4272
|
-
y: Math.max(0, Math.min(
|
|
5570
|
+
x: Math.max(0, Math.min(vp.width - 1, x)),
|
|
5571
|
+
y: Math.max(0, Math.min(vp.height - 1, y))
|
|
4273
5572
|
};
|
|
4274
5573
|
}
|
|
4275
5574
|
|
|
@@ -4284,6 +5583,9 @@ var dec = new TextDecoder();
|
|
|
4284
5583
|
var REQUEST_OPS = /* @__PURE__ */ new Set([
|
|
4285
5584
|
"handoff_notice",
|
|
4286
5585
|
"handoff_clear",
|
|
5586
|
+
"watch_start",
|
|
5587
|
+
"watch_poll",
|
|
5588
|
+
"watch_end",
|
|
4287
5589
|
"navigate",
|
|
4288
5590
|
"tabs",
|
|
4289
5591
|
"snapshot",
|
|
@@ -4297,7 +5599,8 @@ var REQUEST_OPS = /* @__PURE__ */ new Set([
|
|
|
4297
5599
|
"click_at",
|
|
4298
5600
|
"type_at",
|
|
4299
5601
|
"wait",
|
|
4300
|
-
"screenshot"
|
|
5602
|
+
"screenshot",
|
|
5603
|
+
"dialog"
|
|
4301
5604
|
]);
|
|
4302
5605
|
function downloadMaxBytes(env) {
|
|
4303
5606
|
const raw = env.BROWSER_DOWNLOAD_MAX_BYTES;
|
|
@@ -4317,6 +5620,7 @@ function parse(raw) {
|
|
|
4317
5620
|
}
|
|
4318
5621
|
}
|
|
4319
5622
|
var HANDOFF_HOLDS_ROLL_MS = 30 * 6e4;
|
|
5623
|
+
var NOTICE_LAUNCH_WAIT_MS = 5e3;
|
|
4320
5624
|
function isRollCheck(body) {
|
|
4321
5625
|
return typeof body === "object" && body !== null && body.capybara === JSON.parse(ROLL_CHECK_REQUEST).capybara;
|
|
4322
5626
|
}
|
|
@@ -4350,7 +5654,7 @@ async function startDaemon(opts) {
|
|
|
4350
5654
|
mkdirSync2(opts.stateDir, { recursive: true });
|
|
4351
5655
|
let closing = false;
|
|
4352
5656
|
const sessionFile = new SessionFile(opts.stateDir, clock);
|
|
4353
|
-
|
|
5657
|
+
let saved = sessionFile.read();
|
|
4354
5658
|
let live;
|
|
4355
5659
|
const state = new DaemonState({
|
|
4356
5660
|
clock,
|
|
@@ -4421,12 +5725,19 @@ async function startDaemon(opts) {
|
|
|
4421
5725
|
proxy: plan.proxy,
|
|
4422
5726
|
clock,
|
|
4423
5727
|
usage: state,
|
|
5728
|
+
// a pending long wait's watch is its conversation's park
|
|
5729
|
+
parks: state,
|
|
5730
|
+
singleProcess: plan.build === "chromium-headless-shell",
|
|
4424
5731
|
workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
|
|
4425
5732
|
downloadsTmp: plan.downloadsTmp,
|
|
4426
5733
|
downloadMaxBytes: downloadMaxBytes(opts.env),
|
|
4427
5734
|
...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs },
|
|
4428
5735
|
...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
|
|
4429
5736
|
});
|
|
5737
|
+
await session.ready;
|
|
5738
|
+
state.onChange(() => {
|
|
5739
|
+
if (state.control === "agent") void session.restoreDesktop();
|
|
5740
|
+
});
|
|
4430
5741
|
if (plan.shippedDir !== void 0)
|
|
4431
5742
|
session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
|
|
4432
5743
|
if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
|
|
@@ -4528,6 +5839,47 @@ async function startDaemon(opts) {
|
|
|
4528
5839
|
blockedHosts: []
|
|
4529
5840
|
};
|
|
4530
5841
|
}
|
|
5842
|
+
async function watchOp(req) {
|
|
5843
|
+
if (typeof req.watchId !== "string" || req.watchId === "")
|
|
5844
|
+
return fail("The watch needs a watchId.");
|
|
5845
|
+
if (req.op === "watch_poll") {
|
|
5846
|
+
const session2 = live;
|
|
5847
|
+
return {
|
|
5848
|
+
ok: true,
|
|
5849
|
+
watch: session2 === void 0 ? { state: "unknown" } : session2.watchPoll(req),
|
|
5850
|
+
blockedHosts: []
|
|
5851
|
+
};
|
|
5852
|
+
}
|
|
5853
|
+
let session;
|
|
5854
|
+
try {
|
|
5855
|
+
session = await browser();
|
|
5856
|
+
} catch (e) {
|
|
5857
|
+
return launchFailure(e);
|
|
5858
|
+
}
|
|
5859
|
+
if (req.op === "watch_end") {
|
|
5860
|
+
const reply = await session.run(req);
|
|
5861
|
+
if (reply.ok) {
|
|
5862
|
+
const since = state.takeHandbackNote(req.conversationId);
|
|
5863
|
+
if (since !== void 0) reply.userControlledSince = since;
|
|
5864
|
+
}
|
|
5865
|
+
return reply;
|
|
5866
|
+
}
|
|
5867
|
+
let watch;
|
|
5868
|
+
try {
|
|
5869
|
+
watch = session.watchStart(req);
|
|
5870
|
+
} catch (e) {
|
|
5871
|
+
if (e instanceof ActionError)
|
|
5872
|
+
return { ok: false, error: e.code, message: e.message, blockedHosts: [] };
|
|
5873
|
+
throw e;
|
|
5874
|
+
}
|
|
5875
|
+
const page = session.currentPage(req.conversationId);
|
|
5876
|
+
return {
|
|
5877
|
+
ok: true,
|
|
5878
|
+
...page === void 0 ? {} : { page: await session.pageInfo(page) },
|
|
5879
|
+
watch,
|
|
5880
|
+
blockedHosts: []
|
|
5881
|
+
};
|
|
5882
|
+
}
|
|
4531
5883
|
const namesConversation = (raw) => {
|
|
4532
5884
|
const r = raw;
|
|
4533
5885
|
return typeof r.conversationId === "string" && r.conversationId !== "" && typeof r.rootConversationId === "string" && r.rootConversationId !== "";
|
|
@@ -4539,6 +5891,8 @@ async function startDaemon(opts) {
|
|
|
4539
5891
|
if (!namesConversation(raw)) return fail(NO_CONVERSATION_MESSAGE);
|
|
4540
5892
|
const req = raw;
|
|
4541
5893
|
const conv = req.conversationId;
|
|
5894
|
+
const deletedIn = () => deletedTree(conv) ?? deletedTree(req.rootConversationId);
|
|
5895
|
+
if (deletedIn() !== void 0) return fail(CONVERSATION_DELETED_MESSAGE);
|
|
4542
5896
|
state.requestArrived(conv, req.rootConversationId);
|
|
4543
5897
|
let reply;
|
|
4544
5898
|
try {
|
|
@@ -4547,11 +5901,15 @@ async function startDaemon(opts) {
|
|
|
4547
5901
|
reply = fail(e instanceof ActionError ? e.message : String(e));
|
|
4548
5902
|
} finally {
|
|
4549
5903
|
state.requestFinished(conv);
|
|
5904
|
+
const tree = deletedIn();
|
|
5905
|
+
if (tree !== void 0) void forgetDeleted(tree).catch(() => void 0);
|
|
4550
5906
|
}
|
|
4551
5907
|
return { ...reply, tabs: { open: live?.countOf(conv) ?? 0, max: MAX_TABS_PER_CONVERSATION } };
|
|
4552
5908
|
}
|
|
4553
5909
|
async function conversationRequest(req) {
|
|
4554
5910
|
if (req.op === "handoff_notice" || req.op === "handoff_clear") return handoffOp(req);
|
|
5911
|
+
if (req.op === "watch_start" || req.op === "watch_poll" || req.op === "watch_end")
|
|
5912
|
+
return watchOp(req);
|
|
4555
5913
|
state.dropHandoff(req.conversationId);
|
|
4556
5914
|
if (state.control === "user" && req.op !== "wait") {
|
|
4557
5915
|
return { ok: false, error: "taken_over", message: TAKEN_OVER_MESSAGE, blockedHosts: [] };
|
|
@@ -4603,7 +5961,7 @@ async function startDaemon(opts) {
|
|
|
4603
5961
|
}
|
|
4604
5962
|
if (kind === "stream" && context === void 0) {
|
|
4605
5963
|
const ctx = parseViewerContext(raw);
|
|
4606
|
-
if (ctx === null) {
|
|
5964
|
+
if (ctx === null || deletedTree(ctx.conversationId) !== void 0 || deletedTree(ctx.rootConversationId) !== void 0) {
|
|
4607
5965
|
sock.destroy();
|
|
4608
5966
|
return;
|
|
4609
5967
|
}
|
|
@@ -4647,6 +6005,11 @@ async function startDaemon(opts) {
|
|
|
4647
6005
|
if (kind === "request") {
|
|
4648
6006
|
if (handled) return;
|
|
4649
6007
|
handled = true;
|
|
6008
|
+
const deleted2 = parseConversationDeleted(raw);
|
|
6009
|
+
if (deleted2 !== null) {
|
|
6010
|
+
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());
|
|
6011
|
+
return;
|
|
6012
|
+
}
|
|
4650
6013
|
const body = parse(raw);
|
|
4651
6014
|
if (isRollCheck(body)) {
|
|
4652
6015
|
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 +6040,21 @@ async function startDaemon(opts) {
|
|
|
4677
6040
|
for (const m of msgs) onMessage(m);
|
|
4678
6041
|
});
|
|
4679
6042
|
}
|
|
6043
|
+
const deleted = /* @__PURE__ */ new Map();
|
|
6044
|
+
function deletedTree(id) {
|
|
6045
|
+
const now = clock.now();
|
|
6046
|
+
for (const [c, at] of deleted) if (now - at > RESTORE_MAX_AGE_MS) deleted.delete(c);
|
|
6047
|
+
return deleted.has(id) ? id : void 0;
|
|
6048
|
+
}
|
|
6049
|
+
async function forgetDeleted(conversationId) {
|
|
6050
|
+
if (!deleted.has(conversationId)) deleted.set(conversationId, clock.now());
|
|
6051
|
+
const forgotten = state.forgetTree(conversationId);
|
|
6052
|
+
if (saved !== void 0) saved = withoutTree(saved, conversationId);
|
|
6053
|
+
sessionFile.dropTree(conversationId);
|
|
6054
|
+
const session = live ?? (current === void 0 ? void 0 : await within2(current, NOTICE_LAUNCH_WAIT_MS).catch(() => void 0));
|
|
6055
|
+
if (session === void 0) return 0;
|
|
6056
|
+
return session.forgetTree(conversationId, forgotten);
|
|
6057
|
+
}
|
|
4680
6058
|
if (existsSync2(opts.socketPath)) unlinkSync2(opts.socketPath);
|
|
4681
6059
|
const server = createServer(onConnection);
|
|
4682
6060
|
await new Promise((resolve, reject) => {
|