@capybara-hq/plugin-browser 0.1.0-rc.0 → 0.1.0-rc.10
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 +3 -3
- package/README.md +191 -24
- package/dist/index.mjs +409 -118
- package/package.json +2 -2
- package/ui/panel.js +922 -132
- package/ui/service/daemon.mjs +3145 -470
package/ui/service/daemon.mjs
CHANGED
|
@@ -1,8 +1,53 @@
|
|
|
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.77/node_modules/@capybara-hq/plugin-sdk/dist/device-provider.js
|
|
4
|
+
var MAX_PATH_LENGTH = 4096;
|
|
5
|
+
var DEFAULT_SANDBOX_ROOTS = Object.freeze({
|
|
6
|
+
workspace: "/workspace",
|
|
7
|
+
skills: "/skills",
|
|
8
|
+
tmp: "/tmp"
|
|
9
|
+
});
|
|
10
|
+
function sandboxProxyRefusalLayer(reason) {
|
|
11
|
+
const r = reason.trim().toLowerCase();
|
|
12
|
+
if (r.startsWith("address is ") || r.startsWith("resolved to ") || r === "malformed host")
|
|
13
|
+
return "address";
|
|
14
|
+
if (r === "host is not on the allow list")
|
|
15
|
+
return "device";
|
|
16
|
+
return "unknown";
|
|
17
|
+
}
|
|
18
|
+
var DEVICE_REPORT_LIMITS = Object.freeze({
|
|
19
|
+
revisionChars: 128,
|
|
20
|
+
descriptionChars: 300,
|
|
21
|
+
limits: 8,
|
|
22
|
+
limitLabelChars: 60,
|
|
23
|
+
limitValueChars: 60,
|
|
24
|
+
homeChars: 4096,
|
|
25
|
+
changeHintChars: 400
|
|
26
|
+
});
|
|
27
|
+
var DEVICE_SERVICE_FILES_DIGEST_VECTOR = Object.freeze({
|
|
28
|
+
files: Object.freeze({
|
|
29
|
+
"main.js": "console.log(1)\n",
|
|
30
|
+
"lib/a.js": "export const a = 1;\n",
|
|
31
|
+
empty: ""
|
|
32
|
+
}),
|
|
33
|
+
digest: "sha256:7b3959ff2e10237b9f1a255bbecb5dacebd31422fe734b2867403e42913432a5"
|
|
34
|
+
});
|
|
35
|
+
var DEVICE_SCAN_SKIPPED_DIRS = Object.freeze(["node_modules"]);
|
|
36
|
+
var DEVICE_SCAN_SKIPPED_BASE_DIRS = Object.freeze(["Library"]);
|
|
37
|
+
var STOPS = /* @__PURE__ */ new Set([
|
|
38
|
+
"path must be a non-empty string",
|
|
39
|
+
`path must be at most ${MAX_PATH_LENGTH} characters`,
|
|
40
|
+
"path must not contain control characters",
|
|
41
|
+
"path must not contain backslashes",
|
|
42
|
+
"path must be absolute",
|
|
43
|
+
"path must not contain empty segments"
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
// ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.77/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
|
|
4
47
|
var DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
|
|
5
48
|
var DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
|
|
49
|
+
var DEVICE_SERVICE_MACH_ENV = "CAPYBARA_SERVICE_MACH";
|
|
50
|
+
var DEVICE_SERVICE_MACH_CHROMIUM = "chromium";
|
|
6
51
|
var DEVICE_SERVICE_MAX_MESSAGE = 8 * 1024 * 1024;
|
|
7
52
|
var HEADER = 4;
|
|
8
53
|
function encodeServiceMessage(body) {
|
|
@@ -67,29 +112,233 @@ var ServiceMessageDecoder = class {
|
|
|
67
112
|
return out;
|
|
68
113
|
}
|
|
69
114
|
};
|
|
115
|
+
function parseViewerContext(body) {
|
|
116
|
+
let msg;
|
|
117
|
+
try {
|
|
118
|
+
const text = typeof body === "string" ? body : new TextDecoder("utf-8", { fatal: true }).decode(body);
|
|
119
|
+
msg = JSON.parse(text);
|
|
120
|
+
} catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
if (typeof msg !== "object" || msg === null || Array.isArray(msg))
|
|
124
|
+
return null;
|
|
125
|
+
const { kind, conversationId, rootConversationId } = msg;
|
|
126
|
+
if (kind !== "viewer")
|
|
127
|
+
return null;
|
|
128
|
+
if (typeof conversationId !== "string" || conversationId === "")
|
|
129
|
+
return null;
|
|
130
|
+
if (typeof rootConversationId !== "string" || rootConversationId === "")
|
|
131
|
+
return null;
|
|
132
|
+
return { kind: "viewer", conversationId, rootConversationId };
|
|
133
|
+
}
|
|
70
134
|
|
|
71
135
|
// daemon/main.ts
|
|
72
|
-
import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync } from "node:fs";
|
|
136
|
+
import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2 } from "node:fs";
|
|
73
137
|
import { createServer } from "node:net";
|
|
74
138
|
|
|
75
139
|
// daemon/actions.ts
|
|
76
|
-
import {
|
|
140
|
+
import {
|
|
141
|
+
closeSync,
|
|
142
|
+
constants as fsc,
|
|
143
|
+
fstatSync,
|
|
144
|
+
lstatSync,
|
|
145
|
+
mkdirSync,
|
|
146
|
+
openSync,
|
|
147
|
+
readdirSync,
|
|
148
|
+
readSync,
|
|
149
|
+
realpathSync,
|
|
150
|
+
statSync,
|
|
151
|
+
unlinkSync,
|
|
152
|
+
writeSync
|
|
153
|
+
} from "node:fs";
|
|
77
154
|
import { request as httpRequest } from "node:http";
|
|
78
155
|
import { basename, extname, join, sep } from "node:path";
|
|
79
156
|
|
|
80
157
|
// daemon/protocol.ts
|
|
158
|
+
var ROLL_CHECK_REQUEST = '{"capybara":"roll-check"}';
|
|
81
159
|
var VIEWPORT = { width: 1280, height: 800 };
|
|
82
160
|
var SNAPSHOT_MAX_CHARS = 4e4;
|
|
83
161
|
var IDLE_STOP_MS = 15 * 6e4;
|
|
84
162
|
var TAKEOVER_GRACE_MS = 6e4;
|
|
85
|
-
var VIEWER_MAX_FPS =
|
|
163
|
+
var VIEWER_MAX_FPS = 15;
|
|
86
164
|
var VIEWER_UNACKED_FRAMES = 2;
|
|
165
|
+
var VIEWER_TEXT_MAX_CHARS = 1e4;
|
|
166
|
+
function clipCodePoints(text, max) {
|
|
167
|
+
if (text.length <= max) return text;
|
|
168
|
+
return Array.from(text).slice(0, max).join("");
|
|
169
|
+
}
|
|
170
|
+
var VIEWER_CURSORS = [
|
|
171
|
+
"default",
|
|
172
|
+
"pointer",
|
|
173
|
+
"text",
|
|
174
|
+
"vertical-text",
|
|
175
|
+
"crosshair",
|
|
176
|
+
"move",
|
|
177
|
+
"grab",
|
|
178
|
+
"grabbing",
|
|
179
|
+
"not-allowed",
|
|
180
|
+
"no-drop",
|
|
181
|
+
"wait",
|
|
182
|
+
"progress",
|
|
183
|
+
"help",
|
|
184
|
+
"context-menu",
|
|
185
|
+
"cell",
|
|
186
|
+
"copy",
|
|
187
|
+
"alias",
|
|
188
|
+
"zoom-in",
|
|
189
|
+
"zoom-out",
|
|
190
|
+
"col-resize",
|
|
191
|
+
"row-resize",
|
|
192
|
+
"ew-resize",
|
|
193
|
+
"ns-resize",
|
|
194
|
+
"nesw-resize",
|
|
195
|
+
"nwse-resize",
|
|
196
|
+
"n-resize",
|
|
197
|
+
"e-resize",
|
|
198
|
+
"s-resize",
|
|
199
|
+
"w-resize",
|
|
200
|
+
"ne-resize",
|
|
201
|
+
"nw-resize",
|
|
202
|
+
"se-resize",
|
|
203
|
+
"sw-resize",
|
|
204
|
+
"all-scroll",
|
|
205
|
+
"none"
|
|
206
|
+
];
|
|
207
|
+
function toViewerCursor(value) {
|
|
208
|
+
return typeof value === "string" && VIEWER_CURSORS.includes(value) ? value : "default";
|
|
209
|
+
}
|
|
210
|
+
var FRAME_TAG = 0;
|
|
211
|
+
var FRAME_HEADER_BYTES = 9;
|
|
212
|
+
function encodeFrame(f) {
|
|
213
|
+
const out = new Uint8Array(FRAME_HEADER_BYTES + f.jpeg.byteLength);
|
|
214
|
+
const v = new DataView(out.buffer);
|
|
215
|
+
v.setUint8(0, FRAME_TAG);
|
|
216
|
+
v.setUint32(1, f.seq >>> 0);
|
|
217
|
+
v.setUint16(5, f.width);
|
|
218
|
+
v.setUint16(7, f.height);
|
|
219
|
+
out.set(f.jpeg, FRAME_HEADER_BYTES);
|
|
220
|
+
return out;
|
|
221
|
+
}
|
|
87
222
|
var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
|
|
88
223
|
var HANDOFF_MAX_CHARS = 4096;
|
|
89
224
|
var MAX_TABS = 10;
|
|
225
|
+
var MAX_TABS_PER_CONVERSATION = 6;
|
|
226
|
+
var CONVERSATION_IDLE_MS = 15 * 6e4;
|
|
227
|
+
var EVICT_MIN_IDLE_MS = 5 * 6e4;
|
|
228
|
+
var NO_CONVERSATION_MESSAGE = "the request names no conversation";
|
|
90
229
|
var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
|
|
91
230
|
var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
|
|
92
231
|
var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
|
|
232
|
+
var FAVICON_MAX_BYTES = 8 * 1024;
|
|
233
|
+
|
|
234
|
+
// daemon/favicon.ts
|
|
235
|
+
var READ_MAX_BYTES = 64 * 1024;
|
|
236
|
+
var RASTER_EDGE = 32;
|
|
237
|
+
function sniffIcon(b) {
|
|
238
|
+
const at = (i, ...xs) => xs.every((x, j) => b[i + j] === x);
|
|
239
|
+
if (at(0, 137, 80, 78, 71)) return "image/png";
|
|
240
|
+
if (at(0, 0, 0, 1, 0)) return "image/x-icon";
|
|
241
|
+
if (at(0, 71, 73, 70, 56)) return "image/gif";
|
|
242
|
+
if (at(0, 255, 216, 255)) return "image/jpeg";
|
|
243
|
+
if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return "image/webp";
|
|
244
|
+
const head = new TextDecoder().decode(b.subarray(0, 512)).trimStart().toLowerCase();
|
|
245
|
+
if (head.startsWith("<svg") || head.startsWith("<?xml") && head.includes("<svg"))
|
|
246
|
+
return "image/svg+xml";
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
function iconDataUrl(b) {
|
|
250
|
+
if (b.byteLength === 0 || b.byteLength > FAVICON_MAX_BYTES) return null;
|
|
251
|
+
const mime = sniffIcon(b);
|
|
252
|
+
if (mime === null) return null;
|
|
253
|
+
return `data:${mime};base64,${Buffer.from(b).toString("base64")}`;
|
|
254
|
+
}
|
|
255
|
+
async function iconUrlOf(page) {
|
|
256
|
+
let base;
|
|
257
|
+
try {
|
|
258
|
+
base = new URL(page.url());
|
|
259
|
+
} catch {
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
if (base.protocol !== "http:" && base.protocol !== "https:") return null;
|
|
263
|
+
const declared = await page.evaluate(
|
|
264
|
+
`(() => { const l = Array.from(document.querySelectorAll("link[rel][href]")).find((x) => /(^|\\s)icon(\\s|$)/i.test(x.rel)); return l ? l.href : null; })()`
|
|
265
|
+
).catch(() => null);
|
|
266
|
+
if (typeof declared === "string") {
|
|
267
|
+
try {
|
|
268
|
+
const u = new URL(declared, base);
|
|
269
|
+
if (u.protocol === "http:" || u.protocol === "https:") return u.href;
|
|
270
|
+
} catch {
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return new URL("/favicon.ico", base).href;
|
|
274
|
+
}
|
|
275
|
+
async function iconForPanel(cdp, bytes) {
|
|
276
|
+
const direct = iconDataUrl(bytes);
|
|
277
|
+
if (direct !== null) return direct;
|
|
278
|
+
const mime = sniffIcon(bytes);
|
|
279
|
+
if (mime === null || mime === "image/svg+xml") return null;
|
|
280
|
+
const png = await rasterize(cdp, bytes, mime).catch(() => null);
|
|
281
|
+
return png === null || sniffIcon(png) !== "image/png" ? null : iconDataUrl(png);
|
|
282
|
+
}
|
|
283
|
+
async function rasterize(cdp, bytes, mime) {
|
|
284
|
+
const tree = await cdp.send("Page.getFrameTree");
|
|
285
|
+
const world = await cdp.send("Page.createIsolatedWorld", {
|
|
286
|
+
frameId: tree.frameTree.frame.id,
|
|
287
|
+
worldName: "capybara-favicon"
|
|
288
|
+
});
|
|
289
|
+
const b64 = Buffer.from(bytes).toString("base64");
|
|
290
|
+
const n = RASTER_EDGE;
|
|
291
|
+
const expression = `(async () => {
|
|
292
|
+
const raw = atob(${JSON.stringify(b64)});
|
|
293
|
+
const bytes = new Uint8Array(raw.length);
|
|
294
|
+
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
|
|
295
|
+
const bmp = await createImageBitmap(new Blob([bytes], { type: ${JSON.stringify(mime)} }));
|
|
296
|
+
const c = new OffscreenCanvas(${n}, ${n});
|
|
297
|
+
const g = c.getContext("2d");
|
|
298
|
+
const k = Math.min(${n} / bmp.width, ${n} / bmp.height);
|
|
299
|
+
const w = bmp.width * k, h = bmp.height * k;
|
|
300
|
+
g.imageSmoothingQuality = "high";
|
|
301
|
+
g.drawImage(bmp, (${n} - w) / 2, (${n} - h) / 2, w, h);
|
|
302
|
+
const out = new Uint8Array(await (await c.convertToBlob({ type: "image/png" })).arrayBuffer());
|
|
303
|
+
let s = "";
|
|
304
|
+
for (let i = 0; i < out.length; i++) s += String.fromCharCode(out[i]);
|
|
305
|
+
return btoa(s);
|
|
306
|
+
})()`;
|
|
307
|
+
const res = await cdp.send("Runtime.evaluate", {
|
|
308
|
+
expression,
|
|
309
|
+
contextId: world.executionContextId,
|
|
310
|
+
awaitPromise: true,
|
|
311
|
+
returnByValue: true
|
|
312
|
+
});
|
|
313
|
+
const v = res.result?.value;
|
|
314
|
+
if (res.exceptionDetails !== void 0 || typeof v !== "string") return null;
|
|
315
|
+
return new Uint8Array(Buffer.from(v, "base64"));
|
|
316
|
+
}
|
|
317
|
+
async function fetchIcon(cdp, url) {
|
|
318
|
+
const tree = await cdp.send("Page.getFrameTree");
|
|
319
|
+
const res = await cdp.send("Network.loadNetworkResource", {
|
|
320
|
+
frameId: tree.frameTree.frame.id,
|
|
321
|
+
url,
|
|
322
|
+
options: { disableCache: false, includeCredentials: false }
|
|
323
|
+
});
|
|
324
|
+
const r = res.resource;
|
|
325
|
+
if (!r.success || r.httpStatusCode !== 200 || r.stream === void 0) return null;
|
|
326
|
+
const chunks = [];
|
|
327
|
+
let size = 0;
|
|
328
|
+
try {
|
|
329
|
+
for (; ; ) {
|
|
330
|
+
const part = await cdp.send("IO.read", { handle: r.stream, size: 16 * 1024 });
|
|
331
|
+
const buf = Buffer.from(part.data, part.base64Encoded ? "base64" : "utf8");
|
|
332
|
+
size += buf.byteLength;
|
|
333
|
+
if (size > READ_MAX_BYTES) return null;
|
|
334
|
+
chunks.push(buf);
|
|
335
|
+
if (part.eof) break;
|
|
336
|
+
}
|
|
337
|
+
} finally {
|
|
338
|
+
await cdp.send("IO.close", { handle: r.stream }).catch(() => void 0);
|
|
339
|
+
}
|
|
340
|
+
return new Uint8Array(Buffer.concat(chunks));
|
|
341
|
+
}
|
|
93
342
|
|
|
94
343
|
// daemon/snapshot.ts
|
|
95
344
|
var isNode = (line) => line.trimStart().startsWith("- ");
|
|
@@ -120,27 +369,35 @@ var systemClock = {
|
|
|
120
369
|
schedule: (fn, ms) => setTimeout(fn, ms).unref(),
|
|
121
370
|
cancel: (h) => clearTimeout(h)
|
|
122
371
|
};
|
|
372
|
+
var HANDOFF_PARK = "handoff";
|
|
373
|
+
var HANDOFF_PARK_KEY = "";
|
|
374
|
+
var parkId = (kind, key2) => `${kind}\0${key2}`;
|
|
123
375
|
var DaemonState = class {
|
|
124
376
|
clock;
|
|
125
377
|
idleMs;
|
|
126
378
|
graceMs;
|
|
379
|
+
conversationIdleMs;
|
|
127
380
|
onIdle;
|
|
381
|
+
onConversationIdle;
|
|
128
382
|
listeners = /* @__PURE__ */ new Set();
|
|
383
|
+
conversations = /* @__PURE__ */ new Map();
|
|
129
384
|
viewers = 0;
|
|
130
385
|
inflight = 0;
|
|
131
386
|
since;
|
|
132
|
-
|
|
387
|
+
/** Conversations the running takeover concerns (told on their next ok reply after it ends). */
|
|
388
|
+
concerned = /* @__PURE__ */ new Set();
|
|
389
|
+
/** Hand back notes not yet told: conversation id to when the takeover began. */
|
|
390
|
+
notes = /* @__PURE__ */ new Map();
|
|
133
391
|
idleTimer;
|
|
134
392
|
graceTimer;
|
|
135
393
|
disposed = false;
|
|
136
|
-
pendingHandoff;
|
|
137
|
-
/** When the first notice of the pending handoff arrived (the keepalive counts from it). */
|
|
138
|
-
handoffSince;
|
|
139
394
|
constructor(opts) {
|
|
140
395
|
this.clock = opts.clock ?? systemClock;
|
|
141
396
|
this.idleMs = opts.idleMs ?? IDLE_STOP_MS;
|
|
142
397
|
this.graceMs = opts.graceMs ?? TAKEOVER_GRACE_MS;
|
|
398
|
+
this.conversationIdleMs = opts.conversationIdleMs ?? CONVERSATION_IDLE_MS;
|
|
143
399
|
this.onIdle = opts.onIdle;
|
|
400
|
+
this.onConversationIdle = opts.onConversationIdle ?? (() => void 0);
|
|
144
401
|
this.armIdle();
|
|
145
402
|
}
|
|
146
403
|
get control() {
|
|
@@ -156,66 +413,218 @@ var DaemonState = class {
|
|
|
156
413
|
get requestsInFlight() {
|
|
157
414
|
return this.inflight;
|
|
158
415
|
}
|
|
159
|
-
/** Subscribes to control changes; returns the unsubscribe function. */
|
|
416
|
+
/** Subscribes to control, handoff and park changes; returns the unsubscribe function. */
|
|
160
417
|
onChange(fn) {
|
|
161
418
|
this.listeners.add(fn);
|
|
162
419
|
return () => this.listeners.delete(fn);
|
|
163
420
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
421
|
+
// ---- conversations
|
|
422
|
+
/** The conversations the daemon keeps state for (tests, the session file). */
|
|
423
|
+
get conversationIds() {
|
|
424
|
+
return [...this.conversations.keys()];
|
|
167
425
|
}
|
|
168
|
-
/**
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
426
|
+
/** Whether the daemon keeps state for the conversation. */
|
|
427
|
+
known(conversationId) {
|
|
428
|
+
return this.conversations.has(conversationId);
|
|
429
|
+
}
|
|
430
|
+
/** The root of a conversation's tree, when the daemon knows the conversation. */
|
|
431
|
+
rootOf(conversationId) {
|
|
432
|
+
return this.conversations.get(conversationId)?.root;
|
|
433
|
+
}
|
|
434
|
+
entry(conversationId, root) {
|
|
435
|
+
let e = this.conversations.get(conversationId);
|
|
436
|
+
if (e === void 0) {
|
|
437
|
+
e = {
|
|
438
|
+
root,
|
|
439
|
+
inflight: 0,
|
|
440
|
+
lastActiveAt: this.clock.now(),
|
|
441
|
+
pins: 0,
|
|
442
|
+
parks: /* @__PURE__ */ new Map(),
|
|
443
|
+
handoff: void 0,
|
|
444
|
+
idleTimer: void 0
|
|
445
|
+
};
|
|
446
|
+
this.conversations.set(conversationId, e);
|
|
447
|
+
}
|
|
448
|
+
return e;
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Records activity of a conversation that is not a request (it gained a tab: a restore, an
|
|
452
|
+
* adopt, a tab the person opened): its idle countdowns start again.
|
|
453
|
+
*/
|
|
454
|
+
seen(conversationId, root) {
|
|
455
|
+
const e = this.entry(conversationId, root);
|
|
456
|
+
e.lastActiveAt = this.clock.now();
|
|
457
|
+
this.armConversation(conversationId, e);
|
|
458
|
+
}
|
|
459
|
+
/** A request of the conversation arrived (it is in use until {@link requestFinished}). */
|
|
460
|
+
requestArrived(conversationId, root) {
|
|
461
|
+
const e = this.entry(conversationId, root);
|
|
462
|
+
e.inflight++;
|
|
463
|
+
e.lastActiveAt = this.clock.now();
|
|
464
|
+
this.armConversation(conversationId, e);
|
|
465
|
+
}
|
|
466
|
+
/** The conversation's request got its reply. */
|
|
467
|
+
requestFinished(conversationId) {
|
|
468
|
+
const e = this.conversations.get(conversationId);
|
|
469
|
+
if (e === void 0) return;
|
|
470
|
+
e.inflight = Math.max(0, e.inflight - 1);
|
|
471
|
+
e.lastActiveAt = this.clock.now();
|
|
472
|
+
this.armConversation(conversationId, e);
|
|
473
|
+
}
|
|
474
|
+
/** A viewer pins the conversation (its own, or the owner of the tab it shows). */
|
|
475
|
+
pin(conversationId, root) {
|
|
476
|
+
const e = this.entry(conversationId, root);
|
|
477
|
+
e.pins++;
|
|
478
|
+
this.armConversation(conversationId, e);
|
|
479
|
+
}
|
|
480
|
+
unpin(conversationId) {
|
|
481
|
+
const e = this.conversations.get(conversationId);
|
|
482
|
+
if (e === void 0) return;
|
|
483
|
+
e.pins = Math.max(0, e.pins - 1);
|
|
484
|
+
e.lastActiveAt = this.clock.now();
|
|
485
|
+
this.armConversation(conversationId, e);
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Whether the conversation is in use: a request in flight or a conversation park. Adopt of its
|
|
489
|
+
* tabs is refused meanwhile, and the cap eviction skips it.
|
|
490
|
+
*/
|
|
491
|
+
busy(conversationId) {
|
|
492
|
+
const e = this.conversations.get(conversationId);
|
|
493
|
+
if (e === void 0) return false;
|
|
494
|
+
if (e.inflight > 0) return true;
|
|
495
|
+
for (const p of e.parks.values()) if (p.tabId === void 0) return true;
|
|
496
|
+
return false;
|
|
497
|
+
}
|
|
498
|
+
/** Whether a viewer pins the conversation. */
|
|
499
|
+
pinned(conversationId) {
|
|
500
|
+
return (this.conversations.get(conversationId)?.pins ?? 0) > 0;
|
|
501
|
+
}
|
|
502
|
+
/** How long the conversation has been without activity (unknown: forever). */
|
|
503
|
+
idleFor(conversationId) {
|
|
504
|
+
const e = this.conversations.get(conversationId);
|
|
505
|
+
return e === void 0 ? Number.POSITIVE_INFINITY : this.clock.now() - e.lastActiveAt;
|
|
506
|
+
}
|
|
507
|
+
/** The last activity of the conversation (unknown: never). */
|
|
508
|
+
lastActiveAt(conversationId) {
|
|
509
|
+
return this.conversations.get(conversationId)?.lastActiveAt ?? Number.NEGATIVE_INFINITY;
|
|
510
|
+
}
|
|
511
|
+
// ---- parks
|
|
512
|
+
/** Starts (or renews the spec of) a park; a park of the same kind and key keeps its start. */
|
|
513
|
+
park(conversationId, root, spec) {
|
|
514
|
+
const e = this.entry(conversationId, root);
|
|
515
|
+
const id = parkId(spec.kind, spec.key);
|
|
516
|
+
const since = e.parks.get(id)?.since ?? this.clock.now();
|
|
517
|
+
e.parks.set(id, { ...spec, since });
|
|
518
|
+
this.armConversation(conversationId, e);
|
|
519
|
+
this.armIdle();
|
|
520
|
+
this.emit();
|
|
521
|
+
}
|
|
522
|
+
/** Ends a park; an unknown one changes nothing. */
|
|
523
|
+
unpark(conversationId, kind, key2) {
|
|
524
|
+
const e = this.conversations.get(conversationId);
|
|
525
|
+
if (e === void 0 || !e.parks.delete(parkId(kind, key2))) return;
|
|
526
|
+
e.lastActiveAt = this.clock.now();
|
|
527
|
+
this.armConversation(conversationId, e);
|
|
528
|
+
this.armIdle();
|
|
173
529
|
this.emit();
|
|
530
|
+
}
|
|
531
|
+
/** The conversation's parks. */
|
|
532
|
+
parksOf(conversationId) {
|
|
533
|
+
return [...this.conversations.get(conversationId)?.parks.values() ?? []];
|
|
534
|
+
}
|
|
535
|
+
/** Whether a tab park pins the tab. */
|
|
536
|
+
tabParked(tabId) {
|
|
537
|
+
for (const e of this.conversations.values())
|
|
538
|
+
for (const p of e.parks.values()) if (p.tabId === tabId) return true;
|
|
539
|
+
return false;
|
|
540
|
+
}
|
|
541
|
+
/** Drops the tab parks of a tab that closed. */
|
|
542
|
+
tabClosed(tabId) {
|
|
543
|
+
for (const [conv, e] of this.conversations) {
|
|
544
|
+
let changed = false;
|
|
545
|
+
for (const [id, p] of e.parks) if (p.tabId === tabId) changed = e.parks.delete(id) || changed;
|
|
546
|
+
if (changed) this.armConversation(conv, e);
|
|
547
|
+
}
|
|
174
548
|
this.armIdle();
|
|
175
549
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
550
|
+
// ---- handoffs (a park of kind HANDOFF_PARK)
|
|
551
|
+
/** The tree's or every pending handoff, oldest first. */
|
|
552
|
+
handoffs(root) {
|
|
553
|
+
const out = [];
|
|
554
|
+
for (const [conversationId, e] of this.conversations) {
|
|
555
|
+
if (e.handoff === void 0 || root !== void 0 && e.root !== root) continue;
|
|
556
|
+
const since = e.parks.get(parkId(HANDOFF_PARK, HANDOFF_PARK_KEY))?.since ?? 0;
|
|
557
|
+
out.push({ conversationId, rootConversationId: e.root, ...e.handoff, since });
|
|
558
|
+
}
|
|
559
|
+
return out.sort((a, b) => a.since - b.since);
|
|
560
|
+
}
|
|
561
|
+
/** The conversation's pending handoff, if any. */
|
|
562
|
+
handoffOf(conversationId) {
|
|
563
|
+
return this.conversations.get(conversationId)?.handoff;
|
|
564
|
+
}
|
|
565
|
+
/** Records the conversation's handoff question; it replaces an earlier one of the conversation. */
|
|
566
|
+
noticeHandoff(conversationId, root, callId, message) {
|
|
567
|
+
const m = message.length <= HANDOFF_MAX_CHARS ? message : `${message.slice(0, HANDOFF_MAX_CHARS - 1)}\u2026`;
|
|
568
|
+
const e = this.entry(conversationId, root);
|
|
569
|
+
e.handoff = { callId, message: m };
|
|
570
|
+
this.park(conversationId, root, { kind: HANDOFF_PARK, key: HANDOFF_PARK_KEY, persist: true });
|
|
571
|
+
this.emit();
|
|
572
|
+
}
|
|
573
|
+
/** Clears the conversation's pending handoff when it is `callId`'s; a stale clear changes nothing. */
|
|
574
|
+
clearHandoff(conversationId, callId) {
|
|
575
|
+
if (this.conversations.get(conversationId)?.handoff?.callId !== callId) return;
|
|
576
|
+
this.endHandoff(conversationId);
|
|
180
577
|
}
|
|
181
578
|
/**
|
|
182
|
-
* Drops the pending handoff whatever its callId: the next
|
|
183
|
-
* moved on (an aborted run never sends handoff_clear).
|
|
184
|
-
*
|
|
185
|
-
* conversations and the browser is one.
|
|
579
|
+
* Drops the conversation's pending handoff whatever its callId: the conversation's next tool
|
|
580
|
+
* request means its run moved on (an aborted run never sends handoff_clear). Other
|
|
581
|
+
* conversations' handoffs stay.
|
|
186
582
|
*/
|
|
187
|
-
dropHandoff() {
|
|
188
|
-
if (this.
|
|
189
|
-
this.endHandoff();
|
|
583
|
+
dropHandoff(conversationId) {
|
|
584
|
+
if (this.conversations.get(conversationId)?.handoff === void 0) return;
|
|
585
|
+
this.endHandoff(conversationId);
|
|
190
586
|
}
|
|
191
|
-
endHandoff() {
|
|
192
|
-
|
|
193
|
-
|
|
587
|
+
endHandoff(conversationId) {
|
|
588
|
+
const e = this.conversations.get(conversationId);
|
|
589
|
+
if (e === void 0) return;
|
|
590
|
+
e.handoff = void 0;
|
|
591
|
+
this.unpark(conversationId, HANDOFF_PARK, HANDOFF_PARK_KEY);
|
|
194
592
|
this.emit();
|
|
195
|
-
this.armIdle();
|
|
196
593
|
}
|
|
197
|
-
takeover
|
|
594
|
+
// ---- takeover
|
|
595
|
+
/**
|
|
596
|
+
* The person takes control of the browser (every conversation's agent is refused meanwhile).
|
|
597
|
+
* `owners`: the conversations owning a tab now, told on hand back.
|
|
598
|
+
*/
|
|
599
|
+
takeover(owners = []) {
|
|
198
600
|
if (this.since !== void 0) return;
|
|
199
601
|
this.since = this.clock.now();
|
|
200
|
-
this.
|
|
602
|
+
this.concerned = new Set(owners);
|
|
201
603
|
this.emit();
|
|
202
604
|
}
|
|
605
|
+
/** The person used a tab of `conversationId` during the takeover: it is told on hand back. */
|
|
606
|
+
concern(conversationId) {
|
|
607
|
+
if (this.since === void 0 || conversationId === void 0) return;
|
|
608
|
+
this.concerned.add(conversationId);
|
|
609
|
+
}
|
|
203
610
|
handback() {
|
|
204
611
|
if (this.since === void 0) return;
|
|
205
|
-
this.
|
|
612
|
+
for (const c of this.concerned) this.notes.set(c, this.since);
|
|
613
|
+
this.concerned = /* @__PURE__ */ new Set();
|
|
206
614
|
this.since = void 0;
|
|
207
615
|
this.clearGrace();
|
|
208
616
|
this.emit();
|
|
209
617
|
}
|
|
210
618
|
/**
|
|
211
|
-
* When the last takeover began (ISO), once:
|
|
212
|
-
* the agent learns the person drove the browser.
|
|
619
|
+
* When the last takeover that concerned the conversation began (ISO), once: its first ok reply
|
|
620
|
+
* after the hand back carries it so its agent learns the person drove the browser.
|
|
213
621
|
*/
|
|
214
|
-
takeHandbackNote() {
|
|
215
|
-
const n = this.
|
|
216
|
-
this.
|
|
622
|
+
takeHandbackNote(conversationId) {
|
|
623
|
+
const n = this.notes.get(conversationId);
|
|
624
|
+
this.notes.delete(conversationId);
|
|
217
625
|
return n === void 0 ? void 0 : new Date(n).toISOString();
|
|
218
626
|
}
|
|
627
|
+
// ---- viewers and requests (the daemon's own idle stop)
|
|
219
628
|
viewerOpened() {
|
|
220
629
|
this.viewers++;
|
|
221
630
|
this.clearGrace();
|
|
@@ -245,6 +654,10 @@ var DaemonState = class {
|
|
|
245
654
|
this.clearGrace();
|
|
246
655
|
if (this.idleTimer !== void 0) this.clock.cancel(this.idleTimer);
|
|
247
656
|
this.idleTimer = void 0;
|
|
657
|
+
for (const e of this.conversations.values()) {
|
|
658
|
+
if (e.idleTimer !== void 0) this.clock.cancel(e.idleTimer);
|
|
659
|
+
e.idleTimer = void 0;
|
|
660
|
+
}
|
|
248
661
|
this.listeners.clear();
|
|
249
662
|
}
|
|
250
663
|
emit() {
|
|
@@ -255,15 +668,49 @@ var DaemonState = class {
|
|
|
255
668
|
this.graceTimer = void 0;
|
|
256
669
|
}
|
|
257
670
|
/**
|
|
258
|
-
* (Re)starts the idle countdown when
|
|
259
|
-
*
|
|
260
|
-
|
|
671
|
+
* (Re)starts the conversation's idle countdown when it is not in use (no request in flight, no
|
|
672
|
+
* viewer pin, no conversation park); stops it otherwise.
|
|
673
|
+
*/
|
|
674
|
+
armConversation(conversationId, e) {
|
|
675
|
+
if (e.idleTimer !== void 0) this.clock.cancel(e.idleTimer);
|
|
676
|
+
e.idleTimer = void 0;
|
|
677
|
+
if (this.disposed || e.pins > 0 || this.busy(conversationId)) return;
|
|
678
|
+
const wait = Math.max(0, e.lastActiveAt + this.conversationIdleMs - this.clock.now());
|
|
679
|
+
e.idleTimer = this.clock.schedule(() => {
|
|
680
|
+
e.idleTimer = void 0;
|
|
681
|
+
this.idleClose(conversationId, e);
|
|
682
|
+
}, wait);
|
|
683
|
+
}
|
|
684
|
+
/** Closes an idle conversation's tabs and deletes what the daemon keeps for it. */
|
|
685
|
+
idleClose(conversationId, e) {
|
|
686
|
+
if (this.conversations.get(conversationId) !== e) return;
|
|
687
|
+
try {
|
|
688
|
+
this.onConversationIdle(conversationId);
|
|
689
|
+
} finally {
|
|
690
|
+
this.notes.delete(conversationId);
|
|
691
|
+
this.concerned.delete(conversationId);
|
|
692
|
+
if (e.parks.size === 0) this.conversations.delete(conversationId);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
/** When the oldest pending park began, if any. */
|
|
696
|
+
oldestPark() {
|
|
697
|
+
let oldest;
|
|
698
|
+
for (const e of this.conversations.values())
|
|
699
|
+
for (const p of e.parks.values())
|
|
700
|
+
if (oldest === void 0 || p.since < oldest) oldest = p.since;
|
|
701
|
+
return oldest;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* (Re)starts the idle countdown when nothing is in use; stops it otherwise. Pending parks keep
|
|
705
|
+
* the daemon running until {@link HANDOFF_KEEPALIVE_MS} after the oldest one began (the person
|
|
706
|
+
* is still to answer a handoff); the device's idle suspension may still stop the device sooner.
|
|
261
707
|
*/
|
|
262
708
|
armIdle() {
|
|
263
709
|
if (this.idleTimer !== void 0) this.clock.cancel(this.idleTimer);
|
|
264
710
|
this.idleTimer = void 0;
|
|
265
711
|
if (this.disposed || this.viewers > 0 || this.inflight > 0) return;
|
|
266
|
-
const
|
|
712
|
+
const oldest = this.oldestPark();
|
|
713
|
+
const keepalive = oldest === void 0 ? 0 : oldest + HANDOFF_KEEPALIVE_MS - this.clock.now();
|
|
267
714
|
this.idleTimer = this.clock.schedule(
|
|
268
715
|
() => {
|
|
269
716
|
this.idleTimer = void 0;
|
|
@@ -274,6 +721,49 @@ var DaemonState = class {
|
|
|
274
721
|
}
|
|
275
722
|
};
|
|
276
723
|
|
|
724
|
+
// daemon/verification.ts
|
|
725
|
+
var VERIFICATION_NOTE = "This page is a verification (CAPTCHA or bot check) page. Do not try to solve it and do not switch to another site to get around it: call browser_handoff and ask the user to complete the verification, then continue.";
|
|
726
|
+
var URL_RE = /captcha|challenge|antispider|anti-spider|\/sorry\/|wappass\.baidu\.com|\/cdn-cgi\/|\/verify(?:[/?#]|$)|security-?check/i;
|
|
727
|
+
var TITLE_RE = /captcha|verif(?:y|ication)|are you (?:a )?(?:human|robot)|not a robot|just a moment|attention required|security check|unusual traffic|人机验证|安全验证|验证码|请完成验证|访问验证|异常访问|身份验证|滑动验证|拖动滑块/i;
|
|
728
|
+
var VERIFICATION_STATUSES = /* @__PURE__ */ new Set([418, 429]);
|
|
729
|
+
var WIDGET_SELECTOR = [
|
|
730
|
+
...["recaptcha", "hcaptcha", "challenges.cloudflare.com", "turnstile", "geetest", "captcha"].map(
|
|
731
|
+
(s) => `iframe[src*="${s}" i]`
|
|
732
|
+
),
|
|
733
|
+
'[id*="captcha" i]',
|
|
734
|
+
'[class*="captcha" i]'
|
|
735
|
+
].join(", ");
|
|
736
|
+
var MAX_WIDGETS = 10;
|
|
737
|
+
async function hasWidget(page) {
|
|
738
|
+
const found = page.locator(WIDGET_SELECTOR);
|
|
739
|
+
const n = Math.min(await found.count(), MAX_WIDGETS);
|
|
740
|
+
for (let i = 0; i < n; i++) {
|
|
741
|
+
const box = await found.nth(i).boundingBox();
|
|
742
|
+
if (box !== null && box.width > 20 && box.height > 20) return true;
|
|
743
|
+
}
|
|
744
|
+
return false;
|
|
745
|
+
}
|
|
746
|
+
function looksLikeVerification(url, title) {
|
|
747
|
+
let target = url;
|
|
748
|
+
try {
|
|
749
|
+
const u = new URL(url);
|
|
750
|
+
target = `${u.hostname}${u.pathname}${u.search}`;
|
|
751
|
+
} catch {
|
|
752
|
+
}
|
|
753
|
+
return URL_RE.test(target) || TITLE_RE.test(title);
|
|
754
|
+
}
|
|
755
|
+
async function isVerificationPage(page, status) {
|
|
756
|
+
try {
|
|
757
|
+
if (status !== void 0 && VERIFICATION_STATUSES.has(status)) return true;
|
|
758
|
+
const url = page.url();
|
|
759
|
+
if (!/^https?:/.test(url)) return false;
|
|
760
|
+
if (looksLikeVerification(url, await page.title())) return true;
|
|
761
|
+
return await hasWidget(page);
|
|
762
|
+
} catch {
|
|
763
|
+
return false;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
277
767
|
// daemon/actions.ts
|
|
278
768
|
var ActionError = class extends Error {
|
|
279
769
|
constructor(code, message) {
|
|
@@ -282,6 +772,19 @@ var ActionError = class extends Error {
|
|
|
282
772
|
}
|
|
283
773
|
code;
|
|
284
774
|
};
|
|
775
|
+
function blockedHostsOf(c) {
|
|
776
|
+
return [...c.blocked].map(([host, layer]) => ({ host, layer }));
|
|
777
|
+
}
|
|
778
|
+
function blockedMessage(blocked) {
|
|
779
|
+
const device = blocked.filter((b) => b.layer === "device").map((b) => b.host);
|
|
780
|
+
const address = blocked.filter((b) => b.layer === "address").map((b) => b.host);
|
|
781
|
+
return [
|
|
782
|
+
...device.length > 0 ? [`The device's network settings block ${device.join(", ")}.`] : [],
|
|
783
|
+
...address.length > 0 ? [
|
|
784
|
+
`${address.join(", ")} ${address.length === 1 ? "resolves" : "resolve"} to a private or local address on the device, which the browser never reaches from the sandbox.`
|
|
785
|
+
] : []
|
|
786
|
+
].join(" ");
|
|
787
|
+
}
|
|
285
788
|
var DOWNLOAD_WAIT_MS = 1e4;
|
|
286
789
|
var DEFAULT_DOWNLOAD_MAX_BYTES = 200 * 1024 * 1024;
|
|
287
790
|
var DOWNLOAD_POLL_MS = 250;
|
|
@@ -289,6 +792,7 @@ var MAX_NAME_BYTES = 200;
|
|
|
289
792
|
var ACTION_TIMEOUT_MS = 1e4;
|
|
290
793
|
var NAVIGATION_TIMEOUT_MS = 3e4;
|
|
291
794
|
var LOAD_GRACE_MS = 5e3;
|
|
795
|
+
var PAGE_QUERY_MS = 1e3;
|
|
292
796
|
var MAX_WAIT_MS = 6e4;
|
|
293
797
|
var MAX_SCREENSHOT_BYTES = Math.floor((8 * 1024 * 1024 - 64 * 1024) * 3 / 4);
|
|
294
798
|
var MAX_TITLE_CHARS = 2048;
|
|
@@ -323,17 +827,186 @@ function safeFileName(raw) {
|
|
|
323
827
|
if (Buffer.byteLength(ext) > 32) ext = "";
|
|
324
828
|
return utf8Prefix(name.slice(0, name.length - ext.length), MAX_NAME_BYTES - Buffer.byteLength(ext)) + ext;
|
|
325
829
|
}
|
|
326
|
-
function
|
|
830
|
+
function copyInto(source, out) {
|
|
831
|
+
const src = openSync(source, fsc.O_RDONLY | fsc.O_NOFOLLOW);
|
|
327
832
|
try {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
833
|
+
const buf = Buffer.alloc(1024 * 1024);
|
|
834
|
+
for (; ; ) {
|
|
835
|
+
const n = readSync(src, buf, 0, buf.length, null);
|
|
836
|
+
if (n === 0) break;
|
|
837
|
+
let w = 0;
|
|
838
|
+
while (w < n) w += writeSync(out, buf, w, n - w);
|
|
839
|
+
}
|
|
840
|
+
} finally {
|
|
841
|
+
closeSync(src);
|
|
332
842
|
}
|
|
333
843
|
}
|
|
334
844
|
var PROXY_PROBE_TIMEOUT_MS = 5e3;
|
|
845
|
+
var UPLOAD_MAX_BYTES = 50 * 1024 * 1024;
|
|
846
|
+
var UPLOAD_TYPES = {
|
|
847
|
+
".png": "image/png",
|
|
848
|
+
".jpg": "image/jpeg",
|
|
849
|
+
".jpeg": "image/jpeg",
|
|
850
|
+
".gif": "image/gif",
|
|
851
|
+
".webp": "image/webp",
|
|
852
|
+
".svg": "image/svg+xml",
|
|
853
|
+
".pdf": "application/pdf",
|
|
854
|
+
".txt": "text/plain",
|
|
855
|
+
".md": "text/markdown",
|
|
856
|
+
".csv": "text/csv",
|
|
857
|
+
".json": "application/json",
|
|
858
|
+
".html": "text/html",
|
|
859
|
+
".zip": "application/zip",
|
|
860
|
+
".mp4": "video/mp4",
|
|
861
|
+
".mp3": "audio/mpeg",
|
|
862
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
863
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
864
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
|
865
|
+
};
|
|
866
|
+
function within(real, root) {
|
|
867
|
+
return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep);
|
|
868
|
+
}
|
|
869
|
+
var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
|
335
870
|
var REF_RE = /^(f\d+)?e\d+$/;
|
|
336
871
|
var PROXY_FAILURE_RE = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED/;
|
|
872
|
+
var NETWORK_ERROR_RE = /^ERR_(TIMED_OUT|CONNECTION_[A-Z_]+|NAME_NOT_RESOLVED|NAME_RESOLUTION_FAILED|ADDRESS_UNREACHABLE|EMPTY_RESPONSE|NETWORK_[A-Z_]+|SOCKET_NOT_CONNECTED)$/;
|
|
873
|
+
var NO_TAB_TO_WAIT_ON = "This conversation has no browser tab to wait on; call browser_navigate to open a page first.";
|
|
874
|
+
var ERROR_PAGE_INTERRUPT_RE = /is interrupted by another navigation to "chrome-error:/;
|
|
875
|
+
var NETWORK_CHANGED_ATTEMPTS = 4;
|
|
876
|
+
var ERROR_PAGE_WAIT_MS = 2e3;
|
|
877
|
+
var isTimeout = (e) => e instanceof Error && e.name === "TimeoutError";
|
|
878
|
+
var NET_ERROR_MEANINGS = {
|
|
879
|
+
ERR_NAME_NOT_RESOLVED: "the host name does not resolve",
|
|
880
|
+
ERR_CONNECTION_REFUSED: "the host refused the connection",
|
|
881
|
+
ERR_CONNECTION_RESET: "the connection was reset",
|
|
882
|
+
ERR_CONNECTION_CLOSED: "the host closed the connection without an answer",
|
|
883
|
+
ERR_CONNECTION_TIMED_OUT: "the host did not answer the connection",
|
|
884
|
+
ERR_ADDRESS_UNREACHABLE: "the host's address is unreachable",
|
|
885
|
+
ERR_INTERNET_DISCONNECTED: "the device has no network connection",
|
|
886
|
+
ERR_EMPTY_RESPONSE: "the server sent an empty answer",
|
|
887
|
+
ERR_SSL_PROTOCOL_ERROR: "the secure connection failed",
|
|
888
|
+
ERR_CERT_AUTHORITY_INVALID: "the site's certificate is not trusted",
|
|
889
|
+
ERR_CERT_COMMON_NAME_INVALID: "the site's certificate is for another name",
|
|
890
|
+
ERR_CERT_DATE_INVALID: "the site's certificate has expired or is not yet valid",
|
|
891
|
+
ERR_TOO_MANY_REDIRECTS: "the page redirects in a loop"
|
|
892
|
+
};
|
|
893
|
+
function docUrl(raw) {
|
|
894
|
+
try {
|
|
895
|
+
const u = new URL(raw);
|
|
896
|
+
u.hash = "";
|
|
897
|
+
return u.href;
|
|
898
|
+
} catch {
|
|
899
|
+
return raw;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
var NavWatch = class {
|
|
903
|
+
constructor(page, url, pending) {
|
|
904
|
+
this.page = page;
|
|
905
|
+
this.pending = pending;
|
|
906
|
+
this.target = docUrl(url);
|
|
907
|
+
const before = pending();
|
|
908
|
+
if (before !== void 0 && this.isOurs(before)) this.lastOurs = before;
|
|
909
|
+
page.on("request", this.onRequest);
|
|
910
|
+
page.on("framenavigated", this.onNavigated);
|
|
911
|
+
page.on("requestfailed", this.onFailed);
|
|
912
|
+
page.on("requestfinished", this.onFinished);
|
|
913
|
+
}
|
|
914
|
+
page;
|
|
915
|
+
pending;
|
|
916
|
+
target;
|
|
917
|
+
/** The newest main-frame navigation request to the target address (redirects included). */
|
|
918
|
+
lastOurs;
|
|
919
|
+
/** The request of `lastOurs`'s chain whose document the main frame committed. */
|
|
920
|
+
committedOurs;
|
|
921
|
+
/** The request of `lastOurs`'s chain that failed. */
|
|
922
|
+
failedOurs;
|
|
923
|
+
wake;
|
|
924
|
+
onRequest = (r) => {
|
|
925
|
+
if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
|
|
926
|
+
this.lastOurs = this.isOurs(r) ? r : void 0;
|
|
927
|
+
this.wake?.();
|
|
928
|
+
};
|
|
929
|
+
onNavigated = (f) => {
|
|
930
|
+
if (f !== this.page.mainFrame()) return;
|
|
931
|
+
const ours = this.lastOurs;
|
|
932
|
+
if (ours !== void 0 && docUrl(this.page.mainFrame().url()) === docUrl(ours.url()))
|
|
933
|
+
this.committedOurs = ours;
|
|
934
|
+
this.wake?.();
|
|
935
|
+
};
|
|
936
|
+
onFailed = (r) => {
|
|
937
|
+
if (r === this.lastOurs) this.failedOurs = r;
|
|
938
|
+
this.wake?.();
|
|
939
|
+
};
|
|
940
|
+
/** After the session's own `requestfinished` handler (registered first) settled the request. */
|
|
941
|
+
onFinished = (r) => {
|
|
942
|
+
if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
|
|
943
|
+
const wake = () => this.wake?.();
|
|
944
|
+
void r.response().then(wake, wake);
|
|
945
|
+
};
|
|
946
|
+
isOurs(r) {
|
|
947
|
+
let root = r;
|
|
948
|
+
for (let from = r.redirectedFrom(); from !== null; from = from.redirectedFrom()) root = from;
|
|
949
|
+
return docUrl(root.url()) === this.target;
|
|
950
|
+
}
|
|
951
|
+
/** Resolves on the next navigation event or after `ms`. */
|
|
952
|
+
next(ms) {
|
|
953
|
+
return new Promise((resolve) => {
|
|
954
|
+
const timer = setTimeout(done, ms);
|
|
955
|
+
function done() {
|
|
956
|
+
clearTimeout(timer);
|
|
957
|
+
resolve();
|
|
958
|
+
}
|
|
959
|
+
this.wake = () => {
|
|
960
|
+
this.wake = void 0;
|
|
961
|
+
done();
|
|
962
|
+
};
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
/**
|
|
966
|
+
* After an abort: waits (until `deadline`, the navigation's own) while a navigation to the
|
|
967
|
+
* target address is in flight, then tells whether it loaded (its document committed; a script
|
|
968
|
+
* may have moved the page on since), failed, or none of ours took over.
|
|
969
|
+
*/
|
|
970
|
+
async follow(deadline) {
|
|
971
|
+
for (let r = this.pending(); r !== void 0; r = this.pending()) {
|
|
972
|
+
if (!this.isOurs(r)) return { kind: "none" };
|
|
973
|
+
const left2 = deadline - Date.now();
|
|
974
|
+
if (left2 <= 0) return { kind: "none" };
|
|
975
|
+
await this.next(left2);
|
|
976
|
+
}
|
|
977
|
+
const final = this.lastOurs;
|
|
978
|
+
if (final === void 0) return { kind: "none" };
|
|
979
|
+
if (this.failedOurs === final) {
|
|
980
|
+
return { kind: "failed", url: final.url(), error: final.failure()?.errorText ?? "" };
|
|
981
|
+
}
|
|
982
|
+
if (this.committedOurs !== final) return { kind: "none" };
|
|
983
|
+
const left = deadline - Date.now();
|
|
984
|
+
if (left <= 0) return { kind: "none" };
|
|
985
|
+
try {
|
|
986
|
+
await this.page.waitForLoadState("domcontentloaded", { timeout: left });
|
|
987
|
+
} catch {
|
|
988
|
+
return { kind: "none" };
|
|
989
|
+
}
|
|
990
|
+
return { kind: "loaded", response: await final.response().catch(() => null) };
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* The status the newest navigation to the target address was answered with, when it finished
|
|
994
|
+
* without a document (a 204 or 205: Chromium keeps the page and aborts the navigation).
|
|
995
|
+
*/
|
|
996
|
+
async emptyAnswer() {
|
|
997
|
+
const r = this.lastOurs;
|
|
998
|
+
if (r === void 0 || r === this.committedOurs) return void 0;
|
|
999
|
+
const status = (await r.response().catch(() => null))?.status();
|
|
1000
|
+
return status === 204 || status === 205 ? status : void 0;
|
|
1001
|
+
}
|
|
1002
|
+
dispose() {
|
|
1003
|
+
this.page.off("request", this.onRequest);
|
|
1004
|
+
this.page.off("framenavigated", this.onNavigated);
|
|
1005
|
+
this.page.off("requestfailed", this.onFailed);
|
|
1006
|
+
this.page.off("requestfinished", this.onFinished);
|
|
1007
|
+
this.wake?.();
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
337
1010
|
function jpegSize(jpeg) {
|
|
338
1011
|
let i = 2;
|
|
339
1012
|
while (i + 9 < jpeg.length) {
|
|
@@ -371,13 +1044,28 @@ async function captureFitting(cdp, opts) {
|
|
|
371
1044
|
}
|
|
372
1045
|
return null;
|
|
373
1046
|
}
|
|
374
|
-
|
|
1047
|
+
var PROXY_DOWN_CODES = /* @__PURE__ */ new Set([
|
|
1048
|
+
"ECONNREFUSED",
|
|
1049
|
+
"EHOSTUNREACH",
|
|
1050
|
+
"ENETUNREACH",
|
|
1051
|
+
"ENOTFOUND",
|
|
1052
|
+
"EAI_AGAIN"
|
|
1053
|
+
]);
|
|
1054
|
+
async function proxyRefusal(proxy, host, port) {
|
|
1055
|
+
const answer = await probeProxy(proxy, host, port);
|
|
1056
|
+
if (answer.verdict !== "refused") return null;
|
|
1057
|
+
return refusalLayer(answer.reason);
|
|
1058
|
+
}
|
|
1059
|
+
function refusalLayer(reason) {
|
|
1060
|
+
return sandboxProxyRefusalLayer(reason) === "address" ? "address" : "device";
|
|
1061
|
+
}
|
|
1062
|
+
function probeProxy(proxy, host, port) {
|
|
375
1063
|
return new Promise((resolve) => {
|
|
376
1064
|
let url;
|
|
377
1065
|
try {
|
|
378
1066
|
url = new URL(proxy.includes("://") ? proxy : `http://${proxy}`);
|
|
379
1067
|
} catch {
|
|
380
|
-
resolve(
|
|
1068
|
+
resolve({ verdict: "unknown", reason: "" });
|
|
381
1069
|
return;
|
|
382
1070
|
}
|
|
383
1071
|
const headers = { host: `${host}:${port}` };
|
|
@@ -393,16 +1081,34 @@ function proxyRefuses(proxy, host, port) {
|
|
|
393
1081
|
headers,
|
|
394
1082
|
timeout: PROXY_PROBE_TIMEOUT_MS
|
|
395
1083
|
});
|
|
1084
|
+
const answer = (res) => ({
|
|
1085
|
+
verdict: res.statusCode === 403 ? "refused" : res.statusCode === 200 ? "connected" : "unreachable",
|
|
1086
|
+
reason: res.statusMessage ?? ""
|
|
1087
|
+
});
|
|
396
1088
|
req.on("connect", (res, socket) => {
|
|
397
1089
|
socket.destroy();
|
|
398
|
-
resolve(res
|
|
1090
|
+
resolve(answer(res));
|
|
399
1091
|
});
|
|
400
1092
|
req.on("response", (res) => {
|
|
401
1093
|
res.resume();
|
|
402
|
-
resolve(res
|
|
1094
|
+
resolve(answer(res));
|
|
403
1095
|
});
|
|
404
|
-
req.on("timeout", () =>
|
|
405
|
-
|
|
1096
|
+
req.on("timeout", () => {
|
|
1097
|
+
resolve({ verdict: "no_answer", reason: "" });
|
|
1098
|
+
req.destroy();
|
|
1099
|
+
});
|
|
1100
|
+
let connected = false;
|
|
1101
|
+
req.on("socket", (sock) => {
|
|
1102
|
+
if (sock.connecting) sock.once("connect", () => connected = true);
|
|
1103
|
+
else connected = true;
|
|
1104
|
+
});
|
|
1105
|
+
req.on(
|
|
1106
|
+
"error",
|
|
1107
|
+
(e) => resolve({
|
|
1108
|
+
verdict: !connected && PROXY_DOWN_CODES.has(e.code ?? "") ? "proxy_down" : "unknown",
|
|
1109
|
+
reason: ""
|
|
1110
|
+
})
|
|
1111
|
+
);
|
|
406
1112
|
req.end();
|
|
407
1113
|
});
|
|
408
1114
|
}
|
|
@@ -422,10 +1128,46 @@ function normalizeUrl(raw) {
|
|
|
422
1128
|
return url.href;
|
|
423
1129
|
}
|
|
424
1130
|
var firstLine = (e) => (e instanceof Error ? e.message : String(e)).split("\n")[0]?.replace(/^[a-zA-Z.]+: /, "") ?? "";
|
|
1131
|
+
var NO_USAGE = {
|
|
1132
|
+
busy: () => false,
|
|
1133
|
+
pinned: () => false,
|
|
1134
|
+
idleFor: () => Number.POSITIVE_INFINITY,
|
|
1135
|
+
lastActiveAt: () => Number.NEGATIVE_INFINITY,
|
|
1136
|
+
tabParked: () => false,
|
|
1137
|
+
tabClosed: () => void 0,
|
|
1138
|
+
seen: () => void 0,
|
|
1139
|
+
known: () => true
|
|
1140
|
+
};
|
|
1141
|
+
function isStartBlank(tab) {
|
|
1142
|
+
return tab.owner === void 0 && tab.url === "about:blank";
|
|
1143
|
+
}
|
|
1144
|
+
var OTHER_TITLE_CHARS = 120;
|
|
1145
|
+
var notYourTab = (id) => `Tab ${id} belongs to another conversation; call browser_tabs with action adopt and tabId ${id} first if the user asked you to use it.`;
|
|
1146
|
+
var tabInUse = (id) => `Tab ${id} is in use by another conversation right now; retry shortly or open your own tab.`;
|
|
1147
|
+
var tabMoved = (id, title) => `Tab ${id} (${title}) was moved to another conversation.`;
|
|
1148
|
+
var tabEvicted = (id, title) => `Tab ${id} (${title}) was closed to make room for another conversation.`;
|
|
1149
|
+
var CONVERSATION_CAP_MESSAGE = `This conversation has ${MAX_TABS_PER_CONVERSATION} tabs open, the most one conversation keeps; close one first.`;
|
|
1150
|
+
var deviceCapMessage = (own) => own > 0 ? `The browser has ${MAX_TABS} tabs open, the most it keeps (${own} ${own === 1 ? "is" : "are"} this conversation's); close one of yours first.` : `Other conversations hold all ${MAX_TABS} tabs of the browser; retry later or ask the user to close one in the browser panel.`;
|
|
1151
|
+
function bareUrl(raw) {
|
|
1152
|
+
try {
|
|
1153
|
+
const u = new URL(raw);
|
|
1154
|
+
u.search = "";
|
|
1155
|
+
u.hash = "";
|
|
1156
|
+
return u.href;
|
|
1157
|
+
} catch {
|
|
1158
|
+
return raw.replace(/[?#].*$/s, "");
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
function isActing(req) {
|
|
1162
|
+
if (req.op === "handoff_notice" || req.op === "handoff_clear") return false;
|
|
1163
|
+
if (req.op === "tabs") return req.action !== "list" && req.action !== "adopt";
|
|
1164
|
+
return true;
|
|
1165
|
+
}
|
|
425
1166
|
var BrowserSession = class {
|
|
426
1167
|
ctx;
|
|
427
1168
|
proxy;
|
|
428
1169
|
clock;
|
|
1170
|
+
navigationTimeoutMs;
|
|
429
1171
|
/** The device's workspace root (CAPYBARA_SERVICE_WORKSPACE): uploads and downloads stay in it. */
|
|
430
1172
|
workspace;
|
|
431
1173
|
downloadsTmp;
|
|
@@ -434,20 +1176,63 @@ var BrowserSession = class {
|
|
|
434
1176
|
/** Downloads in progress, cancelled together when their bytes pass the cap. */
|
|
435
1177
|
activeDownloads = /* @__PURE__ */ new Set();
|
|
436
1178
|
downloadPoll;
|
|
1179
|
+
/**
|
|
1180
|
+
* Files of downloads cancelled at the cap: Playwright removes them later, and until then they
|
|
1181
|
+
* do not count toward the cap of the downloads that follow.
|
|
1182
|
+
*/
|
|
1183
|
+
cancelledTmp = /* @__PURE__ */ new Set();
|
|
437
1184
|
pages = /* @__PURE__ */ new Map();
|
|
438
1185
|
ids = /* @__PURE__ */ new WeakMap();
|
|
439
1186
|
titles = /* @__PURE__ */ new Map();
|
|
440
1187
|
loadingTabs = /* @__PURE__ */ new Set();
|
|
1188
|
+
/**
|
|
1189
|
+
* Each tab's icon: the address it came from and its data URL (null: none or not usable). Kept
|
|
1190
|
+
* across navigations until the new page's icon is known, so the strip does not flicker.
|
|
1191
|
+
*/
|
|
1192
|
+
favicons = /* @__PURE__ */ new Map();
|
|
1193
|
+
/** Tabs showing a verification page, by tab id (cleared on every main-frame navigation). */
|
|
1194
|
+
blockers = /* @__PURE__ */ new Map();
|
|
1195
|
+
/** The status of each tab's current document (main-frame response), by tab id. */
|
|
1196
|
+
docStatus = /* @__PURE__ */ new Map();
|
|
1197
|
+
/** Each page's main-frame navigation request in flight (until it commits, fails or finishes). */
|
|
1198
|
+
pendingNavs = /* @__PURE__ */ new WeakMap();
|
|
441
1199
|
listeners = /* @__PURE__ */ new Set();
|
|
442
1200
|
collectors = /* @__PURE__ */ new Set();
|
|
443
1201
|
probes = /* @__PURE__ */ new Map();
|
|
444
1202
|
reservedDownloads = /* @__PURE__ */ new Set();
|
|
445
|
-
|
|
1203
|
+
/** Notes of a conversation's pages that arrived with none of its requests in flight. */
|
|
1204
|
+
unreported = /* @__PURE__ */ new Map();
|
|
1205
|
+
/** Device notes (no page: the browser build) for the next reply of any conversation. */
|
|
1206
|
+
unreportedAll = [];
|
|
446
1207
|
nextId = 1;
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
/**
|
|
450
|
-
|
|
1208
|
+
/** Each owned tab's owner (an unowned tab has no entry). */
|
|
1209
|
+
owners = /* @__PURE__ */ new Map();
|
|
1210
|
+
/** Each conversation's active tab. */
|
|
1211
|
+
activeOf = /* @__PURE__ */ new Map();
|
|
1212
|
+
/** The action queues, by {@link queueKey}. */
|
|
1213
|
+
queues = /* @__PURE__ */ new Map();
|
|
1214
|
+
/** A conversation's first tab being claimed or opened (shared by its callers meanwhile). */
|
|
1215
|
+
claiming = /* @__PURE__ */ new Map();
|
|
1216
|
+
/** Tab allocations (claim, open, eviction) one at a time across conversations. */
|
|
1217
|
+
allocChain = Promise.resolve();
|
|
1218
|
+
/** Tabs being opened by the session (not yet tracked): they count toward the device cap. */
|
|
1219
|
+
reserved = 0;
|
|
1220
|
+
/**
|
|
1221
|
+
* Tabs whose close is under way (an idle-closed conversation's, an evicted one): no
|
|
1222
|
+
* conversation owns, claims, adopts or lists them any more, and the device cap leaves them out.
|
|
1223
|
+
*/
|
|
1224
|
+
closing = /* @__PURE__ */ new Set();
|
|
1225
|
+
/** When an agent request last acted on each tab (the eviction's least recently used tab). */
|
|
1226
|
+
tabUsedAt = /* @__PURE__ */ new Map();
|
|
1227
|
+
/** When each tab went to its owner (the next active tab after a loss is the newest). */
|
|
1228
|
+
gainedAt = /* @__PURE__ */ new Map();
|
|
1229
|
+
gainSeq = 0;
|
|
1230
|
+
/** Order of the conversations' last acting requests (a viewer's default shown tab). */
|
|
1231
|
+
actedSeq = /* @__PURE__ */ new Map();
|
|
1232
|
+
actSeq = 0;
|
|
1233
|
+
usage;
|
|
1234
|
+
/** Each tab's latest agent click; `seq` grows with every click (viewers flash only new ones). */
|
|
1235
|
+
clicks = /* @__PURE__ */ new Map();
|
|
451
1236
|
clickSeq = 0;
|
|
452
1237
|
constructor(ctx, opts) {
|
|
453
1238
|
this.ctx = ctx;
|
|
@@ -457,20 +1242,21 @@ var BrowserSession = class {
|
|
|
457
1242
|
this.downloadMaxBytes = opts.downloadMaxBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES;
|
|
458
1243
|
this.downloadWaitMs = opts.downloadWaitMs ?? DOWNLOAD_WAIT_MS;
|
|
459
1244
|
this.clock = opts.clock ?? systemClock;
|
|
1245
|
+
this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
|
|
1246
|
+
this.usage = opts.usage ?? NO_USAGE;
|
|
460
1247
|
ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
|
|
461
|
-
ctx.setDefaultNavigationTimeout(
|
|
1248
|
+
ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
|
|
462
1249
|
ctx.on("page", (p) => {
|
|
463
|
-
if (
|
|
464
|
-
p.close().catch(() => void 0);
|
|
465
|
-
this.note(
|
|
466
|
-
`The page opened a popup, but the browser keeps at most ${MAX_TABS} tabs, so the popup was closed; close a tab and retry if it was needed.`
|
|
467
|
-
);
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
1250
|
+
if (this.ids.has(p)) return;
|
|
470
1251
|
this.track(p);
|
|
471
|
-
this.active = this.ids.get(p);
|
|
472
|
-
this.emit({ type: "active" });
|
|
473
1252
|
this.emit({ type: "state" });
|
|
1253
|
+
queueMicrotask(() => {
|
|
1254
|
+
void this.allocate(async () => {
|
|
1255
|
+
const id = this.ids.get(p);
|
|
1256
|
+
if (id === void 0 || this.owners.has(id) || p.isClosed()) return;
|
|
1257
|
+
if (this.live().length > MAX_TABS) await p.close().catch(() => void 0);
|
|
1258
|
+
});
|
|
1259
|
+
});
|
|
474
1260
|
});
|
|
475
1261
|
for (const p of ctx.pages()) this.track(p);
|
|
476
1262
|
}
|
|
@@ -481,34 +1267,313 @@ var BrowserSession = class {
|
|
|
481
1267
|
this.listeners.add(fn);
|
|
482
1268
|
return () => this.listeners.delete(fn);
|
|
483
1269
|
}
|
|
484
|
-
/** The active tab, opening a blank one when none is left. */
|
|
485
|
-
async activePage() {
|
|
486
|
-
const cur = this.active === void 0 ? void 0 : this.pages.get(this.active);
|
|
487
|
-
if (cur !== void 0 && !cur.isClosed()) return cur;
|
|
488
|
-
const first = [...this.pages.values()].find((p2) => !p2.isClosed());
|
|
489
|
-
if (first !== void 0) {
|
|
490
|
-
this.active = this.ids.get(first);
|
|
491
|
-
return first;
|
|
492
|
-
}
|
|
493
|
-
const p = await this.ctx.newPage();
|
|
494
|
-
this.track(p);
|
|
495
|
-
this.active = this.ids.get(p);
|
|
496
|
-
return p;
|
|
497
|
-
}
|
|
498
1270
|
tabIdOf(page) {
|
|
499
1271
|
return this.ids.get(page) ?? "";
|
|
500
1272
|
}
|
|
1273
|
+
/** The live page of a tab, if it is open (and not closing). */
|
|
1274
|
+
pageById(tabId) {
|
|
1275
|
+
const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
|
|
1276
|
+
return page === void 0 || page.isClosed() || this.closing.has(tabId) ? void 0 : page;
|
|
1277
|
+
}
|
|
1278
|
+
/** The open tabs that are not closing, in tab order. */
|
|
1279
|
+
live() {
|
|
1280
|
+
return [...this.pages.entries()].filter(([id, p]) => !p.isClosed() && !this.closing.has(id));
|
|
1281
|
+
}
|
|
1282
|
+
/** A tab's owner, if it has one. */
|
|
1283
|
+
ownerOf(tabId) {
|
|
1284
|
+
return this.owners.get(tabId);
|
|
1285
|
+
}
|
|
1286
|
+
/** The conversations owning a tab now. */
|
|
1287
|
+
owningConversations() {
|
|
1288
|
+
return [...new Set([...this.owners.values()].map((o) => o.owner))];
|
|
1289
|
+
}
|
|
1290
|
+
/** The conversation's tabs in tab order. */
|
|
1291
|
+
tabsOf(conversationId) {
|
|
1292
|
+
return this.live().map(([id]) => id).filter((id) => this.owners.get(id)?.owner === conversationId);
|
|
1293
|
+
}
|
|
1294
|
+
/** How many tabs the conversation owns. */
|
|
1295
|
+
countOf(conversationId) {
|
|
1296
|
+
return this.tabsOf(conversationId).length;
|
|
1297
|
+
}
|
|
1298
|
+
/** The conversation's active tab id, if it has a live one. */
|
|
1299
|
+
activeTabOf(conversationId) {
|
|
1300
|
+
const id = this.activeOf.get(conversationId);
|
|
1301
|
+
return this.pageById(id) === void 0 ? void 0 : id;
|
|
1302
|
+
}
|
|
1303
|
+
/** The conversation's active page, if it has one (never opens a tab). */
|
|
1304
|
+
currentPage(conversationId) {
|
|
1305
|
+
return this.pageById(this.activeOf.get(conversationId));
|
|
1306
|
+
}
|
|
1307
|
+
/** The order of the conversation's last acting request (higher: later; 0: never). */
|
|
1308
|
+
actedOrder(conversationId) {
|
|
1309
|
+
return this.actedSeq.get(conversationId) ?? 0;
|
|
1310
|
+
}
|
|
1311
|
+
/** The tab's latest agent click, if any. */
|
|
1312
|
+
lastClickOf(tabId) {
|
|
1313
|
+
return tabId === void 0 ? void 0 : this.clicks.get(tabId);
|
|
1314
|
+
}
|
|
1315
|
+
/** Whether the tab is loading a document. */
|
|
1316
|
+
isLoading(tabId) {
|
|
1317
|
+
return tabId !== void 0 && this.loadingTabs.has(tabId);
|
|
1318
|
+
}
|
|
501
1319
|
tabs() {
|
|
502
|
-
return
|
|
503
|
-
id
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
1320
|
+
return this.live().map(([id, p]) => {
|
|
1321
|
+
const blocker = this.blockers.get(id);
|
|
1322
|
+
const icon = this.favicons.get(id)?.data;
|
|
1323
|
+
const o = this.owners.get(id);
|
|
1324
|
+
return {
|
|
1325
|
+
id,
|
|
1326
|
+
title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
|
|
1327
|
+
url: clip(p.url(), MAX_URL_CHARS),
|
|
1328
|
+
active: o !== void 0 && this.activeOf.get(o.owner) === id,
|
|
1329
|
+
...o === void 0 ? {} : { owner: o.owner, root: o.root },
|
|
1330
|
+
...blocker === void 0 ? {} : { blocker },
|
|
1331
|
+
...icon === void 0 || icon === null ? {} : { favicon: icon },
|
|
1332
|
+
...this.loadingTabs.has(id) ? { loading: true } : {}
|
|
1333
|
+
};
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
/** Makes a tab the conversation's active tab (it must own it). */
|
|
1337
|
+
setActive(conversationId, tabId) {
|
|
1338
|
+
if (this.owners.get(tabId)?.owner !== conversationId) return;
|
|
1339
|
+
if (this.activeOf.get(conversationId) === tabId) return;
|
|
1340
|
+
this.activeOf.set(conversationId, tabId);
|
|
1341
|
+
this.emit({ type: "active", conversationId });
|
|
1342
|
+
this.emit({ type: "state" });
|
|
1343
|
+
}
|
|
1344
|
+
/** Gives a tab to a conversation (owner and root); the previous owner's active moves on. */
|
|
1345
|
+
assign(tabId, to) {
|
|
1346
|
+
const before = this.owners.get(tabId);
|
|
1347
|
+
this.owners.set(tabId, to);
|
|
1348
|
+
this.gainedAt.set(tabId, ++this.gainSeq);
|
|
1349
|
+
if (before !== void 0 && before.owner !== to.owner) this.activeMovedOff(before.owner, tabId);
|
|
1350
|
+
return before;
|
|
508
1351
|
}
|
|
509
|
-
/**
|
|
510
|
-
|
|
511
|
-
|
|
1352
|
+
/**
|
|
1353
|
+
* A conversation lost its tab `tabId` (closed or moved): when it was its active tab, the active
|
|
1354
|
+
* tab becomes its most recently opened remaining tab, or none.
|
|
1355
|
+
*/
|
|
1356
|
+
activeMovedOff(conversationId, tabId) {
|
|
1357
|
+
if (this.activeOf.get(conversationId) !== tabId) return;
|
|
1358
|
+
const next = this.newestTabOf(conversationId, tabId);
|
|
1359
|
+
if (next === void 0) this.activeOf.delete(conversationId);
|
|
1360
|
+
else this.activeOf.set(conversationId, next);
|
|
1361
|
+
this.emit({ type: "active", conversationId });
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* The conversation's tab it gained last (opened, claimed, adopted or restored), besides
|
|
1365
|
+
* `except`.
|
|
1366
|
+
*/
|
|
1367
|
+
newestTabOf(conversationId, except) {
|
|
1368
|
+
let best;
|
|
1369
|
+
for (const id of this.tabsOf(conversationId)) {
|
|
1370
|
+
if (id === except) continue;
|
|
1371
|
+
if (best === void 0 || (this.gainedAt.get(id) ?? 0) > (this.gainedAt.get(best) ?? 0))
|
|
1372
|
+
best = id;
|
|
1373
|
+
}
|
|
1374
|
+
return best;
|
|
1375
|
+
}
|
|
1376
|
+
/** Runs a tab allocation (claim, open, eviction) one at a time across conversations. */
|
|
1377
|
+
allocate(fn) {
|
|
1378
|
+
const run = this.allocChain.then(fn, fn);
|
|
1379
|
+
this.allocChain = run.catch(() => void 0);
|
|
1380
|
+
return run;
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* The page an acting request of the conversation acts on: its active tab; with no live tab, an
|
|
1384
|
+
* unowned tab it claims, else a new tab (subject to the caps). Callers that find no tab at the
|
|
1385
|
+
* same time share one claim, so the conversation gets exactly one tab.
|
|
1386
|
+
*/
|
|
1387
|
+
async pageFor(conversationId, root) {
|
|
1388
|
+
const cur = this.currentPage(conversationId);
|
|
1389
|
+
if (cur !== void 0) return cur;
|
|
1390
|
+
const own = this.newestTabOf(conversationId);
|
|
1391
|
+
if (own !== void 0) {
|
|
1392
|
+
this.setActive(conversationId, own);
|
|
1393
|
+
const page = this.pageById(own);
|
|
1394
|
+
if (page !== void 0) return page;
|
|
1395
|
+
}
|
|
1396
|
+
let claim = this.claiming.get(conversationId);
|
|
1397
|
+
if (claim === void 0) {
|
|
1398
|
+
claim = this.allocate(async () => {
|
|
1399
|
+
const now = this.currentPage(conversationId) ?? this.pageById(this.newestTabOf(conversationId));
|
|
1400
|
+
if (now !== void 0) {
|
|
1401
|
+
this.setActive(conversationId, this.tabIdOf(now));
|
|
1402
|
+
return now;
|
|
1403
|
+
}
|
|
1404
|
+
const unowned = this.live().find(
|
|
1405
|
+
([id, p]) => isStartBlank({ owner: this.owners.get(id)?.owner, url: p.url() }) && !this.usage.tabParked(id)
|
|
1406
|
+
);
|
|
1407
|
+
if (unowned !== void 0) {
|
|
1408
|
+
const [id, page] = unowned;
|
|
1409
|
+
this.assign(id, { owner: conversationId, root });
|
|
1410
|
+
this.activeOf.set(conversationId, id);
|
|
1411
|
+
this.emit({ type: "active", conversationId });
|
|
1412
|
+
this.emit({ type: "state" });
|
|
1413
|
+
return page;
|
|
1414
|
+
}
|
|
1415
|
+
return this.openLocked(conversationId, root);
|
|
1416
|
+
}).finally(() => {
|
|
1417
|
+
this.claiming.delete(conversationId);
|
|
1418
|
+
});
|
|
1419
|
+
this.claiming.set(conversationId, claim);
|
|
1420
|
+
}
|
|
1421
|
+
return claim;
|
|
1422
|
+
}
|
|
1423
|
+
/** Opens a new tab for the conversation (the caps apply) and makes it its active tab. */
|
|
1424
|
+
openTab(conversationId, root) {
|
|
1425
|
+
return this.allocate(() => this.openLocked(conversationId, root));
|
|
1426
|
+
}
|
|
1427
|
+
/** {@link openTab} inside the allocation chain. */
|
|
1428
|
+
async openLocked(conversationId, root) {
|
|
1429
|
+
const own = this.countOf(conversationId);
|
|
1430
|
+
if (own >= MAX_TABS_PER_CONVERSATION) throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
|
|
1431
|
+
if (this.live().length + this.reserved >= MAX_TABS && !await this.evict(conversationId))
|
|
1432
|
+
throw new ActionError("failed", deviceCapMessage(own));
|
|
1433
|
+
this.reserved++;
|
|
1434
|
+
let page;
|
|
1435
|
+
try {
|
|
1436
|
+
page = await this.ctx.newPage();
|
|
1437
|
+
} finally {
|
|
1438
|
+
this.reserved--;
|
|
1439
|
+
}
|
|
1440
|
+
this.track(page);
|
|
1441
|
+
const id = this.tabIdOf(page);
|
|
1442
|
+
this.assign(id, { owner: conversationId, root });
|
|
1443
|
+
this.activeOf.set(conversationId, id);
|
|
1444
|
+
this.emit({ type: "active", conversationId });
|
|
1445
|
+
this.emit({ type: "state" });
|
|
1446
|
+
return page;
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Closes one tab to make room at the device cap: an unowned tab first, else a tab of the least
|
|
1450
|
+
* recently active conversation that is evictable (not in use, not pinned by a viewer, idle for
|
|
1451
|
+
* at least EVICT_MIN_IDLE_MS), its least recently used non-active tab before its active one; tabs
|
|
1452
|
+
* a park pins are skipped. Its owner is told. False when no tab qualifies.
|
|
1453
|
+
*/
|
|
1454
|
+
async evict(forConversation) {
|
|
1455
|
+
const live = this.live().filter(([id]) => !this.usage.tabParked(id));
|
|
1456
|
+
const unowned = live.find(([id]) => !this.owners.has(id));
|
|
1457
|
+
if (unowned !== void 0) {
|
|
1458
|
+
await this.closeEvicted(unowned[0], unowned[1]);
|
|
1459
|
+
return true;
|
|
1460
|
+
}
|
|
1461
|
+
const owners = /* @__PURE__ */ new Set();
|
|
1462
|
+
for (const [id] of live) {
|
|
1463
|
+
const o = this.owners.get(id)?.owner;
|
|
1464
|
+
if (o !== void 0 && o !== forConversation && !this.usage.busy(o) && !this.usage.pinned(o) && this.usage.idleFor(o) >= EVICT_MIN_IDLE_MS)
|
|
1465
|
+
owners.add(o);
|
|
1466
|
+
}
|
|
1467
|
+
const victim = [...owners].sort(
|
|
1468
|
+
(a, b) => this.usage.lastActiveAt(a) - this.usage.lastActiveAt(b)
|
|
1469
|
+
)[0];
|
|
1470
|
+
if (victim === void 0) return false;
|
|
1471
|
+
const active = this.activeOf.get(victim);
|
|
1472
|
+
const used = (id) => this.tabUsedAt.get(id) ?? 0;
|
|
1473
|
+
const [tabId, page] = live.filter(([id]) => this.owners.get(id)?.owner === victim).sort(
|
|
1474
|
+
([a], [b]) => (a === active ? 1 : 0) - (b === active ? 1 : 0) || used(a) - used(b)
|
|
1475
|
+
)[0] ?? [];
|
|
1476
|
+
if (tabId === void 0 || page === void 0) return false;
|
|
1477
|
+
const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
|
|
1478
|
+
await this.closeEvicted(tabId, page);
|
|
1479
|
+
this.noteTo(victim, tabEvicted(tabId, title));
|
|
1480
|
+
return true;
|
|
1481
|
+
}
|
|
1482
|
+
/**
|
|
1483
|
+
* Closes an evicted tab, closing from the start: no request or adopt reaches it while its close
|
|
1484
|
+
* runs (the close handler forgets it; a tab that would not close is kept as it was).
|
|
1485
|
+
*/
|
|
1486
|
+
async closeEvicted(tabId, page) {
|
|
1487
|
+
this.closing.add(tabId);
|
|
1488
|
+
await page.close().catch(() => {
|
|
1489
|
+
this.closing.delete(tabId);
|
|
1490
|
+
});
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Moves a tab to the conversation and makes it its active tab (the tool's and a viewer's adopt).
|
|
1494
|
+
* `in_use`: its owner has a request in flight or a park (or a park pins the tab); `cap`: the
|
|
1495
|
+
* conversation already owns MAX_TABS_PER_CONVERSATION tabs. The previous owner is told.
|
|
1496
|
+
*/
|
|
1497
|
+
adopt(conversationId, root, tabId) {
|
|
1498
|
+
this.tabById(tabId);
|
|
1499
|
+
const before = this.owners.get(tabId);
|
|
1500
|
+
if (before?.owner === conversationId) {
|
|
1501
|
+
this.setActive(conversationId, tabId);
|
|
1502
|
+
return "ok";
|
|
1503
|
+
}
|
|
1504
|
+
if (before !== void 0 && this.usage.busy(before.owner) || this.usage.tabParked(tabId))
|
|
1505
|
+
return "in_use";
|
|
1506
|
+
if (this.countOf(conversationId) >= MAX_TABS_PER_CONVERSATION) return "cap";
|
|
1507
|
+
this.assign(tabId, { owner: conversationId, root });
|
|
1508
|
+
this.activeOf.set(conversationId, tabId);
|
|
1509
|
+
this.usage.seen(conversationId, root);
|
|
1510
|
+
if (before !== void 0) {
|
|
1511
|
+
const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
|
|
1512
|
+
this.noteTo(before.owner, tabMoved(tabId, title));
|
|
1513
|
+
}
|
|
1514
|
+
this.emit({ type: "active", conversationId });
|
|
1515
|
+
this.emit({ type: "state" });
|
|
1516
|
+
return "ok";
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Opens a restored tab for its owner (the first claims the start's blank tab) and starts its
|
|
1520
|
+
* navigation without waiting for it.
|
|
1521
|
+
*/
|
|
1522
|
+
async restoreTab(owner, url) {
|
|
1523
|
+
const page = await this.allocate(async () => {
|
|
1524
|
+
const blank = this.live().find(
|
|
1525
|
+
([id2, p]) => isStartBlank({ owner: this.owners.get(id2)?.owner, url: p.url() })
|
|
1526
|
+
);
|
|
1527
|
+
if (blank !== void 0) {
|
|
1528
|
+
this.assign(blank[0], owner);
|
|
1529
|
+
return blank[1];
|
|
1530
|
+
}
|
|
1531
|
+
this.reserved++;
|
|
1532
|
+
try {
|
|
1533
|
+
const p = await this.ctx.newPage();
|
|
1534
|
+
this.track(p);
|
|
1535
|
+
this.assign(this.tabIdOf(p), owner);
|
|
1536
|
+
return p;
|
|
1537
|
+
} finally {
|
|
1538
|
+
this.reserved--;
|
|
1539
|
+
}
|
|
1540
|
+
});
|
|
1541
|
+
const id = this.tabIdOf(page);
|
|
1542
|
+
if (!this.activeOf.has(owner.owner)) this.activeOf.set(owner.owner, id);
|
|
1543
|
+
this.usage.seen(owner.owner, owner.root);
|
|
1544
|
+
this.emit({ type: "active", conversationId: owner.owner });
|
|
1545
|
+
this.emit({ type: "state" });
|
|
1546
|
+
let target;
|
|
1547
|
+
try {
|
|
1548
|
+
target = normalizeUrl(url);
|
|
1549
|
+
} catch {
|
|
1550
|
+
}
|
|
1551
|
+
if (target !== void 0) void this.viewerNav(page, { url: target });
|
|
1552
|
+
return id;
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Closes an idle conversation's tabs (except those a park pins) and forgets what the session
|
|
1556
|
+
* keeps for it.
|
|
1557
|
+
*/
|
|
1558
|
+
async closeConversation(conversationId) {
|
|
1559
|
+
const ids = this.tabsOf(conversationId).filter((id) => !this.usage.tabParked(id));
|
|
1560
|
+
for (const id of ids) {
|
|
1561
|
+
this.closing.add(id);
|
|
1562
|
+
this.owners.delete(id);
|
|
1563
|
+
}
|
|
1564
|
+
this.activeOf.delete(conversationId);
|
|
1565
|
+
this.queues.delete(this.queueKey(conversationId));
|
|
1566
|
+
this.unreported.delete(conversationId);
|
|
1567
|
+
this.claiming.delete(conversationId);
|
|
1568
|
+
this.actedSeq.delete(conversationId);
|
|
1569
|
+
await Promise.all(
|
|
1570
|
+
ids.map(
|
|
1571
|
+
(id) => this.pages.get(id)?.close().catch(() => {
|
|
1572
|
+
this.closing.delete(id);
|
|
1573
|
+
})
|
|
1574
|
+
)
|
|
1575
|
+
);
|
|
1576
|
+
this.emit({ type: "state" });
|
|
512
1577
|
}
|
|
513
1578
|
emit(e) {
|
|
514
1579
|
for (const fn of [...this.listeners]) {
|
|
@@ -524,55 +1589,119 @@ var BrowserSession = class {
|
|
|
524
1589
|
this.ids.set(page, id);
|
|
525
1590
|
this.pages.set(id, page);
|
|
526
1591
|
const refresh = () => {
|
|
527
|
-
page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).finally(() => this.emit({ type: "state" }));
|
|
1592
|
+
page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
|
|
1593
|
+
};
|
|
1594
|
+
const settle = (r) => {
|
|
1595
|
+
if (this.pendingNavs.get(page) === r) this.pendingNavs.delete(page);
|
|
528
1596
|
};
|
|
1597
|
+
page.on("requestfinished", (r) => {
|
|
1598
|
+
if (this.pendingNavs.get(page) !== r) return;
|
|
1599
|
+
void r.response().then(
|
|
1600
|
+
(res) => {
|
|
1601
|
+
const status = res?.status() ?? 0;
|
|
1602
|
+
const redirects = status >= 300 && status < 400 && res?.headers().location;
|
|
1603
|
+
if (!redirects) settle(r);
|
|
1604
|
+
},
|
|
1605
|
+
() => settle(r)
|
|
1606
|
+
);
|
|
1607
|
+
});
|
|
529
1608
|
page.on("request", (r) => {
|
|
530
1609
|
if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
1610
|
+
this.pendingNavs.set(page, r);
|
|
531
1611
|
this.loadingTabs.add(id);
|
|
532
1612
|
this.emit({ type: "state" });
|
|
533
1613
|
}
|
|
534
1614
|
});
|
|
535
1615
|
page.on("framenavigated", (f) => {
|
|
536
|
-
if (f
|
|
1616
|
+
if (f !== page.mainFrame()) return;
|
|
1617
|
+
this.pendingNavs.delete(page);
|
|
1618
|
+
this.blockers.delete(id);
|
|
1619
|
+
refresh();
|
|
537
1620
|
});
|
|
538
1621
|
page.on("domcontentloaded", refresh);
|
|
539
1622
|
page.on("load", () => {
|
|
540
1623
|
this.loadingTabs.delete(id);
|
|
541
1624
|
refresh();
|
|
1625
|
+
void this.resolveFavicon(page, id);
|
|
542
1626
|
});
|
|
543
1627
|
page.on("requestfailed", (r) => {
|
|
1628
|
+
settle(r);
|
|
544
1629
|
const err = r.failure()?.errorText ?? "";
|
|
545
1630
|
if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
546
1631
|
this.loadingTabs.delete(id);
|
|
547
1632
|
this.emit({ type: "state" });
|
|
548
1633
|
}
|
|
549
|
-
if (this.proxy !== void 0 && PROXY_FAILURE_RE.test(err))
|
|
550
|
-
this.checkBlocked(r.url(), this.pageToOpen(page, r));
|
|
1634
|
+
if (this.proxy !== void 0 && (PROXY_FAILURE_RE.test(err) || err.includes("ERR_NETWORK_CHANGED")))
|
|
1635
|
+
this.checkBlocked(page, r.url(), this.pageToOpen(page, r));
|
|
551
1636
|
});
|
|
552
1637
|
page.on("response", (r) => {
|
|
1638
|
+
if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
|
|
1639
|
+
this.docStatus.set(id, r.status());
|
|
553
1640
|
if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
|
|
554
|
-
this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
|
|
1641
|
+
this.checkBlocked(page, r.url(), this.pageToOpen(page, r.request()));
|
|
555
1642
|
}
|
|
556
1643
|
});
|
|
557
|
-
page.on("dialog", (d) => this.onDialog(d));
|
|
558
|
-
page.on("download", (d) => this.onDownload(d));
|
|
1644
|
+
page.on("dialog", (d) => this.onDialog(page, d));
|
|
1645
|
+
page.on("download", (d) => this.onDownload(page, d));
|
|
559
1646
|
page.on("filechooser", () => {
|
|
560
|
-
|
|
561
|
-
this.
|
|
1647
|
+
const o = this.owners.get(id);
|
|
1648
|
+
this.noteTo(
|
|
1649
|
+
o?.owner,
|
|
1650
|
+
"The page opened a file chooser; use the upload tool with the file input's ref."
|
|
1651
|
+
);
|
|
1652
|
+
if (o !== void 0) this.emit({ type: "dialog", kind: "file", message: "", root: o.root });
|
|
562
1653
|
});
|
|
1654
|
+
page.on("popup", (p) => this.onPopup(page, p));
|
|
563
1655
|
page.on("close", () => {
|
|
1656
|
+
this.pendingNavs.delete(page);
|
|
564
1657
|
this.pages.delete(id);
|
|
1658
|
+
this.closing.delete(id);
|
|
565
1659
|
this.titles.delete(id);
|
|
566
1660
|
this.loadingTabs.delete(id);
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
1661
|
+
this.blockers.delete(id);
|
|
1662
|
+
this.favicons.delete(id);
|
|
1663
|
+
this.docStatus.delete(id);
|
|
1664
|
+
this.tabUsedAt.delete(id);
|
|
1665
|
+
this.gainedAt.delete(id);
|
|
1666
|
+
this.clicks.delete(id);
|
|
1667
|
+
const o = this.owners.get(id);
|
|
1668
|
+
this.owners.delete(id);
|
|
1669
|
+
if (o !== void 0) this.activeMovedOff(o.owner, id);
|
|
1670
|
+
this.usage.tabClosed(id);
|
|
572
1671
|
this.emit({ type: "state" });
|
|
573
1672
|
});
|
|
574
1673
|
}
|
|
575
|
-
|
|
1674
|
+
/**
|
|
1675
|
+
* A page opened a popup: it belongs to the opener's owner and becomes its active tab, as in a
|
|
1676
|
+
* desktop browser (an unowned opener leaves it unowned). Past the conversation's cap it is closed
|
|
1677
|
+
* at once; past the device cap a tab is evicted for it, else it is closed; the owner is told.
|
|
1678
|
+
*/
|
|
1679
|
+
onPopup(opener, popup) {
|
|
1680
|
+
this.track(popup);
|
|
1681
|
+
const id = this.tabIdOf(popup);
|
|
1682
|
+
const o = this.owners.get(this.tabIdOf(opener));
|
|
1683
|
+
if (o === void 0 || this.owners.has(id) || popup.isClosed()) return;
|
|
1684
|
+
const closeIt = (why) => {
|
|
1685
|
+
popup.close().catch(() => void 0);
|
|
1686
|
+
this.noteTo(
|
|
1687
|
+
o.owner,
|
|
1688
|
+
`The page opened a popup, but ${why}, so the popup was closed; close a tab and retry if it was needed.`
|
|
1689
|
+
);
|
|
1690
|
+
};
|
|
1691
|
+
if (this.countOf(o.owner) >= MAX_TABS_PER_CONVERSATION) {
|
|
1692
|
+
closeIt(`this conversation keeps at most ${MAX_TABS_PER_CONVERSATION} tabs`);
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
this.assign(id, o);
|
|
1696
|
+
this.activeOf.set(o.owner, id);
|
|
1697
|
+
this.emit({ type: "active", conversationId: o.owner });
|
|
1698
|
+
this.emit({ type: "state" });
|
|
1699
|
+
void this.allocate(async () => {
|
|
1700
|
+
if (popup.isClosed() || this.live().length <= MAX_TABS) return;
|
|
1701
|
+
if (!await this.evict(o.owner)) closeIt(`the browser keeps at most ${MAX_TABS} tabs`);
|
|
1702
|
+
});
|
|
1703
|
+
}
|
|
1704
|
+
onDialog(page, d) {
|
|
576
1705
|
const type = d.type();
|
|
577
1706
|
if (type === "beforeunload") {
|
|
578
1707
|
d.accept().catch(() => void 0);
|
|
@@ -582,24 +1711,50 @@ var BrowserSession = class {
|
|
|
582
1711
|
const message = clip(d.message(), MAX_DIALOG_CHARS);
|
|
583
1712
|
const settle = kind === "alert" ? d.accept() : d.dismiss();
|
|
584
1713
|
settle.catch(() => void 0);
|
|
585
|
-
this.
|
|
1714
|
+
const o = this.owners.get(this.tabIdOf(page));
|
|
1715
|
+
this.noteTo(
|
|
1716
|
+
o?.owner,
|
|
586
1717
|
`The page showed ${kind === "alert" ? "an alert" : `a ${kind}`} dialog: ${JSON.stringify(message)} (${kind === "alert" ? "closed" : "dismissed"}).`
|
|
587
1718
|
);
|
|
588
|
-
this.emit({ type: "dialog", kind, message });
|
|
1719
|
+
if (o !== void 0) this.emit({ type: "dialog", kind, message, root: o.root });
|
|
589
1720
|
}
|
|
590
1721
|
/**
|
|
591
|
-
*
|
|
592
|
-
*
|
|
1722
|
+
* A device note (not about a page: the browser build that runs): the replies of the requests in
|
|
1723
|
+
* flight carry it, else the next reply of any conversation.
|
|
593
1724
|
*/
|
|
594
1725
|
note(text) {
|
|
595
1726
|
const n = clip(text, MAX_DIALOG_CHARS + 200);
|
|
596
1727
|
if (this.collectors.size === 0) {
|
|
597
|
-
this.
|
|
598
|
-
if (this.
|
|
1728
|
+
this.unreportedAll.push(n);
|
|
1729
|
+
if (this.unreportedAll.length > MAX_UNREPORTED) this.unreportedAll.shift();
|
|
599
1730
|
return;
|
|
600
1731
|
}
|
|
601
1732
|
for (const c of this.collectors) c.notes.push(n);
|
|
602
1733
|
}
|
|
1734
|
+
/**
|
|
1735
|
+
* A note for a conversation (about one of its pages): its requests in flight carry it, else its
|
|
1736
|
+
* next reply. A note of an unowned page (`undefined`) reaches nobody.
|
|
1737
|
+
*/
|
|
1738
|
+
noteTo(conversationId, text) {
|
|
1739
|
+
if (conversationId === void 0) return;
|
|
1740
|
+
if (this.countOf(conversationId) === 0 && !this.usage.known(conversationId)) return;
|
|
1741
|
+
const n = clip(text, MAX_DIALOG_CHARS + 200);
|
|
1742
|
+
let delivered = false;
|
|
1743
|
+
for (const c of this.collectors) {
|
|
1744
|
+
if (c.conv !== conversationId) continue;
|
|
1745
|
+
c.notes.push(n);
|
|
1746
|
+
delivered = true;
|
|
1747
|
+
}
|
|
1748
|
+
if (delivered) return;
|
|
1749
|
+
const list = this.unreported.get(conversationId) ?? [];
|
|
1750
|
+
list.push(n);
|
|
1751
|
+
if (list.length > MAX_UNREPORTED) list.shift();
|
|
1752
|
+
this.unreported.set(conversationId, list);
|
|
1753
|
+
}
|
|
1754
|
+
/** The owner of a page, if it has one. */
|
|
1755
|
+
ownerOfPage(page) {
|
|
1756
|
+
return page === null || page === void 0 ? void 0 : this.owners.get(this.tabIdOf(page));
|
|
1757
|
+
}
|
|
603
1758
|
/**
|
|
604
1759
|
* Saves a download into `<workspace>/downloads` under its suggested name (sanitized, numbered
|
|
605
1760
|
* when taken). A request in flight waits for it at most `downloadWaitMs`, then says it is still
|
|
@@ -607,12 +1762,14 @@ var BrowserSession = class {
|
|
|
607
1762
|
* cancelled when together they pass `downloadMaxBytes`, so a page cannot fill the disk.
|
|
608
1763
|
* Without a workspace the download is cancelled.
|
|
609
1764
|
*/
|
|
610
|
-
onDownload(d) {
|
|
1765
|
+
onDownload(page, d) {
|
|
611
1766
|
const shown = JSON.stringify(clip(d.suggestedFilename(), 300));
|
|
612
1767
|
const workspace = this.workspace;
|
|
1768
|
+
const owner = this.ownerOfPage(page)?.owner;
|
|
1769
|
+
const note = (text) => this.noteTo(owner, text);
|
|
613
1770
|
if (workspace === void 0) {
|
|
614
1771
|
d.cancel().catch(() => void 0);
|
|
615
|
-
|
|
1772
|
+
note(
|
|
616
1773
|
`The page started a download (${shown}), which was cancelled: the device has no workspace.`
|
|
617
1774
|
);
|
|
618
1775
|
return;
|
|
@@ -625,21 +1782,20 @@ var BrowserSession = class {
|
|
|
625
1782
|
try {
|
|
626
1783
|
const failure = await d.failure();
|
|
627
1784
|
if (failure !== null) {
|
|
628
|
-
if (failure !== "canceled")
|
|
1785
|
+
if (failure !== "canceled") note(`The download of ${shown} failed: ${failure}.`);
|
|
629
1786
|
return;
|
|
630
1787
|
}
|
|
631
1788
|
const tmp = await d.path();
|
|
632
1789
|
if (statSync(tmp).size > this.downloadMaxBytes) {
|
|
633
|
-
|
|
1790
|
+
note(
|
|
634
1791
|
`The download of ${shown} was not saved: it is larger than ${this.downloadMaxBytes} bytes.`
|
|
635
1792
|
);
|
|
636
1793
|
return;
|
|
637
1794
|
}
|
|
638
|
-
target = this.
|
|
639
|
-
|
|
640
|
-
this.note(`Downloaded ${shown} to ${target}.`);
|
|
1795
|
+
target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
|
|
1796
|
+
note(`Downloaded ${shown} to ${target}.`);
|
|
641
1797
|
} catch (e) {
|
|
642
|
-
|
|
1798
|
+
note(
|
|
643
1799
|
`The download of ${shown} was not saved: ${e instanceof ActionError ? e.message : firstLine(e)}`
|
|
644
1800
|
);
|
|
645
1801
|
} finally {
|
|
@@ -649,10 +1805,64 @@ var BrowserSession = class {
|
|
|
649
1805
|
entry.finished = true;
|
|
650
1806
|
}
|
|
651
1807
|
})();
|
|
652
|
-
for (const c of this.collectors) c.downloads.push(entry);
|
|
1808
|
+
for (const c of this.collectors) if (c.conv === owner) c.downloads.push(entry);
|
|
1809
|
+
}
|
|
1810
|
+
/**
|
|
1811
|
+
* Copies a finished download from Playwright's private file into `<workspace>/downloads` and
|
|
1812
|
+
* returns where. The agent owns that directory, so the target is never written through a path
|
|
1813
|
+
* it could have swapped: each candidate is created exclusively without following a link
|
|
1814
|
+
* (`O_CREAT | O_EXCL | O_NOFOLLOW`), then checked to be the file the resolved path inside the
|
|
1815
|
+
* downloads directory names before any byte is written; a mismatch (a directory swapped for a
|
|
1816
|
+
* link meanwhile) writes nothing, removes the empty file it made (only while that name still
|
|
1817
|
+
* is the file it opened) and fails.
|
|
1818
|
+
*/
|
|
1819
|
+
saveDownload(workspace, name, source) {
|
|
1820
|
+
const dir = this.downloadsDir(workspace);
|
|
1821
|
+
const dirStat = lstatSync(dir);
|
|
1822
|
+
const ext = extname(name);
|
|
1823
|
+
const stem = name.slice(0, name.length - ext.length);
|
|
1824
|
+
for (let i = 0; i < 1e3; i++) {
|
|
1825
|
+
const target = join(dir, i === 0 ? name : `${stem} (${i})${ext}`);
|
|
1826
|
+
if (this.reservedDownloads.has(target)) continue;
|
|
1827
|
+
let out;
|
|
1828
|
+
try {
|
|
1829
|
+
out = openSync(target, fsc.O_WRONLY | fsc.O_CREAT | fsc.O_EXCL | fsc.O_NOFOLLOW, 436);
|
|
1830
|
+
} catch (e) {
|
|
1831
|
+
if (e.code === "EEXIST") continue;
|
|
1832
|
+
throw e;
|
|
1833
|
+
}
|
|
1834
|
+
this.reservedDownloads.add(target);
|
|
1835
|
+
try {
|
|
1836
|
+
let real;
|
|
1837
|
+
try {
|
|
1838
|
+
real = realpathSync(target);
|
|
1839
|
+
} catch {
|
|
1840
|
+
real = "";
|
|
1841
|
+
}
|
|
1842
|
+
const opened = fstatSync(out);
|
|
1843
|
+
const placed = real !== "" && within(real, dir) && sameFile(opened, statSync(real));
|
|
1844
|
+
if (!placed || !sameFile(dirStat, lstatSync(dir))) {
|
|
1845
|
+
try {
|
|
1846
|
+
if (real !== "" && sameFile(opened, lstatSync(real)) && opened.size === 0)
|
|
1847
|
+
unlinkSync(real);
|
|
1848
|
+
} catch {
|
|
1849
|
+
}
|
|
1850
|
+
throw new ActionError(
|
|
1851
|
+
"failed",
|
|
1852
|
+
`${dir} changed while the download was saved; nothing was written. Retry the download.`
|
|
1853
|
+
);
|
|
1854
|
+
}
|
|
1855
|
+
copyInto(source, out);
|
|
1856
|
+
return target;
|
|
1857
|
+
} finally {
|
|
1858
|
+
closeSync(out);
|
|
1859
|
+
this.reservedDownloads.delete(target);
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
throw new ActionError("failed", `No free name for ${name} in ${dir}; remove old downloads.`);
|
|
653
1863
|
}
|
|
654
|
-
/**
|
|
655
|
-
|
|
1864
|
+
/** `<workspace>/downloads` resolved, refusing one that is a link or not a directory. */
|
|
1865
|
+
downloadsDir(workspace) {
|
|
656
1866
|
const root = realpathSync(workspace);
|
|
657
1867
|
const dir = join(root, "downloads");
|
|
658
1868
|
mkdirSync(dir, { recursive: true });
|
|
@@ -663,14 +1873,7 @@ var BrowserSession = class {
|
|
|
663
1873
|
`${dir} is not a plain directory in the workspace; remove it so downloads can be saved.`
|
|
664
1874
|
);
|
|
665
1875
|
}
|
|
666
|
-
|
|
667
|
-
const stem = name.slice(0, name.length - ext.length);
|
|
668
|
-
let target = join(dir, name);
|
|
669
|
-
for (let i = 1; !absent(target) || this.reservedDownloads.has(target); i++) {
|
|
670
|
-
target = join(dir, `${stem} (${i})${ext}`);
|
|
671
|
-
}
|
|
672
|
-
this.reservedDownloads.add(target);
|
|
673
|
-
return target;
|
|
1876
|
+
return dir;
|
|
674
1877
|
}
|
|
675
1878
|
/**
|
|
676
1879
|
* While downloads run, sums the bytes of Playwright's in-progress files and cancels every
|
|
@@ -682,21 +1885,27 @@ var BrowserSession = class {
|
|
|
682
1885
|
this.downloadPoll = void 0;
|
|
683
1886
|
if (this.activeDownloads.size === 0) return;
|
|
684
1887
|
let bytes = 0;
|
|
1888
|
+
let names = [];
|
|
685
1889
|
const dir = this.downloadsTmp;
|
|
686
1890
|
if (dir !== void 0) {
|
|
687
1891
|
try {
|
|
688
|
-
|
|
689
|
-
try {
|
|
690
|
-
bytes += statSync(join(dir, f)).size;
|
|
691
|
-
} catch {
|
|
692
|
-
}
|
|
693
|
-
}
|
|
1892
|
+
names = readdirSync(dir);
|
|
694
1893
|
} catch {
|
|
695
1894
|
}
|
|
1895
|
+
for (const f of this.cancelledTmp) if (!names.includes(f)) this.cancelledTmp.delete(f);
|
|
1896
|
+
for (const f of names) {
|
|
1897
|
+
if (this.cancelledTmp.has(f)) continue;
|
|
1898
|
+
try {
|
|
1899
|
+
bytes += statSync(join(dir, f)).size;
|
|
1900
|
+
} catch {
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
696
1903
|
}
|
|
697
1904
|
if (bytes > this.downloadMaxBytes) {
|
|
1905
|
+
for (const f of names) this.cancelledTmp.add(f);
|
|
698
1906
|
for (const d of this.activeDownloads) {
|
|
699
|
-
this.
|
|
1907
|
+
this.noteTo(
|
|
1908
|
+
this.ownerOfPage(d.page())?.owner,
|
|
700
1909
|
`The download of ${JSON.stringify(clip(d.suggestedFilename(), 300))} was cancelled: downloads in progress passed ${this.downloadMaxBytes} bytes.`
|
|
701
1910
|
);
|
|
702
1911
|
d.cancel().catch(() => void 0);
|
|
@@ -707,29 +1916,69 @@ var BrowserSession = class {
|
|
|
707
1916
|
this.pollDownloads();
|
|
708
1917
|
}, DOWNLOAD_POLL_MS);
|
|
709
1918
|
}
|
|
710
|
-
/**
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
1919
|
+
/**
|
|
1920
|
+
* An upload's bytes, read here and handed to Chromium from memory (never a path Chromium would
|
|
1921
|
+
* open later, after the agent could have swapped it for a link to the service's own files):
|
|
1922
|
+
* opened without following a final link, then accepted only when the resolved path lies in the
|
|
1923
|
+
* workspace and names the very file opened (an intermediate link swapped in either way shows as
|
|
1924
|
+
* another file), a regular file of at most {@link UPLOAD_MAX_BYTES}.
|
|
1925
|
+
*/
|
|
1926
|
+
readUpload(path) {
|
|
1927
|
+
const root = this.uploadRoot();
|
|
1928
|
+
let fd;
|
|
718
1929
|
try {
|
|
719
|
-
|
|
720
|
-
} catch {
|
|
1930
|
+
fd = openSync(path, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
|
|
1931
|
+
} catch (e) {
|
|
1932
|
+
const code = e.code;
|
|
721
1933
|
throw new ActionError(
|
|
722
1934
|
"failed",
|
|
723
|
-
`No file at ${path}; give the absolute path of a file in the workspace (${root}).`
|
|
1935
|
+
code === "ELOOP" ? `${path} is a symbolic link; upload the file it points to by its own path in the workspace.` : `No readable file at ${path}; give the absolute path of a file in the workspace (${root}).`
|
|
724
1936
|
);
|
|
725
1937
|
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
1938
|
+
try {
|
|
1939
|
+
const opened = fstatSync(fd);
|
|
1940
|
+
let real = "";
|
|
1941
|
+
try {
|
|
1942
|
+
real = realpathSync(path);
|
|
1943
|
+
} catch {
|
|
1944
|
+
real = "";
|
|
1945
|
+
}
|
|
1946
|
+
if (!within(real, root) || !sameFile(opened, statSync(real)))
|
|
1947
|
+
throw new ActionError(
|
|
1948
|
+
"failed",
|
|
1949
|
+
`Upload paths must be inside the workspace (${root}); copy the file there first.`
|
|
1950
|
+
);
|
|
1951
|
+
if (!opened.isFile())
|
|
1952
|
+
throw new ActionError("failed", `${path} is not a regular file; upload a file.`);
|
|
1953
|
+
if (opened.size > UPLOAD_MAX_BYTES)
|
|
1954
|
+
throw new ActionError(
|
|
1955
|
+
"failed",
|
|
1956
|
+
`${path} is larger than ${UPLOAD_MAX_BYTES} bytes, the most an upload takes.`
|
|
1957
|
+
);
|
|
1958
|
+
const buffer = Buffer.alloc(opened.size);
|
|
1959
|
+
let off = 0;
|
|
1960
|
+
while (off < buffer.length) {
|
|
1961
|
+
const n = readSync(fd, buffer, off, buffer.length - off, off);
|
|
1962
|
+
if (n === 0) break;
|
|
1963
|
+
off += n;
|
|
1964
|
+
}
|
|
1965
|
+
const name = basename(real);
|
|
1966
|
+
return {
|
|
1967
|
+
name,
|
|
1968
|
+
mimeType: UPLOAD_TYPES[extname(name).toLowerCase()] ?? "application/octet-stream",
|
|
1969
|
+
buffer: buffer.subarray(0, off)
|
|
1970
|
+
};
|
|
1971
|
+
} finally {
|
|
1972
|
+
closeSync(fd);
|
|
731
1973
|
}
|
|
732
|
-
|
|
1974
|
+
}
|
|
1975
|
+
/** The resolved workspace uploads come from. */
|
|
1976
|
+
uploadRoot() {
|
|
1977
|
+
const workspace = this.workspace;
|
|
1978
|
+
if (workspace === void 0) {
|
|
1979
|
+
throw new ActionError("failed", "Uploads are unavailable: the device has no workspace.");
|
|
1980
|
+
}
|
|
1981
|
+
return realpathSync(workspace);
|
|
733
1982
|
}
|
|
734
1983
|
/**
|
|
735
1984
|
* The page a viewer opens once the refused host is allowed: the navigation's target for a
|
|
@@ -742,8 +1991,9 @@ var BrowserSession = class {
|
|
|
742
1991
|
* Probes the proxy for the URL's host and reports it when refused; the viewers' `blocked`
|
|
743
1992
|
* message carries `pageUrl` (default: the URL itself), the page to open once allowed.
|
|
744
1993
|
*/
|
|
745
|
-
checkBlocked(rawUrl, pageUrl) {
|
|
1994
|
+
checkBlocked(page, rawUrl, pageUrl) {
|
|
746
1995
|
const proxy = this.proxy;
|
|
1996
|
+
const owner = this.ownerOfPage(page);
|
|
747
1997
|
if (proxy === void 0) return Promise.resolve(false);
|
|
748
1998
|
let url;
|
|
749
1999
|
try {
|
|
@@ -753,39 +2003,81 @@ var BrowserSession = class {
|
|
|
753
2003
|
}
|
|
754
2004
|
const host = url.hostname;
|
|
755
2005
|
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
|
756
|
-
|
|
2006
|
+
const key2 = `${owner?.owner ?? ""}\0${host}`;
|
|
2007
|
+
let probe = this.probes.get(key2);
|
|
757
2008
|
if (probe === void 0) {
|
|
758
|
-
probe =
|
|
759
|
-
this.probes.delete(
|
|
760
|
-
if (
|
|
761
|
-
for (const c of this.collectors) c.blocked.
|
|
762
|
-
|
|
2009
|
+
probe = proxyRefusal(proxy, host, port).then((layer) => {
|
|
2010
|
+
this.probes.delete(key2);
|
|
2011
|
+
if (layer !== null && owner !== void 0) {
|
|
2012
|
+
for (const c of this.collectors) if (c.conv === owner.owner) c.blocked.set(host, layer);
|
|
2013
|
+
if (layer === "device")
|
|
2014
|
+
this.emit({ type: "blocked", host, url: pageUrl ?? url.href, root: owner.root });
|
|
763
2015
|
}
|
|
764
|
-
return
|
|
2016
|
+
return layer !== null;
|
|
765
2017
|
});
|
|
766
|
-
this.probes.set(
|
|
2018
|
+
this.probes.set(key2, probe);
|
|
767
2019
|
}
|
|
768
|
-
for (const c of this.collectors) c.pending.push(probe);
|
|
2020
|
+
for (const c of this.collectors) if (c.conv === owner?.owner) c.pending.push(probe);
|
|
769
2021
|
return probe;
|
|
770
2022
|
}
|
|
771
|
-
/**
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
2023
|
+
/** `value`, or `fallback` when it takes longer than {@link PAGE_QUERY_MS} (never rejects). */
|
|
2024
|
+
async bounded(value, fallback) {
|
|
2025
|
+
let timer;
|
|
2026
|
+
try {
|
|
2027
|
+
return await Promise.race([
|
|
2028
|
+
value.catch(() => fallback),
|
|
2029
|
+
new Promise((r) => {
|
|
2030
|
+
timer = this.clock.schedule(() => r(fallback), PAGE_QUERY_MS);
|
|
2031
|
+
})
|
|
2032
|
+
]);
|
|
2033
|
+
} finally {
|
|
2034
|
+
this.clock.cancel(timer);
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
/**
|
|
2038
|
+
* The action queue a conversation's requests run in: one per conversation, so one
|
|
2039
|
+
* conversation's slow navigation does not stall another (ruling 7). Falling back to one
|
|
2040
|
+
* device-wide queue is returning a constant here.
|
|
2041
|
+
*/
|
|
2042
|
+
queueKey(conversationId) {
|
|
2043
|
+
return conversationId;
|
|
2044
|
+
}
|
|
2045
|
+
/**
|
|
2046
|
+
* Runs `fn` one at a time with the conversation's other actions (`wait`, the tab list and adopt
|
|
2047
|
+
* run beside them).
|
|
2048
|
+
*/
|
|
2049
|
+
serial(conversationId, fn) {
|
|
2050
|
+
const key2 = this.queueKey(conversationId);
|
|
2051
|
+
const run = (this.queues.get(key2) ?? Promise.resolve()).then(fn, fn);
|
|
2052
|
+
const tail = run.catch(() => void 0);
|
|
2053
|
+
this.queues.set(key2, tail);
|
|
2054
|
+
void tail.then(() => {
|
|
2055
|
+
if (this.queues.get(key2) === tail) this.queues.delete(key2);
|
|
2056
|
+
});
|
|
775
2057
|
return run;
|
|
776
2058
|
}
|
|
777
2059
|
/**
|
|
778
|
-
* Runs a tool request; never throws. `takenOver` is checked when a queued
|
|
779
|
-
* queue: a takeover that began while it waited refuses it. An action already
|
|
780
|
-
* finish (stopping it halfway would leave the page in an unknown state).
|
|
2060
|
+
* Runs a tool request of its conversation; never throws. `takenOver` is checked when a queued
|
|
2061
|
+
* request leaves the queue: a takeover that began while it waited refuses it. An action already
|
|
2062
|
+
* running is left to finish (stopping it halfway would leave the page in an unknown state).
|
|
781
2063
|
*/
|
|
782
2064
|
async run(req, opts = {}) {
|
|
783
|
-
const
|
|
784
|
-
const
|
|
2065
|
+
const conv = req.conversationId;
|
|
2066
|
+
const lateOwn = this.unreported.get(conv) ?? [];
|
|
2067
|
+
this.unreported.delete(conv);
|
|
2068
|
+
const lateAll = this.unreportedAll.splice(0);
|
|
2069
|
+
const c = {
|
|
2070
|
+
conv,
|
|
2071
|
+
blocked: /* @__PURE__ */ new Map(),
|
|
2072
|
+
notes: [...lateAll, ...lateOwn],
|
|
2073
|
+
pending: [],
|
|
2074
|
+
downloads: []
|
|
2075
|
+
};
|
|
785
2076
|
this.collectors.add(c);
|
|
786
2077
|
let reply;
|
|
787
2078
|
try {
|
|
788
|
-
const
|
|
2079
|
+
const beside = req.op === "wait" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
|
|
2080
|
+
const out = await (beside ? this.exec(req) : this.serial(conv, () => {
|
|
789
2081
|
if (opts.takenOver?.() === true)
|
|
790
2082
|
throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
|
|
791
2083
|
return this.exec(req);
|
|
@@ -793,12 +2085,21 @@ var BrowserSession = class {
|
|
|
793
2085
|
await this.settleProbes(c);
|
|
794
2086
|
await this.settleDownloads(c);
|
|
795
2087
|
this.collectors.delete(c);
|
|
796
|
-
const page =
|
|
797
|
-
|
|
2088
|
+
const page = this.currentPage(conv);
|
|
2089
|
+
if (page !== void 0 && isActing(req)) {
|
|
2090
|
+
this.tabUsedAt.set(this.tabIdOf(page), this.clock.now());
|
|
2091
|
+
this.actedSeq.set(conv, ++this.actSeq);
|
|
2092
|
+
}
|
|
2093
|
+
const verifying = page === void 0 || req.op === "tabs" && (req.action === "list" || req.action === "adopt") ? false : await this.checkVerification(page, this.tabIdOf(page));
|
|
2094
|
+
const text = [
|
|
2095
|
+
...verifying ? [VERIFICATION_NOTE] : [],
|
|
2096
|
+
...c.notes,
|
|
2097
|
+
...out.text === void 0 ? [] : [out.text]
|
|
2098
|
+
].join("\n");
|
|
798
2099
|
reply = {
|
|
799
2100
|
ok: true,
|
|
800
|
-
page: await this.pageInfo(page),
|
|
801
|
-
blockedHosts:
|
|
2101
|
+
...page === void 0 ? {} : { page: await this.pageInfo(page) },
|
|
2102
|
+
blockedHosts: blockedHostsOf(c),
|
|
802
2103
|
...text === "" ? {} : { text },
|
|
803
2104
|
...out.image === void 0 ? {} : { image: out.image }
|
|
804
2105
|
};
|
|
@@ -811,10 +2112,12 @@ var BrowserSession = class {
|
|
|
811
2112
|
}
|
|
812
2113
|
if (c.blocked.size > 0 && code !== "no_such_ref" && code !== "taken_over") {
|
|
813
2114
|
code = "blocked";
|
|
814
|
-
message =
|
|
2115
|
+
message = blockedMessage(blockedHostsOf(c));
|
|
815
2116
|
}
|
|
816
|
-
reply = { ok: false, error: code, message, blockedHosts:
|
|
817
|
-
|
|
2117
|
+
reply = { ok: false, error: code, message, blockedHosts: blockedHostsOf(c) };
|
|
2118
|
+
if (lateOwn.length > 0)
|
|
2119
|
+
this.unreported.set(conv, [...lateOwn, ...this.unreported.get(conv) ?? []]);
|
|
2120
|
+
this.unreportedAll.unshift(...lateAll);
|
|
818
2121
|
} finally {
|
|
819
2122
|
this.collectors.delete(c);
|
|
820
2123
|
}
|
|
@@ -848,13 +2151,61 @@ var BrowserSession = class {
|
|
|
848
2151
|
await Promise.allSettled(all);
|
|
849
2152
|
}
|
|
850
2153
|
}
|
|
851
|
-
|
|
852
|
-
|
|
2154
|
+
/**
|
|
2155
|
+
* Finds the loaded page's icon and fetches it through the browser (the device's network rules
|
|
2156
|
+
* apply); a new address replaces the tab's icon, the same one is not fetched again. Any failure
|
|
2157
|
+
* leaves no icon (the panel's placeholder) and never affects the page.
|
|
2158
|
+
*/
|
|
2159
|
+
async resolveFavicon(page, id) {
|
|
853
2160
|
try {
|
|
854
|
-
|
|
2161
|
+
const url = await iconUrlOf(page);
|
|
2162
|
+
if (this.pages.get(id) !== page) return;
|
|
2163
|
+
if (url === null) {
|
|
2164
|
+
if (this.favicons.delete(id)) this.emit({ type: "state" });
|
|
2165
|
+
return;
|
|
2166
|
+
}
|
|
2167
|
+
if (this.favicons.get(id)?.url === url) return;
|
|
2168
|
+
const cdp = await this.ctx.newCDPSession(page);
|
|
2169
|
+
let data = null;
|
|
2170
|
+
try {
|
|
2171
|
+
const bytes = await fetchIcon(cdp, url);
|
|
2172
|
+
data = bytes === null ? null : await iconForPanel(cdp, bytes);
|
|
2173
|
+
} finally {
|
|
2174
|
+
await cdp.detach().catch(() => void 0);
|
|
2175
|
+
}
|
|
2176
|
+
if (this.pages.get(id) !== page) return;
|
|
2177
|
+
this.favicons.set(id, { url, data });
|
|
2178
|
+
this.emit({ type: "state" });
|
|
855
2179
|
} catch {
|
|
856
|
-
title = this.titles.get(this.tabIdOf(page)) ?? "";
|
|
857
2180
|
}
|
|
2181
|
+
}
|
|
2182
|
+
/**
|
|
2183
|
+
* Looks at the tab's page now and records or clears its verification blocker; true when it
|
|
2184
|
+
* shows a verification page.
|
|
2185
|
+
*/
|
|
2186
|
+
async checkVerification(page, id) {
|
|
2187
|
+
if (id === "") return false;
|
|
2188
|
+
const blocked = await this.bounded(isVerificationPage(page, this.docStatus.get(id)), false);
|
|
2189
|
+
if (this.pages.get(id) !== page) return false;
|
|
2190
|
+
const before = this.blockers.get(id);
|
|
2191
|
+
if (blocked) {
|
|
2192
|
+
const url = clip(page.url(), MAX_URL_CHARS);
|
|
2193
|
+
if (before?.url !== url) {
|
|
2194
|
+
this.blockers.set(id, { kind: "verification", url });
|
|
2195
|
+
this.emit({ type: "state" });
|
|
2196
|
+
}
|
|
2197
|
+
} else if (before !== void 0) {
|
|
2198
|
+
this.blockers.delete(id);
|
|
2199
|
+
this.emit({ type: "state" });
|
|
2200
|
+
}
|
|
2201
|
+
return blocked;
|
|
2202
|
+
}
|
|
2203
|
+
async pageInfo(page) {
|
|
2204
|
+
const known = this.titles.get(this.tabIdOf(page)) ?? "";
|
|
2205
|
+
const title = await this.bounded(
|
|
2206
|
+
page.title().catch(() => known),
|
|
2207
|
+
known
|
|
2208
|
+
);
|
|
858
2209
|
return {
|
|
859
2210
|
url: clip(page.url(), MAX_URL_CHARS),
|
|
860
2211
|
title: clip(title, MAX_TITLE_CHARS),
|
|
@@ -901,7 +2252,7 @@ var BrowserSession = class {
|
|
|
901
2252
|
try {
|
|
902
2253
|
const out = await fn();
|
|
903
2254
|
if (navigating && !loaded2) {
|
|
904
|
-
await page.waitForEvent("domcontentloaded", { timeout:
|
|
2255
|
+
await page.waitForEvent("domcontentloaded", { timeout: this.navigationTimeoutMs }).catch(() => void 0);
|
|
905
2256
|
}
|
|
906
2257
|
return out;
|
|
907
2258
|
} finally {
|
|
@@ -922,25 +2273,48 @@ var BrowserSession = class {
|
|
|
922
2273
|
);
|
|
923
2274
|
}
|
|
924
2275
|
}
|
|
925
|
-
markClick(x, y) {
|
|
926
|
-
this.
|
|
2276
|
+
markClick(page, x, y) {
|
|
2277
|
+
this.clicks.set(this.tabIdOf(page), { x, y, seq: ++this.clickSeq });
|
|
927
2278
|
}
|
|
928
2279
|
async goto(page, url) {
|
|
929
2280
|
let res;
|
|
930
2281
|
const download = page.waitForEvent("download", { timeout: ACTION_TIMEOUT_MS });
|
|
931
2282
|
download.catch(() => void 0);
|
|
2283
|
+
const deadline = Date.now() + this.navigationTimeoutMs;
|
|
2284
|
+
const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
|
|
932
2285
|
try {
|
|
933
|
-
res = await
|
|
2286
|
+
res = await this.gotoPastNetworkChange(page, url, watch, deadline);
|
|
934
2287
|
} catch (e) {
|
|
935
2288
|
const msg = firstLine(e);
|
|
936
2289
|
if (msg.includes("Download is starting")) {
|
|
937
2290
|
await download.catch(() => void 0);
|
|
938
2291
|
return;
|
|
939
2292
|
}
|
|
940
|
-
if (
|
|
941
|
-
throw e;
|
|
2293
|
+
if (isTimeout(e)) throw await this.navigationTimedOut(page, url);
|
|
2294
|
+
if (!msg.includes("net::ERR_ABORTED")) throw await this.navigationFailed(page, e, url, msg);
|
|
2295
|
+
const out = await watch.follow(deadline);
|
|
2296
|
+
if (out.kind !== "loaded") {
|
|
2297
|
+
const status = await watch.emptyAnswer();
|
|
2298
|
+
if (status !== void 0)
|
|
2299
|
+
throw new ActionError(
|
|
2300
|
+
"failed",
|
|
2301
|
+
`${url} answered ${status} with no page to show; the tab shows ${page.url()}.`
|
|
2302
|
+
);
|
|
2303
|
+
}
|
|
2304
|
+
if (out.kind === "none") throw e;
|
|
2305
|
+
if (out.kind === "failed") {
|
|
2306
|
+
throw await this.navigationFailed(
|
|
2307
|
+
page,
|
|
2308
|
+
new Error(`${out.error} at ${out.url}`),
|
|
2309
|
+
out.url,
|
|
2310
|
+
out.error
|
|
2311
|
+
);
|
|
2312
|
+
}
|
|
2313
|
+
res = out.response;
|
|
2314
|
+
} finally {
|
|
2315
|
+
watch.dispose();
|
|
942
2316
|
}
|
|
943
|
-
if (res?.status() === 403 && await this.checkBlocked(res.url())) {
|
|
2317
|
+
if (res?.status() === 403 && await this.checkBlocked(page, res.url())) {
|
|
944
2318
|
throw new ActionError(
|
|
945
2319
|
"blocked",
|
|
946
2320
|
`The device's network settings block ${new URL(res.url()).hostname}.`
|
|
@@ -948,19 +2322,182 @@ var BrowserSession = class {
|
|
|
948
2322
|
}
|
|
949
2323
|
await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
|
|
950
2324
|
}
|
|
2325
|
+
/**
|
|
2326
|
+
* `goto` past a change of the device's network (an interface came or went: Wi-Fi, a VPN, a
|
|
2327
|
+
* container network): Chromium answers net::ERR_NETWORK_CHANGED and may keep or restart the
|
|
2328
|
+
* navigation itself, so it is followed first (like one another navigation took over) and run
|
|
2329
|
+
* again only when none goes on, at most {@link NETWORK_CHANGED_ATTEMPTS} times, within the
|
|
2330
|
+
* navigation's deadline.
|
|
2331
|
+
*/
|
|
2332
|
+
async gotoPastNetworkChange(page, url, watch, deadline) {
|
|
2333
|
+
for (let attempt = 1; ; attempt++) {
|
|
2334
|
+
try {
|
|
2335
|
+
return await this.gotoPastLateErrorPage(page, url, watch, deadline);
|
|
2336
|
+
} catch (e) {
|
|
2337
|
+
if (!firstLine(e).includes("net::ERR_NETWORK_CHANGED")) throw e;
|
|
2338
|
+
const out = await watch.follow(deadline);
|
|
2339
|
+
if (out.kind === "loaded") return out.response;
|
|
2340
|
+
if (out.kind === "failed" && !out.error.includes("ERR_NETWORK_CHANGED"))
|
|
2341
|
+
throw new Error(`${out.error} at ${out.url}`);
|
|
2342
|
+
if (attempt >= NETWORK_CHANGED_ATTEMPTS || Date.now() >= deadline) throw e;
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
/**
|
|
2347
|
+
* `page.goto`, past the late error page of the tab's previous failed or stopped navigation:
|
|
2348
|
+
* Chromium can commit that page after Playwright reported the failure (the Linux full build),
|
|
2349
|
+
* and its commit interrupts a navigation started meanwhile. Then this navigation is followed
|
|
2350
|
+
* when it went on in Chromium, and otherwise started once more (the error page is in now),
|
|
2351
|
+
* within the navigation's own deadline.
|
|
2352
|
+
*/
|
|
2353
|
+
async gotoPastLateErrorPage(page, url, watch, deadline) {
|
|
2354
|
+
try {
|
|
2355
|
+
return await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
2356
|
+
} catch (e) {
|
|
2357
|
+
if (!ERROR_PAGE_INTERRUPT_RE.test(firstLine(e))) throw e;
|
|
2358
|
+
const out = await watch.follow(deadline);
|
|
2359
|
+
if (out.kind === "loaded") return out.response;
|
|
2360
|
+
if (out.kind === "failed" && !out.error.includes("net::ERR_ABORTED"))
|
|
2361
|
+
throw new Error(`${out.error} at ${out.url}`);
|
|
2362
|
+
return page.goto(url, {
|
|
2363
|
+
waitUntil: "domcontentloaded",
|
|
2364
|
+
timeout: Math.max(1, deadline - Date.now())
|
|
2365
|
+
});
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
/**
|
|
2369
|
+
* The error of a navigation that failed with Chromium's net error `error`: a host the proxy
|
|
2370
|
+
* refuses is reported as blocked (`run` turns `original` into the blocked reply); any other net
|
|
2371
|
+
* error is `unreachable`, saying what the device's network answered when it went through it.
|
|
2372
|
+
*/
|
|
2373
|
+
async navigationFailed(page, original, url, error) {
|
|
2374
|
+
const net = /net::(ERR_[A-Z_]+)/.exec(error)?.[1];
|
|
2375
|
+
if (net === void 0 || net === "ERR_ABORTED") return original;
|
|
2376
|
+
await this.errorPageCommitted(page);
|
|
2377
|
+
const proxied = PROXY_FAILURE_RE.test(error);
|
|
2378
|
+
if (proxied && await this.checkBlocked(page, url)) return original;
|
|
2379
|
+
if (proxied || NETWORK_ERROR_RE.test(net)) {
|
|
2380
|
+
const verdict = await this.networkVerdict(url);
|
|
2381
|
+
if (verdict?.kind === "proxy_down")
|
|
2382
|
+
return new ActionError(
|
|
2383
|
+
"network_unavailable",
|
|
2384
|
+
`${url} could not be loaded (net::${net}): ${verdict.text}`
|
|
2385
|
+
);
|
|
2386
|
+
if (verdict !== void 0 && verdict.text !== "")
|
|
2387
|
+
return new ActionError(
|
|
2388
|
+
"unreachable",
|
|
2389
|
+
`${url} could not be loaded (net::${net}): ${verdict.text}`
|
|
2390
|
+
);
|
|
2391
|
+
}
|
|
2392
|
+
const meaning = NET_ERROR_MEANINGS[net];
|
|
2393
|
+
return new ActionError(
|
|
2394
|
+
"unreachable",
|
|
2395
|
+
`${url} could not be loaded (net::${net})${meaning === void 0 ? "." : `: ${meaning}.`}`
|
|
2396
|
+
);
|
|
2397
|
+
}
|
|
2398
|
+
/**
|
|
2399
|
+
* Waits (at most {@link ERROR_PAGE_WAIT_MS}) for the error page of the main frame's failed
|
|
2400
|
+
* navigation: Chromium commits it after Playwright reported the failure (the Linux full build
|
|
2401
|
+
* shows it), and a navigation started before that commit is interrupted by it.
|
|
2402
|
+
*/
|
|
2403
|
+
async errorPageCommitted(page) {
|
|
2404
|
+
if (page.isClosed() || page.mainFrame().url().startsWith("chrome-error:")) return;
|
|
2405
|
+
await page.waitForEvent("framenavigated", {
|
|
2406
|
+
predicate: (f) => f === page.mainFrame() && f.url().startsWith("chrome-error:"),
|
|
2407
|
+
timeout: ERROR_PAGE_WAIT_MS
|
|
2408
|
+
}).catch(() => void 0);
|
|
2409
|
+
}
|
|
2410
|
+
/**
|
|
2411
|
+
* The error of a navigation that took longer than its time limit. The navigation is stopped
|
|
2412
|
+
* first (a navigation left in flight keeps the page's scripts and snapshots waiting for a
|
|
2413
|
+
* document that never comes), so the tab goes back to the page it showed and the next request
|
|
2414
|
+
* works on it; the message says what the device's network answered for the host.
|
|
2415
|
+
*/
|
|
2416
|
+
async navigationTimedOut(page, url) {
|
|
2417
|
+
await this.stopNavigation(page);
|
|
2418
|
+
const seconds = Math.round(this.navigationTimeoutMs / 1e3);
|
|
2419
|
+
const verdict = await this.networkVerdict(url, true);
|
|
2420
|
+
const detail = verdict === void 0 || verdict.text === "" ? "no page came in that time." : verdict.text;
|
|
2421
|
+
const now = page.isClosed() ? "" : ` The navigation was stopped; the tab shows ${page.url()}.`;
|
|
2422
|
+
return new ActionError(
|
|
2423
|
+
verdict?.kind === "proxy_down" ? "network_unavailable" : "unreachable",
|
|
2424
|
+
`${url} did not load within ${seconds} s: ${detail}${now}`
|
|
2425
|
+
);
|
|
2426
|
+
}
|
|
2427
|
+
/** Stops the page's navigation in flight (Chromium's stop button); never throws. */
|
|
2428
|
+
async stopNavigation(page) {
|
|
2429
|
+
if (page.isClosed()) return;
|
|
2430
|
+
try {
|
|
2431
|
+
const cdp = await this.ctx.newCDPSession(page);
|
|
2432
|
+
try {
|
|
2433
|
+
await cdp.send("Page.stopLoading");
|
|
2434
|
+
} finally {
|
|
2435
|
+
await cdp.detach().catch(() => void 0);
|
|
2436
|
+
}
|
|
2437
|
+
} catch {
|
|
2438
|
+
}
|
|
2439
|
+
this.pendingNavs.delete(page);
|
|
2440
|
+
const id = this.ids.get(page);
|
|
2441
|
+
if (id !== void 0 && this.loadingTabs.delete(id)) this.emit({ type: "state" });
|
|
2442
|
+
}
|
|
2443
|
+
/**
|
|
2444
|
+
* What the device's proxy answers for the URL's host, and as a sentence (undefined without a
|
|
2445
|
+
* proxy). `timedOut`: the navigation got no page in time.
|
|
2446
|
+
*/
|
|
2447
|
+
async networkVerdict(rawUrl, timedOut = false) {
|
|
2448
|
+
if (this.proxy === void 0) return void 0;
|
|
2449
|
+
let url;
|
|
2450
|
+
try {
|
|
2451
|
+
url = new URL(rawUrl);
|
|
2452
|
+
} catch {
|
|
2453
|
+
return void 0;
|
|
2454
|
+
}
|
|
2455
|
+
const host = url.hostname;
|
|
2456
|
+
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
|
2457
|
+
const answer = await probeProxy(this.proxy, host, port);
|
|
2458
|
+
return { kind: answer.verdict, text: this.verdictText(answer, host, port, timedOut) };
|
|
2459
|
+
}
|
|
2460
|
+
/** The sentence for a proxy's {@link ProxyAnswer} ("" when it says nothing). */
|
|
2461
|
+
verdictText(answer, host, port, timedOut) {
|
|
2462
|
+
switch (answer.verdict) {
|
|
2463
|
+
case "proxy_down":
|
|
2464
|
+
return "the device's network proxy is not reachable, so no page loads on the device right now; this is not a problem of the address.";
|
|
2465
|
+
case "unreachable":
|
|
2466
|
+
return `the device's network could not connect to ${host}:${port} (the name did not resolve, or the host refused or did not answer the connection).`;
|
|
2467
|
+
case "no_answer":
|
|
2468
|
+
return `the device's network got no answer from ${host}:${port}.`;
|
|
2469
|
+
case "connected":
|
|
2470
|
+
return timedOut ? `${host} accepted the connection through the device's network but sent no page in that time.` : `the device's network connects to ${host}:${port}, but the connection failed.`;
|
|
2471
|
+
case "refused":
|
|
2472
|
+
return refusalLayer(answer.reason) === "address" ? `${host} resolves to a private or local address on the device, which the browser never reaches from the sandbox.` : `the device's network settings block ${host}.`;
|
|
2473
|
+
default:
|
|
2474
|
+
return "";
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
951
2477
|
async exec(req) {
|
|
2478
|
+
const conv = req.conversationId;
|
|
2479
|
+
const root = req.rootConversationId;
|
|
2480
|
+
const activePage = () => this.pageFor(conv, root);
|
|
952
2481
|
switch (req.op) {
|
|
953
2482
|
case "navigate": {
|
|
954
|
-
const page = await
|
|
2483
|
+
const page = await activePage();
|
|
955
2484
|
if (req.url !== void 0) {
|
|
956
2485
|
await this.goto(page, normalizeUrl(req.url));
|
|
957
2486
|
} else if (req.action === "back" || req.action === "forward") {
|
|
958
|
-
const r = await (req.action === "back" ? page.goBack() : page.goForward())
|
|
2487
|
+
const r = await (req.action === "back" ? page.goBack() : page.goForward()).catch(
|
|
2488
|
+
async (e) => {
|
|
2489
|
+
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
2490
|
+
throw e;
|
|
2491
|
+
}
|
|
2492
|
+
);
|
|
959
2493
|
if (r === null && page.url() === "about:blank") {
|
|
960
2494
|
return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
|
|
961
2495
|
}
|
|
962
2496
|
} else if (req.action === "reload") {
|
|
963
|
-
await page.reload({ waitUntil: "domcontentloaded" })
|
|
2497
|
+
await page.reload({ waitUntil: "domcontentloaded" }).catch(async (e) => {
|
|
2498
|
+
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
2499
|
+
throw e;
|
|
2500
|
+
});
|
|
964
2501
|
} else {
|
|
965
2502
|
throw new ActionError(
|
|
966
2503
|
"failed",
|
|
@@ -972,40 +2509,40 @@ var BrowserSession = class {
|
|
|
972
2509
|
case "tabs":
|
|
973
2510
|
return this.tabsOp(req);
|
|
974
2511
|
case "snapshot":
|
|
975
|
-
return { text: await takeSnapshot(await
|
|
2512
|
+
return { text: await takeSnapshot(await activePage()) };
|
|
976
2513
|
case "click":
|
|
977
2514
|
case "hover": {
|
|
978
|
-
const page = await
|
|
2515
|
+
const page = await activePage();
|
|
979
2516
|
const loc = await this.locate(page, req.ref);
|
|
980
2517
|
if (req.op === "hover") {
|
|
981
2518
|
await loc.hover();
|
|
982
2519
|
return {};
|
|
983
2520
|
}
|
|
984
2521
|
const at = await this.centerOf(loc);
|
|
985
|
-
if (at !== void 0) this.markClick(at.x, at.y);
|
|
2522
|
+
if (at !== void 0) this.markClick(page, at.x, at.y);
|
|
986
2523
|
await this.settled(page, () => loc.click());
|
|
987
2524
|
return {};
|
|
988
2525
|
}
|
|
989
2526
|
case "type": {
|
|
990
|
-
const page = await
|
|
2527
|
+
const page = await activePage();
|
|
991
2528
|
const loc = await this.locate(page, req.ref);
|
|
992
2529
|
await loc.fill(req.text);
|
|
993
2530
|
if (req.submit === true) await this.settled(page, () => loc.press("Enter"));
|
|
994
2531
|
return {};
|
|
995
2532
|
}
|
|
996
2533
|
case "select": {
|
|
997
|
-
const page = await
|
|
2534
|
+
const page = await activePage();
|
|
998
2535
|
const loc = await this.locate(page, req.ref);
|
|
999
2536
|
const chosen = await this.settled(page, () => loc.selectOption(req.values));
|
|
1000
2537
|
return { text: `Selected ${JSON.stringify(chosen)}.` };
|
|
1001
2538
|
}
|
|
1002
2539
|
case "press": {
|
|
1003
|
-
const page = await
|
|
2540
|
+
const page = await activePage();
|
|
1004
2541
|
await this.settled(page, () => page.keyboard.press(req.key));
|
|
1005
2542
|
return {};
|
|
1006
2543
|
}
|
|
1007
2544
|
case "scroll": {
|
|
1008
|
-
const page = await
|
|
2545
|
+
const page = await activePage();
|
|
1009
2546
|
if (req.ref !== void 0) {
|
|
1010
2547
|
const loc = await this.locate(page, req.ref);
|
|
1011
2548
|
await loc.scrollIntoViewIfNeeded();
|
|
@@ -1019,25 +2556,25 @@ var BrowserSession = class {
|
|
|
1019
2556
|
return {};
|
|
1020
2557
|
}
|
|
1021
2558
|
case "upload": {
|
|
1022
|
-
const page = await
|
|
1023
|
-
const
|
|
2559
|
+
const page = await activePage();
|
|
2560
|
+
const file = this.readUpload(req.path);
|
|
1024
2561
|
const loc = await this.locate(page, req.ref);
|
|
1025
|
-
await loc.setInputFiles(
|
|
2562
|
+
await loc.setInputFiles(file);
|
|
1026
2563
|
return {};
|
|
1027
2564
|
}
|
|
1028
2565
|
case "click_at":
|
|
1029
2566
|
case "type_at": {
|
|
1030
|
-
const page = await
|
|
2567
|
+
const page = await activePage();
|
|
1031
2568
|
this.checkPoint(req.x, req.y);
|
|
1032
|
-
this.markClick(Math.round(req.x), Math.round(req.y));
|
|
2569
|
+
this.markClick(page, Math.round(req.x), Math.round(req.y));
|
|
1033
2570
|
await this.settled(page, () => page.mouse.click(req.x, req.y));
|
|
1034
2571
|
if (req.op === "type_at") await page.keyboard.type(req.text);
|
|
1035
2572
|
return {};
|
|
1036
2573
|
}
|
|
1037
2574
|
case "wait":
|
|
1038
|
-
return this.waitOp(req);
|
|
2575
|
+
return this.waitOp(req, this.currentPage(conv));
|
|
1039
2576
|
case "screenshot": {
|
|
1040
|
-
const page = await
|
|
2577
|
+
const page = await activePage();
|
|
1041
2578
|
const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
|
|
1042
2579
|
if (!(maxBytes > 0))
|
|
1043
2580
|
throw new ActionError("failed", "screenshot needs a positive maxBytes.");
|
|
@@ -1068,56 +2605,79 @@ var BrowserSession = class {
|
|
|
1068
2605
|
);
|
|
1069
2606
|
}
|
|
1070
2607
|
async tabsOp(req) {
|
|
2608
|
+
const conv = req.conversationId;
|
|
2609
|
+
const root = req.rootConversationId;
|
|
1071
2610
|
switch (req.action) {
|
|
1072
|
-
case "list":
|
|
1073
|
-
await this.
|
|
1074
|
-
const lines = await Promise.all(
|
|
1075
|
-
[...this.pages.entries()].map(async ([id, p]) => {
|
|
1076
|
-
const info = await this.pageInfo(p);
|
|
1077
|
-
return `${id}${id === this.active ? " (active)" : ""}: ${info.title || "(no title)"} ${info.url}`;
|
|
1078
|
-
})
|
|
1079
|
-
);
|
|
1080
|
-
return { text: lines.join("\n") };
|
|
1081
|
-
}
|
|
2611
|
+
case "list":
|
|
2612
|
+
return { text: await this.listText(conv, root) };
|
|
1082
2613
|
case "open": {
|
|
1083
|
-
const page = await this.openTab();
|
|
2614
|
+
const page = this.countOf(conv) === 0 ? await this.pageFor(conv, root) : await this.openTab(conv, root);
|
|
1084
2615
|
if (req.url !== void 0) await this.goto(page, normalizeUrl(req.url));
|
|
1085
2616
|
return {};
|
|
1086
2617
|
}
|
|
1087
2618
|
case "switch": {
|
|
1088
|
-
|
|
1089
|
-
this.
|
|
1090
|
-
await page.bringToFront().catch(() => void 0);
|
|
1091
|
-
this.emit({ type: "active" });
|
|
2619
|
+
this.ownTab(conv, req.tabId);
|
|
2620
|
+
this.setActive(conv, req.tabId);
|
|
1092
2621
|
return {};
|
|
1093
2622
|
}
|
|
1094
2623
|
case "close": {
|
|
1095
|
-
const page = this.
|
|
2624
|
+
const page = this.ownTab(conv, req.tabId);
|
|
1096
2625
|
await page.close();
|
|
1097
|
-
|
|
2626
|
+
return {};
|
|
2627
|
+
}
|
|
2628
|
+
case "adopt": {
|
|
2629
|
+
const id = req.tabId;
|
|
2630
|
+
const result = this.adopt(conv, root, this.tabIdOf(this.tabById(id)));
|
|
2631
|
+
if (result === "in_use") throw new ActionError("failed", tabInUse(id ?? ""));
|
|
2632
|
+
if (result === "cap") throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
|
|
1098
2633
|
return {};
|
|
1099
2634
|
}
|
|
1100
2635
|
}
|
|
1101
|
-
throw new ActionError("failed", "tabs needs an action: list, open, switch or
|
|
2636
|
+
throw new ActionError("failed", "tabs needs an action: list, open, switch, close or adopt.");
|
|
1102
2637
|
}
|
|
1103
|
-
/**
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
`The browser has ${MAX_TABS} tabs open, the most it keeps; close one first.`
|
|
1109
|
-
);
|
|
1110
|
-
}
|
|
1111
|
-
const page = await this.ctx.newPage();
|
|
1112
|
-
this.track(page);
|
|
1113
|
-
this.active = this.ids.get(page);
|
|
1114
|
-
this.emit({ type: "active" });
|
|
1115
|
-
this.emit({ type: "state" });
|
|
2638
|
+
/** The conversation's own tab `tabId`; another conversation's is refused with what to do. */
|
|
2639
|
+
ownTab(conversationId, tabId) {
|
|
2640
|
+
const page = this.tabById(tabId);
|
|
2641
|
+
if (this.owners.get(tabId)?.owner !== conversationId)
|
|
2642
|
+
throw new ActionError("failed", notYourTab(tabId));
|
|
1116
2643
|
return page;
|
|
1117
2644
|
}
|
|
2645
|
+
/**
|
|
2646
|
+
* The tab list of a conversation: its own tabs, then its tree's other tabs, then other trees'
|
|
2647
|
+
* tabs (unowned ones too, but not a blank start tab), with ids, titles clipped to
|
|
2648
|
+
* OTHER_TITLE_CHARS and URLs without query or fragment outside its own; no conversation ids.
|
|
2649
|
+
*/
|
|
2650
|
+
async listText(conversationId, root) {
|
|
2651
|
+
const own = [];
|
|
2652
|
+
const tree = [];
|
|
2653
|
+
const device = [];
|
|
2654
|
+
for (const [id, p] of this.live()) {
|
|
2655
|
+
const o = this.owners.get(id);
|
|
2656
|
+
if (o?.owner === conversationId) {
|
|
2657
|
+
const info = await this.pageInfo(p);
|
|
2658
|
+
const active = this.activeOf.get(conversationId) === id ? " (active)" : "";
|
|
2659
|
+
own.push(`${id}${active}: ${info.title || "(no title)"} ${info.url}`);
|
|
2660
|
+
continue;
|
|
2661
|
+
}
|
|
2662
|
+
if (isStartBlank({ owner: o?.owner, url: p.url() })) continue;
|
|
2663
|
+
const title = clip(this.titles.get(id) ?? "", OTHER_TITLE_CHARS) || "(no title)";
|
|
2664
|
+
const line = `${id}: ${title} ${bareUrl(clip(p.url(), MAX_URL_CHARS))}`;
|
|
2665
|
+
if (o !== void 0 && o.root === root) tree.push(line);
|
|
2666
|
+
else device.push(line);
|
|
2667
|
+
}
|
|
2668
|
+
const lines = [...own];
|
|
2669
|
+
if (tree.length > 0) lines.push("Tabs of other conversations in this task:", ...tree);
|
|
2670
|
+
if (device.length > 0) lines.push("Tabs of other conversations on this device:", ...device);
|
|
2671
|
+
if (tree.length + device.length > 0)
|
|
2672
|
+
lines.push(
|
|
2673
|
+
"To use another conversation's tab, call browser_tabs with action adopt and its tabId."
|
|
2674
|
+
);
|
|
2675
|
+
if (lines.length === 0) return "No browser tabs are open.";
|
|
2676
|
+
return lines.join("\n");
|
|
2677
|
+
}
|
|
1118
2678
|
tabById(tabId) {
|
|
1119
|
-
const page =
|
|
1120
|
-
if (page === void 0
|
|
2679
|
+
const page = this.pageById(tabId);
|
|
2680
|
+
if (page === void 0) {
|
|
1121
2681
|
throw new ActionError(
|
|
1122
2682
|
"failed",
|
|
1123
2683
|
`No tab ${JSON.stringify(tabId ?? "")}; list the tabs to see their ids.`
|
|
@@ -1125,18 +2685,13 @@ var BrowserSession = class {
|
|
|
1125
2685
|
}
|
|
1126
2686
|
return page;
|
|
1127
2687
|
}
|
|
1128
|
-
/**
|
|
1129
|
-
async
|
|
1130
|
-
|
|
1131
|
-
this.active = tabId;
|
|
1132
|
-
await page.bringToFront().catch(() => void 0);
|
|
1133
|
-
this.emit({ type: "active" });
|
|
1134
|
-
this.emit({ type: "state" });
|
|
2688
|
+
/** Brings a tab to the front of the window (only a viewer in control decides what is front). */
|
|
2689
|
+
async bringToFront(tabId) {
|
|
2690
|
+
await this.pageById(tabId)?.bringToFront().catch(() => void 0);
|
|
1135
2691
|
}
|
|
1136
|
-
/** Navigates
|
|
1137
|
-
async viewerNav(nav) {
|
|
2692
|
+
/** Navigates a tab for a viewer (address bar, back, forward, reload); never throws. */
|
|
2693
|
+
async viewerNav(page, nav) {
|
|
1138
2694
|
try {
|
|
1139
|
-
const page = await this.activePage();
|
|
1140
2695
|
if (nav.url !== void 0) await this.goto(page, normalizeUrl(nav.url));
|
|
1141
2696
|
else if (nav.action === "back") await page.goBack();
|
|
1142
2697
|
else if (nav.action === "forward") await page.goForward();
|
|
@@ -1144,10 +2699,15 @@ var BrowserSession = class {
|
|
|
1144
2699
|
} catch {
|
|
1145
2700
|
}
|
|
1146
2701
|
}
|
|
1147
|
-
async waitOp(req) {
|
|
2702
|
+
async waitOp(req, page) {
|
|
1148
2703
|
const asked = Number(req.timeoutMs);
|
|
1149
2704
|
const timeout = Number.isFinite(asked) ? Math.max(0, Math.min(MAX_WAIT_MS, Math.floor(asked))) : DEFAULT_WAIT_MS;
|
|
1150
|
-
|
|
2705
|
+
if (page === void 0) {
|
|
2706
|
+
if (req.text !== void 0 || req.ref !== void 0 || req.navigation === true)
|
|
2707
|
+
throw new ActionError("failed", NO_TAB_TO_WAIT_ON);
|
|
2708
|
+
await new Promise((r) => this.clock.schedule(r, timeout));
|
|
2709
|
+
return {};
|
|
2710
|
+
}
|
|
1151
2711
|
if (req.text !== void 0) {
|
|
1152
2712
|
await page.getByText(req.text).first().waitFor({ state: "visible", timeout }).catch((e) => {
|
|
1153
2713
|
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError(
|
|
@@ -1188,15 +2748,33 @@ var BrowserSession = class {
|
|
|
1188
2748
|
};
|
|
1189
2749
|
|
|
1190
2750
|
// daemon/chromium.ts
|
|
1191
|
-
import {
|
|
2751
|
+
import {
|
|
2752
|
+
accessSync,
|
|
2753
|
+
constants,
|
|
2754
|
+
existsSync,
|
|
2755
|
+
lstatSync as lstatSync2,
|
|
2756
|
+
readdirSync as readdirSync2,
|
|
2757
|
+
readFileSync,
|
|
2758
|
+
writeFileSync
|
|
2759
|
+
} from "node:fs";
|
|
1192
2760
|
import { createRequire } from "node:module";
|
|
1193
|
-
import { dirname, join as join2 } from "node:path";
|
|
2761
|
+
import { dirname, isAbsolute, join as join2, relative } from "node:path";
|
|
1194
2762
|
import { fileURLToPath } from "node:url";
|
|
2763
|
+
var SERVICE_MACH_ENV = DEVICE_SERVICE_MACH_ENV;
|
|
2764
|
+
var HEADLESS_SHELL_NOTE = "The browser runs as a headless shell, which sites flag as a bot more often: the machine's capybara-device predates the full browser; ask the user to update capybara-device on that machine.";
|
|
2765
|
+
function chromiumBuild(platform, env = process.env) {
|
|
2766
|
+
if (platform !== "darwin") return "chromium";
|
|
2767
|
+
return env[SERVICE_MACH_ENV] === DEVICE_SERVICE_MACH_CHROMIUM ? "chromium" : "chromium-headless-shell";
|
|
2768
|
+
}
|
|
2769
|
+
var BUILD_DIR = {
|
|
2770
|
+
chromium: "chromium",
|
|
2771
|
+
"chromium-headless-shell": "chromium_headless_shell"
|
|
2772
|
+
};
|
|
1195
2773
|
function envValue(env, name) {
|
|
1196
2774
|
const v = env[name] ?? env[name.toLowerCase()];
|
|
1197
2775
|
return v === void 0 || v === "" ? void 0 : v;
|
|
1198
2776
|
}
|
|
1199
|
-
function
|
|
2777
|
+
function browserRelease(build) {
|
|
1200
2778
|
const candidates = [new URL("./vendor/playwright-core/browsers.json", import.meta.url)];
|
|
1201
2779
|
try {
|
|
1202
2780
|
const pkg = createRequire(import.meta.url).resolve("playwright-core/package.json");
|
|
@@ -1206,13 +2784,25 @@ function headlessShellRevision() {
|
|
|
1206
2784
|
for (const file of candidates) {
|
|
1207
2785
|
try {
|
|
1208
2786
|
const json = JSON.parse(readFileSync(fileURLToPath(file), "utf8"));
|
|
1209
|
-
const
|
|
1210
|
-
if (typeof
|
|
2787
|
+
const b = json.browsers?.find((x) => x.name === build);
|
|
2788
|
+
if (typeof b?.revision === "string" && b.revision !== "")
|
|
2789
|
+
return {
|
|
2790
|
+
revision: b.revision,
|
|
2791
|
+
version: typeof b.browserVersion === "string" ? b.browserVersion : ""
|
|
2792
|
+
};
|
|
1211
2793
|
} catch {
|
|
1212
2794
|
}
|
|
1213
2795
|
}
|
|
1214
2796
|
return void 0;
|
|
1215
2797
|
}
|
|
2798
|
+
function browserRevision(build) {
|
|
2799
|
+
return browserRelease(build)?.revision;
|
|
2800
|
+
}
|
|
2801
|
+
function chromeUserAgent(platform, version) {
|
|
2802
|
+
const major = /^\d+/.exec(version)?.[0] ?? "0";
|
|
2803
|
+
const os = platform === "darwin" ? "Macintosh; Intel Mac OS X 10_15_7" : platform === "win32" ? "Windows NT 10.0; Win64; x64" : "X11; Linux x86_64";
|
|
2804
|
+
return `Mozilla/5.0 (${os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36`;
|
|
2805
|
+
}
|
|
1216
2806
|
function playwrightDownloadHosts(env) {
|
|
1217
2807
|
const custom = envValue(env, "PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST") ?? envValue(env, "PLAYWRIGHT_DOWNLOAD_HOST");
|
|
1218
2808
|
if (custom !== void 0) {
|
|
@@ -1222,17 +2812,107 @@ function playwrightDownloadHosts(env) {
|
|
|
1222
2812
|
return [];
|
|
1223
2813
|
}
|
|
1224
2814
|
}
|
|
1225
|
-
return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com"];
|
|
2815
|
+
return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com", "storage.googleapis.com"];
|
|
2816
|
+
}
|
|
2817
|
+
var MAX_REVISION_SKEW = 10;
|
|
2818
|
+
function shippedRevisionNote(dir, revision) {
|
|
2819
|
+
return `The browser runs ${dir} from the device image, not ${revision === void 0 ? "this plugin's" : `revision ${revision}`}: ask the user to recreate the device on the current image when convenient.`;
|
|
2820
|
+
}
|
|
2821
|
+
var BROWSER_UNAVAILABLE_MESSAGE = "This device offers the browser no place it cannot rewrite: on a local device, update capybara-device on that machine; on a cloud device, its image predates the pinned browser, so ask the user to delete the device and create it again (or wait until it is recreated after a period without use).";
|
|
2822
|
+
var SERVICE_INSTALL_ENV = "CAPYBARA_SERVICE_INSTALL";
|
|
2823
|
+
var SERVICE_INSTALL_SEAL = ".sealed";
|
|
2824
|
+
var BrowserInstalledError = class extends Error {
|
|
2825
|
+
constructor() {
|
|
2826
|
+
super("The browser was installed; the browser service restarts to run it read only.");
|
|
2827
|
+
this.name = "BrowserInstalledError";
|
|
2828
|
+
}
|
|
2829
|
+
};
|
|
2830
|
+
function inside(dir, root) {
|
|
2831
|
+
const rel = relative(root, dir);
|
|
2832
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
1226
2833
|
}
|
|
1227
|
-
function
|
|
2834
|
+
function readOnlyForUs(dir) {
|
|
2835
|
+
try {
|
|
2836
|
+
accessSync(dir, constants.W_OK);
|
|
2837
|
+
return false;
|
|
2838
|
+
} catch {
|
|
2839
|
+
return true;
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
function browsersPathFor(stateDir, env, revision, build) {
|
|
2843
|
+
const install = envValue(env, SERVICE_INSTALL_ENV);
|
|
2844
|
+
if (install !== void 0 && isAbsolute(install)) {
|
|
2845
|
+
let sealed = false;
|
|
2846
|
+
try {
|
|
2847
|
+
sealed = lstatSync2(join2(install, SERVICE_INSTALL_SEAL)).isFile();
|
|
2848
|
+
} catch {
|
|
2849
|
+
sealed = false;
|
|
2850
|
+
}
|
|
2851
|
+
return { browsersPath: install, install: { sealed } };
|
|
2852
|
+
}
|
|
1228
2853
|
const cache = envValue(env, "PLAYWRIGHT_BROWSERS_PATH");
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
2854
|
+
const workspace = envValue(env, "CAPYBARA_SERVICE_WORKSPACE");
|
|
2855
|
+
if (cache !== void 0 && isAbsolute(cache) && (workspace === void 0 || !inside(cache, workspace)) && readOnlyForUs(cache)) {
|
|
2856
|
+
if (revision !== void 0 && existsSync(join2(cache, `${BUILD_DIR[build]}-${revision}`)))
|
|
2857
|
+
return { browsersPath: cache, shipped: true };
|
|
2858
|
+
const near = shippedRevisions(cache, build).filter(
|
|
2859
|
+
(d) => revision !== void 0 && Math.abs(Number(d.slice(BUILD_DIR[build].length + 1)) - Number(revision)) <= MAX_REVISION_SKEW
|
|
2860
|
+
);
|
|
2861
|
+
const newest = near.at(-1);
|
|
2862
|
+
if (newest !== void 0) return { browsersPath: cache, shipped: true, shippedDir: newest };
|
|
2863
|
+
}
|
|
2864
|
+
return { browsersPath: join2(stateDir, "browsers"), unavailable: BROWSER_UNAVAILABLE_MESSAGE };
|
|
2865
|
+
}
|
|
2866
|
+
function shippedRevisions(cache, build) {
|
|
2867
|
+
const re = new RegExp(`^${BUILD_DIR[build]}-(\\d+)$`);
|
|
2868
|
+
let names;
|
|
2869
|
+
try {
|
|
2870
|
+
names = readdirSync2(cache);
|
|
2871
|
+
} catch {
|
|
2872
|
+
return [];
|
|
2873
|
+
}
|
|
2874
|
+
return names.map((n) => ({ n, rev: Number(re.exec(n)?.[1] ?? Number.NaN) })).filter((x) => Number.isFinite(x.rev)).sort((a, b) => a.rev - b.rev).map((x) => x.n);
|
|
1232
2875
|
}
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
2876
|
+
var PLAYWRIGHT_DISABLED_FEATURES = [
|
|
2877
|
+
"AvoidUnnecessaryBeforeUnloadCheckSync",
|
|
2878
|
+
"DestroyProfileOnBrowserClose",
|
|
2879
|
+
"HttpsUpgrades",
|
|
2880
|
+
"HttpsFirstBalancedModeAutoEnable",
|
|
2881
|
+
"LensOverlay",
|
|
2882
|
+
"MediaRouter",
|
|
2883
|
+
"PaintHolding",
|
|
2884
|
+
"ThirdPartyStoragePartitioning",
|
|
2885
|
+
"AvoidCorsURLLoaderRestartOnRedirect",
|
|
2886
|
+
"TcpPortRandomizationWin",
|
|
2887
|
+
"OptimizationHints",
|
|
2888
|
+
"NetworkTimeServiceQuerying",
|
|
2889
|
+
"AimEnabled",
|
|
2890
|
+
"PreconnectToSearch",
|
|
2891
|
+
"msForceBrowserSignIn",
|
|
2892
|
+
"msEdgeUpdateLaunchServicesPreferredVersion"
|
|
2893
|
+
];
|
|
2894
|
+
var DISABLED_FEATURES = [...PLAYWRIGHT_DISABLED_FEATURES, "AcceptCHFrame"];
|
|
2895
|
+
function chromiumLaunchPlan(opts, release = browserRelease(
|
|
2896
|
+
chromiumBuild(opts.platform, opts.env)
|
|
2897
|
+
)) {
|
|
2898
|
+
const build = chromiumBuild(opts.platform, opts.env);
|
|
2899
|
+
const args = [
|
|
2900
|
+
"--headless",
|
|
2901
|
+
"--use-mock-keychain",
|
|
2902
|
+
`--window-size=${VIEWPORT.width},${VIEWPORT.height}`,
|
|
2903
|
+
`--user-agent=${chromeUserAgent(opts.platform, release?.version ?? "")}`,
|
|
2904
|
+
`--disable-features=${DISABLED_FEATURES.join(",")}`,
|
|
2905
|
+
// Chrome reloads a network error page by itself (after 1 s, then backing off): that reload
|
|
2906
|
+
// aborts the agent's next navigation in the tab and asks the proxy for the failed host again
|
|
2907
|
+
"--disable-auto-reload"
|
|
2908
|
+
];
|
|
2909
|
+
if (build === "chromium-headless-shell") args.push("--single-process");
|
|
2910
|
+
let env;
|
|
2911
|
+
if (opts.platform === "darwin") {
|
|
2912
|
+
args.push("--disable-crash-reporter", "--disable-breakpad");
|
|
2913
|
+
const tmp = envValue(opts.env, "TMPDIR");
|
|
2914
|
+
if (tmp !== void 0) env = { MAC_CHROMIUM_TMPDIR: tmp };
|
|
2915
|
+
}
|
|
1236
2916
|
const proxy = envValue(opts.env, "HTTPS_PROXY") ?? envValue(opts.env, "HTTP_PROXY");
|
|
1237
2917
|
let proxyAuth;
|
|
1238
2918
|
if (proxy !== void 0) {
|
|
@@ -1257,7 +2937,9 @@ function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
|
|
|
1257
2937
|
}
|
|
1258
2938
|
}
|
|
1259
2939
|
return {
|
|
1260
|
-
|
|
2940
|
+
...opts.browsersPath === void 0 ? browsersPathFor(opts.stateDir, opts.env, release?.revision, build) : { browsersPath: opts.browsersPath },
|
|
2941
|
+
build,
|
|
2942
|
+
...env === void 0 ? {} : { env },
|
|
1261
2943
|
profileDir: join2(opts.stateDir, "profile"),
|
|
1262
2944
|
downloadsTmp: join2(opts.stateDir, "downloads-tmp"),
|
|
1263
2945
|
args,
|
|
@@ -1280,24 +2962,44 @@ async function loadPlaywright(browsersPath) {
|
|
|
1280
2962
|
loaded = { browsersPath, pw: pw.default ?? pw };
|
|
1281
2963
|
return loaded.pw;
|
|
1282
2964
|
}
|
|
1283
|
-
async function
|
|
2965
|
+
async function registryBrowser(browsersPath, build) {
|
|
1284
2966
|
await loadPlaywright(browsersPath);
|
|
1285
2967
|
const mod = await import("./vendor/playwright-core/lib/coreBundle.js");
|
|
1286
2968
|
const registry = (mod.registry ?? mod.default?.registry)?.registry;
|
|
1287
2969
|
if (registry === void 0) throw new Error("playwright-core has no browser registry");
|
|
1288
|
-
const exe = registry.findExecutable(
|
|
1289
|
-
if (exe === void 0) throw new Error(
|
|
1290
|
-
const
|
|
1291
|
-
if (
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
2970
|
+
const exe = registry.findExecutable(build);
|
|
2971
|
+
if (exe === void 0) throw new Error(`playwright-core does not know ${build}`);
|
|
2972
|
+
const executablePath = exe.executablePath();
|
|
2973
|
+
if (executablePath === void 0 || exe.directory === void 0)
|
|
2974
|
+
throw new Error(`playwright-core has no ${build} for this platform`);
|
|
2975
|
+
return { registry, exe, executablePath, directory: exe.directory };
|
|
2976
|
+
}
|
|
2977
|
+
async function ensureChromium(browsersPath, install = true, build = chromiumBuild(process.platform), fresh = false) {
|
|
2978
|
+
const { registry, exe, executablePath, directory } = await registryBrowser(browsersPath, build);
|
|
2979
|
+
const marked = existsSync(join2(directory, "INSTALLATION_COMPLETE"));
|
|
2980
|
+
if (!fresh && marked && existsSync(executablePath)) return executablePath;
|
|
2981
|
+
if (!install)
|
|
2982
|
+
throw new Error(
|
|
2983
|
+
`the browser in ${browsersPath} is incomplete and read only for the browser service; delete the device and create it again`
|
|
2984
|
+
);
|
|
2985
|
+
await registry.install([exe], { gc: false, force: marked || fresh });
|
|
2986
|
+
if (!existsSync(executablePath)) {
|
|
1295
2987
|
throw new Error("the Chromium download finished without an executable");
|
|
1296
2988
|
}
|
|
1297
|
-
return
|
|
2989
|
+
return executablePath;
|
|
1298
2990
|
}
|
|
1299
2991
|
async function launchChromium(plan) {
|
|
1300
|
-
|
|
2992
|
+
if (plan.unavailable !== void 0) throw new Error(plan.unavailable);
|
|
2993
|
+
if (plan.install?.sealed === false) {
|
|
2994
|
+
await ensureChromium(plan.browsersPath, true, plan.build, true);
|
|
2995
|
+
sealInstall(plan.browsersPath);
|
|
2996
|
+
throw new BrowserInstalledError();
|
|
2997
|
+
}
|
|
2998
|
+
const executablePath = plan.shippedDir === void 0 ? await ensureChromium(
|
|
2999
|
+
plan.browsersPath,
|
|
3000
|
+
plan.install === void 0 && plan.shipped !== true,
|
|
3001
|
+
plan.build
|
|
3002
|
+
) : await shippedExecutable(plan.browsersPath, plan.shippedDir, plan.build);
|
|
1301
3003
|
const pw = await loadPlaywright(plan.browsersPath);
|
|
1302
3004
|
return pw.chromium.launchPersistentContext(plan.profileDir, {
|
|
1303
3005
|
headless: true,
|
|
@@ -1307,72 +3009,181 @@ async function launchChromium(plan) {
|
|
|
1307
3009
|
// downloads are saved into the workspace by the session (actions.ts)
|
|
1308
3010
|
acceptDownloads: true,
|
|
1309
3011
|
downloadsPath: plan.downloadsTmp,
|
|
1310
|
-
...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
|
|
3012
|
+
...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth },
|
|
3013
|
+
...plan.env === void 0 ? {} : { env: { ...process.env, ...plan.env } }
|
|
1311
3014
|
});
|
|
1312
3015
|
}
|
|
3016
|
+
async function shippedExecutable(cache, dir, build) {
|
|
3017
|
+
const { executablePath, directory } = await registryBrowser(cache, build);
|
|
3018
|
+
const path = join2(cache, dir, relative(directory, executablePath));
|
|
3019
|
+
if (!existsSync(path))
|
|
3020
|
+
throw new Error(
|
|
3021
|
+
`the browser shipped in ${join2(cache, dir)} has no executable; ${BROWSER_UNAVAILABLE_MESSAGE}`
|
|
3022
|
+
);
|
|
3023
|
+
return path;
|
|
3024
|
+
}
|
|
3025
|
+
function sealInstall(dir) {
|
|
3026
|
+
try {
|
|
3027
|
+
writeFileSync(join2(dir, SERVICE_INSTALL_SEAL), "", { flag: "wx", mode: 420 });
|
|
3028
|
+
} catch (e) {
|
|
3029
|
+
if (e.code !== "EEXIST") throw e;
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
async function browserProcessId(ctx) {
|
|
3033
|
+
const browser = ctx.browser();
|
|
3034
|
+
if (browser === null) return void 0;
|
|
3035
|
+
try {
|
|
3036
|
+
const cdp = await browser.newBrowserCDPSession();
|
|
3037
|
+
try {
|
|
3038
|
+
const info = await cdp.send("SystemInfo.getProcessInfo");
|
|
3039
|
+
return info.processInfo.find((p) => p.type === "browser")?.id;
|
|
3040
|
+
} finally {
|
|
3041
|
+
await cdp.detach().catch(() => void 0);
|
|
3042
|
+
}
|
|
3043
|
+
} catch {
|
|
3044
|
+
return void 0;
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
function killChromium(pid) {
|
|
3048
|
+
if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) return;
|
|
3049
|
+
try {
|
|
3050
|
+
process.kill(-pid, "SIGKILL");
|
|
3051
|
+
} catch {
|
|
3052
|
+
try {
|
|
3053
|
+
process.kill(pid, "SIGKILL");
|
|
3054
|
+
} catch {
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
3058
|
+
function processAlive(pid) {
|
|
3059
|
+
try {
|
|
3060
|
+
process.kill(pid, 0);
|
|
3061
|
+
return true;
|
|
3062
|
+
} catch (e) {
|
|
3063
|
+
return e.code === "EPERM";
|
|
3064
|
+
}
|
|
3065
|
+
}
|
|
1313
3066
|
|
|
1314
|
-
// daemon/
|
|
1315
|
-
import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3067
|
+
// daemon/cookie-file.ts
|
|
3068
|
+
import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1316
3069
|
import { join as join3 } from "node:path";
|
|
3070
|
+
var key = (c) => `${c.domain}
|
|
3071
|
+
${c.path}
|
|
3072
|
+
${c.name}`;
|
|
3073
|
+
async function saveCookies(ctx, stateDir) {
|
|
3074
|
+
try {
|
|
3075
|
+
const cookies = (await ctx.cookies()).filter((c) => c.expires > 0);
|
|
3076
|
+
const file = join3(stateDir, "cookies.json");
|
|
3077
|
+
writeFileSync2(`${file}.tmp`, JSON.stringify(cookies), { mode: 384 });
|
|
3078
|
+
renameSync(`${file}.tmp`, file);
|
|
3079
|
+
} catch {
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
async function restoreCookies(ctx, stateDir) {
|
|
3083
|
+
try {
|
|
3084
|
+
const saved = JSON.parse(readFileSync2(join3(stateDir, "cookies.json"), "utf8"));
|
|
3085
|
+
if (!Array.isArray(saved)) return;
|
|
3086
|
+
const have = new Set((await ctx.cookies()).map(key));
|
|
3087
|
+
const now = Date.now() / 1e3;
|
|
3088
|
+
const missing = saved.filter(
|
|
3089
|
+
(c) => typeof c?.name === "string" && typeof c.domain === "string" && typeof c.path === "string" && typeof c.value === "string" && typeof c.expires === "number" && c.expires > now && !have.has(key(c))
|
|
3090
|
+
);
|
|
3091
|
+
if (missing.length > 0) await ctx.addCookies(missing);
|
|
3092
|
+
} catch {
|
|
3093
|
+
} finally {
|
|
3094
|
+
rmSync(join3(stateDir, "cookies.json"), { force: true });
|
|
3095
|
+
}
|
|
3096
|
+
}
|
|
3097
|
+
|
|
3098
|
+
// daemon/session-file.ts
|
|
3099
|
+
import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3100
|
+
import { join as join4 } from "node:path";
|
|
1317
3101
|
var RESTORE_MAX_AGE_MS = 10 * 6e4;
|
|
3102
|
+
var SESSION_FILE_VERSION = 2;
|
|
3103
|
+
var isId = (v) => typeof v === "string" && v !== "";
|
|
1318
3104
|
var SessionFile = class {
|
|
1319
3105
|
file;
|
|
1320
3106
|
clock;
|
|
1321
3107
|
queued = false;
|
|
1322
3108
|
forgotten = false;
|
|
1323
3109
|
constructor(stateDir, clock) {
|
|
1324
|
-
this.file =
|
|
3110
|
+
this.file = join4(stateDir, "session.json");
|
|
1325
3111
|
this.clock = clock;
|
|
1326
3112
|
}
|
|
1327
|
-
/** The saved session when it is recent and well formed; undefined otherwise. */
|
|
3113
|
+
/** The saved session when it is recent, of this format and well formed; undefined otherwise. */
|
|
1328
3114
|
read() {
|
|
1329
3115
|
let raw;
|
|
1330
3116
|
try {
|
|
1331
|
-
raw = JSON.parse(
|
|
3117
|
+
raw = JSON.parse(readFileSync3(this.file, "utf8"));
|
|
1332
3118
|
} catch {
|
|
1333
3119
|
return void 0;
|
|
1334
3120
|
}
|
|
1335
3121
|
const s = raw;
|
|
1336
|
-
if (typeof s !== "object" || s === null || typeof s.savedAt !== "number" || this.clock.now() - s.savedAt > RESTORE_MAX_AGE_MS || !Array.isArray(s.tabs))
|
|
3122
|
+
if (typeof s !== "object" || s === null || s.version !== SESSION_FILE_VERSION || typeof s.savedAt !== "number" || this.clock.now() - s.savedAt > RESTORE_MAX_AGE_MS || !Array.isArray(s.tabs) || !Array.isArray(s.conversations))
|
|
1337
3123
|
return void 0;
|
|
1338
3124
|
const tabs = s.tabs.filter(
|
|
1339
|
-
(
|
|
1340
|
-
);
|
|
1341
|
-
const
|
|
1342
|
-
const
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
3125
|
+
(t) => typeof t === "object" && t !== null && typeof t.url === "string" && /^https?:\/\//i.test(t.url) && isId(t.owner) && isId(t.root)
|
|
3126
|
+
).slice(0, MAX_TABS).map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
|
|
3127
|
+
const conversations = [];
|
|
3128
|
+
for (const c of s.conversations) {
|
|
3129
|
+
if (typeof c !== "object" || c === null) continue;
|
|
3130
|
+
const x = c;
|
|
3131
|
+
if (!isId(x.id) || !isId(x.root)) continue;
|
|
3132
|
+
const h = x.handoff;
|
|
3133
|
+
const handoff = typeof h === "object" && h !== null && isId(h.callId) && typeof h.message === "string" ? { callId: h.callId, message: h.message.slice(0, HANDOFF_MAX_CHARS) } : void 0;
|
|
3134
|
+
const parks = Array.isArray(x.parks) ? x.parks.filter(
|
|
3135
|
+
(p) => typeof p === "object" && p !== null && isId(p.kind) && typeof p.key === "string"
|
|
3136
|
+
).map((p) => ({ kind: p.kind, key: p.key })) : [];
|
|
3137
|
+
conversations.push({
|
|
3138
|
+
id: x.id,
|
|
3139
|
+
root: x.root,
|
|
3140
|
+
...typeof x.active === "number" ? { active: x.active } : {},
|
|
3141
|
+
...handoff === void 0 ? {} : { handoff },
|
|
3142
|
+
...parks.length === 0 ? {} : { parks }
|
|
3143
|
+
});
|
|
3144
|
+
}
|
|
3145
|
+
return { version: SESSION_FILE_VERSION, savedAt: s.savedAt, tabs, conversations };
|
|
1349
3146
|
}
|
|
1350
3147
|
/**
|
|
1351
|
-
* Writes the session soon (coalesced): the tabs
|
|
1352
|
-
* the write runs.
|
|
3148
|
+
* Writes the session soon (coalesced): the tabs with their owners, and per conversation its
|
|
3149
|
+
* active tab, pending handoff and persistent parks, all read when the write runs.
|
|
1353
3150
|
*/
|
|
1354
|
-
save(session,
|
|
3151
|
+
save(session, state) {
|
|
1355
3152
|
if (this.queued || this.forgotten) return;
|
|
1356
3153
|
this.queued = true;
|
|
1357
3154
|
queueMicrotask(() => {
|
|
1358
3155
|
this.queued = false;
|
|
1359
3156
|
if (this.forgotten) return;
|
|
1360
|
-
const
|
|
1361
|
-
|
|
1362
|
-
const kept = all.filter((t) => /^https?:\/\//i.test(t.url));
|
|
1363
|
-
const active = Math.max(
|
|
1364
|
-
0,
|
|
1365
|
-
kept.findIndex((t) => t.active)
|
|
3157
|
+
const kept = session.tabs().filter(
|
|
3158
|
+
(t) => t.owner !== void 0 && t.root !== void 0 && /^https?:\/\//i.test(t.url)
|
|
1366
3159
|
);
|
|
3160
|
+
const tabs = kept.map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
|
|
3161
|
+
const ids = /* @__PURE__ */ new Set([...kept.map((t) => t.owner), ...state.conversationIds]);
|
|
3162
|
+
const conversations = [];
|
|
3163
|
+
for (const id of ids) {
|
|
3164
|
+
const root = kept.find((t) => t.owner === id)?.root ?? state.rootOf(id);
|
|
3165
|
+
if (root === void 0) continue;
|
|
3166
|
+
const active = kept.findIndex((t) => t.owner === id && t.active);
|
|
3167
|
+
const handoff = state.handoffOf(id);
|
|
3168
|
+
const parks = state.parksOf(id).filter((p) => p.persist === true && p.tabId === void 0 && p.kind !== HANDOFF_PARK).map((p) => ({ kind: p.kind, key: p.key }));
|
|
3169
|
+
if (active < 0 && handoff === void 0 && parks.length === 0) continue;
|
|
3170
|
+
conversations.push({
|
|
3171
|
+
id,
|
|
3172
|
+
root,
|
|
3173
|
+
...active < 0 ? {} : { active },
|
|
3174
|
+
...handoff === void 0 ? {} : { handoff },
|
|
3175
|
+
...parks.length === 0 ? {} : { parks }
|
|
3176
|
+
});
|
|
3177
|
+
}
|
|
1367
3178
|
const body = {
|
|
3179
|
+
version: SESSION_FILE_VERSION,
|
|
1368
3180
|
savedAt: this.clock.now(),
|
|
1369
|
-
tabs
|
|
1370
|
-
|
|
1371
|
-
...handoff === void 0 ? {} : { handoff }
|
|
3181
|
+
tabs,
|
|
3182
|
+
conversations
|
|
1372
3183
|
};
|
|
1373
3184
|
try {
|
|
1374
|
-
|
|
1375
|
-
|
|
3185
|
+
writeFileSync3(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
|
|
3186
|
+
renameSync2(`${this.file}.tmp`, this.file);
|
|
1376
3187
|
} catch {
|
|
1377
3188
|
}
|
|
1378
3189
|
});
|
|
@@ -1380,45 +3191,361 @@ var SessionFile = class {
|
|
|
1380
3191
|
/** Removes the file and stops saving (an idle stop). */
|
|
1381
3192
|
forget() {
|
|
1382
3193
|
this.forgotten = true;
|
|
1383
|
-
|
|
3194
|
+
rmSync2(this.file, { force: true });
|
|
3195
|
+
}
|
|
3196
|
+
/** Gives the conversations their pending handoffs and persistent parks back. */
|
|
3197
|
+
restoreState(state, saved) {
|
|
3198
|
+
for (const c of saved.conversations) {
|
|
3199
|
+
if (c.handoff !== void 0)
|
|
3200
|
+
state.noticeHandoff(c.id, c.root, c.handoff.callId, c.handoff.message);
|
|
3201
|
+
for (const p of c.parks ?? []) state.park(c.id, c.root, { ...p, persist: true });
|
|
3202
|
+
}
|
|
1384
3203
|
}
|
|
1385
3204
|
/**
|
|
1386
|
-
* Opens the saved tabs in a browser that has only its first blank tab
|
|
1387
|
-
*
|
|
3205
|
+
* Opens the saved tabs, each for its owner, in a browser that has only its first blank tab, and
|
|
3206
|
+
* gives each conversation its active tab back. The navigations are started, not awaited: the
|
|
3207
|
+
* first request after a restart does not wait for every page to load.
|
|
1388
3208
|
*/
|
|
1389
3209
|
async restoreTabs(session, saved) {
|
|
1390
|
-
if (saved.tabs.length === 0) return;
|
|
1391
3210
|
const ids = [];
|
|
1392
|
-
for (const
|
|
3211
|
+
for (const t of saved.tabs) {
|
|
1393
3212
|
try {
|
|
1394
|
-
|
|
1395
|
-
ids.push(session.tabIdOf(page));
|
|
1396
|
-
void session.viewerNav({ url: normalizeUrl(url) });
|
|
3213
|
+
ids.push(await session.restoreTab({ owner: t.owner, root: t.root }, t.url));
|
|
1397
3214
|
} catch {
|
|
3215
|
+
ids.push(void 0);
|
|
3216
|
+
}
|
|
3217
|
+
}
|
|
3218
|
+
for (const c of saved.conversations) {
|
|
3219
|
+
const id = c.active === void 0 ? void 0 : ids[c.active];
|
|
3220
|
+
if (id !== void 0) session.setActive(c.id, id);
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
};
|
|
3224
|
+
|
|
3225
|
+
// daemon/cursor.ts
|
|
3226
|
+
var CURSOR_MAX_FRAMES = 20;
|
|
3227
|
+
var MAX_DEPTH = 3;
|
|
3228
|
+
var WORLD = "capybara-cursor";
|
|
3229
|
+
var CURSOR_FUNCTION = `function (x, y) {
|
|
3230
|
+
const el = this.nodeType === 1 ? this : this.parentElement;
|
|
3231
|
+
if (!el) return { cursor: "default" };
|
|
3232
|
+
if (el.tagName === "IFRAME" || el.tagName === "FRAME") return { frame: true };
|
|
3233
|
+
const doc = el.ownerDocument;
|
|
3234
|
+
const view = doc.defaultView;
|
|
3235
|
+
const style = view.getComputedStyle(el);
|
|
3236
|
+
// "url(a.cur) 4 4, pointer": an image cursor's keyword fallback is the last item
|
|
3237
|
+
const parts = String(style.cursor).split(",");
|
|
3238
|
+
const cursor = parts[parts.length - 1].trim();
|
|
3239
|
+
if (cursor !== "auto") return { cursor };
|
|
3240
|
+
const NOT_TEXT = ["button", "submit", "reset", "checkbox", "radio", "range", "color", "file", "image", "hidden"];
|
|
3241
|
+
const tag = el.tagName;
|
|
3242
|
+
const editable = el.isContentEditable || tag === "TEXTAREA" ||
|
|
3243
|
+
(tag === "INPUT" && !NOT_TEXT.includes(String(el.type).toLowerCase()));
|
|
3244
|
+
if (editable && !el.disabled) return { cursor: "text" };
|
|
3245
|
+
if (style.userSelect === "none") return { cursor: "default" };
|
|
3246
|
+
const range = doc.caretRangeFromPoint ? doc.caretRangeFromPoint(x, y) : null;
|
|
3247
|
+
const node = range ? range.startContainer : null;
|
|
3248
|
+
if (!node || node.nodeType !== 3) return { cursor: "default" };
|
|
3249
|
+
const probe = doc.createRange();
|
|
3250
|
+
for (const [a, b] of [[range.startOffset, range.startOffset + 1], [range.startOffset - 1, range.startOffset]]) {
|
|
3251
|
+
if (a < 0 || b > node.length) continue;
|
|
3252
|
+
probe.setStart(node, a);
|
|
3253
|
+
probe.setEnd(node, b);
|
|
3254
|
+
for (const r of probe.getClientRects())
|
|
3255
|
+
if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) return { cursor: "text" };
|
|
3256
|
+
}
|
|
3257
|
+
return { cursor: "default" };
|
|
3258
|
+
}`;
|
|
3259
|
+
var CursorResolver = class {
|
|
3260
|
+
constructor(context, page, cdp) {
|
|
3261
|
+
this.context = context;
|
|
3262
|
+
this.page = page;
|
|
3263
|
+
this.cdp = cdp;
|
|
3264
|
+
page.on("framedetached", this.onFrameDetached);
|
|
3265
|
+
}
|
|
3266
|
+
context;
|
|
3267
|
+
page;
|
|
3268
|
+
cdp;
|
|
3269
|
+
/** Isolated world execution contexts, per CDP session and frame id. */
|
|
3270
|
+
worlds = /* @__PURE__ */ new WeakMap();
|
|
3271
|
+
/** Sessions of out-of-process frames entered, detached with their frame or on dispose. */
|
|
3272
|
+
sessions = /* @__PURE__ */ new Map();
|
|
3273
|
+
onFrameDetached = (frame) => {
|
|
3274
|
+
const cdp = this.sessions.get(frame);
|
|
3275
|
+
if (cdp === void 0) return;
|
|
3276
|
+
this.sessions.delete(frame);
|
|
3277
|
+
cdp.detach().catch(() => void 0);
|
|
3278
|
+
};
|
|
3279
|
+
/** How many out-of-process frame sessions are open (a test seam). */
|
|
3280
|
+
get openSessions() {
|
|
3281
|
+
return this.sessions.size;
|
|
3282
|
+
}
|
|
3283
|
+
/** Detaches the frame sessions this resolver opened (the viewer detached from the page). */
|
|
3284
|
+
dispose() {
|
|
3285
|
+
this.page.off("framedetached", this.onFrameDetached);
|
|
3286
|
+
for (const cdp of this.sessions.values()) cdp.detach().catch(() => void 0);
|
|
3287
|
+
this.sessions.clear();
|
|
3288
|
+
}
|
|
3289
|
+
/** The cursor Chromium would show at viewport point (x, y). */
|
|
3290
|
+
async at(x, y) {
|
|
3291
|
+
let cdp = this.cdp;
|
|
3292
|
+
let frame = this.page.mainFrame();
|
|
3293
|
+
let px = x;
|
|
3294
|
+
let py = y;
|
|
3295
|
+
for (let depth = 0; depth <= MAX_DEPTH; depth++) {
|
|
3296
|
+
const hit = await this.hitTest(cdp, px, py);
|
|
3297
|
+
const answer = await this.answerAt(cdp, hit, px, py);
|
|
3298
|
+
if (answer.cursor !== void 0) return toViewerCursor(answer.cursor);
|
|
3299
|
+
if (!answer.frame || depth === MAX_DEPTH) return "default";
|
|
3300
|
+
const box = await cdp.send("DOM.getBoxModel", { backendNodeId: hit.backendNodeId });
|
|
3301
|
+
const [left = 0, top = 0] = box.model.content;
|
|
3302
|
+
const [borderLeft = 0, borderTop = 0] = box.model.border;
|
|
3303
|
+
const child = await this.childAt(frame, borderLeft + (x - px), borderTop + (y - py));
|
|
3304
|
+
if (child === void 0) return "default";
|
|
3305
|
+
frame = child.frame;
|
|
3306
|
+
cdp = child.cdp;
|
|
3307
|
+
px = px - left;
|
|
3308
|
+
py = py - top;
|
|
3309
|
+
}
|
|
3310
|
+
return "default";
|
|
3311
|
+
}
|
|
3312
|
+
async hitTest(cdp, x, y) {
|
|
3313
|
+
return await cdp.send("DOM.getNodeForLocation", {
|
|
3314
|
+
x: Math.round(x),
|
|
3315
|
+
y: Math.round(y),
|
|
3316
|
+
includeUserAgentShadowDOM: false,
|
|
3317
|
+
ignorePointerEventsNone: false
|
|
3318
|
+
});
|
|
3319
|
+
}
|
|
3320
|
+
/** The answer for a hit node, at the point in the node's own frame. */
|
|
3321
|
+
async answerAt(cdp, hit, x, y) {
|
|
3322
|
+
const frameId = hit.frameId ?? await this.mainFrameId(cdp);
|
|
3323
|
+
const offset = await this.frameOffset(cdp, frameId);
|
|
3324
|
+
return this.run(cdp, frameId, hit.backendNodeId, x - offset.x, y - offset.y);
|
|
3325
|
+
}
|
|
3326
|
+
async run(cdp, frameId, backendNodeId, x, y) {
|
|
3327
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
3328
|
+
const contextId = await this.world(cdp, frameId, attempt > 0);
|
|
3329
|
+
try {
|
|
3330
|
+
const { object } = await cdp.send("DOM.resolveNode", {
|
|
3331
|
+
backendNodeId,
|
|
3332
|
+
executionContextId: contextId
|
|
3333
|
+
});
|
|
3334
|
+
if (object.objectId === void 0) return { cursor: "default" };
|
|
3335
|
+
const r = await cdp.send("Runtime.callFunctionOn", {
|
|
3336
|
+
objectId: object.objectId,
|
|
3337
|
+
functionDeclaration: CURSOR_FUNCTION,
|
|
3338
|
+
arguments: [{ value: x }, { value: y }],
|
|
3339
|
+
returnByValue: true
|
|
3340
|
+
});
|
|
3341
|
+
await cdp.send("Runtime.releaseObject", { objectId: object.objectId }).catch(() => {
|
|
3342
|
+
});
|
|
3343
|
+
return r.result.value ?? { cursor: "default" };
|
|
3344
|
+
} catch (e) {
|
|
3345
|
+
if (attempt > 0) throw e;
|
|
1398
3346
|
}
|
|
1399
3347
|
}
|
|
1400
|
-
|
|
1401
|
-
|
|
3348
|
+
return { cursor: "default" };
|
|
3349
|
+
}
|
|
3350
|
+
async world(cdp, frameId, fresh) {
|
|
3351
|
+
let byFrame = this.worlds.get(cdp);
|
|
3352
|
+
if (byFrame === void 0) {
|
|
3353
|
+
byFrame = /* @__PURE__ */ new Map();
|
|
3354
|
+
this.worlds.set(cdp, byFrame);
|
|
3355
|
+
}
|
|
3356
|
+
const known = byFrame.get(frameId);
|
|
3357
|
+
if (known !== void 0 && !fresh) return known;
|
|
3358
|
+
const { executionContextId } = await cdp.send("Page.createIsolatedWorld", {
|
|
3359
|
+
frameId,
|
|
3360
|
+
worldName: WORLD
|
|
3361
|
+
});
|
|
3362
|
+
byFrame.set(frameId, executionContextId);
|
|
3363
|
+
return executionContextId;
|
|
3364
|
+
}
|
|
3365
|
+
async mainFrameId(cdp) {
|
|
3366
|
+
const { frameTree } = await cdp.send("Page.getFrameTree");
|
|
3367
|
+
return frameTree.frame.id;
|
|
3368
|
+
}
|
|
3369
|
+
/** The offset of an in-process frame's viewport in the session's root (0 for its main frame). */
|
|
3370
|
+
async frameOffset(cdp, frameId) {
|
|
3371
|
+
if (frameId === await this.mainFrameId(cdp)) return { x: 0, y: 0 };
|
|
3372
|
+
const owner = await cdp.send("DOM.getFrameOwner", { frameId });
|
|
3373
|
+
const box = await cdp.send("DOM.getBoxModel", { backendNodeId: owner.backendNodeId });
|
|
3374
|
+
return { x: box.model.content[0] ?? 0, y: box.model.content[1] ?? 0 };
|
|
3375
|
+
}
|
|
3376
|
+
/**
|
|
3377
|
+
* The child frame of `parent` whose element's border box starts at (left, top), in the page's
|
|
3378
|
+
* (main frame) coordinates.
|
|
3379
|
+
*/
|
|
3380
|
+
async childAt(parent, left, top) {
|
|
3381
|
+
for (const child of parent.childFrames().slice(0, CURSOR_MAX_FRAMES)) {
|
|
3382
|
+
const handle = await child.frameElement().catch(() => null);
|
|
3383
|
+
const box = await handle?.boundingBox().catch(() => null);
|
|
3384
|
+
await handle?.dispose();
|
|
3385
|
+
if (box === null || box === void 0) continue;
|
|
3386
|
+
if (Math.abs(box.x - left) > 3 || Math.abs(box.y - top) > 3) continue;
|
|
3387
|
+
let cdp = this.sessions.get(child);
|
|
3388
|
+
if (cdp === void 0) {
|
|
3389
|
+
cdp = await this.context.newCDPSession(child);
|
|
3390
|
+
this.sessions.set(child, cdp);
|
|
3391
|
+
}
|
|
3392
|
+
return { frame: child, cdp };
|
|
3393
|
+
}
|
|
3394
|
+
return void 0;
|
|
3395
|
+
}
|
|
3396
|
+
};
|
|
3397
|
+
|
|
3398
|
+
// daemon/viewer-pacing.ts
|
|
3399
|
+
var TARGET_LINK_MS = 120;
|
|
3400
|
+
var PING_WINDOW = 10;
|
|
3401
|
+
var RTT_WINDOW = 16;
|
|
3402
|
+
var LINK_ALPHA = 0.5;
|
|
3403
|
+
var FramePacer = class {
|
|
3404
|
+
minIntervalMs;
|
|
3405
|
+
maxUnacked;
|
|
3406
|
+
inFlight = [];
|
|
3407
|
+
pings = [];
|
|
3408
|
+
rtts = [];
|
|
3409
|
+
lastSentAt = Number.NEGATIVE_INFINITY;
|
|
3410
|
+
link;
|
|
3411
|
+
constructor(opts) {
|
|
3412
|
+
this.minIntervalMs = 1e3 / opts.maxFps;
|
|
3413
|
+
this.maxUnacked = opts.maxUnacked;
|
|
3414
|
+
}
|
|
3415
|
+
/** The smoothed time frames take over the path's own round trip; undefined before any ack. */
|
|
3416
|
+
get linkMs() {
|
|
3417
|
+
return this.link;
|
|
3418
|
+
}
|
|
3419
|
+
get unacked() {
|
|
3420
|
+
return this.inFlight.length;
|
|
3421
|
+
}
|
|
3422
|
+
/** The path's round trip without queueing, as far as measured. */
|
|
3423
|
+
get baseRttMs() {
|
|
3424
|
+
if (this.pings.length > 0) return Math.min(...this.pings);
|
|
3425
|
+
if (this.rtts.length > 0) return Math.min(...this.rtts);
|
|
3426
|
+
return void 0;
|
|
3427
|
+
}
|
|
3428
|
+
/** Whether a frame may be sent at `now`, and if only the rate cap holds it, for how long. */
|
|
3429
|
+
decide(now) {
|
|
3430
|
+
const n = this.inFlight.length;
|
|
3431
|
+
if (n >= this.maxUnacked) return { ok: false };
|
|
3432
|
+
if (n > 0 && this.link !== void 0 && this.link > TARGET_LINK_MS) return { ok: false };
|
|
3433
|
+
const wait = this.lastSentAt + this.minIntervalMs - now;
|
|
3434
|
+
return wait > 0 ? { ok: false, waitMs: wait } : { ok: true };
|
|
3435
|
+
}
|
|
3436
|
+
/** Records a frame sent at `now` (every frame counts, the first after an attach too). */
|
|
3437
|
+
sent(seq, now) {
|
|
3438
|
+
this.inFlight.push({ seq, at: now });
|
|
3439
|
+
this.lastSentAt = now;
|
|
3440
|
+
}
|
|
3441
|
+
/** Records the viewer's ack of every frame up to `seq` at `now`; returns the sample, if any. */
|
|
3442
|
+
acked(seq, now) {
|
|
3443
|
+
let last;
|
|
3444
|
+
while (this.inFlight.length > 0 && this.inFlight[0].seq <= seq) {
|
|
3445
|
+
last = this.inFlight.shift();
|
|
3446
|
+
}
|
|
3447
|
+
if (last === void 0) return void 0;
|
|
3448
|
+
const rtt = Math.max(0, now - last.at);
|
|
3449
|
+
this.rtts.push(rtt);
|
|
3450
|
+
if (this.rtts.length > RTT_WINDOW) this.rtts.shift();
|
|
3451
|
+
const sample = Math.max(0, rtt - (this.baseRttMs ?? rtt));
|
|
3452
|
+
this.link = this.link === void 0 ? sample : this.link * (1 - LINK_ALPHA) + sample * LINK_ALPHA;
|
|
3453
|
+
return sample;
|
|
3454
|
+
}
|
|
3455
|
+
/** Records a ping's round trip (a tiny message both ways on the same path as the frames). */
|
|
3456
|
+
pinged(rttMs) {
|
|
3457
|
+
if (!Number.isFinite(rttMs) || rttMs < 0) return;
|
|
3458
|
+
this.pings.push(rttMs);
|
|
3459
|
+
if (this.pings.length > PING_WINDOW) this.pings.shift();
|
|
3460
|
+
}
|
|
3461
|
+
/** Forgets frames in flight (a screencast restart: their acks may never come). */
|
|
3462
|
+
reset() {
|
|
3463
|
+
this.inFlight.length = 0;
|
|
3464
|
+
}
|
|
3465
|
+
};
|
|
3466
|
+
var QUALITY_STEPS = [60, 45, 35, 25];
|
|
3467
|
+
var SHRINK_STEPS = [1, 0.8, 0.65, 0.5, 0.35, 0.25];
|
|
3468
|
+
var ADAPT_SHRINK_STEPS = 4;
|
|
3469
|
+
var UP_AFTER_QUICK_FRAMES = 6;
|
|
3470
|
+
var FrameQuality = class {
|
|
3471
|
+
step = 0;
|
|
3472
|
+
quick = 0;
|
|
3473
|
+
get quality() {
|
|
3474
|
+
return QUALITY_STEPS[Math.min(this.step, QUALITY_STEPS.length - 1)];
|
|
3475
|
+
}
|
|
3476
|
+
get shrink() {
|
|
3477
|
+
const s = Math.max(0, this.step - (QUALITY_STEPS.length - 1));
|
|
3478
|
+
return SHRINK_STEPS[Math.min(s, SHRINK_STEPS.length - 1)];
|
|
3479
|
+
}
|
|
3480
|
+
/** The lowest step the link adaptation goes to. */
|
|
3481
|
+
get adaptMaxStep() {
|
|
3482
|
+
return QUALITY_STEPS.length - 1 + ADAPT_SHRINK_STEPS - 1;
|
|
3483
|
+
}
|
|
3484
|
+
get maxStep() {
|
|
3485
|
+
return QUALITY_STEPS.length - 1 + SHRINK_STEPS.length - 1;
|
|
3486
|
+
}
|
|
3487
|
+
/** One acked frame's link time; true when the step changed (restart the screencast). */
|
|
3488
|
+
observe(linkMs) {
|
|
3489
|
+
if (linkMs > TARGET_LINK_MS * 1.25) {
|
|
3490
|
+
this.quick = 0;
|
|
3491
|
+
if (this.step >= this.adaptMaxStep) return false;
|
|
3492
|
+
this.step++;
|
|
3493
|
+
return true;
|
|
3494
|
+
}
|
|
3495
|
+
if (linkMs < TARGET_LINK_MS / 2) {
|
|
3496
|
+
this.quick++;
|
|
3497
|
+
if (this.quick >= UP_AFTER_QUICK_FRAMES && this.step > 0) {
|
|
3498
|
+
this.step--;
|
|
3499
|
+
this.quick = 0;
|
|
3500
|
+
return true;
|
|
3501
|
+
}
|
|
3502
|
+
} else this.quick = 0;
|
|
3503
|
+
return false;
|
|
3504
|
+
}
|
|
3505
|
+
/** A frame too large for one message: always one step smaller. */
|
|
3506
|
+
tooLarge() {
|
|
3507
|
+
this.quick = 0;
|
|
3508
|
+
if (this.step >= this.maxStep) return false;
|
|
3509
|
+
this.step++;
|
|
3510
|
+
return true;
|
|
1402
3511
|
}
|
|
1403
3512
|
};
|
|
1404
3513
|
|
|
1405
3514
|
// daemon/viewer.ts
|
|
1406
|
-
var
|
|
1407
|
-
var
|
|
1408
|
-
var
|
|
3515
|
+
var VIEWER_PING_MS = 1e3;
|
|
3516
|
+
var RESTART_MIN_MS = 500;
|
|
3517
|
+
var ENCODE_MAX_INTERVAL_MS = 500;
|
|
3518
|
+
var CURSOR_TIMEOUT_MS = 200;
|
|
1409
3519
|
var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.max(16, Math.min(max, Math.floor(n))) : max;
|
|
1410
3520
|
var ViewerSession = class {
|
|
1411
3521
|
browser;
|
|
1412
3522
|
state;
|
|
3523
|
+
/** The viewer's conversation and the root of its tree (from the kernel's viewer context). */
|
|
3524
|
+
conv;
|
|
3525
|
+
root;
|
|
3526
|
+
/** The tab the person (or a new handoff) chose to show; cleared when it leaves the tree. */
|
|
3527
|
+
choice;
|
|
3528
|
+
/** The tab shown now (computed with every state). */
|
|
3529
|
+
shown;
|
|
3530
|
+
/** The other conversation the viewer pins because it shows one of its tabs. */
|
|
3531
|
+
pinnedOwner;
|
|
3532
|
+
/** Group keys of the tree's other conversations, in order of first appearance. */
|
|
3533
|
+
groups = /* @__PURE__ */ new Map();
|
|
3534
|
+
/** The tree's handoffs seen so far (a new one moves the shown tab to its conversation). */
|
|
3535
|
+
seenHandoffs = /* @__PURE__ */ new Set();
|
|
1413
3536
|
out;
|
|
1414
3537
|
clock;
|
|
1415
3538
|
frameMaxBytes;
|
|
1416
3539
|
unsubscribe = [];
|
|
1417
3540
|
maxWidth = VIEWPORT.width;
|
|
1418
3541
|
maxHeight = VIEWPORT.height;
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
3542
|
+
pacer = new FramePacer({
|
|
3543
|
+
maxFps: VIEWER_MAX_FPS,
|
|
3544
|
+
maxUnacked: VIEWER_UNACKED_FRAMES
|
|
3545
|
+
});
|
|
3546
|
+
/** Quality and scale: lowered while frames are slow on the link or over the message cap. */
|
|
3547
|
+
frameQuality = new FrameQuality();
|
|
3548
|
+
lastRestartAt = Number.NEGATIVE_INFINITY;
|
|
1422
3549
|
started = false;
|
|
1423
3550
|
closed = false;
|
|
1424
3551
|
page;
|
|
@@ -1428,17 +3555,48 @@ var ViewerSession = class {
|
|
|
1428
3555
|
inputChain = Promise.resolve();
|
|
1429
3556
|
/** Bumped on close and hand back: input queued before it is dropped, not replayed. */
|
|
1430
3557
|
inputGen = 0;
|
|
3558
|
+
/**
|
|
3559
|
+
* The newest pointer position not yet applied, while a move for it waits on the input chain:
|
|
3560
|
+
* later moves replace it (the newest wins) instead of queueing behind it.
|
|
3561
|
+
*/
|
|
3562
|
+
moveSlot;
|
|
3563
|
+
/** The cursor last sent (reset when control returns to the agent). */
|
|
3564
|
+
cursor;
|
|
3565
|
+
/** Resolves cursors on the attached page (off the input chain, see {@link wantCursor}). */
|
|
3566
|
+
cursorResolver;
|
|
3567
|
+
/** The newest pointer position whose cursor is wanted; one resolution runs at a time. */
|
|
3568
|
+
cursorPoint;
|
|
3569
|
+
/** The resolver a resolution loop runs for (one loop per resolver, one lookup at a time). */
|
|
3570
|
+
cursorLoop;
|
|
3571
|
+
/**
|
|
3572
|
+
* Keys and buttons this viewer pressed and has not released: released for the agent when
|
|
3573
|
+
* control returns to it or the viewer ends, whatever reached the page of the person's input.
|
|
3574
|
+
*/
|
|
3575
|
+
heldKeys = /* @__PURE__ */ new Map();
|
|
3576
|
+
heldButtons = /* @__PURE__ */ new Map();
|
|
1431
3577
|
seq = 0;
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
3578
|
+
/**
|
|
3579
|
+
* The newest screencast frame waiting for room (viewer acks, transport, rate cap). A newer one
|
|
3580
|
+
* replaces it: a frame is never queued behind a stale one.
|
|
3581
|
+
*/
|
|
1435
3582
|
pending;
|
|
3583
|
+
/** Chromium frames received but not acked to Chromium yet (it encodes the next after an ack). */
|
|
3584
|
+
encodeAck;
|
|
3585
|
+
encodeTimer;
|
|
3586
|
+
lastEncodeAckAt = Number.NEGATIVE_INFINITY;
|
|
1436
3587
|
pumpTimer;
|
|
3588
|
+
pingTimer;
|
|
3589
|
+
pingSeq = 0;
|
|
3590
|
+
pingsSent = /* @__PURE__ */ new Map();
|
|
1437
3591
|
draining = false;
|
|
1438
3592
|
stateQueued = false;
|
|
3593
|
+
lastControl = "agent";
|
|
1439
3594
|
constructor(opts) {
|
|
1440
3595
|
this.browser = opts.browser;
|
|
1441
3596
|
this.state = opts.state;
|
|
3597
|
+
this.conv = opts.conversationId;
|
|
3598
|
+
this.root = opts.rootConversationId;
|
|
3599
|
+
this.state.pin(this.conv, this.root);
|
|
1442
3600
|
this.out = opts.transport;
|
|
1443
3601
|
this.clock = opts.clock;
|
|
1444
3602
|
this.frameMaxBytes = opts.frameMaxBytes;
|
|
@@ -1454,12 +3612,17 @@ var ViewerSession = class {
|
|
|
1454
3612
|
if (m.t !== "hello") return;
|
|
1455
3613
|
this.started = true;
|
|
1456
3614
|
this.setSize(m.maxWidth, m.maxHeight);
|
|
3615
|
+
this.lastControl = this.state.control;
|
|
1457
3616
|
this.unsubscribe.push(
|
|
1458
3617
|
this.browser.on((e) => this.onSession(e)),
|
|
1459
|
-
this.state.onChange(() => this.
|
|
3618
|
+
this.state.onChange(() => this.onControl())
|
|
1460
3619
|
);
|
|
3620
|
+
const pending = this.state.handoffs(this.root);
|
|
3621
|
+
this.seenHandoffs = new Set(pending.map(handoffKey));
|
|
3622
|
+
const newest = pending.at(-1);
|
|
3623
|
+
if (newest !== void 0) this.choice = this.browser.activeTabOf(newest.conversationId);
|
|
1461
3624
|
this.sendState();
|
|
1462
|
-
|
|
3625
|
+
this.ping();
|
|
1463
3626
|
return;
|
|
1464
3627
|
}
|
|
1465
3628
|
switch (m.t) {
|
|
@@ -1472,39 +3635,64 @@ var ViewerSession = class {
|
|
|
1472
3635
|
});
|
|
1473
3636
|
return;
|
|
1474
3637
|
case "frame-ack":
|
|
1475
|
-
if (typeof m.seq === "number"
|
|
3638
|
+
if (typeof m.seq === "number") this.onAck(Math.min(m.seq, this.seq));
|
|
1476
3639
|
this.pump();
|
|
1477
3640
|
return;
|
|
3641
|
+
case "pong": {
|
|
3642
|
+
const sentAt = typeof m.id === "number" ? this.pingsSent.get(m.id) : void 0;
|
|
3643
|
+
if (sentAt !== void 0) {
|
|
3644
|
+
this.pingsSent.delete(m.id);
|
|
3645
|
+
this.pacer.pinged(this.clock.now() - sentAt);
|
|
3646
|
+
}
|
|
3647
|
+
return;
|
|
3648
|
+
}
|
|
1478
3649
|
case "takeover":
|
|
1479
|
-
this.state.takeover();
|
|
3650
|
+
this.state.takeover(this.browser.owningConversations());
|
|
1480
3651
|
return;
|
|
1481
3652
|
case "handback":
|
|
1482
3653
|
this.inputGen++;
|
|
1483
3654
|
this.state.handback();
|
|
1484
3655
|
return;
|
|
1485
3656
|
case "mouse":
|
|
1486
|
-
|
|
3657
|
+
if (m.kind === "move") this.move(m);
|
|
3658
|
+
else this.input(() => this.mouse(m));
|
|
1487
3659
|
return;
|
|
1488
3660
|
case "key":
|
|
1489
3661
|
this.input(() => this.key(m));
|
|
1490
3662
|
return;
|
|
1491
3663
|
case "nav":
|
|
1492
|
-
this.input(
|
|
1493
|
-
|
|
3664
|
+
this.input(async () => {
|
|
3665
|
+
let page = this.shownPage();
|
|
3666
|
+
if (page === void 0) {
|
|
3667
|
+
if (typeof m.url !== "string") return;
|
|
3668
|
+
page = await this.openOwnTab();
|
|
3669
|
+
if (page === void 0) return;
|
|
3670
|
+
}
|
|
3671
|
+
this.concern(this.browser.tabIdOf(page));
|
|
3672
|
+
await this.browser.viewerNav(page, {
|
|
1494
3673
|
...typeof m.url === "string" ? { url: m.url } : {},
|
|
1495
3674
|
...m.action === void 0 ? {} : { action: m.action }
|
|
1496
|
-
})
|
|
1497
|
-
);
|
|
3675
|
+
});
|
|
3676
|
+
});
|
|
3677
|
+
return;
|
|
3678
|
+
case "show":
|
|
3679
|
+
if (typeof m.tabId === "string" && this.inTree(m.tabId)) {
|
|
3680
|
+
this.choice = m.tabId;
|
|
3681
|
+
this.queueState();
|
|
3682
|
+
}
|
|
1498
3683
|
return;
|
|
1499
3684
|
case "tab":
|
|
3685
|
+
if (m.action === "adopt") {
|
|
3686
|
+
this.adopt(m.tabId);
|
|
3687
|
+
return;
|
|
3688
|
+
}
|
|
1500
3689
|
this.input(async () => {
|
|
1501
3690
|
try {
|
|
1502
|
-
if (m.action === "open") await this.
|
|
1503
|
-
else if (m.action === "switch" && m.tabId !== void 0)
|
|
1504
|
-
|
|
1505
|
-
|
|
3691
|
+
if (m.action === "open") await this.openOwnTab();
|
|
3692
|
+
else if (m.action === "switch" && m.tabId !== void 0) this.switchTo(m.tabId);
|
|
3693
|
+
else if (m.action === "close" && m.tabId !== void 0 && this.inTree(m.tabId)) {
|
|
3694
|
+
this.concern(m.tabId);
|
|
1506
3695
|
await this.browser.tabById(m.tabId).close();
|
|
1507
|
-
await this.browser.activePage();
|
|
1508
3696
|
}
|
|
1509
3697
|
} catch {
|
|
1510
3698
|
}
|
|
@@ -1512,26 +3700,206 @@ var ViewerSession = class {
|
|
|
1512
3700
|
return;
|
|
1513
3701
|
}
|
|
1514
3702
|
}
|
|
1515
|
-
/**
|
|
3703
|
+
/** Whether a tab belongs to the viewer's tree. */
|
|
3704
|
+
inTree(tabId) {
|
|
3705
|
+
return this.browser.ownerOf(tabId)?.root === this.root && this.browser.pageById(tabId) !== void 0;
|
|
3706
|
+
}
|
|
3707
|
+
/** The shown tab's page, if the tree has one. */
|
|
3708
|
+
shownPage() {
|
|
3709
|
+
return this.browser.pageById(this.shown);
|
|
3710
|
+
}
|
|
3711
|
+
/** The person used a tab during the takeover: its owner gets the hand back note. */
|
|
3712
|
+
concern(tabId) {
|
|
3713
|
+
if (tabId === void 0) return;
|
|
3714
|
+
this.state.concern(this.browser.ownerOf(tabId)?.owner);
|
|
3715
|
+
}
|
|
3716
|
+
/**
|
|
3717
|
+
* A tab the person opens: owned by the viewer's conversation, made its active tab and shown
|
|
3718
|
+
* (the caps apply; a refusal opens nothing).
|
|
3719
|
+
*/
|
|
3720
|
+
async openOwnTab() {
|
|
3721
|
+
try {
|
|
3722
|
+
const page = this.browser.countOf(this.conv) === 0 ? await this.browser.pageFor(this.conv, this.root) : await this.browser.openTab(this.conv, this.root);
|
|
3723
|
+
this.state.concern(this.conv);
|
|
3724
|
+
this.choice = void 0;
|
|
3725
|
+
this.queueState();
|
|
3726
|
+
return page;
|
|
3727
|
+
} catch {
|
|
3728
|
+
return void 0;
|
|
3729
|
+
}
|
|
3730
|
+
}
|
|
3731
|
+
/**
|
|
3732
|
+
* Shows a tab of the tree and brings it to the front (a viewer in control decides what is
|
|
3733
|
+
* front). A tab of the viewer's own conversation also becomes its active tab (the person chose
|
|
3734
|
+
* it); another conversation's tab changes only the shown tab, never that agent's active tab.
|
|
3735
|
+
*/
|
|
3736
|
+
switchTo(tabId) {
|
|
3737
|
+
if (!this.inTree(tabId)) return;
|
|
3738
|
+
if (this.browser.ownerOf(tabId)?.owner === this.conv) {
|
|
3739
|
+
this.browser.setActive(this.conv, tabId);
|
|
3740
|
+
this.choice = void 0;
|
|
3741
|
+
} else this.choice = tabId;
|
|
3742
|
+
void this.browser.bringToFront(tabId);
|
|
3743
|
+
this.queueState();
|
|
3744
|
+
}
|
|
3745
|
+
/**
|
|
3746
|
+
* Moves another tree's tab (or an unowned one) to the viewer's conversation, as the tool's adopt;
|
|
3747
|
+
* a tab of the viewer's own tree is ignored (inside the tree the person drives tabs without
|
|
3748
|
+
* moving them). A tab whose owner is in use answers the `tab_in_use` notice.
|
|
3749
|
+
*/
|
|
3750
|
+
adopt(tabId) {
|
|
3751
|
+
if (typeof tabId !== "string" || this.browser.pageById(tabId) === void 0) return;
|
|
3752
|
+
if (this.browser.ownerOf(tabId)?.root === this.root) return;
|
|
3753
|
+
let result;
|
|
3754
|
+
try {
|
|
3755
|
+
result = this.browser.adopt(this.conv, this.root, tabId);
|
|
3756
|
+
} catch {
|
|
3757
|
+
return;
|
|
3758
|
+
}
|
|
3759
|
+
if (result === "in_use") this.send({ t: "notice", code: "tab_in_use" });
|
|
3760
|
+
else if (result === "cap") this.send({ t: "notice", code: "tab_cap" });
|
|
3761
|
+
else if (result === "ok") {
|
|
3762
|
+
this.choice = void 0;
|
|
3763
|
+
this.queueState();
|
|
3764
|
+
}
|
|
3765
|
+
}
|
|
3766
|
+
/**
|
|
3767
|
+
* Runs viewer input in arrival order, apart from the screencast chain, and only while the person
|
|
3768
|
+
* holds control: input from a viewer in the watch state (the agent drives) is dropped, both when
|
|
3769
|
+
* it arrives and when its turn comes.
|
|
3770
|
+
*/
|
|
1516
3771
|
input(fn) {
|
|
3772
|
+
if (this.state.control !== "user") return;
|
|
3773
|
+
this.moveSlot = void 0;
|
|
1517
3774
|
const gen = this.inputGen;
|
|
1518
|
-
const guarded = () => gen === this.inputGen && !this.closed ? fn() : Promise.resolve();
|
|
3775
|
+
const guarded = () => gen === this.inputGen && !this.closed && this.state.control === "user" ? fn() : Promise.resolve();
|
|
1519
3776
|
const run = this.inputChain.then(guarded, guarded);
|
|
1520
3777
|
this.inputChain = run.catch(() => void 0);
|
|
1521
3778
|
}
|
|
1522
|
-
/**
|
|
3779
|
+
/** A pointer move: coalesced while one waits (the newest position wins), then the cursor. */
|
|
3780
|
+
move(m) {
|
|
3781
|
+
if (this.state.control !== "user") return;
|
|
3782
|
+
const p = point(m);
|
|
3783
|
+
if (p === null) return;
|
|
3784
|
+
if (this.moveSlot !== void 0) {
|
|
3785
|
+
this.moveSlot.x = p.x;
|
|
3786
|
+
this.moveSlot.y = p.y;
|
|
3787
|
+
return;
|
|
3788
|
+
}
|
|
3789
|
+
const slot = { ...p };
|
|
3790
|
+
this.input(async () => {
|
|
3791
|
+
if (this.moveSlot === slot) this.moveSlot = void 0;
|
|
3792
|
+
const page = this.shownPage();
|
|
3793
|
+
if (page === void 0) return;
|
|
3794
|
+
try {
|
|
3795
|
+
await page.mouse.move(slot.x, slot.y);
|
|
3796
|
+
} catch {
|
|
3797
|
+
return;
|
|
3798
|
+
}
|
|
3799
|
+
this.wantCursor(slot.x, slot.y);
|
|
3800
|
+
});
|
|
3801
|
+
this.moveSlot = slot;
|
|
3802
|
+
}
|
|
3803
|
+
/**
|
|
3804
|
+
* Asks for the page's cursor at (x, y): resolved off the input chain (a click never waits for
|
|
3805
|
+
* it), the newest position wins while one resolution runs, and an answer later than
|
|
3806
|
+
* CURSOR_TIMEOUT_MS is dropped.
|
|
3807
|
+
*/
|
|
3808
|
+
wantCursor(x, y) {
|
|
3809
|
+
this.cursorPoint = { x, y };
|
|
3810
|
+
const resolver = this.cursorResolver;
|
|
3811
|
+
if (resolver === void 0 || this.cursorLoop === resolver) return;
|
|
3812
|
+
this.cursorLoop = resolver;
|
|
3813
|
+
void (async () => {
|
|
3814
|
+
try {
|
|
3815
|
+
while (!this.closed && this.cursorResolver === resolver) {
|
|
3816
|
+
const p = this.cursorPoint;
|
|
3817
|
+
this.cursorPoint = void 0;
|
|
3818
|
+
if (p === void 0) return;
|
|
3819
|
+
const started = this.clock.now();
|
|
3820
|
+
const cursor = await resolver.at(p.x, p.y).catch(() => void 0);
|
|
3821
|
+
if (cursor === void 0 || this.clock.now() - started > CURSOR_TIMEOUT_MS) continue;
|
|
3822
|
+
if (this.cursorPoint !== void 0) continue;
|
|
3823
|
+
if (cursor === this.cursor || this.closed || this.state.control !== "user") continue;
|
|
3824
|
+
this.cursor = cursor;
|
|
3825
|
+
this.send({ t: "cursor", cursor });
|
|
3826
|
+
}
|
|
3827
|
+
} finally {
|
|
3828
|
+
if (this.cursorLoop === resolver) this.cursorLoop = void 0;
|
|
3829
|
+
}
|
|
3830
|
+
})();
|
|
3831
|
+
}
|
|
3832
|
+
/**
|
|
3833
|
+
* Releases the keys and buttons this viewer still holds (straight, not on the input chain and
|
|
3834
|
+
* not through the control gate): the agent must not inherit a held Shift or a drag.
|
|
3835
|
+
*/
|
|
3836
|
+
async releaseHeld() {
|
|
3837
|
+
if (this.heldKeys.size === 0 && this.heldButtons.size === 0) return;
|
|
3838
|
+
const keys = [...this.heldKeys];
|
|
3839
|
+
const buttons = [...this.heldButtons];
|
|
3840
|
+
this.heldKeys.clear();
|
|
3841
|
+
this.heldButtons.clear();
|
|
3842
|
+
for (const [key2, page] of keys) await page.keyboard.up(key2).catch(() => void 0);
|
|
3843
|
+
for (const [button, page] of buttons) {
|
|
3844
|
+
await page.mouse.move(-1, -1).catch(() => void 0);
|
|
3845
|
+
await page.mouse.up({ button }).catch(() => void 0);
|
|
3846
|
+
}
|
|
3847
|
+
}
|
|
3848
|
+
/** Whether input this viewer applied should stay applied (still in control, not closed). */
|
|
3849
|
+
get driving() {
|
|
3850
|
+
return !this.closed && this.state.control === "user";
|
|
3851
|
+
}
|
|
3852
|
+
/** Ends the viewer: stops its screencast and its subscriptions, and lets go of its pins. */
|
|
1523
3853
|
async close() {
|
|
1524
3854
|
if (this.closed) return;
|
|
1525
3855
|
this.closed = true;
|
|
1526
3856
|
this.inputGen++;
|
|
3857
|
+
this.state.unpin(this.conv);
|
|
3858
|
+
if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
|
|
3859
|
+
this.pinnedOwner = void 0;
|
|
3860
|
+
await this.releaseHeld();
|
|
1527
3861
|
for (const u of this.unsubscribe.splice(0)) u();
|
|
1528
|
-
|
|
3862
|
+
for (const t of [this.pumpTimer, this.pingTimer, this.encodeTimer])
|
|
3863
|
+
if (t !== void 0) this.clock.cancel(t);
|
|
1529
3864
|
await this.serial(() => this.detach());
|
|
1530
3865
|
}
|
|
1531
3866
|
setSize(w, h) {
|
|
1532
3867
|
this.maxWidth = clampDim(w, VIEWPORT.width);
|
|
1533
3868
|
this.maxHeight = clampDim(h, VIEWPORT.height);
|
|
1534
|
-
|
|
3869
|
+
}
|
|
3870
|
+
/** Pings the viewer every VIEWER_PING_MS (its pong measures the path, see the pacing). */
|
|
3871
|
+
ping() {
|
|
3872
|
+
if (this.closed) return;
|
|
3873
|
+
const id = ++this.pingSeq;
|
|
3874
|
+
this.pingsSent.set(id, this.clock.now());
|
|
3875
|
+
for (const old of this.pingsSent.keys()) if (old < id - 4) this.pingsSent.delete(old);
|
|
3876
|
+
this.send({ t: "ping", id });
|
|
3877
|
+
this.pingTimer = this.clock.schedule(() => this.ping(), VIEWER_PING_MS);
|
|
3878
|
+
}
|
|
3879
|
+
/**
|
|
3880
|
+
* Control or handoffs changed: a new state; input of the old control dropped; a new handoff of
|
|
3881
|
+
* the tree shows its conversation's active tab.
|
|
3882
|
+
*/
|
|
3883
|
+
onControl() {
|
|
3884
|
+
const pending = this.state.handoffs(this.root);
|
|
3885
|
+
const fresh = pending.filter((h) => !this.seenHandoffs.has(handoffKey(h))).at(-1);
|
|
3886
|
+
this.seenHandoffs = new Set(pending.map(handoffKey));
|
|
3887
|
+
if (fresh !== void 0) {
|
|
3888
|
+
const tab = this.browser.activeTabOf(fresh.conversationId);
|
|
3889
|
+
if (tab !== void 0) this.choice = tab;
|
|
3890
|
+
}
|
|
3891
|
+
const control = this.state.control;
|
|
3892
|
+
if (control !== this.lastControl) {
|
|
3893
|
+
this.lastControl = control;
|
|
3894
|
+
this.moveSlot = void 0;
|
|
3895
|
+
this.cursor = void 0;
|
|
3896
|
+
this.cursorPoint = void 0;
|
|
3897
|
+
if (control === "agent") {
|
|
3898
|
+
this.inputGen++;
|
|
3899
|
+
void this.releaseHeld();
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3902
|
+
this.queueState();
|
|
1535
3903
|
}
|
|
1536
3904
|
serial(fn) {
|
|
1537
3905
|
const run = this.chain.then(fn, fn);
|
|
@@ -1545,45 +3913,58 @@ var ViewerSession = class {
|
|
|
1545
3913
|
*/
|
|
1546
3914
|
fitted(m) {
|
|
1547
3915
|
const fits = (x) => Buffer.byteLength(JSON.stringify(x)) <= this.frameMaxBytes;
|
|
1548
|
-
if (
|
|
3916
|
+
if (fits(m)) return m;
|
|
1549
3917
|
let small;
|
|
1550
3918
|
if (m.t === "state") {
|
|
1551
|
-
const
|
|
3919
|
+
const plain = { ...m, tabs: m.tabs.map(({ favicon: _icon, ...t }) => t) };
|
|
3920
|
+
if (fits(plain)) return plain;
|
|
3921
|
+
m = plain;
|
|
1552
3922
|
small = {
|
|
1553
3923
|
...m,
|
|
1554
|
-
tabs: m.tabs.map((t) => ({
|
|
1555
|
-
|
|
3924
|
+
tabs: m.tabs.map((t) => ({
|
|
3925
|
+
...t,
|
|
3926
|
+
title: clip(t.title, 200),
|
|
3927
|
+
url: clip(t.url, 200),
|
|
3928
|
+
...t.blocker === void 0 ? {} : { blocker: { ...t.blocker, url: clip(t.blocker.url, 200) } }
|
|
3929
|
+
})),
|
|
3930
|
+
otherTabs: m.otherTabs.map((t) => ({
|
|
3931
|
+
...t,
|
|
3932
|
+
title: clip(t.title, 200),
|
|
3933
|
+
url: clip(t.url, 200)
|
|
3934
|
+
})),
|
|
3935
|
+
handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) }))
|
|
1556
3936
|
};
|
|
1557
3937
|
} else if (m.t === "dialog") {
|
|
1558
3938
|
small = { ...m, message: clip(m.message, 200) };
|
|
1559
|
-
} else {
|
|
3939
|
+
} else if (m.t === "blocked") {
|
|
1560
3940
|
small = { ...m, url: clip(m.url, 200) };
|
|
1561
|
-
}
|
|
3941
|
+
} else return null;
|
|
1562
3942
|
return fits(small) ? small : null;
|
|
1563
3943
|
}
|
|
3944
|
+
/** Sends a JSON message at once: it never waits behind a held frame. */
|
|
1564
3945
|
send(raw) {
|
|
1565
3946
|
if (this.closed) return;
|
|
1566
3947
|
const m = this.fitted(raw);
|
|
1567
3948
|
if (m === null) return;
|
|
1568
|
-
if (!this.out.send(m)
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
3949
|
+
if (!this.out.send(m)) this.awaitDrain();
|
|
3950
|
+
}
|
|
3951
|
+
awaitDrain() {
|
|
3952
|
+
if (this.draining) return;
|
|
3953
|
+
this.draining = true;
|
|
3954
|
+
this.out.whenDrained().then(() => {
|
|
3955
|
+
this.draining = false;
|
|
3956
|
+
this.pump();
|
|
3957
|
+
});
|
|
1575
3958
|
}
|
|
1576
3959
|
onSession(e) {
|
|
1577
3960
|
if (e.type === "state") this.queueState();
|
|
1578
3961
|
else if (e.type === "active") {
|
|
3962
|
+
if (e.conversationId === this.conv) this.choice = void 0;
|
|
3963
|
+
else if (this.shown !== void 0 && this.browser.ownerOf(this.shown)?.owner === e.conversationId)
|
|
3964
|
+
this.choice = this.browser.activeTabOf(e.conversationId);
|
|
1579
3965
|
this.queueState();
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
if (page === this.page) return;
|
|
1583
|
-
await this.detach();
|
|
1584
|
-
await this.attach();
|
|
1585
|
-
});
|
|
1586
|
-
} else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
|
|
3966
|
+
} else if (e.root !== this.root) return;
|
|
3967
|
+
else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
|
|
1587
3968
|
else this.send({ t: "dialog", kind: e.kind, message: e.message });
|
|
1588
3969
|
}
|
|
1589
3970
|
/** Coalesces bursts of changes into one state message. */
|
|
@@ -1595,40 +3976,119 @@ var ViewerSession = class {
|
|
|
1595
3976
|
this.sendState();
|
|
1596
3977
|
});
|
|
1597
3978
|
}
|
|
3979
|
+
/**
|
|
3980
|
+
* The tab to show: the chosen one while it is in the tree; else the viewer's conversation's
|
|
3981
|
+
* active tab; else the active tab of the tree's conversation that acted last; else the tree's
|
|
3982
|
+
* first tab; none when the tree owns no tab.
|
|
3983
|
+
*/
|
|
3984
|
+
computeShown(tree) {
|
|
3985
|
+
if (this.choice !== void 0 && tree.some((t) => t.id === this.choice)) return this.choice;
|
|
3986
|
+
this.choice = void 0;
|
|
3987
|
+
const own = this.browser.activeTabOf(this.conv);
|
|
3988
|
+
if (own !== void 0) return own;
|
|
3989
|
+
let best;
|
|
3990
|
+
for (const owner of new Set(tree.map((t) => t.owner))) {
|
|
3991
|
+
if (owner === void 0) continue;
|
|
3992
|
+
const tab = this.browser.activeTabOf(owner);
|
|
3993
|
+
const order = this.browser.actedOrder(owner);
|
|
3994
|
+
if (tab !== void 0 && (best === void 0 || order > best.order)) best = { tab, order };
|
|
3995
|
+
}
|
|
3996
|
+
return best?.tab ?? tree[0]?.id;
|
|
3997
|
+
}
|
|
3998
|
+
/** Pins the owner of the shown tab (besides the viewer's own conversation). */
|
|
3999
|
+
pinShownOwner() {
|
|
4000
|
+
const owner = this.shown === void 0 ? void 0 : this.browser.ownerOf(this.shown);
|
|
4001
|
+
const next = owner === void 0 || owner.owner === this.conv ? void 0 : owner.owner;
|
|
4002
|
+
if (next === this.pinnedOwner) return;
|
|
4003
|
+
if (next !== void 0 && owner !== void 0) this.state.pin(next, owner.root);
|
|
4004
|
+
if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
|
|
4005
|
+
this.pinnedOwner = next;
|
|
4006
|
+
}
|
|
4007
|
+
groupOf(owner) {
|
|
4008
|
+
if (owner === this.conv || owner === void 0) return "own";
|
|
4009
|
+
let g = this.groups.get(owner);
|
|
4010
|
+
if (g === void 0) {
|
|
4011
|
+
g = `sub${this.groups.size + 1}`;
|
|
4012
|
+
this.groups.set(owner, g);
|
|
4013
|
+
}
|
|
4014
|
+
return g;
|
|
4015
|
+
}
|
|
1598
4016
|
sendState() {
|
|
1599
|
-
|
|
1600
|
-
const
|
|
1601
|
-
const
|
|
4017
|
+
if (this.closed) return;
|
|
4018
|
+
const all = this.browser.tabs();
|
|
4019
|
+
const tree = all.filter((t) => t.root === this.root);
|
|
4020
|
+
this.shown = this.computeShown(tree);
|
|
4021
|
+
this.pinShownOwner();
|
|
4022
|
+
if (this.browser.pageById(this.shown) !== this.page) {
|
|
4023
|
+
void this.serial(async () => {
|
|
4024
|
+
if (this.browser.pageById(this.shown) === this.page) return;
|
|
4025
|
+
await this.detach();
|
|
4026
|
+
await this.attach();
|
|
4027
|
+
});
|
|
4028
|
+
}
|
|
4029
|
+
const order = /* @__PURE__ */ new Map([["own", 0]]);
|
|
4030
|
+
const tabs = tree.map((t) => {
|
|
4031
|
+
const group = this.groupOf(t.owner);
|
|
4032
|
+
if (!order.has(group)) order.set(group, order.size);
|
|
4033
|
+
return {
|
|
4034
|
+
id: t.id,
|
|
4035
|
+
title: t.title,
|
|
4036
|
+
url: t.url,
|
|
4037
|
+
active: t.id === this.shown,
|
|
4038
|
+
group,
|
|
4039
|
+
...t.blocker === void 0 ? {} : { blocker: t.blocker },
|
|
4040
|
+
...t.favicon === void 0 ? {} : { favicon: t.favicon },
|
|
4041
|
+
...t.loading === true ? { loading: true } : {}
|
|
4042
|
+
};
|
|
4043
|
+
});
|
|
4044
|
+
tabs.sort((a, b) => (order.get(a.group) ?? 0) - (order.get(b.group) ?? 0));
|
|
4045
|
+
const shownTab = tree.find((t) => t.id === this.shown);
|
|
4046
|
+
const last = this.browser.lastClickOf(this.shown);
|
|
1602
4047
|
this.send({
|
|
1603
4048
|
t: "state",
|
|
1604
4049
|
tabs,
|
|
1605
|
-
|
|
1606
|
-
|
|
4050
|
+
...this.shown === void 0 ? {} : { shown: this.shown },
|
|
4051
|
+
otherTabs: all.filter((t) => t.root !== this.root && !isStartBlank(t)).map((t) => ({ id: t.id, title: t.title, url: t.url })),
|
|
4052
|
+
loading: this.browser.isLoading(this.shown),
|
|
4053
|
+
secure: shownTab?.url.startsWith("https:") ?? false,
|
|
1607
4054
|
control: this.state.control,
|
|
1608
4055
|
...last === void 0 ? {} : { lastClick: last },
|
|
1609
|
-
|
|
4056
|
+
handoffs: this.state.handoffs(this.root).map((h) => ({
|
|
4057
|
+
callId: h.callId,
|
|
4058
|
+
conversationId: h.conversationId,
|
|
4059
|
+
message: h.message,
|
|
4060
|
+
tabIds: this.browser.tabsOf(h.conversationId)
|
|
4061
|
+
}))
|
|
1610
4062
|
});
|
|
1611
4063
|
}
|
|
1612
4064
|
get scale() {
|
|
1613
|
-
return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.shrink;
|
|
4065
|
+
return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.frameQuality.shrink;
|
|
1614
4066
|
}
|
|
1615
|
-
/** Room for the JPEG
|
|
4067
|
+
/** Room for the JPEG in one frame message. */
|
|
1616
4068
|
get jpegBudget() {
|
|
1617
|
-
return
|
|
4069
|
+
return this.frameMaxBytes - FRAME_HEADER_BYTES;
|
|
1618
4070
|
}
|
|
1619
4071
|
async attach() {
|
|
1620
4072
|
if (this.closed) return;
|
|
1621
|
-
const page =
|
|
4073
|
+
const page = this.shownPage();
|
|
4074
|
+
if (page === void 0) return;
|
|
1622
4075
|
const cdp = await this.browser.context.newCDPSession(page);
|
|
1623
4076
|
this.page = page;
|
|
1624
4077
|
this.cdp = cdp;
|
|
1625
4078
|
cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
|
|
4079
|
+
this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
|
|
1626
4080
|
const first = await captureFitting(cdp, {
|
|
1627
4081
|
maxBytes: this.jpegBudget,
|
|
1628
4082
|
maxScale: this.scale
|
|
1629
4083
|
}).catch(() => null);
|
|
1630
4084
|
if (first !== null && this.cdp === cdp) {
|
|
1631
|
-
this.
|
|
4085
|
+
this.pending = {
|
|
4086
|
+
cdp,
|
|
4087
|
+
jpeg: Buffer.from(first.data, "base64"),
|
|
4088
|
+
width: first.width,
|
|
4089
|
+
height: first.height
|
|
4090
|
+
};
|
|
4091
|
+
this.pump();
|
|
1632
4092
|
}
|
|
1633
4093
|
await this.startScreencast(cdp);
|
|
1634
4094
|
}
|
|
@@ -1636,7 +4096,7 @@ var ViewerSession = class {
|
|
|
1636
4096
|
if (this.closed || this.cdp !== cdp) return;
|
|
1637
4097
|
await cdp.send("Page.startScreencast", {
|
|
1638
4098
|
format: "jpeg",
|
|
1639
|
-
quality: this.quality,
|
|
4099
|
+
quality: this.frameQuality.quality,
|
|
1640
4100
|
maxWidth: Math.max(16, Math.floor(VIEWPORT.width * this.scale)),
|
|
1641
4101
|
maxHeight: Math.max(16, Math.floor(VIEWPORT.height * this.scale)),
|
|
1642
4102
|
everyNthFrame: 1
|
|
@@ -1647,93 +4107,163 @@ var ViewerSession = class {
|
|
|
1647
4107
|
this.cdp = void 0;
|
|
1648
4108
|
this.page = void 0;
|
|
1649
4109
|
this.pending = void 0;
|
|
4110
|
+
this.encodeAck = void 0;
|
|
4111
|
+
this.cursorResolver?.dispose();
|
|
4112
|
+
this.cursorResolver = void 0;
|
|
1650
4113
|
if (cdp === void 0) return;
|
|
1651
4114
|
await cdp.send("Page.stopScreencast").catch(() => void 0);
|
|
1652
4115
|
await cdp.detach().catch(() => void 0);
|
|
1653
4116
|
}
|
|
1654
4117
|
sendFrame(jpeg, width, height) {
|
|
1655
4118
|
this.seq++;
|
|
1656
|
-
this.
|
|
1657
|
-
this.
|
|
4119
|
+
this.pacer.sent(this.seq, this.clock.now());
|
|
4120
|
+
if (!this.out.sendFrame(encodeFrame({ seq: this.seq, width, height, jpeg }))) this.awaitDrain();
|
|
4121
|
+
}
|
|
4122
|
+
/** The viewer acked frames up to `seq`: the link time adapts quality and scale. */
|
|
4123
|
+
onAck(seq) {
|
|
4124
|
+
const sample = this.pacer.acked(seq, this.clock.now());
|
|
4125
|
+
if (sample === void 0) return;
|
|
4126
|
+
if (this.clock.now() - this.lastRestartAt < RESTART_MIN_MS) return;
|
|
4127
|
+
if (this.frameQuality.observe(this.pacer.linkMs ?? sample)) this.restart();
|
|
4128
|
+
}
|
|
4129
|
+
/** Restarts the screencast at the current quality and scale. */
|
|
4130
|
+
restart() {
|
|
4131
|
+
const cdp = this.cdp;
|
|
4132
|
+
if (cdp === void 0) return;
|
|
4133
|
+
this.lastRestartAt = this.clock.now();
|
|
4134
|
+
this.pacer.reset();
|
|
4135
|
+
void this.serial(async () => {
|
|
4136
|
+
if (this.cdp !== cdp) return;
|
|
4137
|
+
await cdp.send("Page.stopScreencast").catch(() => void 0);
|
|
4138
|
+
this.pending = void 0;
|
|
4139
|
+
this.encodeAck = void 0;
|
|
4140
|
+
await this.startScreencast(cdp);
|
|
4141
|
+
});
|
|
1658
4142
|
}
|
|
1659
4143
|
onFrame(cdp, f) {
|
|
1660
4144
|
if (this.closed || this.cdp !== cdp) return;
|
|
1661
4145
|
const bytes = Buffer.from(f.data, "base64");
|
|
1662
4146
|
if (bytes.length > this.jpegBudget) {
|
|
1663
4147
|
cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => void 0);
|
|
1664
|
-
if (this.
|
|
1665
|
-
else this.shrink *= 0.75;
|
|
1666
|
-
void this.serial(async () => {
|
|
1667
|
-
if (this.cdp !== cdp) return;
|
|
1668
|
-
await cdp.send("Page.stopScreencast").catch(() => void 0);
|
|
1669
|
-
await this.startScreencast(cdp);
|
|
1670
|
-
});
|
|
4148
|
+
if (this.frameQuality.tooLarge()) this.restart();
|
|
1671
4149
|
return;
|
|
1672
4150
|
}
|
|
1673
4151
|
const { width, height } = jpegSize(bytes);
|
|
1674
|
-
this.pending = { cdp,
|
|
4152
|
+
this.pending = { cdp, jpeg: bytes, width, height };
|
|
4153
|
+
this.encodeAck = { cdp, sessionId: f.sessionId };
|
|
1675
4154
|
this.pump();
|
|
4155
|
+
this.scheduleEncodeAck();
|
|
4156
|
+
}
|
|
4157
|
+
/**
|
|
4158
|
+
* Lets Chromium encode its next frame (screencastFrameAck): at most at the viewer's frame rate
|
|
4159
|
+
* while frames flow, and while one waits for the viewer only every ENCODE_MAX_INTERVAL_MS, so
|
|
4160
|
+
* the frame sent when room comes is a recent one without encoding frames nobody gets.
|
|
4161
|
+
*/
|
|
4162
|
+
scheduleEncodeAck() {
|
|
4163
|
+
if (this.encodeTimer !== void 0) this.clock.cancel(this.encodeTimer);
|
|
4164
|
+
this.encodeTimer = void 0;
|
|
4165
|
+
const ack = this.encodeAck;
|
|
4166
|
+
if (ack === void 0 || this.closed) return;
|
|
4167
|
+
const gap = this.pending === void 0 ? 1e3 / VIEWER_MAX_FPS : ENCODE_MAX_INTERVAL_MS;
|
|
4168
|
+
const wait = this.lastEncodeAckAt + gap - this.clock.now();
|
|
4169
|
+
if (wait > 0) {
|
|
4170
|
+
this.encodeTimer = this.clock.schedule(() => {
|
|
4171
|
+
this.encodeTimer = void 0;
|
|
4172
|
+
this.scheduleEncodeAck();
|
|
4173
|
+
}, wait);
|
|
4174
|
+
return;
|
|
4175
|
+
}
|
|
4176
|
+
this.encodeAck = void 0;
|
|
4177
|
+
if (this.cdp !== ack.cdp) return;
|
|
4178
|
+
this.lastEncodeAckAt = this.clock.now();
|
|
4179
|
+
ack.cdp.send("Page.screencastFrameAck", { sessionId: ack.sessionId }).catch(() => void 0);
|
|
1676
4180
|
}
|
|
1677
4181
|
/**
|
|
1678
|
-
* Sends the
|
|
1679
|
-
*
|
|
1680
|
-
* the previous one sooner than 1000 / VIEWER_MAX_FPS ms, the first after an attach included.
|
|
4182
|
+
* Sends the newest screencast frame once the pacer allows (viewer acks, link time, rate cap)
|
|
4183
|
+
* and the transport is not backed up.
|
|
1681
4184
|
*/
|
|
1682
4185
|
pump() {
|
|
1683
4186
|
const pending = this.pending;
|
|
1684
4187
|
if (pending === void 0 || this.closed || this.draining) return;
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
if (this.pumpTimer === void 0) {
|
|
4188
|
+
const d = this.pacer.decide(this.clock.now());
|
|
4189
|
+
if (!d.ok) {
|
|
4190
|
+
if (d.waitMs !== void 0 && this.pumpTimer === void 0) {
|
|
1689
4191
|
this.pumpTimer = this.clock.schedule(() => {
|
|
1690
4192
|
this.pumpTimer = void 0;
|
|
1691
4193
|
this.pump();
|
|
1692
|
-
},
|
|
4194
|
+
}, d.waitMs);
|
|
1693
4195
|
}
|
|
1694
4196
|
return;
|
|
1695
4197
|
}
|
|
1696
4198
|
this.pending = void 0;
|
|
1697
4199
|
if (this.cdp !== pending.cdp) return;
|
|
1698
|
-
this.sendFrame(pending.
|
|
1699
|
-
|
|
4200
|
+
this.sendFrame(pending.jpeg, pending.width, pending.height);
|
|
4201
|
+
this.scheduleEncodeAck();
|
|
1700
4202
|
}
|
|
1701
4203
|
async mouse(m) {
|
|
1702
|
-
const page =
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
4204
|
+
const page = this.shownPage();
|
|
4205
|
+
const p = point(m);
|
|
4206
|
+
if (p === null || page === void 0) return;
|
|
4207
|
+
this.concern(this.browser.tabIdOf(page));
|
|
4208
|
+
const { x, y } = p;
|
|
1706
4209
|
const button = m.button === "right" ? "right" : "left";
|
|
1707
4210
|
try {
|
|
1708
|
-
if (m.kind === "
|
|
1709
|
-
else if (m.kind === "down") {
|
|
4211
|
+
if (m.kind === "down") {
|
|
1710
4212
|
await page.mouse.move(x, y);
|
|
1711
4213
|
await page.mouse.down({ button });
|
|
4214
|
+
if (this.driving) this.heldButtons.set(button, page);
|
|
4215
|
+
else await page.mouse.up({ button });
|
|
1712
4216
|
} else if (m.kind === "up") {
|
|
4217
|
+
this.heldButtons.delete(button);
|
|
1713
4218
|
await page.mouse.move(x, y);
|
|
1714
4219
|
await page.mouse.up({ button });
|
|
1715
4220
|
} else if (m.kind === "wheel") {
|
|
1716
4221
|
await page.mouse.move(x, y);
|
|
1717
4222
|
await page.mouse.wheel(Number(m.dx) || 0, Number(m.dy) || 0);
|
|
1718
|
-
}
|
|
4223
|
+
} else return;
|
|
1719
4224
|
} catch {
|
|
4225
|
+
return;
|
|
1720
4226
|
}
|
|
4227
|
+
if (m.kind !== "down") this.wantCursor(x, y);
|
|
1721
4228
|
}
|
|
1722
4229
|
async key(m) {
|
|
1723
|
-
const page =
|
|
4230
|
+
const page = this.shownPage();
|
|
4231
|
+
if (page === void 0) return;
|
|
4232
|
+
this.concern(this.browser.tabIdOf(page));
|
|
1724
4233
|
try {
|
|
1725
4234
|
if (m.kind === "char") {
|
|
1726
4235
|
const text = m.text ?? m.key;
|
|
1727
|
-
if (typeof text === "string" && text !== "")
|
|
1728
|
-
|
|
1729
|
-
else if (m.kind === "
|
|
4236
|
+
if (typeof text === "string" && text !== "")
|
|
4237
|
+
await page.keyboard.insertText(clipCodePoints(text, VIEWER_TEXT_MAX_CHARS));
|
|
4238
|
+
} else if (m.kind === "down") {
|
|
4239
|
+
await page.keyboard.down(m.key);
|
|
4240
|
+
if (this.driving) this.heldKeys.set(m.key, page);
|
|
4241
|
+
else await page.keyboard.up(m.key);
|
|
4242
|
+
} else if (m.kind === "up") {
|
|
4243
|
+
this.heldKeys.delete(m.key);
|
|
4244
|
+
await page.keyboard.up(m.key);
|
|
4245
|
+
}
|
|
1730
4246
|
} catch {
|
|
1731
4247
|
}
|
|
1732
4248
|
}
|
|
1733
4249
|
};
|
|
4250
|
+
var handoffKey = (h) => `${h.conversationId}\0${h.callId}`;
|
|
4251
|
+
function point(m) {
|
|
4252
|
+
const x = Number(m.x);
|
|
4253
|
+
const y = Number(m.y);
|
|
4254
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
|
|
4255
|
+
return {
|
|
4256
|
+
x: Math.max(0, Math.min(VIEWPORT.width - 1, x)),
|
|
4257
|
+
y: Math.max(0, Math.min(VIEWPORT.height - 1, y))
|
|
4258
|
+
};
|
|
4259
|
+
}
|
|
1734
4260
|
|
|
1735
4261
|
// daemon/main.ts
|
|
4262
|
+
var SEALED_EXIT_GRACE_MS = 2e3;
|
|
1736
4263
|
var SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
|
|
4264
|
+
var BROWSER_CLOSE_GRACE_MS = 3e3;
|
|
4265
|
+
var PROCESS_POLL_MS = 10;
|
|
4266
|
+
var COOKIE_SAVE_MS = 500;
|
|
1737
4267
|
var enc = new TextEncoder();
|
|
1738
4268
|
var dec = new TextDecoder();
|
|
1739
4269
|
var REQUEST_OPS = /* @__PURE__ */ new Set([
|
|
@@ -1771,6 +4301,10 @@ function parse(raw) {
|
|
|
1771
4301
|
return void 0;
|
|
1772
4302
|
}
|
|
1773
4303
|
}
|
|
4304
|
+
var HANDOFF_HOLDS_ROLL_MS = 30 * 6e4;
|
|
4305
|
+
function isRollCheck(body) {
|
|
4306
|
+
return typeof body === "object" && body !== null && body.capybara === JSON.parse(ROLL_CHECK_REQUEST).capybara;
|
|
4307
|
+
}
|
|
1774
4308
|
function write(sock, value, tooLarge) {
|
|
1775
4309
|
if (sock.destroyed) return false;
|
|
1776
4310
|
let framed;
|
|
@@ -1802,78 +4336,168 @@ async function startDaemon(opts) {
|
|
|
1802
4336
|
let closing = false;
|
|
1803
4337
|
const sessionFile = new SessionFile(opts.stateDir, clock);
|
|
1804
4338
|
const saved = sessionFile.read();
|
|
4339
|
+
let live;
|
|
1805
4340
|
const state = new DaemonState({
|
|
1806
4341
|
clock,
|
|
1807
4342
|
...opts.idleMs === void 0 ? {} : { idleMs: opts.idleMs },
|
|
4343
|
+
...opts.conversationIdleMs === void 0 ? {} : { conversationIdleMs: opts.conversationIdleMs },
|
|
1808
4344
|
onIdle: () => {
|
|
1809
4345
|
sessionFile.forget();
|
|
1810
4346
|
opts.onIdle?.();
|
|
4347
|
+
},
|
|
4348
|
+
onConversationIdle: (conversationId) => {
|
|
4349
|
+
void live?.closeConversation(conversationId);
|
|
1811
4350
|
}
|
|
1812
4351
|
});
|
|
1813
|
-
if (saved
|
|
1814
|
-
state.noticeHandoff(saved.handoff.callId, saved.handoff.message);
|
|
4352
|
+
if (saved !== void 0) sessionFile.restoreState(state, saved);
|
|
1815
4353
|
const launch = opts.launch ?? launchChromium;
|
|
4354
|
+
const closeGraceMs = opts.browserCloseGraceMs ?? BROWSER_CLOSE_GRACE_MS;
|
|
1816
4355
|
let current;
|
|
4356
|
+
let running;
|
|
1817
4357
|
let restored = false;
|
|
4358
|
+
function within2(value, ms) {
|
|
4359
|
+
let timer;
|
|
4360
|
+
return Promise.race([
|
|
4361
|
+
value,
|
|
4362
|
+
new Promise((r) => {
|
|
4363
|
+
timer = clock.schedule(() => r(void 0), ms);
|
|
4364
|
+
})
|
|
4365
|
+
]).finally(() => clock.cancel(timer));
|
|
4366
|
+
}
|
|
1818
4367
|
function browser() {
|
|
1819
4368
|
if (current !== void 0) return current;
|
|
4369
|
+
if (closing) return Promise.reject(new Error("The browser daemon is stopping."));
|
|
1820
4370
|
const starting = launch(plan).then(async (ctx) => {
|
|
4371
|
+
let pid;
|
|
4372
|
+
let failed = false;
|
|
4373
|
+
try {
|
|
4374
|
+
return await sessionOn(
|
|
4375
|
+
ctx,
|
|
4376
|
+
(id) => {
|
|
4377
|
+
pid = id;
|
|
4378
|
+
},
|
|
4379
|
+
() => failed
|
|
4380
|
+
);
|
|
4381
|
+
} catch (e) {
|
|
4382
|
+
failed = true;
|
|
4383
|
+
await closeOrKill(ctx.close(), () => pid);
|
|
4384
|
+
throw e;
|
|
4385
|
+
}
|
|
4386
|
+
});
|
|
4387
|
+
current = starting;
|
|
4388
|
+
starting.catch(() => {
|
|
4389
|
+
if (current === starting) current = void 0;
|
|
4390
|
+
live = void 0;
|
|
4391
|
+
if (running?.launch === starting) running = void 0;
|
|
4392
|
+
});
|
|
4393
|
+
return starting;
|
|
4394
|
+
async function sessionOn(ctx, setPid, failed) {
|
|
4395
|
+
let gone = false;
|
|
1821
4396
|
ctx.on("close", () => {
|
|
1822
|
-
|
|
4397
|
+
gone = true;
|
|
4398
|
+
if (running?.launch === starting) running = void 0;
|
|
4399
|
+
if (!closing && !failed()) opts.onBrowserGone?.();
|
|
1823
4400
|
});
|
|
4401
|
+
const pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
|
|
4402
|
+
setPid(pid);
|
|
4403
|
+
if (!gone) running = { launch: starting, pid, ctx };
|
|
1824
4404
|
const workspace = opts.env[SERVICE_WORKSPACE_ENV];
|
|
1825
4405
|
const session = new BrowserSession(ctx, {
|
|
1826
4406
|
proxy: plan.proxy,
|
|
1827
4407
|
clock,
|
|
4408
|
+
usage: state,
|
|
1828
4409
|
workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
|
|
1829
4410
|
downloadsTmp: plan.downloadsTmp,
|
|
1830
4411
|
downloadMaxBytes: downloadMaxBytes(opts.env),
|
|
1831
|
-
...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
|
|
4412
|
+
...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs },
|
|
4413
|
+
...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
|
|
1832
4414
|
});
|
|
1833
|
-
if (
|
|
4415
|
+
if (plan.shippedDir !== void 0)
|
|
4416
|
+
session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
|
|
4417
|
+
if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
|
|
4418
|
+
session.note(HEADLESS_SHELL_NOTE);
|
|
4419
|
+
if (!closing) await restoreCookies(ctx, opts.stateDir);
|
|
4420
|
+
if (!restored && !closing) {
|
|
1834
4421
|
restored = true;
|
|
1835
4422
|
if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
|
|
1836
4423
|
}
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
4424
|
+
if (!closing) {
|
|
4425
|
+
const save = () => sessionFile.save(session, state);
|
|
4426
|
+
session.on(save);
|
|
4427
|
+
state.onChange(save);
|
|
4428
|
+
}
|
|
4429
|
+
if (!failed()) live = session;
|
|
1840
4430
|
return session;
|
|
1841
|
-
}
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
4431
|
+
}
|
|
4432
|
+
}
|
|
4433
|
+
async function closeOrKill(closingBrowser, pid) {
|
|
4434
|
+
const done = closingBrowser.then(
|
|
4435
|
+
() => true,
|
|
4436
|
+
() => true
|
|
4437
|
+
);
|
|
4438
|
+
if (await within2(done, closeGraceMs) === true) return;
|
|
4439
|
+
const id = pid();
|
|
4440
|
+
if (id === void 0) return;
|
|
4441
|
+
killChromium(id);
|
|
4442
|
+
await within2(done, closeGraceMs);
|
|
1847
4443
|
}
|
|
1848
4444
|
async function launchFailure(e) {
|
|
4445
|
+
if (e instanceof BrowserInstalledError)
|
|
4446
|
+
return { ok: false, error: "restart", message: e.message, blockedHosts: [] };
|
|
4447
|
+
if (plan.unavailable !== void 0) return fail(plan.unavailable);
|
|
1849
4448
|
const cause = e instanceof Error ? e.message.split("\n")[0] : String(e);
|
|
1850
4449
|
const proxy = plan.proxy;
|
|
1851
4450
|
const refused = proxy === void 0 ? [] : (await Promise.all(
|
|
1852
|
-
playwrightDownloadHosts(opts.env).map(
|
|
1853
|
-
|
|
1854
|
-
|
|
4451
|
+
playwrightDownloadHosts(opts.env).map(async (host) => {
|
|
4452
|
+
const layer = await proxyRefusal(proxy, host, 443);
|
|
4453
|
+
return layer === null ? void 0 : { host, layer };
|
|
4454
|
+
})
|
|
1855
4455
|
)).filter((h) => h !== void 0);
|
|
1856
4456
|
if (refused.length > 0)
|
|
1857
4457
|
return {
|
|
1858
4458
|
ok: false,
|
|
1859
4459
|
error: "blocked",
|
|
1860
|
-
message: `${DOWNLOAD_BLOCKED_PREFIX}${refused.join(", ")}.`,
|
|
4460
|
+
message: `${DOWNLOAD_BLOCKED_PREFIX}${refused.map((r) => r.host).join(", ")}.`,
|
|
1861
4461
|
blockedHosts: refused
|
|
1862
4462
|
};
|
|
1863
4463
|
return fail(
|
|
1864
4464
|
`The browser could not start in the device: ${cause}. The next browser call tries again.`
|
|
1865
4465
|
);
|
|
1866
4466
|
}
|
|
4467
|
+
async function stopBrowser() {
|
|
4468
|
+
const starting = current;
|
|
4469
|
+
if (starting === void 0) return;
|
|
4470
|
+
const r = running?.launch === starting ? running : void 0;
|
|
4471
|
+
const pid = r?.pid;
|
|
4472
|
+
if (r !== void 0) await within2(saveCookies(r.ctx, opts.stateDir), COOKIE_SAVE_MS);
|
|
4473
|
+
await closeOrKill(
|
|
4474
|
+
starting.then(
|
|
4475
|
+
async (session) => {
|
|
4476
|
+
await session.close();
|
|
4477
|
+
if (pid !== void 0) await processGone(pid);
|
|
4478
|
+
},
|
|
4479
|
+
() => void 0
|
|
4480
|
+
),
|
|
4481
|
+
() => pid
|
|
4482
|
+
);
|
|
4483
|
+
}
|
|
4484
|
+
async function processGone(pid) {
|
|
4485
|
+
while (processAlive(pid)) await new Promise((r) => clock.schedule(r, PROCESS_POLL_MS));
|
|
4486
|
+
}
|
|
1867
4487
|
const ready = browser().then(() => void 0);
|
|
1868
|
-
ready.catch(() =>
|
|
4488
|
+
ready.catch((e) => {
|
|
4489
|
+
if (e instanceof BrowserInstalledError)
|
|
4490
|
+
clock.schedule(() => opts.onSealed?.(), SEALED_EXIT_GRACE_MS);
|
|
4491
|
+
});
|
|
1869
4492
|
async function handoffOp(req) {
|
|
1870
4493
|
if (typeof req.callId !== "string" || req.callId === "")
|
|
1871
4494
|
return fail("The handoff needs a callId.");
|
|
4495
|
+
const conv = req.conversationId;
|
|
1872
4496
|
if (req.op === "handoff_notice") {
|
|
1873
4497
|
if (typeof req.message !== "string") return fail("The handoff notice needs a message.");
|
|
1874
|
-
state.noticeHandoff(req.callId, req.message);
|
|
4498
|
+
state.noticeHandoff(conv, req.rootConversationId, req.callId, req.message);
|
|
1875
4499
|
} else {
|
|
1876
|
-
state.clearHandoff(req.callId);
|
|
4500
|
+
state.clearHandoff(conv, req.callId);
|
|
1877
4501
|
if (req.handback === true) state.handback();
|
|
1878
4502
|
}
|
|
1879
4503
|
let session;
|
|
@@ -1882,15 +4506,38 @@ async function startDaemon(opts) {
|
|
|
1882
4506
|
} catch (e) {
|
|
1883
4507
|
return launchFailure(e);
|
|
1884
4508
|
}
|
|
1885
|
-
|
|
4509
|
+
const page = session.currentPage(conv);
|
|
4510
|
+
return {
|
|
4511
|
+
ok: true,
|
|
4512
|
+
...page === void 0 ? {} : { page: await session.pageInfo(page) },
|
|
4513
|
+
blockedHosts: []
|
|
4514
|
+
};
|
|
1886
4515
|
}
|
|
4516
|
+
const namesConversation = (raw) => {
|
|
4517
|
+
const r = raw;
|
|
4518
|
+
return typeof r.conversationId === "string" && r.conversationId !== "" && typeof r.rootConversationId === "string" && r.rootConversationId !== "";
|
|
4519
|
+
};
|
|
1887
4520
|
async function handleRequest(raw) {
|
|
1888
4521
|
if (typeof raw !== "object" || raw === null || !REQUEST_OPS.has(String(raw.op))) {
|
|
1889
4522
|
return fail("Unknown browser request.");
|
|
1890
4523
|
}
|
|
4524
|
+
if (!namesConversation(raw)) return fail(NO_CONVERSATION_MESSAGE);
|
|
1891
4525
|
const req = raw;
|
|
4526
|
+
const conv = req.conversationId;
|
|
4527
|
+
state.requestArrived(conv, req.rootConversationId);
|
|
4528
|
+
let reply;
|
|
4529
|
+
try {
|
|
4530
|
+
reply = await conversationRequest(req);
|
|
4531
|
+
} catch (e) {
|
|
4532
|
+
reply = fail(e instanceof ActionError ? e.message : String(e));
|
|
4533
|
+
} finally {
|
|
4534
|
+
state.requestFinished(conv);
|
|
4535
|
+
}
|
|
4536
|
+
return { ...reply, tabs: { open: live?.countOf(conv) ?? 0, max: MAX_TABS_PER_CONVERSATION } };
|
|
4537
|
+
}
|
|
4538
|
+
async function conversationRequest(req) {
|
|
1892
4539
|
if (req.op === "handoff_notice" || req.op === "handoff_clear") return handoffOp(req);
|
|
1893
|
-
state.dropHandoff();
|
|
4540
|
+
state.dropHandoff(req.conversationId);
|
|
1894
4541
|
if (state.control === "user" && req.op !== "wait") {
|
|
1895
4542
|
return { ok: false, error: "taken_over", message: TAKEN_OVER_MESSAGE, blockedHosts: [] };
|
|
1896
4543
|
}
|
|
@@ -1902,7 +4549,7 @@ async function startDaemon(opts) {
|
|
|
1902
4549
|
}
|
|
1903
4550
|
const reply = await session.run(req, { takenOver: () => state.control === "user" });
|
|
1904
4551
|
if (reply.ok) {
|
|
1905
|
-
const since = state.takeHandbackNote();
|
|
4552
|
+
const since = state.takeHandbackNote(req.conversationId);
|
|
1906
4553
|
if (since !== void 0) reply.userControlledSince = since;
|
|
1907
4554
|
}
|
|
1908
4555
|
return reply;
|
|
@@ -1912,6 +4559,7 @@ async function startDaemon(opts) {
|
|
|
1912
4559
|
sockets.add(sock);
|
|
1913
4560
|
const decoder = new ServiceMessageDecoder();
|
|
1914
4561
|
let kind;
|
|
4562
|
+
let context;
|
|
1915
4563
|
let handled = false;
|
|
1916
4564
|
let viewer;
|
|
1917
4565
|
let opened = false;
|
|
@@ -1934,42 +4582,68 @@ async function startDaemon(opts) {
|
|
|
1934
4582
|
if (kind === void 0) {
|
|
1935
4583
|
const first = parse(raw);
|
|
1936
4584
|
if (first?.kind === "request") kind = "request";
|
|
1937
|
-
else if (first?.kind === "stream")
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
4585
|
+
else if (first?.kind === "stream") kind = "stream";
|
|
4586
|
+
else sock.destroy();
|
|
4587
|
+
return;
|
|
4588
|
+
}
|
|
4589
|
+
if (kind === "stream" && context === void 0) {
|
|
4590
|
+
const ctx = parseViewerContext(raw);
|
|
4591
|
+
if (ctx === null) {
|
|
4592
|
+
sock.destroy();
|
|
4593
|
+
return;
|
|
4594
|
+
}
|
|
4595
|
+
context = {
|
|
4596
|
+
conversationId: ctx.conversationId,
|
|
4597
|
+
rootConversationId: ctx.rootConversationId
|
|
4598
|
+
};
|
|
4599
|
+
const viewerContext = context;
|
|
4600
|
+
opened = true;
|
|
4601
|
+
state.viewerOpened();
|
|
4602
|
+
browser().then(
|
|
4603
|
+
(session) => {
|
|
4604
|
+
if (sock.destroyed) return;
|
|
4605
|
+
viewer = new ViewerSession({
|
|
4606
|
+
browser: session,
|
|
4607
|
+
state,
|
|
4608
|
+
conversationId: viewerContext.conversationId,
|
|
4609
|
+
rootConversationId: viewerContext.rootConversationId,
|
|
4610
|
+
clock,
|
|
4611
|
+
frameMaxBytes: frameCap,
|
|
4612
|
+
transport: {
|
|
4613
|
+
send: (m) => {
|
|
4614
|
+
let dropped = false;
|
|
4615
|
+
const ok = write(sock, m, () => {
|
|
4616
|
+
dropped = true;
|
|
4617
|
+
});
|
|
4618
|
+
return ok || dropped || sock.destroyed;
|
|
4619
|
+
},
|
|
4620
|
+
sendFrame: (frame) => {
|
|
4621
|
+
if (sock.destroyed) return true;
|
|
4622
|
+
return sock.write(encodeServiceMessage(frame));
|
|
4623
|
+
},
|
|
4624
|
+
whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
|
|
4625
|
+
}
|
|
4626
|
+
});
|
|
4627
|
+
},
|
|
4628
|
+
() => sock.destroy()
|
|
4629
|
+
);
|
|
1964
4630
|
return;
|
|
1965
4631
|
}
|
|
1966
4632
|
if (kind === "request") {
|
|
1967
4633
|
if (handled) return;
|
|
1968
4634
|
handled = true;
|
|
4635
|
+
const body = parse(raw);
|
|
4636
|
+
if (isRollCheck(body)) {
|
|
4637
|
+
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;
|
|
4638
|
+
write(sock, reason === void 0 ? { busy: false } : { busy: true, reason });
|
|
4639
|
+
sock.end();
|
|
4640
|
+
return;
|
|
4641
|
+
}
|
|
1969
4642
|
state.requestStarted();
|
|
1970
|
-
handleRequest(
|
|
4643
|
+
handleRequest(body).catch((e) => fail(e instanceof ActionError ? e.message : String(e))).then((reply) => {
|
|
1971
4644
|
write(sock, reply, () => write(sock, fail(REPLY_TOO_LARGE_MESSAGE), () => void 0));
|
|
1972
4645
|
sock.end();
|
|
4646
|
+
if (!reply.ok && reply.error === "restart") sock.once("close", () => opts.onSealed?.());
|
|
1973
4647
|
}).catch(() => sock.destroy()).finally(() => state.requestEnded());
|
|
1974
4648
|
return;
|
|
1975
4649
|
}
|
|
@@ -1988,7 +4662,7 @@ async function startDaemon(opts) {
|
|
|
1988
4662
|
for (const m of msgs) onMessage(m);
|
|
1989
4663
|
});
|
|
1990
4664
|
}
|
|
1991
|
-
if (existsSync2(opts.socketPath))
|
|
4665
|
+
if (existsSync2(opts.socketPath)) unlinkSync2(opts.socketPath);
|
|
1992
4666
|
const server = createServer(onConnection);
|
|
1993
4667
|
await new Promise((resolve, reject) => {
|
|
1994
4668
|
server.once("error", reject);
|
|
@@ -2009,11 +4683,10 @@ async function startDaemon(opts) {
|
|
|
2009
4683
|
server.close(() => r());
|
|
2010
4684
|
for (const s of sockets) s.destroy();
|
|
2011
4685
|
});
|
|
2012
|
-
|
|
2013
|
-
await session?.close();
|
|
4686
|
+
await stopBrowser();
|
|
2014
4687
|
if (existsSync2(opts.socketPath)) {
|
|
2015
4688
|
try {
|
|
2016
|
-
|
|
4689
|
+
unlinkSync2(opts.socketPath);
|
|
2017
4690
|
} catch {
|
|
2018
4691
|
}
|
|
2019
4692
|
}
|
|
@@ -2049,7 +4722,9 @@ async function main() {
|
|
|
2049
4722
|
stateDir,
|
|
2050
4723
|
env: process.env,
|
|
2051
4724
|
onIdle: () => stop(0, "idle"),
|
|
2052
|
-
onBrowserGone: () => stop(1, "Chromium exited")
|
|
4725
|
+
onBrowserGone: () => stop(1, "Chromium exited"),
|
|
4726
|
+
// installed and sealed: the next start runs the browser read only
|
|
4727
|
+
onSealed: () => stop(0, "browser installed and sealed; restart to run it")
|
|
2053
4728
|
});
|
|
2054
4729
|
process.stderr.write(`browser daemon: listening on ${socketPath}
|
|
2055
4730
|
`);
|