@capybara-hq/plugin-browser 0.1.0-rc.1 → 0.1.0-rc.11
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 +3144 -464
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.78/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.78/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();
|
|
173
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);
|
|
174
528
|
this.armIdle();
|
|
529
|
+
this.emit();
|
|
175
530
|
}
|
|
176
|
-
/**
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
+
}
|
|
548
|
+
this.armIdle();
|
|
549
|
+
}
|
|
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,222 @@ 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 INTERRUPTED_BY_RE = /is interrupted by another navigation to "([^"]*)"/;
|
|
876
|
+
var ERROR_PAGE_WAIT_MS = 2e3;
|
|
877
|
+
var isTimeout = (e) => e instanceof Error && e.name === "TimeoutError";
|
|
878
|
+
function timeoutError(message) {
|
|
879
|
+
const e = new Error(message);
|
|
880
|
+
e.name = "TimeoutError";
|
|
881
|
+
return e;
|
|
882
|
+
}
|
|
883
|
+
var NET_ERROR_MEANINGS = {
|
|
884
|
+
ERR_NAME_NOT_RESOLVED: "the host name does not resolve",
|
|
885
|
+
ERR_CONNECTION_REFUSED: "the host refused the connection",
|
|
886
|
+
ERR_CONNECTION_RESET: "the connection was reset",
|
|
887
|
+
ERR_CONNECTION_CLOSED: "the host closed the connection without an answer",
|
|
888
|
+
ERR_CONNECTION_TIMED_OUT: "the host did not answer the connection",
|
|
889
|
+
ERR_ADDRESS_UNREACHABLE: "the host's address is unreachable",
|
|
890
|
+
ERR_INTERNET_DISCONNECTED: "the device has no network connection",
|
|
891
|
+
ERR_EMPTY_RESPONSE: "the server sent an empty answer",
|
|
892
|
+
ERR_SSL_PROTOCOL_ERROR: "the secure connection failed",
|
|
893
|
+
ERR_CERT_AUTHORITY_INVALID: "the site's certificate is not trusted",
|
|
894
|
+
ERR_CERT_COMMON_NAME_INVALID: "the site's certificate is for another name",
|
|
895
|
+
ERR_CERT_DATE_INVALID: "the site's certificate has expired or is not yet valid",
|
|
896
|
+
ERR_TOO_MANY_REDIRECTS: "the page redirects in a loop"
|
|
897
|
+
};
|
|
898
|
+
function docUrl(raw) {
|
|
899
|
+
try {
|
|
900
|
+
const u = new URL(raw);
|
|
901
|
+
u.hash = "";
|
|
902
|
+
return u.href;
|
|
903
|
+
} catch {
|
|
904
|
+
return raw;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
async function pastNetworkChanges(run, follow, deadline, now = Date.now) {
|
|
908
|
+
for (; ; ) {
|
|
909
|
+
try {
|
|
910
|
+
return await run();
|
|
911
|
+
} catch (e) {
|
|
912
|
+
if (!firstLine(e).includes("net::ERR_NETWORK_CHANGED")) throw e;
|
|
913
|
+
const out = await follow();
|
|
914
|
+
if (out.kind === "loaded") return out.response;
|
|
915
|
+
if (out.kind === "failed" && !out.error.includes("ERR_NETWORK_CHANGED"))
|
|
916
|
+
throw new Error(`${out.error} at ${out.url}`);
|
|
917
|
+
if (now() >= deadline) throw timeoutError(`${firstLine(e)}, past the navigation's deadline`);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
async function pastInterrupts(run, follow, url, deadline, now = Date.now) {
|
|
922
|
+
for (; ; ) {
|
|
923
|
+
try {
|
|
924
|
+
return await run();
|
|
925
|
+
} catch (e) {
|
|
926
|
+
const msg = firstLine(e);
|
|
927
|
+
const by = INTERRUPTED_BY_RE.exec(msg)?.[1];
|
|
928
|
+
const sameAddress = by !== void 0 && docUrl(by) === docUrl(url);
|
|
929
|
+
if (!ERROR_PAGE_INTERRUPT_RE.test(msg) && !sameAddress) throw e;
|
|
930
|
+
const out = await follow();
|
|
931
|
+
if (out.kind === "loaded") return out.response;
|
|
932
|
+
if (out.kind === "failed" && !out.error.includes("net::ERR_ABORTED"))
|
|
933
|
+
throw new Error(`${out.error} at ${out.url}`);
|
|
934
|
+
if (now() >= deadline) throw timeoutError(`${msg}, past the navigation's deadline`);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
var NavWatch = class {
|
|
939
|
+
constructor(page, url, pending) {
|
|
940
|
+
this.page = page;
|
|
941
|
+
this.pending = pending;
|
|
942
|
+
this.target = docUrl(url);
|
|
943
|
+
const before = pending();
|
|
944
|
+
if (before !== void 0 && this.isOurs(before)) this.lastOurs = before;
|
|
945
|
+
page.on("request", this.onRequest);
|
|
946
|
+
page.on("framenavigated", this.onNavigated);
|
|
947
|
+
page.on("requestfailed", this.onFailed);
|
|
948
|
+
page.on("requestfinished", this.onFinished);
|
|
949
|
+
}
|
|
950
|
+
page;
|
|
951
|
+
pending;
|
|
952
|
+
target;
|
|
953
|
+
/** The newest main-frame navigation request to the target address (redirects included). */
|
|
954
|
+
lastOurs;
|
|
955
|
+
/** The request of `lastOurs`'s chain whose document the main frame committed. */
|
|
956
|
+
committedOurs;
|
|
957
|
+
/** The request of `lastOurs`'s chain that failed. */
|
|
958
|
+
failedOurs;
|
|
959
|
+
wake;
|
|
960
|
+
onRequest = (r) => {
|
|
961
|
+
if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
|
|
962
|
+
this.lastOurs = this.isOurs(r) ? r : void 0;
|
|
963
|
+
this.wake?.();
|
|
964
|
+
};
|
|
965
|
+
onNavigated = (f) => {
|
|
966
|
+
if (f !== this.page.mainFrame()) return;
|
|
967
|
+
const ours = this.lastOurs;
|
|
968
|
+
if (ours !== void 0 && docUrl(this.page.mainFrame().url()) === docUrl(ours.url()))
|
|
969
|
+
this.committedOurs = ours;
|
|
970
|
+
this.wake?.();
|
|
971
|
+
};
|
|
972
|
+
onFailed = (r) => {
|
|
973
|
+
if (r === this.lastOurs) this.failedOurs = r;
|
|
974
|
+
this.wake?.();
|
|
975
|
+
};
|
|
976
|
+
/** After the session's own `requestfinished` handler (registered first) settled the request. */
|
|
977
|
+
onFinished = (r) => {
|
|
978
|
+
if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
|
|
979
|
+
const wake = () => this.wake?.();
|
|
980
|
+
void r.response().then(wake, wake);
|
|
981
|
+
};
|
|
982
|
+
isOurs(r) {
|
|
983
|
+
let root = r;
|
|
984
|
+
for (let from = r.redirectedFrom(); from !== null; from = from.redirectedFrom()) root = from;
|
|
985
|
+
return docUrl(root.url()) === this.target;
|
|
986
|
+
}
|
|
987
|
+
/** Resolves on the next navigation event or after `ms`. */
|
|
988
|
+
next(ms) {
|
|
989
|
+
return new Promise((resolve) => {
|
|
990
|
+
const timer = setTimeout(done, ms);
|
|
991
|
+
function done() {
|
|
992
|
+
clearTimeout(timer);
|
|
993
|
+
resolve();
|
|
994
|
+
}
|
|
995
|
+
this.wake = () => {
|
|
996
|
+
this.wake = void 0;
|
|
997
|
+
done();
|
|
998
|
+
};
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* After an abort: waits (until `deadline`, the navigation's own) while a navigation to the
|
|
1003
|
+
* target address is in flight, then tells whether it loaded (its document committed; a script
|
|
1004
|
+
* may have moved the page on since), failed, or none of ours took over.
|
|
1005
|
+
*/
|
|
1006
|
+
async follow(deadline) {
|
|
1007
|
+
for (let r = this.pending(); r !== void 0; r = this.pending()) {
|
|
1008
|
+
if (!this.isOurs(r)) return { kind: "none" };
|
|
1009
|
+
const left2 = deadline - Date.now();
|
|
1010
|
+
if (left2 <= 0) return { kind: "none" };
|
|
1011
|
+
await this.next(left2);
|
|
1012
|
+
}
|
|
1013
|
+
const final = this.lastOurs;
|
|
1014
|
+
if (final === void 0) return { kind: "none" };
|
|
1015
|
+
if (this.failedOurs === final) {
|
|
1016
|
+
return { kind: "failed", url: final.url(), error: final.failure()?.errorText ?? "" };
|
|
1017
|
+
}
|
|
1018
|
+
if (this.committedOurs !== final) return { kind: "none" };
|
|
1019
|
+
const left = deadline - Date.now();
|
|
1020
|
+
if (left <= 0) return { kind: "none" };
|
|
1021
|
+
try {
|
|
1022
|
+
await this.page.waitForLoadState("domcontentloaded", { timeout: left });
|
|
1023
|
+
} catch {
|
|
1024
|
+
return { kind: "none" };
|
|
1025
|
+
}
|
|
1026
|
+
return { kind: "loaded", response: await final.response().catch(() => null) };
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* The status the newest navigation to the target address was answered with, when it finished
|
|
1030
|
+
* without a document (a 204 or 205: Chromium keeps the page and aborts the navigation).
|
|
1031
|
+
*/
|
|
1032
|
+
async emptyAnswer() {
|
|
1033
|
+
const r = this.lastOurs;
|
|
1034
|
+
if (r === void 0 || r === this.committedOurs) return void 0;
|
|
1035
|
+
const status = (await r.response().catch(() => null))?.status();
|
|
1036
|
+
return status === 204 || status === 205 ? status : void 0;
|
|
1037
|
+
}
|
|
1038
|
+
dispose() {
|
|
1039
|
+
this.page.off("request", this.onRequest);
|
|
1040
|
+
this.page.off("framenavigated", this.onNavigated);
|
|
1041
|
+
this.page.off("requestfailed", this.onFailed);
|
|
1042
|
+
this.page.off("requestfinished", this.onFinished);
|
|
1043
|
+
this.wake?.();
|
|
1044
|
+
}
|
|
1045
|
+
};
|
|
337
1046
|
function jpegSize(jpeg) {
|
|
338
1047
|
let i = 2;
|
|
339
1048
|
while (i + 9 < jpeg.length) {
|
|
@@ -371,13 +1080,28 @@ async function captureFitting(cdp, opts) {
|
|
|
371
1080
|
}
|
|
372
1081
|
return null;
|
|
373
1082
|
}
|
|
374
|
-
|
|
1083
|
+
var PROXY_DOWN_CODES = /* @__PURE__ */ new Set([
|
|
1084
|
+
"ECONNREFUSED",
|
|
1085
|
+
"EHOSTUNREACH",
|
|
1086
|
+
"ENETUNREACH",
|
|
1087
|
+
"ENOTFOUND",
|
|
1088
|
+
"EAI_AGAIN"
|
|
1089
|
+
]);
|
|
1090
|
+
async function proxyRefusal(proxy, host, port) {
|
|
1091
|
+
const answer = await probeProxy(proxy, host, port);
|
|
1092
|
+
if (answer.verdict !== "refused") return null;
|
|
1093
|
+
return refusalLayer(answer.reason);
|
|
1094
|
+
}
|
|
1095
|
+
function refusalLayer(reason) {
|
|
1096
|
+
return sandboxProxyRefusalLayer(reason) === "address" ? "address" : "device";
|
|
1097
|
+
}
|
|
1098
|
+
function probeProxy(proxy, host, port) {
|
|
375
1099
|
return new Promise((resolve) => {
|
|
376
1100
|
let url;
|
|
377
1101
|
try {
|
|
378
1102
|
url = new URL(proxy.includes("://") ? proxy : `http://${proxy}`);
|
|
379
1103
|
} catch {
|
|
380
|
-
resolve(
|
|
1104
|
+
resolve({ verdict: "unknown", reason: "" });
|
|
381
1105
|
return;
|
|
382
1106
|
}
|
|
383
1107
|
const headers = { host: `${host}:${port}` };
|
|
@@ -393,16 +1117,34 @@ function proxyRefuses(proxy, host, port) {
|
|
|
393
1117
|
headers,
|
|
394
1118
|
timeout: PROXY_PROBE_TIMEOUT_MS
|
|
395
1119
|
});
|
|
1120
|
+
const answer = (res) => ({
|
|
1121
|
+
verdict: res.statusCode === 403 ? "refused" : res.statusCode === 200 ? "connected" : "unreachable",
|
|
1122
|
+
reason: res.statusMessage ?? ""
|
|
1123
|
+
});
|
|
396
1124
|
req.on("connect", (res, socket) => {
|
|
397
1125
|
socket.destroy();
|
|
398
|
-
resolve(res
|
|
1126
|
+
resolve(answer(res));
|
|
399
1127
|
});
|
|
400
1128
|
req.on("response", (res) => {
|
|
401
1129
|
res.resume();
|
|
402
|
-
resolve(res
|
|
1130
|
+
resolve(answer(res));
|
|
1131
|
+
});
|
|
1132
|
+
req.on("timeout", () => {
|
|
1133
|
+
resolve({ verdict: "no_answer", reason: "" });
|
|
1134
|
+
req.destroy();
|
|
1135
|
+
});
|
|
1136
|
+
let connected = false;
|
|
1137
|
+
req.on("socket", (sock) => {
|
|
1138
|
+
if (sock.connecting) sock.once("connect", () => connected = true);
|
|
1139
|
+
else connected = true;
|
|
403
1140
|
});
|
|
404
|
-
req.on(
|
|
405
|
-
|
|
1141
|
+
req.on(
|
|
1142
|
+
"error",
|
|
1143
|
+
(e) => resolve({
|
|
1144
|
+
verdict: !connected && PROXY_DOWN_CODES.has(e.code ?? "") ? "proxy_down" : "unknown",
|
|
1145
|
+
reason: ""
|
|
1146
|
+
})
|
|
1147
|
+
);
|
|
406
1148
|
req.end();
|
|
407
1149
|
});
|
|
408
1150
|
}
|
|
@@ -422,10 +1164,46 @@ function normalizeUrl(raw) {
|
|
|
422
1164
|
return url.href;
|
|
423
1165
|
}
|
|
424
1166
|
var firstLine = (e) => (e instanceof Error ? e.message : String(e)).split("\n")[0]?.replace(/^[a-zA-Z.]+: /, "") ?? "";
|
|
1167
|
+
var NO_USAGE = {
|
|
1168
|
+
busy: () => false,
|
|
1169
|
+
pinned: () => false,
|
|
1170
|
+
idleFor: () => Number.POSITIVE_INFINITY,
|
|
1171
|
+
lastActiveAt: () => Number.NEGATIVE_INFINITY,
|
|
1172
|
+
tabParked: () => false,
|
|
1173
|
+
tabClosed: () => void 0,
|
|
1174
|
+
seen: () => void 0,
|
|
1175
|
+
known: () => true
|
|
1176
|
+
};
|
|
1177
|
+
function isStartBlank(tab) {
|
|
1178
|
+
return tab.owner === void 0 && tab.url === "about:blank";
|
|
1179
|
+
}
|
|
1180
|
+
var OTHER_TITLE_CHARS = 120;
|
|
1181
|
+
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.`;
|
|
1182
|
+
var tabInUse = (id) => `Tab ${id} is in use by another conversation right now; retry shortly or open your own tab.`;
|
|
1183
|
+
var tabMoved = (id, title) => `Tab ${id} (${title}) was moved to another conversation.`;
|
|
1184
|
+
var tabEvicted = (id, title) => `Tab ${id} (${title}) was closed to make room for another conversation.`;
|
|
1185
|
+
var CONVERSATION_CAP_MESSAGE = `This conversation has ${MAX_TABS_PER_CONVERSATION} tabs open, the most one conversation keeps; close one first.`;
|
|
1186
|
+
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.`;
|
|
1187
|
+
function bareUrl(raw) {
|
|
1188
|
+
try {
|
|
1189
|
+
const u = new URL(raw);
|
|
1190
|
+
u.search = "";
|
|
1191
|
+
u.hash = "";
|
|
1192
|
+
return u.href;
|
|
1193
|
+
} catch {
|
|
1194
|
+
return raw.replace(/[?#].*$/s, "");
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
function isActing(req) {
|
|
1198
|
+
if (req.op === "handoff_notice" || req.op === "handoff_clear") return false;
|
|
1199
|
+
if (req.op === "tabs") return req.action !== "list" && req.action !== "adopt";
|
|
1200
|
+
return true;
|
|
1201
|
+
}
|
|
425
1202
|
var BrowserSession = class {
|
|
426
1203
|
ctx;
|
|
427
1204
|
proxy;
|
|
428
1205
|
clock;
|
|
1206
|
+
navigationTimeoutMs;
|
|
429
1207
|
/** The device's workspace root (CAPYBARA_SERVICE_WORKSPACE): uploads and downloads stay in it. */
|
|
430
1208
|
workspace;
|
|
431
1209
|
downloadsTmp;
|
|
@@ -443,16 +1221,54 @@ var BrowserSession = class {
|
|
|
443
1221
|
ids = /* @__PURE__ */ new WeakMap();
|
|
444
1222
|
titles = /* @__PURE__ */ new Map();
|
|
445
1223
|
loadingTabs = /* @__PURE__ */ new Set();
|
|
1224
|
+
/**
|
|
1225
|
+
* Each tab's icon: the address it came from and its data URL (null: none or not usable). Kept
|
|
1226
|
+
* across navigations until the new page's icon is known, so the strip does not flicker.
|
|
1227
|
+
*/
|
|
1228
|
+
favicons = /* @__PURE__ */ new Map();
|
|
1229
|
+
/** Tabs showing a verification page, by tab id (cleared on every main-frame navigation). */
|
|
1230
|
+
blockers = /* @__PURE__ */ new Map();
|
|
1231
|
+
/** The status of each tab's current document (main-frame response), by tab id. */
|
|
1232
|
+
docStatus = /* @__PURE__ */ new Map();
|
|
1233
|
+
/** Each page's main-frame navigation request in flight (until it commits, fails or finishes). */
|
|
1234
|
+
pendingNavs = /* @__PURE__ */ new WeakMap();
|
|
446
1235
|
listeners = /* @__PURE__ */ new Set();
|
|
447
1236
|
collectors = /* @__PURE__ */ new Set();
|
|
448
1237
|
probes = /* @__PURE__ */ new Map();
|
|
449
1238
|
reservedDownloads = /* @__PURE__ */ new Set();
|
|
450
|
-
|
|
1239
|
+
/** Notes of a conversation's pages that arrived with none of its requests in flight. */
|
|
1240
|
+
unreported = /* @__PURE__ */ new Map();
|
|
1241
|
+
/** Device notes (no page: the browser build) for the next reply of any conversation. */
|
|
1242
|
+
unreportedAll = [];
|
|
451
1243
|
nextId = 1;
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
/**
|
|
455
|
-
|
|
1244
|
+
/** Each owned tab's owner (an unowned tab has no entry). */
|
|
1245
|
+
owners = /* @__PURE__ */ new Map();
|
|
1246
|
+
/** Each conversation's active tab. */
|
|
1247
|
+
activeOf = /* @__PURE__ */ new Map();
|
|
1248
|
+
/** The action queues, by {@link queueKey}. */
|
|
1249
|
+
queues = /* @__PURE__ */ new Map();
|
|
1250
|
+
/** A conversation's first tab being claimed or opened (shared by its callers meanwhile). */
|
|
1251
|
+
claiming = /* @__PURE__ */ new Map();
|
|
1252
|
+
/** Tab allocations (claim, open, eviction) one at a time across conversations. */
|
|
1253
|
+
allocChain = Promise.resolve();
|
|
1254
|
+
/** Tabs being opened by the session (not yet tracked): they count toward the device cap. */
|
|
1255
|
+
reserved = 0;
|
|
1256
|
+
/**
|
|
1257
|
+
* Tabs whose close is under way (an idle-closed conversation's, an evicted one): no
|
|
1258
|
+
* conversation owns, claims, adopts or lists them any more, and the device cap leaves them out.
|
|
1259
|
+
*/
|
|
1260
|
+
closing = /* @__PURE__ */ new Set();
|
|
1261
|
+
/** When an agent request last acted on each tab (the eviction's least recently used tab). */
|
|
1262
|
+
tabUsedAt = /* @__PURE__ */ new Map();
|
|
1263
|
+
/** When each tab went to its owner (the next active tab after a loss is the newest). */
|
|
1264
|
+
gainedAt = /* @__PURE__ */ new Map();
|
|
1265
|
+
gainSeq = 0;
|
|
1266
|
+
/** Order of the conversations' last acting requests (a viewer's default shown tab). */
|
|
1267
|
+
actedSeq = /* @__PURE__ */ new Map();
|
|
1268
|
+
actSeq = 0;
|
|
1269
|
+
usage;
|
|
1270
|
+
/** Each tab's latest agent click; `seq` grows with every click (viewers flash only new ones). */
|
|
1271
|
+
clicks = /* @__PURE__ */ new Map();
|
|
456
1272
|
clickSeq = 0;
|
|
457
1273
|
constructor(ctx, opts) {
|
|
458
1274
|
this.ctx = ctx;
|
|
@@ -462,20 +1278,21 @@ var BrowserSession = class {
|
|
|
462
1278
|
this.downloadMaxBytes = opts.downloadMaxBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES;
|
|
463
1279
|
this.downloadWaitMs = opts.downloadWaitMs ?? DOWNLOAD_WAIT_MS;
|
|
464
1280
|
this.clock = opts.clock ?? systemClock;
|
|
1281
|
+
this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
|
|
1282
|
+
this.usage = opts.usage ?? NO_USAGE;
|
|
465
1283
|
ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
|
|
466
|
-
ctx.setDefaultNavigationTimeout(
|
|
1284
|
+
ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
|
|
467
1285
|
ctx.on("page", (p) => {
|
|
468
|
-
if (
|
|
469
|
-
p.close().catch(() => void 0);
|
|
470
|
-
this.note(
|
|
471
|
-
`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.`
|
|
472
|
-
);
|
|
473
|
-
return;
|
|
474
|
-
}
|
|
1286
|
+
if (this.ids.has(p)) return;
|
|
475
1287
|
this.track(p);
|
|
476
|
-
this.active = this.ids.get(p);
|
|
477
|
-
this.emit({ type: "active" });
|
|
478
1288
|
this.emit({ type: "state" });
|
|
1289
|
+
queueMicrotask(() => {
|
|
1290
|
+
void this.allocate(async () => {
|
|
1291
|
+
const id = this.ids.get(p);
|
|
1292
|
+
if (id === void 0 || this.owners.has(id) || p.isClosed()) return;
|
|
1293
|
+
if (this.live().length > MAX_TABS) await p.close().catch(() => void 0);
|
|
1294
|
+
});
|
|
1295
|
+
});
|
|
479
1296
|
});
|
|
480
1297
|
for (const p of ctx.pages()) this.track(p);
|
|
481
1298
|
}
|
|
@@ -486,34 +1303,313 @@ var BrowserSession = class {
|
|
|
486
1303
|
this.listeners.add(fn);
|
|
487
1304
|
return () => this.listeners.delete(fn);
|
|
488
1305
|
}
|
|
489
|
-
/** The active tab, opening a blank one when none is left. */
|
|
490
|
-
async activePage() {
|
|
491
|
-
const cur = this.active === void 0 ? void 0 : this.pages.get(this.active);
|
|
492
|
-
if (cur !== void 0 && !cur.isClosed()) return cur;
|
|
493
|
-
const first = [...this.pages.values()].find((p2) => !p2.isClosed());
|
|
494
|
-
if (first !== void 0) {
|
|
495
|
-
this.active = this.ids.get(first);
|
|
496
|
-
return first;
|
|
497
|
-
}
|
|
498
|
-
const p = await this.ctx.newPage();
|
|
499
|
-
this.track(p);
|
|
500
|
-
this.active = this.ids.get(p);
|
|
501
|
-
return p;
|
|
502
|
-
}
|
|
503
1306
|
tabIdOf(page) {
|
|
504
1307
|
return this.ids.get(page) ?? "";
|
|
505
1308
|
}
|
|
1309
|
+
/** The live page of a tab, if it is open (and not closing). */
|
|
1310
|
+
pageById(tabId) {
|
|
1311
|
+
const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
|
|
1312
|
+
return page === void 0 || page.isClosed() || this.closing.has(tabId) ? void 0 : page;
|
|
1313
|
+
}
|
|
1314
|
+
/** The open tabs that are not closing, in tab order. */
|
|
1315
|
+
live() {
|
|
1316
|
+
return [...this.pages.entries()].filter(([id, p]) => !p.isClosed() && !this.closing.has(id));
|
|
1317
|
+
}
|
|
1318
|
+
/** A tab's owner, if it has one. */
|
|
1319
|
+
ownerOf(tabId) {
|
|
1320
|
+
return this.owners.get(tabId);
|
|
1321
|
+
}
|
|
1322
|
+
/** The conversations owning a tab now. */
|
|
1323
|
+
owningConversations() {
|
|
1324
|
+
return [...new Set([...this.owners.values()].map((o) => o.owner))];
|
|
1325
|
+
}
|
|
1326
|
+
/** The conversation's tabs in tab order. */
|
|
1327
|
+
tabsOf(conversationId) {
|
|
1328
|
+
return this.live().map(([id]) => id).filter((id) => this.owners.get(id)?.owner === conversationId);
|
|
1329
|
+
}
|
|
1330
|
+
/** How many tabs the conversation owns. */
|
|
1331
|
+
countOf(conversationId) {
|
|
1332
|
+
return this.tabsOf(conversationId).length;
|
|
1333
|
+
}
|
|
1334
|
+
/** The conversation's active tab id, if it has a live one. */
|
|
1335
|
+
activeTabOf(conversationId) {
|
|
1336
|
+
const id = this.activeOf.get(conversationId);
|
|
1337
|
+
return this.pageById(id) === void 0 ? void 0 : id;
|
|
1338
|
+
}
|
|
1339
|
+
/** The conversation's active page, if it has one (never opens a tab). */
|
|
1340
|
+
currentPage(conversationId) {
|
|
1341
|
+
return this.pageById(this.activeOf.get(conversationId));
|
|
1342
|
+
}
|
|
1343
|
+
/** The order of the conversation's last acting request (higher: later; 0: never). */
|
|
1344
|
+
actedOrder(conversationId) {
|
|
1345
|
+
return this.actedSeq.get(conversationId) ?? 0;
|
|
1346
|
+
}
|
|
1347
|
+
/** The tab's latest agent click, if any. */
|
|
1348
|
+
lastClickOf(tabId) {
|
|
1349
|
+
return tabId === void 0 ? void 0 : this.clicks.get(tabId);
|
|
1350
|
+
}
|
|
1351
|
+
/** Whether the tab is loading a document. */
|
|
1352
|
+
isLoading(tabId) {
|
|
1353
|
+
return tabId !== void 0 && this.loadingTabs.has(tabId);
|
|
1354
|
+
}
|
|
506
1355
|
tabs() {
|
|
507
|
-
return
|
|
508
|
-
id
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
1356
|
+
return this.live().map(([id, p]) => {
|
|
1357
|
+
const blocker = this.blockers.get(id);
|
|
1358
|
+
const icon = this.favicons.get(id)?.data;
|
|
1359
|
+
const o = this.owners.get(id);
|
|
1360
|
+
return {
|
|
1361
|
+
id,
|
|
1362
|
+
title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
|
|
1363
|
+
url: clip(p.url(), MAX_URL_CHARS),
|
|
1364
|
+
active: o !== void 0 && this.activeOf.get(o.owner) === id,
|
|
1365
|
+
...o === void 0 ? {} : { owner: o.owner, root: o.root },
|
|
1366
|
+
...blocker === void 0 ? {} : { blocker },
|
|
1367
|
+
...icon === void 0 || icon === null ? {} : { favicon: icon },
|
|
1368
|
+
...this.loadingTabs.has(id) ? { loading: true } : {}
|
|
1369
|
+
};
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
/** Makes a tab the conversation's active tab (it must own it). */
|
|
1373
|
+
setActive(conversationId, tabId) {
|
|
1374
|
+
if (this.owners.get(tabId)?.owner !== conversationId) return;
|
|
1375
|
+
if (this.activeOf.get(conversationId) === tabId) return;
|
|
1376
|
+
this.activeOf.set(conversationId, tabId);
|
|
1377
|
+
this.emit({ type: "active", conversationId });
|
|
1378
|
+
this.emit({ type: "state" });
|
|
1379
|
+
}
|
|
1380
|
+
/** Gives a tab to a conversation (owner and root); the previous owner's active moves on. */
|
|
1381
|
+
assign(tabId, to) {
|
|
1382
|
+
const before = this.owners.get(tabId);
|
|
1383
|
+
this.owners.set(tabId, to);
|
|
1384
|
+
this.gainedAt.set(tabId, ++this.gainSeq);
|
|
1385
|
+
if (before !== void 0 && before.owner !== to.owner) this.activeMovedOff(before.owner, tabId);
|
|
1386
|
+
return before;
|
|
513
1387
|
}
|
|
514
|
-
/**
|
|
515
|
-
|
|
516
|
-
|
|
1388
|
+
/**
|
|
1389
|
+
* A conversation lost its tab `tabId` (closed or moved): when it was its active tab, the active
|
|
1390
|
+
* tab becomes its most recently opened remaining tab, or none.
|
|
1391
|
+
*/
|
|
1392
|
+
activeMovedOff(conversationId, tabId) {
|
|
1393
|
+
if (this.activeOf.get(conversationId) !== tabId) return;
|
|
1394
|
+
const next = this.newestTabOf(conversationId, tabId);
|
|
1395
|
+
if (next === void 0) this.activeOf.delete(conversationId);
|
|
1396
|
+
else this.activeOf.set(conversationId, next);
|
|
1397
|
+
this.emit({ type: "active", conversationId });
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* The conversation's tab it gained last (opened, claimed, adopted or restored), besides
|
|
1401
|
+
* `except`.
|
|
1402
|
+
*/
|
|
1403
|
+
newestTabOf(conversationId, except) {
|
|
1404
|
+
let best;
|
|
1405
|
+
for (const id of this.tabsOf(conversationId)) {
|
|
1406
|
+
if (id === except) continue;
|
|
1407
|
+
if (best === void 0 || (this.gainedAt.get(id) ?? 0) > (this.gainedAt.get(best) ?? 0))
|
|
1408
|
+
best = id;
|
|
1409
|
+
}
|
|
1410
|
+
return best;
|
|
1411
|
+
}
|
|
1412
|
+
/** Runs a tab allocation (claim, open, eviction) one at a time across conversations. */
|
|
1413
|
+
allocate(fn) {
|
|
1414
|
+
const run = this.allocChain.then(fn, fn);
|
|
1415
|
+
this.allocChain = run.catch(() => void 0);
|
|
1416
|
+
return run;
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* The page an acting request of the conversation acts on: its active tab; with no live tab, an
|
|
1420
|
+
* unowned tab it claims, else a new tab (subject to the caps). Callers that find no tab at the
|
|
1421
|
+
* same time share one claim, so the conversation gets exactly one tab.
|
|
1422
|
+
*/
|
|
1423
|
+
async pageFor(conversationId, root) {
|
|
1424
|
+
const cur = this.currentPage(conversationId);
|
|
1425
|
+
if (cur !== void 0) return cur;
|
|
1426
|
+
const own = this.newestTabOf(conversationId);
|
|
1427
|
+
if (own !== void 0) {
|
|
1428
|
+
this.setActive(conversationId, own);
|
|
1429
|
+
const page = this.pageById(own);
|
|
1430
|
+
if (page !== void 0) return page;
|
|
1431
|
+
}
|
|
1432
|
+
let claim = this.claiming.get(conversationId);
|
|
1433
|
+
if (claim === void 0) {
|
|
1434
|
+
claim = this.allocate(async () => {
|
|
1435
|
+
const now = this.currentPage(conversationId) ?? this.pageById(this.newestTabOf(conversationId));
|
|
1436
|
+
if (now !== void 0) {
|
|
1437
|
+
this.setActive(conversationId, this.tabIdOf(now));
|
|
1438
|
+
return now;
|
|
1439
|
+
}
|
|
1440
|
+
const unowned = this.live().find(
|
|
1441
|
+
([id, p]) => isStartBlank({ owner: this.owners.get(id)?.owner, url: p.url() }) && !this.usage.tabParked(id)
|
|
1442
|
+
);
|
|
1443
|
+
if (unowned !== void 0) {
|
|
1444
|
+
const [id, page] = unowned;
|
|
1445
|
+
this.assign(id, { owner: conversationId, root });
|
|
1446
|
+
this.activeOf.set(conversationId, id);
|
|
1447
|
+
this.emit({ type: "active", conversationId });
|
|
1448
|
+
this.emit({ type: "state" });
|
|
1449
|
+
return page;
|
|
1450
|
+
}
|
|
1451
|
+
return this.openLocked(conversationId, root);
|
|
1452
|
+
}).finally(() => {
|
|
1453
|
+
this.claiming.delete(conversationId);
|
|
1454
|
+
});
|
|
1455
|
+
this.claiming.set(conversationId, claim);
|
|
1456
|
+
}
|
|
1457
|
+
return claim;
|
|
1458
|
+
}
|
|
1459
|
+
/** Opens a new tab for the conversation (the caps apply) and makes it its active tab. */
|
|
1460
|
+
openTab(conversationId, root) {
|
|
1461
|
+
return this.allocate(() => this.openLocked(conversationId, root));
|
|
1462
|
+
}
|
|
1463
|
+
/** {@link openTab} inside the allocation chain. */
|
|
1464
|
+
async openLocked(conversationId, root) {
|
|
1465
|
+
const own = this.countOf(conversationId);
|
|
1466
|
+
if (own >= MAX_TABS_PER_CONVERSATION) throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
|
|
1467
|
+
if (this.live().length + this.reserved >= MAX_TABS && !await this.evict(conversationId))
|
|
1468
|
+
throw new ActionError("failed", deviceCapMessage(own));
|
|
1469
|
+
this.reserved++;
|
|
1470
|
+
let page;
|
|
1471
|
+
try {
|
|
1472
|
+
page = await this.ctx.newPage();
|
|
1473
|
+
} finally {
|
|
1474
|
+
this.reserved--;
|
|
1475
|
+
}
|
|
1476
|
+
this.track(page);
|
|
1477
|
+
const id = this.tabIdOf(page);
|
|
1478
|
+
this.assign(id, { owner: conversationId, root });
|
|
1479
|
+
this.activeOf.set(conversationId, id);
|
|
1480
|
+
this.emit({ type: "active", conversationId });
|
|
1481
|
+
this.emit({ type: "state" });
|
|
1482
|
+
return page;
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* Closes one tab to make room at the device cap: an unowned tab first, else a tab of the least
|
|
1486
|
+
* recently active conversation that is evictable (not in use, not pinned by a viewer, idle for
|
|
1487
|
+
* at least EVICT_MIN_IDLE_MS), its least recently used non-active tab before its active one; tabs
|
|
1488
|
+
* a park pins are skipped. Its owner is told. False when no tab qualifies.
|
|
1489
|
+
*/
|
|
1490
|
+
async evict(forConversation) {
|
|
1491
|
+
const live = this.live().filter(([id]) => !this.usage.tabParked(id));
|
|
1492
|
+
const unowned = live.find(([id]) => !this.owners.has(id));
|
|
1493
|
+
if (unowned !== void 0) {
|
|
1494
|
+
await this.closeEvicted(unowned[0], unowned[1]);
|
|
1495
|
+
return true;
|
|
1496
|
+
}
|
|
1497
|
+
const owners = /* @__PURE__ */ new Set();
|
|
1498
|
+
for (const [id] of live) {
|
|
1499
|
+
const o = this.owners.get(id)?.owner;
|
|
1500
|
+
if (o !== void 0 && o !== forConversation && !this.usage.busy(o) && !this.usage.pinned(o) && this.usage.idleFor(o) >= EVICT_MIN_IDLE_MS)
|
|
1501
|
+
owners.add(o);
|
|
1502
|
+
}
|
|
1503
|
+
const victim = [...owners].sort(
|
|
1504
|
+
(a, b) => this.usage.lastActiveAt(a) - this.usage.lastActiveAt(b)
|
|
1505
|
+
)[0];
|
|
1506
|
+
if (victim === void 0) return false;
|
|
1507
|
+
const active = this.activeOf.get(victim);
|
|
1508
|
+
const used = (id) => this.tabUsedAt.get(id) ?? 0;
|
|
1509
|
+
const [tabId, page] = live.filter(([id]) => this.owners.get(id)?.owner === victim).sort(
|
|
1510
|
+
([a], [b]) => (a === active ? 1 : 0) - (b === active ? 1 : 0) || used(a) - used(b)
|
|
1511
|
+
)[0] ?? [];
|
|
1512
|
+
if (tabId === void 0 || page === void 0) return false;
|
|
1513
|
+
const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
|
|
1514
|
+
await this.closeEvicted(tabId, page);
|
|
1515
|
+
this.noteTo(victim, tabEvicted(tabId, title));
|
|
1516
|
+
return true;
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Closes an evicted tab, closing from the start: no request or adopt reaches it while its close
|
|
1520
|
+
* runs (the close handler forgets it; a tab that would not close is kept as it was).
|
|
1521
|
+
*/
|
|
1522
|
+
async closeEvicted(tabId, page) {
|
|
1523
|
+
this.closing.add(tabId);
|
|
1524
|
+
await page.close().catch(() => {
|
|
1525
|
+
this.closing.delete(tabId);
|
|
1526
|
+
});
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* Moves a tab to the conversation and makes it its active tab (the tool's and a viewer's adopt).
|
|
1530
|
+
* `in_use`: its owner has a request in flight or a park (or a park pins the tab); `cap`: the
|
|
1531
|
+
* conversation already owns MAX_TABS_PER_CONVERSATION tabs. The previous owner is told.
|
|
1532
|
+
*/
|
|
1533
|
+
adopt(conversationId, root, tabId) {
|
|
1534
|
+
this.tabById(tabId);
|
|
1535
|
+
const before = this.owners.get(tabId);
|
|
1536
|
+
if (before?.owner === conversationId) {
|
|
1537
|
+
this.setActive(conversationId, tabId);
|
|
1538
|
+
return "ok";
|
|
1539
|
+
}
|
|
1540
|
+
if (before !== void 0 && this.usage.busy(before.owner) || this.usage.tabParked(tabId))
|
|
1541
|
+
return "in_use";
|
|
1542
|
+
if (this.countOf(conversationId) >= MAX_TABS_PER_CONVERSATION) return "cap";
|
|
1543
|
+
this.assign(tabId, { owner: conversationId, root });
|
|
1544
|
+
this.activeOf.set(conversationId, tabId);
|
|
1545
|
+
this.usage.seen(conversationId, root);
|
|
1546
|
+
if (before !== void 0) {
|
|
1547
|
+
const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
|
|
1548
|
+
this.noteTo(before.owner, tabMoved(tabId, title));
|
|
1549
|
+
}
|
|
1550
|
+
this.emit({ type: "active", conversationId });
|
|
1551
|
+
this.emit({ type: "state" });
|
|
1552
|
+
return "ok";
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Opens a restored tab for its owner (the first claims the start's blank tab) and starts its
|
|
1556
|
+
* navigation without waiting for it.
|
|
1557
|
+
*/
|
|
1558
|
+
async restoreTab(owner, url) {
|
|
1559
|
+
const page = await this.allocate(async () => {
|
|
1560
|
+
const blank = this.live().find(
|
|
1561
|
+
([id2, p]) => isStartBlank({ owner: this.owners.get(id2)?.owner, url: p.url() })
|
|
1562
|
+
);
|
|
1563
|
+
if (blank !== void 0) {
|
|
1564
|
+
this.assign(blank[0], owner);
|
|
1565
|
+
return blank[1];
|
|
1566
|
+
}
|
|
1567
|
+
this.reserved++;
|
|
1568
|
+
try {
|
|
1569
|
+
const p = await this.ctx.newPage();
|
|
1570
|
+
this.track(p);
|
|
1571
|
+
this.assign(this.tabIdOf(p), owner);
|
|
1572
|
+
return p;
|
|
1573
|
+
} finally {
|
|
1574
|
+
this.reserved--;
|
|
1575
|
+
}
|
|
1576
|
+
});
|
|
1577
|
+
const id = this.tabIdOf(page);
|
|
1578
|
+
if (!this.activeOf.has(owner.owner)) this.activeOf.set(owner.owner, id);
|
|
1579
|
+
this.usage.seen(owner.owner, owner.root);
|
|
1580
|
+
this.emit({ type: "active", conversationId: owner.owner });
|
|
1581
|
+
this.emit({ type: "state" });
|
|
1582
|
+
let target;
|
|
1583
|
+
try {
|
|
1584
|
+
target = normalizeUrl(url);
|
|
1585
|
+
} catch {
|
|
1586
|
+
}
|
|
1587
|
+
if (target !== void 0) void this.viewerNav(page, { url: target });
|
|
1588
|
+
return id;
|
|
1589
|
+
}
|
|
1590
|
+
/**
|
|
1591
|
+
* Closes an idle conversation's tabs (except those a park pins) and forgets what the session
|
|
1592
|
+
* keeps for it.
|
|
1593
|
+
*/
|
|
1594
|
+
async closeConversation(conversationId) {
|
|
1595
|
+
const ids = this.tabsOf(conversationId).filter((id) => !this.usage.tabParked(id));
|
|
1596
|
+
for (const id of ids) {
|
|
1597
|
+
this.closing.add(id);
|
|
1598
|
+
this.owners.delete(id);
|
|
1599
|
+
}
|
|
1600
|
+
this.activeOf.delete(conversationId);
|
|
1601
|
+
this.queues.delete(this.queueKey(conversationId));
|
|
1602
|
+
this.unreported.delete(conversationId);
|
|
1603
|
+
this.claiming.delete(conversationId);
|
|
1604
|
+
this.actedSeq.delete(conversationId);
|
|
1605
|
+
await Promise.all(
|
|
1606
|
+
ids.map(
|
|
1607
|
+
(id) => this.pages.get(id)?.close().catch(() => {
|
|
1608
|
+
this.closing.delete(id);
|
|
1609
|
+
})
|
|
1610
|
+
)
|
|
1611
|
+
);
|
|
1612
|
+
this.emit({ type: "state" });
|
|
517
1613
|
}
|
|
518
1614
|
emit(e) {
|
|
519
1615
|
for (const fn of [...this.listeners]) {
|
|
@@ -529,55 +1625,119 @@ var BrowserSession = class {
|
|
|
529
1625
|
this.ids.set(page, id);
|
|
530
1626
|
this.pages.set(id, page);
|
|
531
1627
|
const refresh = () => {
|
|
532
|
-
page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).finally(() => this.emit({ type: "state" }));
|
|
1628
|
+
page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
|
|
533
1629
|
};
|
|
1630
|
+
const settle = (r) => {
|
|
1631
|
+
if (this.pendingNavs.get(page) === r) this.pendingNavs.delete(page);
|
|
1632
|
+
};
|
|
1633
|
+
page.on("requestfinished", (r) => {
|
|
1634
|
+
if (this.pendingNavs.get(page) !== r) return;
|
|
1635
|
+
void r.response().then(
|
|
1636
|
+
(res) => {
|
|
1637
|
+
const status = res?.status() ?? 0;
|
|
1638
|
+
const redirects = status >= 300 && status < 400 && res?.headers().location;
|
|
1639
|
+
if (!redirects) settle(r);
|
|
1640
|
+
},
|
|
1641
|
+
() => settle(r)
|
|
1642
|
+
);
|
|
1643
|
+
});
|
|
534
1644
|
page.on("request", (r) => {
|
|
535
1645
|
if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
1646
|
+
this.pendingNavs.set(page, r);
|
|
536
1647
|
this.loadingTabs.add(id);
|
|
537
1648
|
this.emit({ type: "state" });
|
|
538
1649
|
}
|
|
539
1650
|
});
|
|
540
1651
|
page.on("framenavigated", (f) => {
|
|
541
|
-
if (f
|
|
1652
|
+
if (f !== page.mainFrame()) return;
|
|
1653
|
+
this.pendingNavs.delete(page);
|
|
1654
|
+
this.blockers.delete(id);
|
|
1655
|
+
refresh();
|
|
542
1656
|
});
|
|
543
1657
|
page.on("domcontentloaded", refresh);
|
|
544
1658
|
page.on("load", () => {
|
|
545
1659
|
this.loadingTabs.delete(id);
|
|
546
1660
|
refresh();
|
|
1661
|
+
void this.resolveFavicon(page, id);
|
|
547
1662
|
});
|
|
548
1663
|
page.on("requestfailed", (r) => {
|
|
1664
|
+
settle(r);
|
|
549
1665
|
const err = r.failure()?.errorText ?? "";
|
|
550
1666
|
if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
551
1667
|
this.loadingTabs.delete(id);
|
|
552
1668
|
this.emit({ type: "state" });
|
|
553
1669
|
}
|
|
554
|
-
if (this.proxy !== void 0 && PROXY_FAILURE_RE.test(err))
|
|
555
|
-
this.checkBlocked(r.url(), this.pageToOpen(page, r));
|
|
1670
|
+
if (this.proxy !== void 0 && (PROXY_FAILURE_RE.test(err) || err.includes("ERR_NETWORK_CHANGED")))
|
|
1671
|
+
this.checkBlocked(page, r.url(), this.pageToOpen(page, r));
|
|
556
1672
|
});
|
|
557
1673
|
page.on("response", (r) => {
|
|
1674
|
+
if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
|
|
1675
|
+
this.docStatus.set(id, r.status());
|
|
558
1676
|
if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
|
|
559
|
-
this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
|
|
1677
|
+
this.checkBlocked(page, r.url(), this.pageToOpen(page, r.request()));
|
|
560
1678
|
}
|
|
561
1679
|
});
|
|
562
|
-
page.on("dialog", (d) => this.onDialog(d));
|
|
563
|
-
page.on("download", (d) => this.onDownload(d));
|
|
1680
|
+
page.on("dialog", (d) => this.onDialog(page, d));
|
|
1681
|
+
page.on("download", (d) => this.onDownload(page, d));
|
|
564
1682
|
page.on("filechooser", () => {
|
|
565
|
-
|
|
566
|
-
this.
|
|
1683
|
+
const o = this.owners.get(id);
|
|
1684
|
+
this.noteTo(
|
|
1685
|
+
o?.owner,
|
|
1686
|
+
"The page opened a file chooser; use the upload tool with the file input's ref."
|
|
1687
|
+
);
|
|
1688
|
+
if (o !== void 0) this.emit({ type: "dialog", kind: "file", message: "", root: o.root });
|
|
567
1689
|
});
|
|
1690
|
+
page.on("popup", (p) => this.onPopup(page, p));
|
|
568
1691
|
page.on("close", () => {
|
|
1692
|
+
this.pendingNavs.delete(page);
|
|
569
1693
|
this.pages.delete(id);
|
|
1694
|
+
this.closing.delete(id);
|
|
570
1695
|
this.titles.delete(id);
|
|
571
1696
|
this.loadingTabs.delete(id);
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
1697
|
+
this.blockers.delete(id);
|
|
1698
|
+
this.favicons.delete(id);
|
|
1699
|
+
this.docStatus.delete(id);
|
|
1700
|
+
this.tabUsedAt.delete(id);
|
|
1701
|
+
this.gainedAt.delete(id);
|
|
1702
|
+
this.clicks.delete(id);
|
|
1703
|
+
const o = this.owners.get(id);
|
|
1704
|
+
this.owners.delete(id);
|
|
1705
|
+
if (o !== void 0) this.activeMovedOff(o.owner, id);
|
|
1706
|
+
this.usage.tabClosed(id);
|
|
577
1707
|
this.emit({ type: "state" });
|
|
578
1708
|
});
|
|
579
1709
|
}
|
|
580
|
-
|
|
1710
|
+
/**
|
|
1711
|
+
* A page opened a popup: it belongs to the opener's owner and becomes its active tab, as in a
|
|
1712
|
+
* desktop browser (an unowned opener leaves it unowned). Past the conversation's cap it is closed
|
|
1713
|
+
* at once; past the device cap a tab is evicted for it, else it is closed; the owner is told.
|
|
1714
|
+
*/
|
|
1715
|
+
onPopup(opener, popup) {
|
|
1716
|
+
this.track(popup);
|
|
1717
|
+
const id = this.tabIdOf(popup);
|
|
1718
|
+
const o = this.owners.get(this.tabIdOf(opener));
|
|
1719
|
+
if (o === void 0 || this.owners.has(id) || popup.isClosed()) return;
|
|
1720
|
+
const closeIt = (why) => {
|
|
1721
|
+
popup.close().catch(() => void 0);
|
|
1722
|
+
this.noteTo(
|
|
1723
|
+
o.owner,
|
|
1724
|
+
`The page opened a popup, but ${why}, so the popup was closed; close a tab and retry if it was needed.`
|
|
1725
|
+
);
|
|
1726
|
+
};
|
|
1727
|
+
if (this.countOf(o.owner) >= MAX_TABS_PER_CONVERSATION) {
|
|
1728
|
+
closeIt(`this conversation keeps at most ${MAX_TABS_PER_CONVERSATION} tabs`);
|
|
1729
|
+
return;
|
|
1730
|
+
}
|
|
1731
|
+
this.assign(id, o);
|
|
1732
|
+
this.activeOf.set(o.owner, id);
|
|
1733
|
+
this.emit({ type: "active", conversationId: o.owner });
|
|
1734
|
+
this.emit({ type: "state" });
|
|
1735
|
+
void this.allocate(async () => {
|
|
1736
|
+
if (popup.isClosed() || this.live().length <= MAX_TABS) return;
|
|
1737
|
+
if (!await this.evict(o.owner)) closeIt(`the browser keeps at most ${MAX_TABS} tabs`);
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
onDialog(page, d) {
|
|
581
1741
|
const type = d.type();
|
|
582
1742
|
if (type === "beforeunload") {
|
|
583
1743
|
d.accept().catch(() => void 0);
|
|
@@ -587,24 +1747,50 @@ var BrowserSession = class {
|
|
|
587
1747
|
const message = clip(d.message(), MAX_DIALOG_CHARS);
|
|
588
1748
|
const settle = kind === "alert" ? d.accept() : d.dismiss();
|
|
589
1749
|
settle.catch(() => void 0);
|
|
590
|
-
this.
|
|
1750
|
+
const o = this.owners.get(this.tabIdOf(page));
|
|
1751
|
+
this.noteTo(
|
|
1752
|
+
o?.owner,
|
|
591
1753
|
`The page showed ${kind === "alert" ? "an alert" : `a ${kind}`} dialog: ${JSON.stringify(message)} (${kind === "alert" ? "closed" : "dismissed"}).`
|
|
592
1754
|
);
|
|
593
|
-
this.emit({ type: "dialog", kind, message });
|
|
1755
|
+
if (o !== void 0) this.emit({ type: "dialog", kind, message, root: o.root });
|
|
594
1756
|
}
|
|
595
1757
|
/**
|
|
596
|
-
*
|
|
597
|
-
*
|
|
1758
|
+
* A device note (not about a page: the browser build that runs): the replies of the requests in
|
|
1759
|
+
* flight carry it, else the next reply of any conversation.
|
|
598
1760
|
*/
|
|
599
1761
|
note(text) {
|
|
600
1762
|
const n = clip(text, MAX_DIALOG_CHARS + 200);
|
|
601
1763
|
if (this.collectors.size === 0) {
|
|
602
|
-
this.
|
|
603
|
-
if (this.
|
|
1764
|
+
this.unreportedAll.push(n);
|
|
1765
|
+
if (this.unreportedAll.length > MAX_UNREPORTED) this.unreportedAll.shift();
|
|
604
1766
|
return;
|
|
605
1767
|
}
|
|
606
1768
|
for (const c of this.collectors) c.notes.push(n);
|
|
607
1769
|
}
|
|
1770
|
+
/**
|
|
1771
|
+
* A note for a conversation (about one of its pages): its requests in flight carry it, else its
|
|
1772
|
+
* next reply. A note of an unowned page (`undefined`) reaches nobody.
|
|
1773
|
+
*/
|
|
1774
|
+
noteTo(conversationId, text) {
|
|
1775
|
+
if (conversationId === void 0) return;
|
|
1776
|
+
if (this.countOf(conversationId) === 0 && !this.usage.known(conversationId)) return;
|
|
1777
|
+
const n = clip(text, MAX_DIALOG_CHARS + 200);
|
|
1778
|
+
let delivered = false;
|
|
1779
|
+
for (const c of this.collectors) {
|
|
1780
|
+
if (c.conv !== conversationId) continue;
|
|
1781
|
+
c.notes.push(n);
|
|
1782
|
+
delivered = true;
|
|
1783
|
+
}
|
|
1784
|
+
if (delivered) return;
|
|
1785
|
+
const list = this.unreported.get(conversationId) ?? [];
|
|
1786
|
+
list.push(n);
|
|
1787
|
+
if (list.length > MAX_UNREPORTED) list.shift();
|
|
1788
|
+
this.unreported.set(conversationId, list);
|
|
1789
|
+
}
|
|
1790
|
+
/** The owner of a page, if it has one. */
|
|
1791
|
+
ownerOfPage(page) {
|
|
1792
|
+
return page === null || page === void 0 ? void 0 : this.owners.get(this.tabIdOf(page));
|
|
1793
|
+
}
|
|
608
1794
|
/**
|
|
609
1795
|
* Saves a download into `<workspace>/downloads` under its suggested name (sanitized, numbered
|
|
610
1796
|
* when taken). A request in flight waits for it at most `downloadWaitMs`, then says it is still
|
|
@@ -612,12 +1798,14 @@ var BrowserSession = class {
|
|
|
612
1798
|
* cancelled when together they pass `downloadMaxBytes`, so a page cannot fill the disk.
|
|
613
1799
|
* Without a workspace the download is cancelled.
|
|
614
1800
|
*/
|
|
615
|
-
onDownload(d) {
|
|
1801
|
+
onDownload(page, d) {
|
|
616
1802
|
const shown = JSON.stringify(clip(d.suggestedFilename(), 300));
|
|
617
1803
|
const workspace = this.workspace;
|
|
1804
|
+
const owner = this.ownerOfPage(page)?.owner;
|
|
1805
|
+
const note = (text) => this.noteTo(owner, text);
|
|
618
1806
|
if (workspace === void 0) {
|
|
619
1807
|
d.cancel().catch(() => void 0);
|
|
620
|
-
|
|
1808
|
+
note(
|
|
621
1809
|
`The page started a download (${shown}), which was cancelled: the device has no workspace.`
|
|
622
1810
|
);
|
|
623
1811
|
return;
|
|
@@ -630,21 +1818,20 @@ var BrowserSession = class {
|
|
|
630
1818
|
try {
|
|
631
1819
|
const failure = await d.failure();
|
|
632
1820
|
if (failure !== null) {
|
|
633
|
-
if (failure !== "canceled")
|
|
1821
|
+
if (failure !== "canceled") note(`The download of ${shown} failed: ${failure}.`);
|
|
634
1822
|
return;
|
|
635
1823
|
}
|
|
636
1824
|
const tmp = await d.path();
|
|
637
1825
|
if (statSync(tmp).size > this.downloadMaxBytes) {
|
|
638
|
-
|
|
1826
|
+
note(
|
|
639
1827
|
`The download of ${shown} was not saved: it is larger than ${this.downloadMaxBytes} bytes.`
|
|
640
1828
|
);
|
|
641
1829
|
return;
|
|
642
1830
|
}
|
|
643
|
-
target = this.
|
|
644
|
-
|
|
645
|
-
this.note(`Downloaded ${shown} to ${target}.`);
|
|
1831
|
+
target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
|
|
1832
|
+
note(`Downloaded ${shown} to ${target}.`);
|
|
646
1833
|
} catch (e) {
|
|
647
|
-
|
|
1834
|
+
note(
|
|
648
1835
|
`The download of ${shown} was not saved: ${e instanceof ActionError ? e.message : firstLine(e)}`
|
|
649
1836
|
);
|
|
650
1837
|
} finally {
|
|
@@ -654,10 +1841,64 @@ var BrowserSession = class {
|
|
|
654
1841
|
entry.finished = true;
|
|
655
1842
|
}
|
|
656
1843
|
})();
|
|
657
|
-
for (const c of this.collectors) c.downloads.push(entry);
|
|
1844
|
+
for (const c of this.collectors) if (c.conv === owner) c.downloads.push(entry);
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* Copies a finished download from Playwright's private file into `<workspace>/downloads` and
|
|
1848
|
+
* returns where. The agent owns that directory, so the target is never written through a path
|
|
1849
|
+
* it could have swapped: each candidate is created exclusively without following a link
|
|
1850
|
+
* (`O_CREAT | O_EXCL | O_NOFOLLOW`), then checked to be the file the resolved path inside the
|
|
1851
|
+
* downloads directory names before any byte is written; a mismatch (a directory swapped for a
|
|
1852
|
+
* link meanwhile) writes nothing, removes the empty file it made (only while that name still
|
|
1853
|
+
* is the file it opened) and fails.
|
|
1854
|
+
*/
|
|
1855
|
+
saveDownload(workspace, name, source) {
|
|
1856
|
+
const dir = this.downloadsDir(workspace);
|
|
1857
|
+
const dirStat = lstatSync(dir);
|
|
1858
|
+
const ext = extname(name);
|
|
1859
|
+
const stem = name.slice(0, name.length - ext.length);
|
|
1860
|
+
for (let i = 0; i < 1e3; i++) {
|
|
1861
|
+
const target = join(dir, i === 0 ? name : `${stem} (${i})${ext}`);
|
|
1862
|
+
if (this.reservedDownloads.has(target)) continue;
|
|
1863
|
+
let out;
|
|
1864
|
+
try {
|
|
1865
|
+
out = openSync(target, fsc.O_WRONLY | fsc.O_CREAT | fsc.O_EXCL | fsc.O_NOFOLLOW, 436);
|
|
1866
|
+
} catch (e) {
|
|
1867
|
+
if (e.code === "EEXIST") continue;
|
|
1868
|
+
throw e;
|
|
1869
|
+
}
|
|
1870
|
+
this.reservedDownloads.add(target);
|
|
1871
|
+
try {
|
|
1872
|
+
let real;
|
|
1873
|
+
try {
|
|
1874
|
+
real = realpathSync(target);
|
|
1875
|
+
} catch {
|
|
1876
|
+
real = "";
|
|
1877
|
+
}
|
|
1878
|
+
const opened = fstatSync(out);
|
|
1879
|
+
const placed = real !== "" && within(real, dir) && sameFile(opened, statSync(real));
|
|
1880
|
+
if (!placed || !sameFile(dirStat, lstatSync(dir))) {
|
|
1881
|
+
try {
|
|
1882
|
+
if (real !== "" && sameFile(opened, lstatSync(real)) && opened.size === 0)
|
|
1883
|
+
unlinkSync(real);
|
|
1884
|
+
} catch {
|
|
1885
|
+
}
|
|
1886
|
+
throw new ActionError(
|
|
1887
|
+
"failed",
|
|
1888
|
+
`${dir} changed while the download was saved; nothing was written. Retry the download.`
|
|
1889
|
+
);
|
|
1890
|
+
}
|
|
1891
|
+
copyInto(source, out);
|
|
1892
|
+
return target;
|
|
1893
|
+
} finally {
|
|
1894
|
+
closeSync(out);
|
|
1895
|
+
this.reservedDownloads.delete(target);
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
throw new ActionError("failed", `No free name for ${name} in ${dir}; remove old downloads.`);
|
|
658
1899
|
}
|
|
659
|
-
/**
|
|
660
|
-
|
|
1900
|
+
/** `<workspace>/downloads` resolved, refusing one that is a link or not a directory. */
|
|
1901
|
+
downloadsDir(workspace) {
|
|
661
1902
|
const root = realpathSync(workspace);
|
|
662
1903
|
const dir = join(root, "downloads");
|
|
663
1904
|
mkdirSync(dir, { recursive: true });
|
|
@@ -668,14 +1909,7 @@ var BrowserSession = class {
|
|
|
668
1909
|
`${dir} is not a plain directory in the workspace; remove it so downloads can be saved.`
|
|
669
1910
|
);
|
|
670
1911
|
}
|
|
671
|
-
|
|
672
|
-
const stem = name.slice(0, name.length - ext.length);
|
|
673
|
-
let target = join(dir, name);
|
|
674
|
-
for (let i = 1; !absent(target) || this.reservedDownloads.has(target); i++) {
|
|
675
|
-
target = join(dir, `${stem} (${i})${ext}`);
|
|
676
|
-
}
|
|
677
|
-
this.reservedDownloads.add(target);
|
|
678
|
-
return target;
|
|
1912
|
+
return dir;
|
|
679
1913
|
}
|
|
680
1914
|
/**
|
|
681
1915
|
* While downloads run, sums the bytes of Playwright's in-progress files and cancels every
|
|
@@ -706,7 +1940,8 @@ var BrowserSession = class {
|
|
|
706
1940
|
if (bytes > this.downloadMaxBytes) {
|
|
707
1941
|
for (const f of names) this.cancelledTmp.add(f);
|
|
708
1942
|
for (const d of this.activeDownloads) {
|
|
709
|
-
this.
|
|
1943
|
+
this.noteTo(
|
|
1944
|
+
this.ownerOfPage(d.page())?.owner,
|
|
710
1945
|
`The download of ${JSON.stringify(clip(d.suggestedFilename(), 300))} was cancelled: downloads in progress passed ${this.downloadMaxBytes} bytes.`
|
|
711
1946
|
);
|
|
712
1947
|
d.cancel().catch(() => void 0);
|
|
@@ -717,29 +1952,69 @@ var BrowserSession = class {
|
|
|
717
1952
|
this.pollDownloads();
|
|
718
1953
|
}, DOWNLOAD_POLL_MS);
|
|
719
1954
|
}
|
|
720
|
-
/**
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
1955
|
+
/**
|
|
1956
|
+
* An upload's bytes, read here and handed to Chromium from memory (never a path Chromium would
|
|
1957
|
+
* open later, after the agent could have swapped it for a link to the service's own files):
|
|
1958
|
+
* opened without following a final link, then accepted only when the resolved path lies in the
|
|
1959
|
+
* workspace and names the very file opened (an intermediate link swapped in either way shows as
|
|
1960
|
+
* another file), a regular file of at most {@link UPLOAD_MAX_BYTES}.
|
|
1961
|
+
*/
|
|
1962
|
+
readUpload(path) {
|
|
1963
|
+
const root = this.uploadRoot();
|
|
1964
|
+
let fd;
|
|
728
1965
|
try {
|
|
729
|
-
|
|
730
|
-
} catch {
|
|
1966
|
+
fd = openSync(path, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
|
|
1967
|
+
} catch (e) {
|
|
1968
|
+
const code = e.code;
|
|
731
1969
|
throw new ActionError(
|
|
732
1970
|
"failed",
|
|
733
|
-
`No file at ${path}; give the absolute path of a file in the workspace (${root}).`
|
|
1971
|
+
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}).`
|
|
734
1972
|
);
|
|
735
1973
|
}
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
1974
|
+
try {
|
|
1975
|
+
const opened = fstatSync(fd);
|
|
1976
|
+
let real = "";
|
|
1977
|
+
try {
|
|
1978
|
+
real = realpathSync(path);
|
|
1979
|
+
} catch {
|
|
1980
|
+
real = "";
|
|
1981
|
+
}
|
|
1982
|
+
if (!within(real, root) || !sameFile(opened, statSync(real)))
|
|
1983
|
+
throw new ActionError(
|
|
1984
|
+
"failed",
|
|
1985
|
+
`Upload paths must be inside the workspace (${root}); copy the file there first.`
|
|
1986
|
+
);
|
|
1987
|
+
if (!opened.isFile())
|
|
1988
|
+
throw new ActionError("failed", `${path} is not a regular file; upload a file.`);
|
|
1989
|
+
if (opened.size > UPLOAD_MAX_BYTES)
|
|
1990
|
+
throw new ActionError(
|
|
1991
|
+
"failed",
|
|
1992
|
+
`${path} is larger than ${UPLOAD_MAX_BYTES} bytes, the most an upload takes.`
|
|
1993
|
+
);
|
|
1994
|
+
const buffer = Buffer.alloc(opened.size);
|
|
1995
|
+
let off = 0;
|
|
1996
|
+
while (off < buffer.length) {
|
|
1997
|
+
const n = readSync(fd, buffer, off, buffer.length - off, off);
|
|
1998
|
+
if (n === 0) break;
|
|
1999
|
+
off += n;
|
|
2000
|
+
}
|
|
2001
|
+
const name = basename(real);
|
|
2002
|
+
return {
|
|
2003
|
+
name,
|
|
2004
|
+
mimeType: UPLOAD_TYPES[extname(name).toLowerCase()] ?? "application/octet-stream",
|
|
2005
|
+
buffer: buffer.subarray(0, off)
|
|
2006
|
+
};
|
|
2007
|
+
} finally {
|
|
2008
|
+
closeSync(fd);
|
|
741
2009
|
}
|
|
742
|
-
|
|
2010
|
+
}
|
|
2011
|
+
/** The resolved workspace uploads come from. */
|
|
2012
|
+
uploadRoot() {
|
|
2013
|
+
const workspace = this.workspace;
|
|
2014
|
+
if (workspace === void 0) {
|
|
2015
|
+
throw new ActionError("failed", "Uploads are unavailable: the device has no workspace.");
|
|
2016
|
+
}
|
|
2017
|
+
return realpathSync(workspace);
|
|
743
2018
|
}
|
|
744
2019
|
/**
|
|
745
2020
|
* The page a viewer opens once the refused host is allowed: the navigation's target for a
|
|
@@ -752,8 +2027,9 @@ var BrowserSession = class {
|
|
|
752
2027
|
* Probes the proxy for the URL's host and reports it when refused; the viewers' `blocked`
|
|
753
2028
|
* message carries `pageUrl` (default: the URL itself), the page to open once allowed.
|
|
754
2029
|
*/
|
|
755
|
-
checkBlocked(rawUrl, pageUrl) {
|
|
2030
|
+
checkBlocked(page, rawUrl, pageUrl) {
|
|
756
2031
|
const proxy = this.proxy;
|
|
2032
|
+
const owner = this.ownerOfPage(page);
|
|
757
2033
|
if (proxy === void 0) return Promise.resolve(false);
|
|
758
2034
|
let url;
|
|
759
2035
|
try {
|
|
@@ -763,39 +2039,81 @@ var BrowserSession = class {
|
|
|
763
2039
|
}
|
|
764
2040
|
const host = url.hostname;
|
|
765
2041
|
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
|
766
|
-
|
|
2042
|
+
const key2 = `${owner?.owner ?? ""}\0${host}`;
|
|
2043
|
+
let probe = this.probes.get(key2);
|
|
767
2044
|
if (probe === void 0) {
|
|
768
|
-
probe =
|
|
769
|
-
this.probes.delete(
|
|
770
|
-
if (
|
|
771
|
-
for (const c of this.collectors) c.blocked.
|
|
772
|
-
|
|
2045
|
+
probe = proxyRefusal(proxy, host, port).then((layer) => {
|
|
2046
|
+
this.probes.delete(key2);
|
|
2047
|
+
if (layer !== null && owner !== void 0) {
|
|
2048
|
+
for (const c of this.collectors) if (c.conv === owner.owner) c.blocked.set(host, layer);
|
|
2049
|
+
if (layer === "device")
|
|
2050
|
+
this.emit({ type: "blocked", host, url: pageUrl ?? url.href, root: owner.root });
|
|
773
2051
|
}
|
|
774
|
-
return
|
|
2052
|
+
return layer !== null;
|
|
775
2053
|
});
|
|
776
|
-
this.probes.set(
|
|
2054
|
+
this.probes.set(key2, probe);
|
|
777
2055
|
}
|
|
778
|
-
for (const c of this.collectors) c.pending.push(probe);
|
|
2056
|
+
for (const c of this.collectors) if (c.conv === owner?.owner) c.pending.push(probe);
|
|
779
2057
|
return probe;
|
|
780
2058
|
}
|
|
781
|
-
/**
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
2059
|
+
/** `value`, or `fallback` when it takes longer than {@link PAGE_QUERY_MS} (never rejects). */
|
|
2060
|
+
async bounded(value, fallback) {
|
|
2061
|
+
let timer;
|
|
2062
|
+
try {
|
|
2063
|
+
return await Promise.race([
|
|
2064
|
+
value.catch(() => fallback),
|
|
2065
|
+
new Promise((r) => {
|
|
2066
|
+
timer = this.clock.schedule(() => r(fallback), PAGE_QUERY_MS);
|
|
2067
|
+
})
|
|
2068
|
+
]);
|
|
2069
|
+
} finally {
|
|
2070
|
+
this.clock.cancel(timer);
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
/**
|
|
2074
|
+
* The action queue a conversation's requests run in: one per conversation, so one
|
|
2075
|
+
* conversation's slow navigation does not stall another (ruling 7). Falling back to one
|
|
2076
|
+
* device-wide queue is returning a constant here.
|
|
2077
|
+
*/
|
|
2078
|
+
queueKey(conversationId) {
|
|
2079
|
+
return conversationId;
|
|
2080
|
+
}
|
|
2081
|
+
/**
|
|
2082
|
+
* Runs `fn` one at a time with the conversation's other actions (`wait`, the tab list and adopt
|
|
2083
|
+
* run beside them).
|
|
2084
|
+
*/
|
|
2085
|
+
serial(conversationId, fn) {
|
|
2086
|
+
const key2 = this.queueKey(conversationId);
|
|
2087
|
+
const run = (this.queues.get(key2) ?? Promise.resolve()).then(fn, fn);
|
|
2088
|
+
const tail = run.catch(() => void 0);
|
|
2089
|
+
this.queues.set(key2, tail);
|
|
2090
|
+
void tail.then(() => {
|
|
2091
|
+
if (this.queues.get(key2) === tail) this.queues.delete(key2);
|
|
2092
|
+
});
|
|
785
2093
|
return run;
|
|
786
2094
|
}
|
|
787
2095
|
/**
|
|
788
|
-
* Runs a tool request; never throws. `takenOver` is checked when a queued
|
|
789
|
-
* queue: a takeover that began while it waited refuses it. An action already
|
|
790
|
-
* finish (stopping it halfway would leave the page in an unknown state).
|
|
2096
|
+
* Runs a tool request of its conversation; never throws. `takenOver` is checked when a queued
|
|
2097
|
+
* request leaves the queue: a takeover that began while it waited refuses it. An action already
|
|
2098
|
+
* running is left to finish (stopping it halfway would leave the page in an unknown state).
|
|
791
2099
|
*/
|
|
792
2100
|
async run(req, opts = {}) {
|
|
793
|
-
const
|
|
794
|
-
const
|
|
2101
|
+
const conv = req.conversationId;
|
|
2102
|
+
const lateOwn = this.unreported.get(conv) ?? [];
|
|
2103
|
+
this.unreported.delete(conv);
|
|
2104
|
+
const lateAll = this.unreportedAll.splice(0);
|
|
2105
|
+
const c = {
|
|
2106
|
+
conv,
|
|
2107
|
+
blocked: /* @__PURE__ */ new Map(),
|
|
2108
|
+
notes: [...lateAll, ...lateOwn],
|
|
2109
|
+
pending: [],
|
|
2110
|
+
downloads: []
|
|
2111
|
+
};
|
|
795
2112
|
this.collectors.add(c);
|
|
796
2113
|
let reply;
|
|
797
2114
|
try {
|
|
798
|
-
const
|
|
2115
|
+
const beside = req.op === "wait" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
|
|
2116
|
+
const out = await (beside ? this.exec(req) : this.serial(conv, () => {
|
|
799
2117
|
if (opts.takenOver?.() === true)
|
|
800
2118
|
throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
|
|
801
2119
|
return this.exec(req);
|
|
@@ -803,12 +2121,21 @@ var BrowserSession = class {
|
|
|
803
2121
|
await this.settleProbes(c);
|
|
804
2122
|
await this.settleDownloads(c);
|
|
805
2123
|
this.collectors.delete(c);
|
|
806
|
-
const page =
|
|
807
|
-
|
|
2124
|
+
const page = this.currentPage(conv);
|
|
2125
|
+
if (page !== void 0 && isActing(req)) {
|
|
2126
|
+
this.tabUsedAt.set(this.tabIdOf(page), this.clock.now());
|
|
2127
|
+
this.actedSeq.set(conv, ++this.actSeq);
|
|
2128
|
+
}
|
|
2129
|
+
const verifying = page === void 0 || req.op === "tabs" && (req.action === "list" || req.action === "adopt") ? false : await this.checkVerification(page, this.tabIdOf(page));
|
|
2130
|
+
const text = [
|
|
2131
|
+
...verifying ? [VERIFICATION_NOTE] : [],
|
|
2132
|
+
...c.notes,
|
|
2133
|
+
...out.text === void 0 ? [] : [out.text]
|
|
2134
|
+
].join("\n");
|
|
808
2135
|
reply = {
|
|
809
2136
|
ok: true,
|
|
810
|
-
page: await this.pageInfo(page),
|
|
811
|
-
blockedHosts:
|
|
2137
|
+
...page === void 0 ? {} : { page: await this.pageInfo(page) },
|
|
2138
|
+
blockedHosts: blockedHostsOf(c),
|
|
812
2139
|
...text === "" ? {} : { text },
|
|
813
2140
|
...out.image === void 0 ? {} : { image: out.image }
|
|
814
2141
|
};
|
|
@@ -821,10 +2148,12 @@ var BrowserSession = class {
|
|
|
821
2148
|
}
|
|
822
2149
|
if (c.blocked.size > 0 && code !== "no_such_ref" && code !== "taken_over") {
|
|
823
2150
|
code = "blocked";
|
|
824
|
-
message =
|
|
2151
|
+
message = blockedMessage(blockedHostsOf(c));
|
|
825
2152
|
}
|
|
826
|
-
reply = { ok: false, error: code, message, blockedHosts:
|
|
827
|
-
|
|
2153
|
+
reply = { ok: false, error: code, message, blockedHosts: blockedHostsOf(c) };
|
|
2154
|
+
if (lateOwn.length > 0)
|
|
2155
|
+
this.unreported.set(conv, [...lateOwn, ...this.unreported.get(conv) ?? []]);
|
|
2156
|
+
this.unreportedAll.unshift(...lateAll);
|
|
828
2157
|
} finally {
|
|
829
2158
|
this.collectors.delete(c);
|
|
830
2159
|
}
|
|
@@ -858,13 +2187,61 @@ var BrowserSession = class {
|
|
|
858
2187
|
await Promise.allSettled(all);
|
|
859
2188
|
}
|
|
860
2189
|
}
|
|
861
|
-
|
|
862
|
-
|
|
2190
|
+
/**
|
|
2191
|
+
* Finds the loaded page's icon and fetches it through the browser (the device's network rules
|
|
2192
|
+
* apply); a new address replaces the tab's icon, the same one is not fetched again. Any failure
|
|
2193
|
+
* leaves no icon (the panel's placeholder) and never affects the page.
|
|
2194
|
+
*/
|
|
2195
|
+
async resolveFavicon(page, id) {
|
|
863
2196
|
try {
|
|
864
|
-
|
|
2197
|
+
const url = await iconUrlOf(page);
|
|
2198
|
+
if (this.pages.get(id) !== page) return;
|
|
2199
|
+
if (url === null) {
|
|
2200
|
+
if (this.favicons.delete(id)) this.emit({ type: "state" });
|
|
2201
|
+
return;
|
|
2202
|
+
}
|
|
2203
|
+
if (this.favicons.get(id)?.url === url) return;
|
|
2204
|
+
const cdp = await this.ctx.newCDPSession(page);
|
|
2205
|
+
let data = null;
|
|
2206
|
+
try {
|
|
2207
|
+
const bytes = await fetchIcon(cdp, url);
|
|
2208
|
+
data = bytes === null ? null : await iconForPanel(cdp, bytes);
|
|
2209
|
+
} finally {
|
|
2210
|
+
await cdp.detach().catch(() => void 0);
|
|
2211
|
+
}
|
|
2212
|
+
if (this.pages.get(id) !== page) return;
|
|
2213
|
+
this.favicons.set(id, { url, data });
|
|
2214
|
+
this.emit({ type: "state" });
|
|
865
2215
|
} catch {
|
|
866
|
-
title = this.titles.get(this.tabIdOf(page)) ?? "";
|
|
867
2216
|
}
|
|
2217
|
+
}
|
|
2218
|
+
/**
|
|
2219
|
+
* Looks at the tab's page now and records or clears its verification blocker; true when it
|
|
2220
|
+
* shows a verification page.
|
|
2221
|
+
*/
|
|
2222
|
+
async checkVerification(page, id) {
|
|
2223
|
+
if (id === "") return false;
|
|
2224
|
+
const blocked = await this.bounded(isVerificationPage(page, this.docStatus.get(id)), false);
|
|
2225
|
+
if (this.pages.get(id) !== page) return false;
|
|
2226
|
+
const before = this.blockers.get(id);
|
|
2227
|
+
if (blocked) {
|
|
2228
|
+
const url = clip(page.url(), MAX_URL_CHARS);
|
|
2229
|
+
if (before?.url !== url) {
|
|
2230
|
+
this.blockers.set(id, { kind: "verification", url });
|
|
2231
|
+
this.emit({ type: "state" });
|
|
2232
|
+
}
|
|
2233
|
+
} else if (before !== void 0) {
|
|
2234
|
+
this.blockers.delete(id);
|
|
2235
|
+
this.emit({ type: "state" });
|
|
2236
|
+
}
|
|
2237
|
+
return blocked;
|
|
2238
|
+
}
|
|
2239
|
+
async pageInfo(page) {
|
|
2240
|
+
const known = this.titles.get(this.tabIdOf(page)) ?? "";
|
|
2241
|
+
const title = await this.bounded(
|
|
2242
|
+
page.title().catch(() => known),
|
|
2243
|
+
known
|
|
2244
|
+
);
|
|
868
2245
|
return {
|
|
869
2246
|
url: clip(page.url(), MAX_URL_CHARS),
|
|
870
2247
|
title: clip(title, MAX_TITLE_CHARS),
|
|
@@ -911,7 +2288,7 @@ var BrowserSession = class {
|
|
|
911
2288
|
try {
|
|
912
2289
|
const out = await fn();
|
|
913
2290
|
if (navigating && !loaded2) {
|
|
914
|
-
await page.waitForEvent("domcontentloaded", { timeout:
|
|
2291
|
+
await page.waitForEvent("domcontentloaded", { timeout: this.navigationTimeoutMs }).catch(() => void 0);
|
|
915
2292
|
}
|
|
916
2293
|
return out;
|
|
917
2294
|
} finally {
|
|
@@ -932,25 +2309,48 @@ var BrowserSession = class {
|
|
|
932
2309
|
);
|
|
933
2310
|
}
|
|
934
2311
|
}
|
|
935
|
-
markClick(x, y) {
|
|
936
|
-
this.
|
|
2312
|
+
markClick(page, x, y) {
|
|
2313
|
+
this.clicks.set(this.tabIdOf(page), { x, y, seq: ++this.clickSeq });
|
|
937
2314
|
}
|
|
938
2315
|
async goto(page, url) {
|
|
939
2316
|
let res;
|
|
940
2317
|
const download = page.waitForEvent("download", { timeout: ACTION_TIMEOUT_MS });
|
|
941
2318
|
download.catch(() => void 0);
|
|
2319
|
+
const deadline = Date.now() + this.navigationTimeoutMs;
|
|
2320
|
+
const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
|
|
942
2321
|
try {
|
|
943
|
-
res = await
|
|
2322
|
+
res = await this.gotoPastNetworkChange(page, url, watch, deadline);
|
|
944
2323
|
} catch (e) {
|
|
945
2324
|
const msg = firstLine(e);
|
|
946
2325
|
if (msg.includes("Download is starting")) {
|
|
947
2326
|
await download.catch(() => void 0);
|
|
948
2327
|
return;
|
|
949
2328
|
}
|
|
950
|
-
if (
|
|
951
|
-
throw e;
|
|
2329
|
+
if (isTimeout(e)) throw await this.navigationTimedOut(page, url);
|
|
2330
|
+
if (!msg.includes("net::ERR_ABORTED")) throw await this.navigationFailed(page, e, url, msg);
|
|
2331
|
+
const out = await watch.follow(deadline);
|
|
2332
|
+
if (out.kind !== "loaded") {
|
|
2333
|
+
const status = await watch.emptyAnswer();
|
|
2334
|
+
if (status !== void 0)
|
|
2335
|
+
throw new ActionError(
|
|
2336
|
+
"failed",
|
|
2337
|
+
`${url} answered ${status} with no page to show; the tab shows ${page.url()}.`
|
|
2338
|
+
);
|
|
2339
|
+
}
|
|
2340
|
+
if (out.kind === "none") throw e;
|
|
2341
|
+
if (out.kind === "failed") {
|
|
2342
|
+
throw await this.navigationFailed(
|
|
2343
|
+
page,
|
|
2344
|
+
new Error(`${out.error} at ${out.url}`),
|
|
2345
|
+
out.url,
|
|
2346
|
+
out.error
|
|
2347
|
+
);
|
|
2348
|
+
}
|
|
2349
|
+
res = out.response;
|
|
2350
|
+
} finally {
|
|
2351
|
+
watch.dispose();
|
|
952
2352
|
}
|
|
953
|
-
if (res?.status() === 403 && await this.checkBlocked(res.url())) {
|
|
2353
|
+
if (res?.status() === 403 && await this.checkBlocked(page, res.url())) {
|
|
954
2354
|
throw new ActionError(
|
|
955
2355
|
"blocked",
|
|
956
2356
|
`The device's network settings block ${new URL(res.url()).hostname}.`
|
|
@@ -958,19 +2358,161 @@ var BrowserSession = class {
|
|
|
958
2358
|
}
|
|
959
2359
|
await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
|
|
960
2360
|
}
|
|
2361
|
+
/** `goto` past changes of the device's network ({@link pastNetworkChanges}). */
|
|
2362
|
+
gotoPastNetworkChange(page, url, watch, deadline) {
|
|
2363
|
+
return pastNetworkChanges(
|
|
2364
|
+
() => this.gotoPastLateErrorPage(page, url, watch, deadline),
|
|
2365
|
+
() => watch.follow(deadline),
|
|
2366
|
+
deadline
|
|
2367
|
+
);
|
|
2368
|
+
}
|
|
2369
|
+
/** `page.goto`, past the late error page of the tab's previous navigation ({@link pastInterrupts}). */
|
|
2370
|
+
gotoPastLateErrorPage(page, url, watch, deadline) {
|
|
2371
|
+
return pastInterrupts(
|
|
2372
|
+
// a run after an interrupt or a network change gets what is left of the navigation's
|
|
2373
|
+
// time, not all of it
|
|
2374
|
+
() => page.goto(url, {
|
|
2375
|
+
waitUntil: "domcontentloaded",
|
|
2376
|
+
timeout: Math.max(1, deadline - Date.now())
|
|
2377
|
+
}),
|
|
2378
|
+
() => watch.follow(deadline),
|
|
2379
|
+
url,
|
|
2380
|
+
deadline
|
|
2381
|
+
);
|
|
2382
|
+
}
|
|
2383
|
+
/**
|
|
2384
|
+
* The error of a navigation that failed with Chromium's net error `error`: a host the proxy
|
|
2385
|
+
* refuses is reported as blocked (`run` turns `original` into the blocked reply); any other net
|
|
2386
|
+
* error is `unreachable`, saying what the device's network answered when it went through it.
|
|
2387
|
+
*/
|
|
2388
|
+
async navigationFailed(page, original, url, error) {
|
|
2389
|
+
const net = /net::(ERR_[A-Z_]+)/.exec(error)?.[1];
|
|
2390
|
+
if (net === void 0 || net === "ERR_ABORTED") return original;
|
|
2391
|
+
await this.errorPageCommitted(page);
|
|
2392
|
+
const proxied = PROXY_FAILURE_RE.test(error);
|
|
2393
|
+
if (proxied && await this.checkBlocked(page, url)) return original;
|
|
2394
|
+
if (proxied || NETWORK_ERROR_RE.test(net)) {
|
|
2395
|
+
const verdict = await this.networkVerdict(url);
|
|
2396
|
+
if (verdict?.kind === "proxy_down")
|
|
2397
|
+
return new ActionError(
|
|
2398
|
+
"network_unavailable",
|
|
2399
|
+
`${url} could not be loaded (net::${net}): ${verdict.text}`
|
|
2400
|
+
);
|
|
2401
|
+
if (verdict !== void 0 && verdict.text !== "")
|
|
2402
|
+
return new ActionError(
|
|
2403
|
+
"unreachable",
|
|
2404
|
+
`${url} could not be loaded (net::${net}): ${verdict.text}`
|
|
2405
|
+
);
|
|
2406
|
+
}
|
|
2407
|
+
const meaning = NET_ERROR_MEANINGS[net];
|
|
2408
|
+
return new ActionError(
|
|
2409
|
+
"unreachable",
|
|
2410
|
+
`${url} could not be loaded (net::${net})${meaning === void 0 ? "." : `: ${meaning}.`}`
|
|
2411
|
+
);
|
|
2412
|
+
}
|
|
2413
|
+
/**
|
|
2414
|
+
* Waits (at most {@link ERROR_PAGE_WAIT_MS}) for the error page of the main frame's failed
|
|
2415
|
+
* navigation: Chromium commits it after Playwright reported the failure (the Linux full build
|
|
2416
|
+
* shows it), and a navigation started before that commit is interrupted by it.
|
|
2417
|
+
*/
|
|
2418
|
+
async errorPageCommitted(page) {
|
|
2419
|
+
if (page.isClosed() || page.mainFrame().url().startsWith("chrome-error:")) return;
|
|
2420
|
+
await page.waitForEvent("framenavigated", {
|
|
2421
|
+
predicate: (f) => f === page.mainFrame() && f.url().startsWith("chrome-error:"),
|
|
2422
|
+
timeout: ERROR_PAGE_WAIT_MS
|
|
2423
|
+
}).catch(() => void 0);
|
|
2424
|
+
}
|
|
2425
|
+
/**
|
|
2426
|
+
* The error of a navigation that took longer than its time limit. The navigation is stopped
|
|
2427
|
+
* first (a navigation left in flight keeps the page's scripts and snapshots waiting for a
|
|
2428
|
+
* document that never comes), so the tab goes back to the page it showed and the next request
|
|
2429
|
+
* works on it; the message says what the device's network answered for the host.
|
|
2430
|
+
*/
|
|
2431
|
+
async navigationTimedOut(page, url) {
|
|
2432
|
+
await this.stopNavigation(page);
|
|
2433
|
+
const seconds = Math.round(this.navigationTimeoutMs / 1e3);
|
|
2434
|
+
const verdict = await this.networkVerdict(url, true);
|
|
2435
|
+
const detail = verdict === void 0 || verdict.text === "" ? "no page came in that time." : verdict.text;
|
|
2436
|
+
const now = page.isClosed() ? "" : ` The navigation was stopped; the tab shows ${page.url()}.`;
|
|
2437
|
+
return new ActionError(
|
|
2438
|
+
verdict?.kind === "proxy_down" ? "network_unavailable" : "unreachable",
|
|
2439
|
+
`${url} did not load within ${seconds} s: ${detail}${now}`
|
|
2440
|
+
);
|
|
2441
|
+
}
|
|
2442
|
+
/** Stops the page's navigation in flight (Chromium's stop button); never throws. */
|
|
2443
|
+
async stopNavigation(page) {
|
|
2444
|
+
if (page.isClosed()) return;
|
|
2445
|
+
try {
|
|
2446
|
+
const cdp = await this.ctx.newCDPSession(page);
|
|
2447
|
+
try {
|
|
2448
|
+
await cdp.send("Page.stopLoading");
|
|
2449
|
+
} finally {
|
|
2450
|
+
await cdp.detach().catch(() => void 0);
|
|
2451
|
+
}
|
|
2452
|
+
} catch {
|
|
2453
|
+
}
|
|
2454
|
+
this.pendingNavs.delete(page);
|
|
2455
|
+
const id = this.ids.get(page);
|
|
2456
|
+
if (id !== void 0 && this.loadingTabs.delete(id)) this.emit({ type: "state" });
|
|
2457
|
+
}
|
|
2458
|
+
/**
|
|
2459
|
+
* What the device's proxy answers for the URL's host, and as a sentence (undefined without a
|
|
2460
|
+
* proxy). `timedOut`: the navigation got no page in time.
|
|
2461
|
+
*/
|
|
2462
|
+
async networkVerdict(rawUrl, timedOut = false) {
|
|
2463
|
+
if (this.proxy === void 0) return void 0;
|
|
2464
|
+
let url;
|
|
2465
|
+
try {
|
|
2466
|
+
url = new URL(rawUrl);
|
|
2467
|
+
} catch {
|
|
2468
|
+
return void 0;
|
|
2469
|
+
}
|
|
2470
|
+
const host = url.hostname;
|
|
2471
|
+
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
|
2472
|
+
const answer = await probeProxy(this.proxy, host, port);
|
|
2473
|
+
return { kind: answer.verdict, text: this.verdictText(answer, host, port, timedOut) };
|
|
2474
|
+
}
|
|
2475
|
+
/** The sentence for a proxy's {@link ProxyAnswer} ("" when it says nothing). */
|
|
2476
|
+
verdictText(answer, host, port, timedOut) {
|
|
2477
|
+
switch (answer.verdict) {
|
|
2478
|
+
case "proxy_down":
|
|
2479
|
+
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.";
|
|
2480
|
+
case "unreachable":
|
|
2481
|
+
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).`;
|
|
2482
|
+
case "no_answer":
|
|
2483
|
+
return `the device's network got no answer from ${host}:${port}.`;
|
|
2484
|
+
case "connected":
|
|
2485
|
+
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.`;
|
|
2486
|
+
case "refused":
|
|
2487
|
+
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}.`;
|
|
2488
|
+
default:
|
|
2489
|
+
return "";
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
961
2492
|
async exec(req) {
|
|
2493
|
+
const conv = req.conversationId;
|
|
2494
|
+
const root = req.rootConversationId;
|
|
2495
|
+
const activePage = () => this.pageFor(conv, root);
|
|
962
2496
|
switch (req.op) {
|
|
963
2497
|
case "navigate": {
|
|
964
|
-
const page = await
|
|
2498
|
+
const page = await activePage();
|
|
965
2499
|
if (req.url !== void 0) {
|
|
966
2500
|
await this.goto(page, normalizeUrl(req.url));
|
|
967
2501
|
} else if (req.action === "back" || req.action === "forward") {
|
|
968
|
-
const r = await (req.action === "back" ? page.goBack() : page.goForward())
|
|
2502
|
+
const r = await (req.action === "back" ? page.goBack() : page.goForward()).catch(
|
|
2503
|
+
async (e) => {
|
|
2504
|
+
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
2505
|
+
throw e;
|
|
2506
|
+
}
|
|
2507
|
+
);
|
|
969
2508
|
if (r === null && page.url() === "about:blank") {
|
|
970
2509
|
return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
|
|
971
2510
|
}
|
|
972
2511
|
} else if (req.action === "reload") {
|
|
973
|
-
await page.reload({ waitUntil: "domcontentloaded" })
|
|
2512
|
+
await page.reload({ waitUntil: "domcontentloaded" }).catch(async (e) => {
|
|
2513
|
+
if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
|
|
2514
|
+
throw e;
|
|
2515
|
+
});
|
|
974
2516
|
} else {
|
|
975
2517
|
throw new ActionError(
|
|
976
2518
|
"failed",
|
|
@@ -982,40 +2524,40 @@ var BrowserSession = class {
|
|
|
982
2524
|
case "tabs":
|
|
983
2525
|
return this.tabsOp(req);
|
|
984
2526
|
case "snapshot":
|
|
985
|
-
return { text: await takeSnapshot(await
|
|
2527
|
+
return { text: await takeSnapshot(await activePage()) };
|
|
986
2528
|
case "click":
|
|
987
2529
|
case "hover": {
|
|
988
|
-
const page = await
|
|
2530
|
+
const page = await activePage();
|
|
989
2531
|
const loc = await this.locate(page, req.ref);
|
|
990
2532
|
if (req.op === "hover") {
|
|
991
2533
|
await loc.hover();
|
|
992
2534
|
return {};
|
|
993
2535
|
}
|
|
994
2536
|
const at = await this.centerOf(loc);
|
|
995
|
-
if (at !== void 0) this.markClick(at.x, at.y);
|
|
2537
|
+
if (at !== void 0) this.markClick(page, at.x, at.y);
|
|
996
2538
|
await this.settled(page, () => loc.click());
|
|
997
2539
|
return {};
|
|
998
2540
|
}
|
|
999
2541
|
case "type": {
|
|
1000
|
-
const page = await
|
|
2542
|
+
const page = await activePage();
|
|
1001
2543
|
const loc = await this.locate(page, req.ref);
|
|
1002
2544
|
await loc.fill(req.text);
|
|
1003
2545
|
if (req.submit === true) await this.settled(page, () => loc.press("Enter"));
|
|
1004
2546
|
return {};
|
|
1005
2547
|
}
|
|
1006
2548
|
case "select": {
|
|
1007
|
-
const page = await
|
|
2549
|
+
const page = await activePage();
|
|
1008
2550
|
const loc = await this.locate(page, req.ref);
|
|
1009
2551
|
const chosen = await this.settled(page, () => loc.selectOption(req.values));
|
|
1010
2552
|
return { text: `Selected ${JSON.stringify(chosen)}.` };
|
|
1011
2553
|
}
|
|
1012
2554
|
case "press": {
|
|
1013
|
-
const page = await
|
|
2555
|
+
const page = await activePage();
|
|
1014
2556
|
await this.settled(page, () => page.keyboard.press(req.key));
|
|
1015
2557
|
return {};
|
|
1016
2558
|
}
|
|
1017
2559
|
case "scroll": {
|
|
1018
|
-
const page = await
|
|
2560
|
+
const page = await activePage();
|
|
1019
2561
|
if (req.ref !== void 0) {
|
|
1020
2562
|
const loc = await this.locate(page, req.ref);
|
|
1021
2563
|
await loc.scrollIntoViewIfNeeded();
|
|
@@ -1029,25 +2571,25 @@ var BrowserSession = class {
|
|
|
1029
2571
|
return {};
|
|
1030
2572
|
}
|
|
1031
2573
|
case "upload": {
|
|
1032
|
-
const page = await
|
|
1033
|
-
const
|
|
2574
|
+
const page = await activePage();
|
|
2575
|
+
const file = this.readUpload(req.path);
|
|
1034
2576
|
const loc = await this.locate(page, req.ref);
|
|
1035
|
-
await loc.setInputFiles(
|
|
2577
|
+
await loc.setInputFiles(file);
|
|
1036
2578
|
return {};
|
|
1037
2579
|
}
|
|
1038
2580
|
case "click_at":
|
|
1039
2581
|
case "type_at": {
|
|
1040
|
-
const page = await
|
|
2582
|
+
const page = await activePage();
|
|
1041
2583
|
this.checkPoint(req.x, req.y);
|
|
1042
|
-
this.markClick(Math.round(req.x), Math.round(req.y));
|
|
2584
|
+
this.markClick(page, Math.round(req.x), Math.round(req.y));
|
|
1043
2585
|
await this.settled(page, () => page.mouse.click(req.x, req.y));
|
|
1044
2586
|
if (req.op === "type_at") await page.keyboard.type(req.text);
|
|
1045
2587
|
return {};
|
|
1046
2588
|
}
|
|
1047
2589
|
case "wait":
|
|
1048
|
-
return this.waitOp(req);
|
|
2590
|
+
return this.waitOp(req, this.currentPage(conv));
|
|
1049
2591
|
case "screenshot": {
|
|
1050
|
-
const page = await
|
|
2592
|
+
const page = await activePage();
|
|
1051
2593
|
const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
|
|
1052
2594
|
if (!(maxBytes > 0))
|
|
1053
2595
|
throw new ActionError("failed", "screenshot needs a positive maxBytes.");
|
|
@@ -1078,56 +2620,79 @@ var BrowserSession = class {
|
|
|
1078
2620
|
);
|
|
1079
2621
|
}
|
|
1080
2622
|
async tabsOp(req) {
|
|
2623
|
+
const conv = req.conversationId;
|
|
2624
|
+
const root = req.rootConversationId;
|
|
1081
2625
|
switch (req.action) {
|
|
1082
|
-
case "list":
|
|
1083
|
-
await this.
|
|
1084
|
-
const lines = await Promise.all(
|
|
1085
|
-
[...this.pages.entries()].map(async ([id, p]) => {
|
|
1086
|
-
const info = await this.pageInfo(p);
|
|
1087
|
-
return `${id}${id === this.active ? " (active)" : ""}: ${info.title || "(no title)"} ${info.url}`;
|
|
1088
|
-
})
|
|
1089
|
-
);
|
|
1090
|
-
return { text: lines.join("\n") };
|
|
1091
|
-
}
|
|
2626
|
+
case "list":
|
|
2627
|
+
return { text: await this.listText(conv, root) };
|
|
1092
2628
|
case "open": {
|
|
1093
|
-
const page = await this.openTab();
|
|
2629
|
+
const page = this.countOf(conv) === 0 ? await this.pageFor(conv, root) : await this.openTab(conv, root);
|
|
1094
2630
|
if (req.url !== void 0) await this.goto(page, normalizeUrl(req.url));
|
|
1095
2631
|
return {};
|
|
1096
2632
|
}
|
|
1097
2633
|
case "switch": {
|
|
1098
|
-
|
|
1099
|
-
this.
|
|
1100
|
-
await page.bringToFront().catch(() => void 0);
|
|
1101
|
-
this.emit({ type: "active" });
|
|
2634
|
+
this.ownTab(conv, req.tabId);
|
|
2635
|
+
this.setActive(conv, req.tabId);
|
|
1102
2636
|
return {};
|
|
1103
2637
|
}
|
|
1104
2638
|
case "close": {
|
|
1105
|
-
const page = this.
|
|
2639
|
+
const page = this.ownTab(conv, req.tabId);
|
|
1106
2640
|
await page.close();
|
|
1107
|
-
|
|
2641
|
+
return {};
|
|
2642
|
+
}
|
|
2643
|
+
case "adopt": {
|
|
2644
|
+
const id = req.tabId;
|
|
2645
|
+
const result = this.adopt(conv, root, this.tabIdOf(this.tabById(id)));
|
|
2646
|
+
if (result === "in_use") throw new ActionError("failed", tabInUse(id ?? ""));
|
|
2647
|
+
if (result === "cap") throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
|
|
1108
2648
|
return {};
|
|
1109
2649
|
}
|
|
1110
2650
|
}
|
|
1111
|
-
throw new ActionError("failed", "tabs needs an action: list, open, switch or
|
|
2651
|
+
throw new ActionError("failed", "tabs needs an action: list, open, switch, close or adopt.");
|
|
1112
2652
|
}
|
|
1113
|
-
/**
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
`The browser has ${MAX_TABS} tabs open, the most it keeps; close one first.`
|
|
1119
|
-
);
|
|
1120
|
-
}
|
|
1121
|
-
const page = await this.ctx.newPage();
|
|
1122
|
-
this.track(page);
|
|
1123
|
-
this.active = this.ids.get(page);
|
|
1124
|
-
this.emit({ type: "active" });
|
|
1125
|
-
this.emit({ type: "state" });
|
|
2653
|
+
/** The conversation's own tab `tabId`; another conversation's is refused with what to do. */
|
|
2654
|
+
ownTab(conversationId, tabId) {
|
|
2655
|
+
const page = this.tabById(tabId);
|
|
2656
|
+
if (this.owners.get(tabId)?.owner !== conversationId)
|
|
2657
|
+
throw new ActionError("failed", notYourTab(tabId));
|
|
1126
2658
|
return page;
|
|
1127
2659
|
}
|
|
2660
|
+
/**
|
|
2661
|
+
* The tab list of a conversation: its own tabs, then its tree's other tabs, then other trees'
|
|
2662
|
+
* tabs (unowned ones too, but not a blank start tab), with ids, titles clipped to
|
|
2663
|
+
* OTHER_TITLE_CHARS and URLs without query or fragment outside its own; no conversation ids.
|
|
2664
|
+
*/
|
|
2665
|
+
async listText(conversationId, root) {
|
|
2666
|
+
const own = [];
|
|
2667
|
+
const tree = [];
|
|
2668
|
+
const device = [];
|
|
2669
|
+
for (const [id, p] of this.live()) {
|
|
2670
|
+
const o = this.owners.get(id);
|
|
2671
|
+
if (o?.owner === conversationId) {
|
|
2672
|
+
const info = await this.pageInfo(p);
|
|
2673
|
+
const active = this.activeOf.get(conversationId) === id ? " (active)" : "";
|
|
2674
|
+
own.push(`${id}${active}: ${info.title || "(no title)"} ${info.url}`);
|
|
2675
|
+
continue;
|
|
2676
|
+
}
|
|
2677
|
+
if (isStartBlank({ owner: o?.owner, url: p.url() })) continue;
|
|
2678
|
+
const title = clip(this.titles.get(id) ?? "", OTHER_TITLE_CHARS) || "(no title)";
|
|
2679
|
+
const line = `${id}: ${title} ${bareUrl(clip(p.url(), MAX_URL_CHARS))}`;
|
|
2680
|
+
if (o !== void 0 && o.root === root) tree.push(line);
|
|
2681
|
+
else device.push(line);
|
|
2682
|
+
}
|
|
2683
|
+
const lines = [...own];
|
|
2684
|
+
if (tree.length > 0) lines.push("Tabs of other conversations in this task:", ...tree);
|
|
2685
|
+
if (device.length > 0) lines.push("Tabs of other conversations on this device:", ...device);
|
|
2686
|
+
if (tree.length + device.length > 0)
|
|
2687
|
+
lines.push(
|
|
2688
|
+
"To use another conversation's tab, call browser_tabs with action adopt and its tabId."
|
|
2689
|
+
);
|
|
2690
|
+
if (lines.length === 0) return "No browser tabs are open.";
|
|
2691
|
+
return lines.join("\n");
|
|
2692
|
+
}
|
|
1128
2693
|
tabById(tabId) {
|
|
1129
|
-
const page =
|
|
1130
|
-
if (page === void 0
|
|
2694
|
+
const page = this.pageById(tabId);
|
|
2695
|
+
if (page === void 0) {
|
|
1131
2696
|
throw new ActionError(
|
|
1132
2697
|
"failed",
|
|
1133
2698
|
`No tab ${JSON.stringify(tabId ?? "")}; list the tabs to see their ids.`
|
|
@@ -1135,18 +2700,13 @@ var BrowserSession = class {
|
|
|
1135
2700
|
}
|
|
1136
2701
|
return page;
|
|
1137
2702
|
}
|
|
1138
|
-
/**
|
|
1139
|
-
async
|
|
1140
|
-
|
|
1141
|
-
this.active = tabId;
|
|
1142
|
-
await page.bringToFront().catch(() => void 0);
|
|
1143
|
-
this.emit({ type: "active" });
|
|
1144
|
-
this.emit({ type: "state" });
|
|
2703
|
+
/** Brings a tab to the front of the window (only a viewer in control decides what is front). */
|
|
2704
|
+
async bringToFront(tabId) {
|
|
2705
|
+
await this.pageById(tabId)?.bringToFront().catch(() => void 0);
|
|
1145
2706
|
}
|
|
1146
|
-
/** Navigates
|
|
1147
|
-
async viewerNav(nav) {
|
|
2707
|
+
/** Navigates a tab for a viewer (address bar, back, forward, reload); never throws. */
|
|
2708
|
+
async viewerNav(page, nav) {
|
|
1148
2709
|
try {
|
|
1149
|
-
const page = await this.activePage();
|
|
1150
2710
|
if (nav.url !== void 0) await this.goto(page, normalizeUrl(nav.url));
|
|
1151
2711
|
else if (nav.action === "back") await page.goBack();
|
|
1152
2712
|
else if (nav.action === "forward") await page.goForward();
|
|
@@ -1154,10 +2714,15 @@ var BrowserSession = class {
|
|
|
1154
2714
|
} catch {
|
|
1155
2715
|
}
|
|
1156
2716
|
}
|
|
1157
|
-
async waitOp(req) {
|
|
2717
|
+
async waitOp(req, page) {
|
|
1158
2718
|
const asked = Number(req.timeoutMs);
|
|
1159
2719
|
const timeout = Number.isFinite(asked) ? Math.max(0, Math.min(MAX_WAIT_MS, Math.floor(asked))) : DEFAULT_WAIT_MS;
|
|
1160
|
-
|
|
2720
|
+
if (page === void 0) {
|
|
2721
|
+
if (req.text !== void 0 || req.ref !== void 0 || req.navigation === true)
|
|
2722
|
+
throw new ActionError("failed", NO_TAB_TO_WAIT_ON);
|
|
2723
|
+
await new Promise((r) => this.clock.schedule(r, timeout));
|
|
2724
|
+
return {};
|
|
2725
|
+
}
|
|
1161
2726
|
if (req.text !== void 0) {
|
|
1162
2727
|
await page.getByText(req.text).first().waitFor({ state: "visible", timeout }).catch((e) => {
|
|
1163
2728
|
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError(
|
|
@@ -1198,15 +2763,33 @@ var BrowserSession = class {
|
|
|
1198
2763
|
};
|
|
1199
2764
|
|
|
1200
2765
|
// daemon/chromium.ts
|
|
1201
|
-
import {
|
|
2766
|
+
import {
|
|
2767
|
+
accessSync,
|
|
2768
|
+
constants,
|
|
2769
|
+
existsSync,
|
|
2770
|
+
lstatSync as lstatSync2,
|
|
2771
|
+
readdirSync as readdirSync2,
|
|
2772
|
+
readFileSync,
|
|
2773
|
+
writeFileSync
|
|
2774
|
+
} from "node:fs";
|
|
1202
2775
|
import { createRequire } from "node:module";
|
|
1203
|
-
import { dirname, join as join2 } from "node:path";
|
|
2776
|
+
import { dirname, isAbsolute, join as join2, relative } from "node:path";
|
|
1204
2777
|
import { fileURLToPath } from "node:url";
|
|
2778
|
+
var SERVICE_MACH_ENV = DEVICE_SERVICE_MACH_ENV;
|
|
2779
|
+
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.";
|
|
2780
|
+
function chromiumBuild(platform, env = process.env) {
|
|
2781
|
+
if (platform !== "darwin") return "chromium";
|
|
2782
|
+
return env[SERVICE_MACH_ENV] === DEVICE_SERVICE_MACH_CHROMIUM ? "chromium" : "chromium-headless-shell";
|
|
2783
|
+
}
|
|
2784
|
+
var BUILD_DIR = {
|
|
2785
|
+
chromium: "chromium",
|
|
2786
|
+
"chromium-headless-shell": "chromium_headless_shell"
|
|
2787
|
+
};
|
|
1205
2788
|
function envValue(env, name) {
|
|
1206
2789
|
const v = env[name] ?? env[name.toLowerCase()];
|
|
1207
2790
|
return v === void 0 || v === "" ? void 0 : v;
|
|
1208
2791
|
}
|
|
1209
|
-
function
|
|
2792
|
+
function browserRelease(build) {
|
|
1210
2793
|
const candidates = [new URL("./vendor/playwright-core/browsers.json", import.meta.url)];
|
|
1211
2794
|
try {
|
|
1212
2795
|
const pkg = createRequire(import.meta.url).resolve("playwright-core/package.json");
|
|
@@ -1216,13 +2799,25 @@ function headlessShellRevision() {
|
|
|
1216
2799
|
for (const file of candidates) {
|
|
1217
2800
|
try {
|
|
1218
2801
|
const json = JSON.parse(readFileSync(fileURLToPath(file), "utf8"));
|
|
1219
|
-
const
|
|
1220
|
-
if (typeof
|
|
2802
|
+
const b = json.browsers?.find((x) => x.name === build);
|
|
2803
|
+
if (typeof b?.revision === "string" && b.revision !== "")
|
|
2804
|
+
return {
|
|
2805
|
+
revision: b.revision,
|
|
2806
|
+
version: typeof b.browserVersion === "string" ? b.browserVersion : ""
|
|
2807
|
+
};
|
|
1221
2808
|
} catch {
|
|
1222
2809
|
}
|
|
1223
2810
|
}
|
|
1224
2811
|
return void 0;
|
|
1225
2812
|
}
|
|
2813
|
+
function browserRevision(build) {
|
|
2814
|
+
return browserRelease(build)?.revision;
|
|
2815
|
+
}
|
|
2816
|
+
function chromeUserAgent(platform, version) {
|
|
2817
|
+
const major = /^\d+/.exec(version)?.[0] ?? "0";
|
|
2818
|
+
const os = platform === "darwin" ? "Macintosh; Intel Mac OS X 10_15_7" : platform === "win32" ? "Windows NT 10.0; Win64; x64" : "X11; Linux x86_64";
|
|
2819
|
+
return `Mozilla/5.0 (${os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36`;
|
|
2820
|
+
}
|
|
1226
2821
|
function playwrightDownloadHosts(env) {
|
|
1227
2822
|
const custom = envValue(env, "PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST") ?? envValue(env, "PLAYWRIGHT_DOWNLOAD_HOST");
|
|
1228
2823
|
if (custom !== void 0) {
|
|
@@ -1232,17 +2827,107 @@ function playwrightDownloadHosts(env) {
|
|
|
1232
2827
|
return [];
|
|
1233
2828
|
}
|
|
1234
2829
|
}
|
|
1235
|
-
return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com"];
|
|
2830
|
+
return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com", "storage.googleapis.com"];
|
|
2831
|
+
}
|
|
2832
|
+
var MAX_REVISION_SKEW = 10;
|
|
2833
|
+
function shippedRevisionNote(dir, revision) {
|
|
2834
|
+
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.`;
|
|
2835
|
+
}
|
|
2836
|
+
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).";
|
|
2837
|
+
var SERVICE_INSTALL_ENV = "CAPYBARA_SERVICE_INSTALL";
|
|
2838
|
+
var SERVICE_INSTALL_SEAL = ".sealed";
|
|
2839
|
+
var BrowserInstalledError = class extends Error {
|
|
2840
|
+
constructor() {
|
|
2841
|
+
super("The browser was installed; the browser service restarts to run it read only.");
|
|
2842
|
+
this.name = "BrowserInstalledError";
|
|
2843
|
+
}
|
|
2844
|
+
};
|
|
2845
|
+
function inside(dir, root) {
|
|
2846
|
+
const rel = relative(root, dir);
|
|
2847
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
1236
2848
|
}
|
|
1237
|
-
function
|
|
2849
|
+
function readOnlyForUs(dir) {
|
|
2850
|
+
try {
|
|
2851
|
+
accessSync(dir, constants.W_OK);
|
|
2852
|
+
return false;
|
|
2853
|
+
} catch {
|
|
2854
|
+
return true;
|
|
2855
|
+
}
|
|
2856
|
+
}
|
|
2857
|
+
function browsersPathFor(stateDir, env, revision, build) {
|
|
2858
|
+
const install = envValue(env, SERVICE_INSTALL_ENV);
|
|
2859
|
+
if (install !== void 0 && isAbsolute(install)) {
|
|
2860
|
+
let sealed = false;
|
|
2861
|
+
try {
|
|
2862
|
+
sealed = lstatSync2(join2(install, SERVICE_INSTALL_SEAL)).isFile();
|
|
2863
|
+
} catch {
|
|
2864
|
+
sealed = false;
|
|
2865
|
+
}
|
|
2866
|
+
return { browsersPath: install, install: { sealed } };
|
|
2867
|
+
}
|
|
1238
2868
|
const cache = envValue(env, "PLAYWRIGHT_BROWSERS_PATH");
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
2869
|
+
const workspace = envValue(env, "CAPYBARA_SERVICE_WORKSPACE");
|
|
2870
|
+
if (cache !== void 0 && isAbsolute(cache) && (workspace === void 0 || !inside(cache, workspace)) && readOnlyForUs(cache)) {
|
|
2871
|
+
if (revision !== void 0 && existsSync(join2(cache, `${BUILD_DIR[build]}-${revision}`)))
|
|
2872
|
+
return { browsersPath: cache, shipped: true };
|
|
2873
|
+
const near = shippedRevisions(cache, build).filter(
|
|
2874
|
+
(d) => revision !== void 0 && Math.abs(Number(d.slice(BUILD_DIR[build].length + 1)) - Number(revision)) <= MAX_REVISION_SKEW
|
|
2875
|
+
);
|
|
2876
|
+
const newest = near.at(-1);
|
|
2877
|
+
if (newest !== void 0) return { browsersPath: cache, shipped: true, shippedDir: newest };
|
|
2878
|
+
}
|
|
2879
|
+
return { browsersPath: join2(stateDir, "browsers"), unavailable: BROWSER_UNAVAILABLE_MESSAGE };
|
|
2880
|
+
}
|
|
2881
|
+
function shippedRevisions(cache, build) {
|
|
2882
|
+
const re = new RegExp(`^${BUILD_DIR[build]}-(\\d+)$`);
|
|
2883
|
+
let names;
|
|
2884
|
+
try {
|
|
2885
|
+
names = readdirSync2(cache);
|
|
2886
|
+
} catch {
|
|
2887
|
+
return [];
|
|
2888
|
+
}
|
|
2889
|
+
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);
|
|
1242
2890
|
}
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
2891
|
+
var PLAYWRIGHT_DISABLED_FEATURES = [
|
|
2892
|
+
"AvoidUnnecessaryBeforeUnloadCheckSync",
|
|
2893
|
+
"DestroyProfileOnBrowserClose",
|
|
2894
|
+
"HttpsUpgrades",
|
|
2895
|
+
"HttpsFirstBalancedModeAutoEnable",
|
|
2896
|
+
"LensOverlay",
|
|
2897
|
+
"MediaRouter",
|
|
2898
|
+
"PaintHolding",
|
|
2899
|
+
"ThirdPartyStoragePartitioning",
|
|
2900
|
+
"AvoidCorsURLLoaderRestartOnRedirect",
|
|
2901
|
+
"TcpPortRandomizationWin",
|
|
2902
|
+
"OptimizationHints",
|
|
2903
|
+
"NetworkTimeServiceQuerying",
|
|
2904
|
+
"AimEnabled",
|
|
2905
|
+
"PreconnectToSearch",
|
|
2906
|
+
"msForceBrowserSignIn",
|
|
2907
|
+
"msEdgeUpdateLaunchServicesPreferredVersion"
|
|
2908
|
+
];
|
|
2909
|
+
var DISABLED_FEATURES = [...PLAYWRIGHT_DISABLED_FEATURES, "AcceptCHFrame"];
|
|
2910
|
+
function chromiumLaunchPlan(opts, release = browserRelease(
|
|
2911
|
+
chromiumBuild(opts.platform, opts.env)
|
|
2912
|
+
)) {
|
|
2913
|
+
const build = chromiumBuild(opts.platform, opts.env);
|
|
2914
|
+
const args = [
|
|
2915
|
+
"--headless",
|
|
2916
|
+
"--use-mock-keychain",
|
|
2917
|
+
`--window-size=${VIEWPORT.width},${VIEWPORT.height}`,
|
|
2918
|
+
`--user-agent=${chromeUserAgent(opts.platform, release?.version ?? "")}`,
|
|
2919
|
+
`--disable-features=${DISABLED_FEATURES.join(",")}`,
|
|
2920
|
+
// Chrome reloads a network error page by itself (after 1 s, then backing off): that reload
|
|
2921
|
+
// aborts the agent's next navigation in the tab and asks the proxy for the failed host again
|
|
2922
|
+
"--disable-auto-reload"
|
|
2923
|
+
];
|
|
2924
|
+
if (build === "chromium-headless-shell") args.push("--single-process");
|
|
2925
|
+
let env;
|
|
2926
|
+
if (opts.platform === "darwin") {
|
|
2927
|
+
args.push("--disable-crash-reporter", "--disable-breakpad");
|
|
2928
|
+
const tmp = envValue(opts.env, "TMPDIR");
|
|
2929
|
+
if (tmp !== void 0) env = { MAC_CHROMIUM_TMPDIR: tmp };
|
|
2930
|
+
}
|
|
1246
2931
|
const proxy = envValue(opts.env, "HTTPS_PROXY") ?? envValue(opts.env, "HTTP_PROXY");
|
|
1247
2932
|
let proxyAuth;
|
|
1248
2933
|
if (proxy !== void 0) {
|
|
@@ -1267,7 +2952,9 @@ function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
|
|
|
1267
2952
|
}
|
|
1268
2953
|
}
|
|
1269
2954
|
return {
|
|
1270
|
-
|
|
2955
|
+
...opts.browsersPath === void 0 ? browsersPathFor(opts.stateDir, opts.env, release?.revision, build) : { browsersPath: opts.browsersPath },
|
|
2956
|
+
build,
|
|
2957
|
+
...env === void 0 ? {} : { env },
|
|
1271
2958
|
profileDir: join2(opts.stateDir, "profile"),
|
|
1272
2959
|
downloadsTmp: join2(opts.stateDir, "downloads-tmp"),
|
|
1273
2960
|
args,
|
|
@@ -1290,24 +2977,44 @@ async function loadPlaywright(browsersPath) {
|
|
|
1290
2977
|
loaded = { browsersPath, pw: pw.default ?? pw };
|
|
1291
2978
|
return loaded.pw;
|
|
1292
2979
|
}
|
|
1293
|
-
async function
|
|
2980
|
+
async function registryBrowser(browsersPath, build) {
|
|
1294
2981
|
await loadPlaywright(browsersPath);
|
|
1295
2982
|
const mod = await import("./vendor/playwright-core/lib/coreBundle.js");
|
|
1296
2983
|
const registry = (mod.registry ?? mod.default?.registry)?.registry;
|
|
1297
2984
|
if (registry === void 0) throw new Error("playwright-core has no browser registry");
|
|
1298
|
-
const exe = registry.findExecutable(
|
|
1299
|
-
if (exe === void 0) throw new Error(
|
|
1300
|
-
const
|
|
1301
|
-
if (
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
2985
|
+
const exe = registry.findExecutable(build);
|
|
2986
|
+
if (exe === void 0) throw new Error(`playwright-core does not know ${build}`);
|
|
2987
|
+
const executablePath = exe.executablePath();
|
|
2988
|
+
if (executablePath === void 0 || exe.directory === void 0)
|
|
2989
|
+
throw new Error(`playwright-core has no ${build} for this platform`);
|
|
2990
|
+
return { registry, exe, executablePath, directory: exe.directory };
|
|
2991
|
+
}
|
|
2992
|
+
async function ensureChromium(browsersPath, install = true, build = chromiumBuild(process.platform), fresh = false) {
|
|
2993
|
+
const { registry, exe, executablePath, directory } = await registryBrowser(browsersPath, build);
|
|
2994
|
+
const marked = existsSync(join2(directory, "INSTALLATION_COMPLETE"));
|
|
2995
|
+
if (!fresh && marked && existsSync(executablePath)) return executablePath;
|
|
2996
|
+
if (!install)
|
|
2997
|
+
throw new Error(
|
|
2998
|
+
`the browser in ${browsersPath} is incomplete and read only for the browser service; delete the device and create it again`
|
|
2999
|
+
);
|
|
3000
|
+
await registry.install([exe], { gc: false, force: marked || fresh });
|
|
3001
|
+
if (!existsSync(executablePath)) {
|
|
1305
3002
|
throw new Error("the Chromium download finished without an executable");
|
|
1306
3003
|
}
|
|
1307
|
-
return
|
|
3004
|
+
return executablePath;
|
|
1308
3005
|
}
|
|
1309
3006
|
async function launchChromium(plan) {
|
|
1310
|
-
|
|
3007
|
+
if (plan.unavailable !== void 0) throw new Error(plan.unavailable);
|
|
3008
|
+
if (plan.install?.sealed === false) {
|
|
3009
|
+
await ensureChromium(plan.browsersPath, true, plan.build, true);
|
|
3010
|
+
sealInstall(plan.browsersPath);
|
|
3011
|
+
throw new BrowserInstalledError();
|
|
3012
|
+
}
|
|
3013
|
+
const executablePath = plan.shippedDir === void 0 ? await ensureChromium(
|
|
3014
|
+
plan.browsersPath,
|
|
3015
|
+
plan.install === void 0 && plan.shipped !== true,
|
|
3016
|
+
plan.build
|
|
3017
|
+
) : await shippedExecutable(plan.browsersPath, plan.shippedDir, plan.build);
|
|
1311
3018
|
const pw = await loadPlaywright(plan.browsersPath);
|
|
1312
3019
|
return pw.chromium.launchPersistentContext(plan.profileDir, {
|
|
1313
3020
|
headless: true,
|
|
@@ -1317,72 +3024,181 @@ async function launchChromium(plan) {
|
|
|
1317
3024
|
// downloads are saved into the workspace by the session (actions.ts)
|
|
1318
3025
|
acceptDownloads: true,
|
|
1319
3026
|
downloadsPath: plan.downloadsTmp,
|
|
1320
|
-
...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
|
|
3027
|
+
...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth },
|
|
3028
|
+
...plan.env === void 0 ? {} : { env: { ...process.env, ...plan.env } }
|
|
1321
3029
|
});
|
|
1322
3030
|
}
|
|
3031
|
+
async function shippedExecutable(cache, dir, build) {
|
|
3032
|
+
const { executablePath, directory } = await registryBrowser(cache, build);
|
|
3033
|
+
const path = join2(cache, dir, relative(directory, executablePath));
|
|
3034
|
+
if (!existsSync(path))
|
|
3035
|
+
throw new Error(
|
|
3036
|
+
`the browser shipped in ${join2(cache, dir)} has no executable; ${BROWSER_UNAVAILABLE_MESSAGE}`
|
|
3037
|
+
);
|
|
3038
|
+
return path;
|
|
3039
|
+
}
|
|
3040
|
+
function sealInstall(dir) {
|
|
3041
|
+
try {
|
|
3042
|
+
writeFileSync(join2(dir, SERVICE_INSTALL_SEAL), "", { flag: "wx", mode: 420 });
|
|
3043
|
+
} catch (e) {
|
|
3044
|
+
if (e.code !== "EEXIST") throw e;
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
async function browserProcessId(ctx) {
|
|
3048
|
+
const browser = ctx.browser();
|
|
3049
|
+
if (browser === null) return void 0;
|
|
3050
|
+
try {
|
|
3051
|
+
const cdp = await browser.newBrowserCDPSession();
|
|
3052
|
+
try {
|
|
3053
|
+
const info = await cdp.send("SystemInfo.getProcessInfo");
|
|
3054
|
+
return info.processInfo.find((p) => p.type === "browser")?.id;
|
|
3055
|
+
} finally {
|
|
3056
|
+
await cdp.detach().catch(() => void 0);
|
|
3057
|
+
}
|
|
3058
|
+
} catch {
|
|
3059
|
+
return void 0;
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
function killChromium(pid) {
|
|
3063
|
+
if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) return;
|
|
3064
|
+
try {
|
|
3065
|
+
process.kill(-pid, "SIGKILL");
|
|
3066
|
+
} catch {
|
|
3067
|
+
try {
|
|
3068
|
+
process.kill(pid, "SIGKILL");
|
|
3069
|
+
} catch {
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
function processAlive(pid) {
|
|
3074
|
+
try {
|
|
3075
|
+
process.kill(pid, 0);
|
|
3076
|
+
return true;
|
|
3077
|
+
} catch (e) {
|
|
3078
|
+
return e.code === "EPERM";
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
1323
3081
|
|
|
1324
|
-
// daemon/
|
|
1325
|
-
import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3082
|
+
// daemon/cookie-file.ts
|
|
3083
|
+
import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1326
3084
|
import { join as join3 } from "node:path";
|
|
3085
|
+
var key = (c) => `${c.domain}
|
|
3086
|
+
${c.path}
|
|
3087
|
+
${c.name}`;
|
|
3088
|
+
async function saveCookies(ctx, stateDir) {
|
|
3089
|
+
try {
|
|
3090
|
+
const cookies = (await ctx.cookies()).filter((c) => c.expires > 0);
|
|
3091
|
+
const file = join3(stateDir, "cookies.json");
|
|
3092
|
+
writeFileSync2(`${file}.tmp`, JSON.stringify(cookies), { mode: 384 });
|
|
3093
|
+
renameSync(`${file}.tmp`, file);
|
|
3094
|
+
} catch {
|
|
3095
|
+
}
|
|
3096
|
+
}
|
|
3097
|
+
async function restoreCookies(ctx, stateDir) {
|
|
3098
|
+
try {
|
|
3099
|
+
const saved = JSON.parse(readFileSync2(join3(stateDir, "cookies.json"), "utf8"));
|
|
3100
|
+
if (!Array.isArray(saved)) return;
|
|
3101
|
+
const have = new Set((await ctx.cookies()).map(key));
|
|
3102
|
+
const now = Date.now() / 1e3;
|
|
3103
|
+
const missing = saved.filter(
|
|
3104
|
+
(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))
|
|
3105
|
+
);
|
|
3106
|
+
if (missing.length > 0) await ctx.addCookies(missing);
|
|
3107
|
+
} catch {
|
|
3108
|
+
} finally {
|
|
3109
|
+
rmSync(join3(stateDir, "cookies.json"), { force: true });
|
|
3110
|
+
}
|
|
3111
|
+
}
|
|
3112
|
+
|
|
3113
|
+
// daemon/session-file.ts
|
|
3114
|
+
import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3115
|
+
import { join as join4 } from "node:path";
|
|
1327
3116
|
var RESTORE_MAX_AGE_MS = 10 * 6e4;
|
|
3117
|
+
var SESSION_FILE_VERSION = 2;
|
|
3118
|
+
var isId = (v) => typeof v === "string" && v !== "";
|
|
1328
3119
|
var SessionFile = class {
|
|
1329
3120
|
file;
|
|
1330
3121
|
clock;
|
|
1331
3122
|
queued = false;
|
|
1332
3123
|
forgotten = false;
|
|
1333
3124
|
constructor(stateDir, clock) {
|
|
1334
|
-
this.file =
|
|
3125
|
+
this.file = join4(stateDir, "session.json");
|
|
1335
3126
|
this.clock = clock;
|
|
1336
3127
|
}
|
|
1337
|
-
/** The saved session when it is recent and well formed; undefined otherwise. */
|
|
3128
|
+
/** The saved session when it is recent, of this format and well formed; undefined otherwise. */
|
|
1338
3129
|
read() {
|
|
1339
3130
|
let raw;
|
|
1340
3131
|
try {
|
|
1341
|
-
raw = JSON.parse(
|
|
3132
|
+
raw = JSON.parse(readFileSync3(this.file, "utf8"));
|
|
1342
3133
|
} catch {
|
|
1343
3134
|
return void 0;
|
|
1344
3135
|
}
|
|
1345
3136
|
const s = raw;
|
|
1346
|
-
if (typeof s !== "object" || s === null || typeof s.savedAt !== "number" || this.clock.now() - s.savedAt > RESTORE_MAX_AGE_MS || !Array.isArray(s.tabs))
|
|
3137
|
+
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))
|
|
1347
3138
|
return void 0;
|
|
1348
3139
|
const tabs = s.tabs.filter(
|
|
1349
|
-
(
|
|
1350
|
-
);
|
|
1351
|
-
const
|
|
1352
|
-
const
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
3140
|
+
(t) => typeof t === "object" && t !== null && typeof t.url === "string" && /^https?:\/\//i.test(t.url) && isId(t.owner) && isId(t.root)
|
|
3141
|
+
).slice(0, MAX_TABS).map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
|
|
3142
|
+
const conversations = [];
|
|
3143
|
+
for (const c of s.conversations) {
|
|
3144
|
+
if (typeof c !== "object" || c === null) continue;
|
|
3145
|
+
const x = c;
|
|
3146
|
+
if (!isId(x.id) || !isId(x.root)) continue;
|
|
3147
|
+
const h = x.handoff;
|
|
3148
|
+
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;
|
|
3149
|
+
const parks = Array.isArray(x.parks) ? x.parks.filter(
|
|
3150
|
+
(p) => typeof p === "object" && p !== null && isId(p.kind) && typeof p.key === "string"
|
|
3151
|
+
).map((p) => ({ kind: p.kind, key: p.key })) : [];
|
|
3152
|
+
conversations.push({
|
|
3153
|
+
id: x.id,
|
|
3154
|
+
root: x.root,
|
|
3155
|
+
...typeof x.active === "number" ? { active: x.active } : {},
|
|
3156
|
+
...handoff === void 0 ? {} : { handoff },
|
|
3157
|
+
...parks.length === 0 ? {} : { parks }
|
|
3158
|
+
});
|
|
3159
|
+
}
|
|
3160
|
+
return { version: SESSION_FILE_VERSION, savedAt: s.savedAt, tabs, conversations };
|
|
1359
3161
|
}
|
|
1360
3162
|
/**
|
|
1361
|
-
* Writes the session soon (coalesced): the tabs
|
|
1362
|
-
* the write runs.
|
|
3163
|
+
* Writes the session soon (coalesced): the tabs with their owners, and per conversation its
|
|
3164
|
+
* active tab, pending handoff and persistent parks, all read when the write runs.
|
|
1363
3165
|
*/
|
|
1364
|
-
save(session,
|
|
3166
|
+
save(session, state) {
|
|
1365
3167
|
if (this.queued || this.forgotten) return;
|
|
1366
3168
|
this.queued = true;
|
|
1367
3169
|
queueMicrotask(() => {
|
|
1368
3170
|
this.queued = false;
|
|
1369
3171
|
if (this.forgotten) return;
|
|
1370
|
-
const
|
|
1371
|
-
|
|
1372
|
-
const kept = all.filter((t) => /^https?:\/\//i.test(t.url));
|
|
1373
|
-
const active = Math.max(
|
|
1374
|
-
0,
|
|
1375
|
-
kept.findIndex((t) => t.active)
|
|
3172
|
+
const kept = session.tabs().filter(
|
|
3173
|
+
(t) => t.owner !== void 0 && t.root !== void 0 && /^https?:\/\//i.test(t.url)
|
|
1376
3174
|
);
|
|
3175
|
+
const tabs = kept.map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
|
|
3176
|
+
const ids = /* @__PURE__ */ new Set([...kept.map((t) => t.owner), ...state.conversationIds]);
|
|
3177
|
+
const conversations = [];
|
|
3178
|
+
for (const id of ids) {
|
|
3179
|
+
const root = kept.find((t) => t.owner === id)?.root ?? state.rootOf(id);
|
|
3180
|
+
if (root === void 0) continue;
|
|
3181
|
+
const active = kept.findIndex((t) => t.owner === id && t.active);
|
|
3182
|
+
const handoff = state.handoffOf(id);
|
|
3183
|
+
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 }));
|
|
3184
|
+
if (active < 0 && handoff === void 0 && parks.length === 0) continue;
|
|
3185
|
+
conversations.push({
|
|
3186
|
+
id,
|
|
3187
|
+
root,
|
|
3188
|
+
...active < 0 ? {} : { active },
|
|
3189
|
+
...handoff === void 0 ? {} : { handoff },
|
|
3190
|
+
...parks.length === 0 ? {} : { parks }
|
|
3191
|
+
});
|
|
3192
|
+
}
|
|
1377
3193
|
const body = {
|
|
3194
|
+
version: SESSION_FILE_VERSION,
|
|
1378
3195
|
savedAt: this.clock.now(),
|
|
1379
|
-
tabs
|
|
1380
|
-
|
|
1381
|
-
...handoff === void 0 ? {} : { handoff }
|
|
3196
|
+
tabs,
|
|
3197
|
+
conversations
|
|
1382
3198
|
};
|
|
1383
3199
|
try {
|
|
1384
|
-
|
|
1385
|
-
|
|
3200
|
+
writeFileSync3(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
|
|
3201
|
+
renameSync2(`${this.file}.tmp`, this.file);
|
|
1386
3202
|
} catch {
|
|
1387
3203
|
}
|
|
1388
3204
|
});
|
|
@@ -1390,45 +3206,361 @@ var SessionFile = class {
|
|
|
1390
3206
|
/** Removes the file and stops saving (an idle stop). */
|
|
1391
3207
|
forget() {
|
|
1392
3208
|
this.forgotten = true;
|
|
1393
|
-
|
|
3209
|
+
rmSync2(this.file, { force: true });
|
|
3210
|
+
}
|
|
3211
|
+
/** Gives the conversations their pending handoffs and persistent parks back. */
|
|
3212
|
+
restoreState(state, saved) {
|
|
3213
|
+
for (const c of saved.conversations) {
|
|
3214
|
+
if (c.handoff !== void 0)
|
|
3215
|
+
state.noticeHandoff(c.id, c.root, c.handoff.callId, c.handoff.message);
|
|
3216
|
+
for (const p of c.parks ?? []) state.park(c.id, c.root, { ...p, persist: true });
|
|
3217
|
+
}
|
|
1394
3218
|
}
|
|
1395
3219
|
/**
|
|
1396
|
-
* Opens the saved tabs in a browser that has only its first blank tab
|
|
1397
|
-
*
|
|
3220
|
+
* Opens the saved tabs, each for its owner, in a browser that has only its first blank tab, and
|
|
3221
|
+
* gives each conversation its active tab back. The navigations are started, not awaited: the
|
|
3222
|
+
* first request after a restart does not wait for every page to load.
|
|
1398
3223
|
*/
|
|
1399
3224
|
async restoreTabs(session, saved) {
|
|
1400
|
-
if (saved.tabs.length === 0) return;
|
|
1401
3225
|
const ids = [];
|
|
1402
|
-
for (const
|
|
3226
|
+
for (const t of saved.tabs) {
|
|
1403
3227
|
try {
|
|
1404
|
-
|
|
1405
|
-
ids.push(session.tabIdOf(page));
|
|
1406
|
-
void session.viewerNav({ url: normalizeUrl(url) });
|
|
3228
|
+
ids.push(await session.restoreTab({ owner: t.owner, root: t.root }, t.url));
|
|
1407
3229
|
} catch {
|
|
3230
|
+
ids.push(void 0);
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
3233
|
+
for (const c of saved.conversations) {
|
|
3234
|
+
const id = c.active === void 0 ? void 0 : ids[c.active];
|
|
3235
|
+
if (id !== void 0) session.setActive(c.id, id);
|
|
3236
|
+
}
|
|
3237
|
+
}
|
|
3238
|
+
};
|
|
3239
|
+
|
|
3240
|
+
// daemon/cursor.ts
|
|
3241
|
+
var CURSOR_MAX_FRAMES = 20;
|
|
3242
|
+
var MAX_DEPTH = 3;
|
|
3243
|
+
var WORLD = "capybara-cursor";
|
|
3244
|
+
var CURSOR_FUNCTION = `function (x, y) {
|
|
3245
|
+
const el = this.nodeType === 1 ? this : this.parentElement;
|
|
3246
|
+
if (!el) return { cursor: "default" };
|
|
3247
|
+
if (el.tagName === "IFRAME" || el.tagName === "FRAME") return { frame: true };
|
|
3248
|
+
const doc = el.ownerDocument;
|
|
3249
|
+
const view = doc.defaultView;
|
|
3250
|
+
const style = view.getComputedStyle(el);
|
|
3251
|
+
// "url(a.cur) 4 4, pointer": an image cursor's keyword fallback is the last item
|
|
3252
|
+
const parts = String(style.cursor).split(",");
|
|
3253
|
+
const cursor = parts[parts.length - 1].trim();
|
|
3254
|
+
if (cursor !== "auto") return { cursor };
|
|
3255
|
+
const NOT_TEXT = ["button", "submit", "reset", "checkbox", "radio", "range", "color", "file", "image", "hidden"];
|
|
3256
|
+
const tag = el.tagName;
|
|
3257
|
+
const editable = el.isContentEditable || tag === "TEXTAREA" ||
|
|
3258
|
+
(tag === "INPUT" && !NOT_TEXT.includes(String(el.type).toLowerCase()));
|
|
3259
|
+
if (editable && !el.disabled) return { cursor: "text" };
|
|
3260
|
+
if (style.userSelect === "none") return { cursor: "default" };
|
|
3261
|
+
const range = doc.caretRangeFromPoint ? doc.caretRangeFromPoint(x, y) : null;
|
|
3262
|
+
const node = range ? range.startContainer : null;
|
|
3263
|
+
if (!node || node.nodeType !== 3) return { cursor: "default" };
|
|
3264
|
+
const probe = doc.createRange();
|
|
3265
|
+
for (const [a, b] of [[range.startOffset, range.startOffset + 1], [range.startOffset - 1, range.startOffset]]) {
|
|
3266
|
+
if (a < 0 || b > node.length) continue;
|
|
3267
|
+
probe.setStart(node, a);
|
|
3268
|
+
probe.setEnd(node, b);
|
|
3269
|
+
for (const r of probe.getClientRects())
|
|
3270
|
+
if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) return { cursor: "text" };
|
|
3271
|
+
}
|
|
3272
|
+
return { cursor: "default" };
|
|
3273
|
+
}`;
|
|
3274
|
+
var CursorResolver = class {
|
|
3275
|
+
constructor(context, page, cdp) {
|
|
3276
|
+
this.context = context;
|
|
3277
|
+
this.page = page;
|
|
3278
|
+
this.cdp = cdp;
|
|
3279
|
+
page.on("framedetached", this.onFrameDetached);
|
|
3280
|
+
}
|
|
3281
|
+
context;
|
|
3282
|
+
page;
|
|
3283
|
+
cdp;
|
|
3284
|
+
/** Isolated world execution contexts, per CDP session and frame id. */
|
|
3285
|
+
worlds = /* @__PURE__ */ new WeakMap();
|
|
3286
|
+
/** Sessions of out-of-process frames entered, detached with their frame or on dispose. */
|
|
3287
|
+
sessions = /* @__PURE__ */ new Map();
|
|
3288
|
+
onFrameDetached = (frame) => {
|
|
3289
|
+
const cdp = this.sessions.get(frame);
|
|
3290
|
+
if (cdp === void 0) return;
|
|
3291
|
+
this.sessions.delete(frame);
|
|
3292
|
+
cdp.detach().catch(() => void 0);
|
|
3293
|
+
};
|
|
3294
|
+
/** How many out-of-process frame sessions are open (a test seam). */
|
|
3295
|
+
get openSessions() {
|
|
3296
|
+
return this.sessions.size;
|
|
3297
|
+
}
|
|
3298
|
+
/** Detaches the frame sessions this resolver opened (the viewer detached from the page). */
|
|
3299
|
+
dispose() {
|
|
3300
|
+
this.page.off("framedetached", this.onFrameDetached);
|
|
3301
|
+
for (const cdp of this.sessions.values()) cdp.detach().catch(() => void 0);
|
|
3302
|
+
this.sessions.clear();
|
|
3303
|
+
}
|
|
3304
|
+
/** The cursor Chromium would show at viewport point (x, y). */
|
|
3305
|
+
async at(x, y) {
|
|
3306
|
+
let cdp = this.cdp;
|
|
3307
|
+
let frame = this.page.mainFrame();
|
|
3308
|
+
let px = x;
|
|
3309
|
+
let py = y;
|
|
3310
|
+
for (let depth = 0; depth <= MAX_DEPTH; depth++) {
|
|
3311
|
+
const hit = await this.hitTest(cdp, px, py);
|
|
3312
|
+
const answer = await this.answerAt(cdp, hit, px, py);
|
|
3313
|
+
if (answer.cursor !== void 0) return toViewerCursor(answer.cursor);
|
|
3314
|
+
if (!answer.frame || depth === MAX_DEPTH) return "default";
|
|
3315
|
+
const box = await cdp.send("DOM.getBoxModel", { backendNodeId: hit.backendNodeId });
|
|
3316
|
+
const [left = 0, top = 0] = box.model.content;
|
|
3317
|
+
const [borderLeft = 0, borderTop = 0] = box.model.border;
|
|
3318
|
+
const child = await this.childAt(frame, borderLeft + (x - px), borderTop + (y - py));
|
|
3319
|
+
if (child === void 0) return "default";
|
|
3320
|
+
frame = child.frame;
|
|
3321
|
+
cdp = child.cdp;
|
|
3322
|
+
px = px - left;
|
|
3323
|
+
py = py - top;
|
|
3324
|
+
}
|
|
3325
|
+
return "default";
|
|
3326
|
+
}
|
|
3327
|
+
async hitTest(cdp, x, y) {
|
|
3328
|
+
return await cdp.send("DOM.getNodeForLocation", {
|
|
3329
|
+
x: Math.round(x),
|
|
3330
|
+
y: Math.round(y),
|
|
3331
|
+
includeUserAgentShadowDOM: false,
|
|
3332
|
+
ignorePointerEventsNone: false
|
|
3333
|
+
});
|
|
3334
|
+
}
|
|
3335
|
+
/** The answer for a hit node, at the point in the node's own frame. */
|
|
3336
|
+
async answerAt(cdp, hit, x, y) {
|
|
3337
|
+
const frameId = hit.frameId ?? await this.mainFrameId(cdp);
|
|
3338
|
+
const offset = await this.frameOffset(cdp, frameId);
|
|
3339
|
+
return this.run(cdp, frameId, hit.backendNodeId, x - offset.x, y - offset.y);
|
|
3340
|
+
}
|
|
3341
|
+
async run(cdp, frameId, backendNodeId, x, y) {
|
|
3342
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
3343
|
+
const contextId = await this.world(cdp, frameId, attempt > 0);
|
|
3344
|
+
try {
|
|
3345
|
+
const { object } = await cdp.send("DOM.resolveNode", {
|
|
3346
|
+
backendNodeId,
|
|
3347
|
+
executionContextId: contextId
|
|
3348
|
+
});
|
|
3349
|
+
if (object.objectId === void 0) return { cursor: "default" };
|
|
3350
|
+
const r = await cdp.send("Runtime.callFunctionOn", {
|
|
3351
|
+
objectId: object.objectId,
|
|
3352
|
+
functionDeclaration: CURSOR_FUNCTION,
|
|
3353
|
+
arguments: [{ value: x }, { value: y }],
|
|
3354
|
+
returnByValue: true
|
|
3355
|
+
});
|
|
3356
|
+
await cdp.send("Runtime.releaseObject", { objectId: object.objectId }).catch(() => {
|
|
3357
|
+
});
|
|
3358
|
+
return r.result.value ?? { cursor: "default" };
|
|
3359
|
+
} catch (e) {
|
|
3360
|
+
if (attempt > 0) throw e;
|
|
1408
3361
|
}
|
|
1409
3362
|
}
|
|
1410
|
-
|
|
1411
|
-
|
|
3363
|
+
return { cursor: "default" };
|
|
3364
|
+
}
|
|
3365
|
+
async world(cdp, frameId, fresh) {
|
|
3366
|
+
let byFrame = this.worlds.get(cdp);
|
|
3367
|
+
if (byFrame === void 0) {
|
|
3368
|
+
byFrame = /* @__PURE__ */ new Map();
|
|
3369
|
+
this.worlds.set(cdp, byFrame);
|
|
3370
|
+
}
|
|
3371
|
+
const known = byFrame.get(frameId);
|
|
3372
|
+
if (known !== void 0 && !fresh) return known;
|
|
3373
|
+
const { executionContextId } = await cdp.send("Page.createIsolatedWorld", {
|
|
3374
|
+
frameId,
|
|
3375
|
+
worldName: WORLD
|
|
3376
|
+
});
|
|
3377
|
+
byFrame.set(frameId, executionContextId);
|
|
3378
|
+
return executionContextId;
|
|
3379
|
+
}
|
|
3380
|
+
async mainFrameId(cdp) {
|
|
3381
|
+
const { frameTree } = await cdp.send("Page.getFrameTree");
|
|
3382
|
+
return frameTree.frame.id;
|
|
3383
|
+
}
|
|
3384
|
+
/** The offset of an in-process frame's viewport in the session's root (0 for its main frame). */
|
|
3385
|
+
async frameOffset(cdp, frameId) {
|
|
3386
|
+
if (frameId === await this.mainFrameId(cdp)) return { x: 0, y: 0 };
|
|
3387
|
+
const owner = await cdp.send("DOM.getFrameOwner", { frameId });
|
|
3388
|
+
const box = await cdp.send("DOM.getBoxModel", { backendNodeId: owner.backendNodeId });
|
|
3389
|
+
return { x: box.model.content[0] ?? 0, y: box.model.content[1] ?? 0 };
|
|
3390
|
+
}
|
|
3391
|
+
/**
|
|
3392
|
+
* The child frame of `parent` whose element's border box starts at (left, top), in the page's
|
|
3393
|
+
* (main frame) coordinates.
|
|
3394
|
+
*/
|
|
3395
|
+
async childAt(parent, left, top) {
|
|
3396
|
+
for (const child of parent.childFrames().slice(0, CURSOR_MAX_FRAMES)) {
|
|
3397
|
+
const handle = await child.frameElement().catch(() => null);
|
|
3398
|
+
const box = await handle?.boundingBox().catch(() => null);
|
|
3399
|
+
await handle?.dispose();
|
|
3400
|
+
if (box === null || box === void 0) continue;
|
|
3401
|
+
if (Math.abs(box.x - left) > 3 || Math.abs(box.y - top) > 3) continue;
|
|
3402
|
+
let cdp = this.sessions.get(child);
|
|
3403
|
+
if (cdp === void 0) {
|
|
3404
|
+
cdp = await this.context.newCDPSession(child);
|
|
3405
|
+
this.sessions.set(child, cdp);
|
|
3406
|
+
}
|
|
3407
|
+
return { frame: child, cdp };
|
|
3408
|
+
}
|
|
3409
|
+
return void 0;
|
|
3410
|
+
}
|
|
3411
|
+
};
|
|
3412
|
+
|
|
3413
|
+
// daemon/viewer-pacing.ts
|
|
3414
|
+
var TARGET_LINK_MS = 120;
|
|
3415
|
+
var PING_WINDOW = 10;
|
|
3416
|
+
var RTT_WINDOW = 16;
|
|
3417
|
+
var LINK_ALPHA = 0.5;
|
|
3418
|
+
var FramePacer = class {
|
|
3419
|
+
minIntervalMs;
|
|
3420
|
+
maxUnacked;
|
|
3421
|
+
inFlight = [];
|
|
3422
|
+
pings = [];
|
|
3423
|
+
rtts = [];
|
|
3424
|
+
lastSentAt = Number.NEGATIVE_INFINITY;
|
|
3425
|
+
link;
|
|
3426
|
+
constructor(opts) {
|
|
3427
|
+
this.minIntervalMs = 1e3 / opts.maxFps;
|
|
3428
|
+
this.maxUnacked = opts.maxUnacked;
|
|
3429
|
+
}
|
|
3430
|
+
/** The smoothed time frames take over the path's own round trip; undefined before any ack. */
|
|
3431
|
+
get linkMs() {
|
|
3432
|
+
return this.link;
|
|
3433
|
+
}
|
|
3434
|
+
get unacked() {
|
|
3435
|
+
return this.inFlight.length;
|
|
3436
|
+
}
|
|
3437
|
+
/** The path's round trip without queueing, as far as measured. */
|
|
3438
|
+
get baseRttMs() {
|
|
3439
|
+
if (this.pings.length > 0) return Math.min(...this.pings);
|
|
3440
|
+
if (this.rtts.length > 0) return Math.min(...this.rtts);
|
|
3441
|
+
return void 0;
|
|
3442
|
+
}
|
|
3443
|
+
/** Whether a frame may be sent at `now`, and if only the rate cap holds it, for how long. */
|
|
3444
|
+
decide(now) {
|
|
3445
|
+
const n = this.inFlight.length;
|
|
3446
|
+
if (n >= this.maxUnacked) return { ok: false };
|
|
3447
|
+
if (n > 0 && this.link !== void 0 && this.link > TARGET_LINK_MS) return { ok: false };
|
|
3448
|
+
const wait = this.lastSentAt + this.minIntervalMs - now;
|
|
3449
|
+
return wait > 0 ? { ok: false, waitMs: wait } : { ok: true };
|
|
3450
|
+
}
|
|
3451
|
+
/** Records a frame sent at `now` (every frame counts, the first after an attach too). */
|
|
3452
|
+
sent(seq, now) {
|
|
3453
|
+
this.inFlight.push({ seq, at: now });
|
|
3454
|
+
this.lastSentAt = now;
|
|
3455
|
+
}
|
|
3456
|
+
/** Records the viewer's ack of every frame up to `seq` at `now`; returns the sample, if any. */
|
|
3457
|
+
acked(seq, now) {
|
|
3458
|
+
let last;
|
|
3459
|
+
while (this.inFlight.length > 0 && this.inFlight[0].seq <= seq) {
|
|
3460
|
+
last = this.inFlight.shift();
|
|
3461
|
+
}
|
|
3462
|
+
if (last === void 0) return void 0;
|
|
3463
|
+
const rtt = Math.max(0, now - last.at);
|
|
3464
|
+
this.rtts.push(rtt);
|
|
3465
|
+
if (this.rtts.length > RTT_WINDOW) this.rtts.shift();
|
|
3466
|
+
const sample = Math.max(0, rtt - (this.baseRttMs ?? rtt));
|
|
3467
|
+
this.link = this.link === void 0 ? sample : this.link * (1 - LINK_ALPHA) + sample * LINK_ALPHA;
|
|
3468
|
+
return sample;
|
|
3469
|
+
}
|
|
3470
|
+
/** Records a ping's round trip (a tiny message both ways on the same path as the frames). */
|
|
3471
|
+
pinged(rttMs) {
|
|
3472
|
+
if (!Number.isFinite(rttMs) || rttMs < 0) return;
|
|
3473
|
+
this.pings.push(rttMs);
|
|
3474
|
+
if (this.pings.length > PING_WINDOW) this.pings.shift();
|
|
3475
|
+
}
|
|
3476
|
+
/** Forgets frames in flight (a screencast restart: their acks may never come). */
|
|
3477
|
+
reset() {
|
|
3478
|
+
this.inFlight.length = 0;
|
|
3479
|
+
}
|
|
3480
|
+
};
|
|
3481
|
+
var QUALITY_STEPS = [60, 45, 35, 25];
|
|
3482
|
+
var SHRINK_STEPS = [1, 0.8, 0.65, 0.5, 0.35, 0.25];
|
|
3483
|
+
var ADAPT_SHRINK_STEPS = 4;
|
|
3484
|
+
var UP_AFTER_QUICK_FRAMES = 6;
|
|
3485
|
+
var FrameQuality = class {
|
|
3486
|
+
step = 0;
|
|
3487
|
+
quick = 0;
|
|
3488
|
+
get quality() {
|
|
3489
|
+
return QUALITY_STEPS[Math.min(this.step, QUALITY_STEPS.length - 1)];
|
|
3490
|
+
}
|
|
3491
|
+
get shrink() {
|
|
3492
|
+
const s = Math.max(0, this.step - (QUALITY_STEPS.length - 1));
|
|
3493
|
+
return SHRINK_STEPS[Math.min(s, SHRINK_STEPS.length - 1)];
|
|
3494
|
+
}
|
|
3495
|
+
/** The lowest step the link adaptation goes to. */
|
|
3496
|
+
get adaptMaxStep() {
|
|
3497
|
+
return QUALITY_STEPS.length - 1 + ADAPT_SHRINK_STEPS - 1;
|
|
3498
|
+
}
|
|
3499
|
+
get maxStep() {
|
|
3500
|
+
return QUALITY_STEPS.length - 1 + SHRINK_STEPS.length - 1;
|
|
3501
|
+
}
|
|
3502
|
+
/** One acked frame's link time; true when the step changed (restart the screencast). */
|
|
3503
|
+
observe(linkMs) {
|
|
3504
|
+
if (linkMs > TARGET_LINK_MS * 1.25) {
|
|
3505
|
+
this.quick = 0;
|
|
3506
|
+
if (this.step >= this.adaptMaxStep) return false;
|
|
3507
|
+
this.step++;
|
|
3508
|
+
return true;
|
|
3509
|
+
}
|
|
3510
|
+
if (linkMs < TARGET_LINK_MS / 2) {
|
|
3511
|
+
this.quick++;
|
|
3512
|
+
if (this.quick >= UP_AFTER_QUICK_FRAMES && this.step > 0) {
|
|
3513
|
+
this.step--;
|
|
3514
|
+
this.quick = 0;
|
|
3515
|
+
return true;
|
|
3516
|
+
}
|
|
3517
|
+
} else this.quick = 0;
|
|
3518
|
+
return false;
|
|
3519
|
+
}
|
|
3520
|
+
/** A frame too large for one message: always one step smaller. */
|
|
3521
|
+
tooLarge() {
|
|
3522
|
+
this.quick = 0;
|
|
3523
|
+
if (this.step >= this.maxStep) return false;
|
|
3524
|
+
this.step++;
|
|
3525
|
+
return true;
|
|
1412
3526
|
}
|
|
1413
3527
|
};
|
|
1414
3528
|
|
|
1415
3529
|
// daemon/viewer.ts
|
|
1416
|
-
var
|
|
1417
|
-
var
|
|
1418
|
-
var
|
|
3530
|
+
var VIEWER_PING_MS = 1e3;
|
|
3531
|
+
var RESTART_MIN_MS = 500;
|
|
3532
|
+
var ENCODE_MAX_INTERVAL_MS = 500;
|
|
3533
|
+
var CURSOR_TIMEOUT_MS = 200;
|
|
1419
3534
|
var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.max(16, Math.min(max, Math.floor(n))) : max;
|
|
1420
3535
|
var ViewerSession = class {
|
|
1421
3536
|
browser;
|
|
1422
3537
|
state;
|
|
3538
|
+
/** The viewer's conversation and the root of its tree (from the kernel's viewer context). */
|
|
3539
|
+
conv;
|
|
3540
|
+
root;
|
|
3541
|
+
/** The tab the person (or a new handoff) chose to show; cleared when it leaves the tree. */
|
|
3542
|
+
choice;
|
|
3543
|
+
/** The tab shown now (computed with every state). */
|
|
3544
|
+
shown;
|
|
3545
|
+
/** The other conversation the viewer pins because it shows one of its tabs. */
|
|
3546
|
+
pinnedOwner;
|
|
3547
|
+
/** Group keys of the tree's other conversations, in order of first appearance. */
|
|
3548
|
+
groups = /* @__PURE__ */ new Map();
|
|
3549
|
+
/** The tree's handoffs seen so far (a new one moves the shown tab to its conversation). */
|
|
3550
|
+
seenHandoffs = /* @__PURE__ */ new Set();
|
|
1423
3551
|
out;
|
|
1424
3552
|
clock;
|
|
1425
3553
|
frameMaxBytes;
|
|
1426
3554
|
unsubscribe = [];
|
|
1427
3555
|
maxWidth = VIEWPORT.width;
|
|
1428
3556
|
maxHeight = VIEWPORT.height;
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
3557
|
+
pacer = new FramePacer({
|
|
3558
|
+
maxFps: VIEWER_MAX_FPS,
|
|
3559
|
+
maxUnacked: VIEWER_UNACKED_FRAMES
|
|
3560
|
+
});
|
|
3561
|
+
/** Quality and scale: lowered while frames are slow on the link or over the message cap. */
|
|
3562
|
+
frameQuality = new FrameQuality();
|
|
3563
|
+
lastRestartAt = Number.NEGATIVE_INFINITY;
|
|
1432
3564
|
started = false;
|
|
1433
3565
|
closed = false;
|
|
1434
3566
|
page;
|
|
@@ -1438,17 +3570,48 @@ var ViewerSession = class {
|
|
|
1438
3570
|
inputChain = Promise.resolve();
|
|
1439
3571
|
/** Bumped on close and hand back: input queued before it is dropped, not replayed. */
|
|
1440
3572
|
inputGen = 0;
|
|
3573
|
+
/**
|
|
3574
|
+
* The newest pointer position not yet applied, while a move for it waits on the input chain:
|
|
3575
|
+
* later moves replace it (the newest wins) instead of queueing behind it.
|
|
3576
|
+
*/
|
|
3577
|
+
moveSlot;
|
|
3578
|
+
/** The cursor last sent (reset when control returns to the agent). */
|
|
3579
|
+
cursor;
|
|
3580
|
+
/** Resolves cursors on the attached page (off the input chain, see {@link wantCursor}). */
|
|
3581
|
+
cursorResolver;
|
|
3582
|
+
/** The newest pointer position whose cursor is wanted; one resolution runs at a time. */
|
|
3583
|
+
cursorPoint;
|
|
3584
|
+
/** The resolver a resolution loop runs for (one loop per resolver, one lookup at a time). */
|
|
3585
|
+
cursorLoop;
|
|
3586
|
+
/**
|
|
3587
|
+
* Keys and buttons this viewer pressed and has not released: released for the agent when
|
|
3588
|
+
* control returns to it or the viewer ends, whatever reached the page of the person's input.
|
|
3589
|
+
*/
|
|
3590
|
+
heldKeys = /* @__PURE__ */ new Map();
|
|
3591
|
+
heldButtons = /* @__PURE__ */ new Map();
|
|
1441
3592
|
seq = 0;
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
3593
|
+
/**
|
|
3594
|
+
* The newest screencast frame waiting for room (viewer acks, transport, rate cap). A newer one
|
|
3595
|
+
* replaces it: a frame is never queued behind a stale one.
|
|
3596
|
+
*/
|
|
1445
3597
|
pending;
|
|
3598
|
+
/** Chromium frames received but not acked to Chromium yet (it encodes the next after an ack). */
|
|
3599
|
+
encodeAck;
|
|
3600
|
+
encodeTimer;
|
|
3601
|
+
lastEncodeAckAt = Number.NEGATIVE_INFINITY;
|
|
1446
3602
|
pumpTimer;
|
|
3603
|
+
pingTimer;
|
|
3604
|
+
pingSeq = 0;
|
|
3605
|
+
pingsSent = /* @__PURE__ */ new Map();
|
|
1447
3606
|
draining = false;
|
|
1448
3607
|
stateQueued = false;
|
|
3608
|
+
lastControl = "agent";
|
|
1449
3609
|
constructor(opts) {
|
|
1450
3610
|
this.browser = opts.browser;
|
|
1451
3611
|
this.state = opts.state;
|
|
3612
|
+
this.conv = opts.conversationId;
|
|
3613
|
+
this.root = opts.rootConversationId;
|
|
3614
|
+
this.state.pin(this.conv, this.root);
|
|
1452
3615
|
this.out = opts.transport;
|
|
1453
3616
|
this.clock = opts.clock;
|
|
1454
3617
|
this.frameMaxBytes = opts.frameMaxBytes;
|
|
@@ -1464,12 +3627,17 @@ var ViewerSession = class {
|
|
|
1464
3627
|
if (m.t !== "hello") return;
|
|
1465
3628
|
this.started = true;
|
|
1466
3629
|
this.setSize(m.maxWidth, m.maxHeight);
|
|
3630
|
+
this.lastControl = this.state.control;
|
|
1467
3631
|
this.unsubscribe.push(
|
|
1468
3632
|
this.browser.on((e) => this.onSession(e)),
|
|
1469
|
-
this.state.onChange(() => this.
|
|
3633
|
+
this.state.onChange(() => this.onControl())
|
|
1470
3634
|
);
|
|
3635
|
+
const pending = this.state.handoffs(this.root);
|
|
3636
|
+
this.seenHandoffs = new Set(pending.map(handoffKey));
|
|
3637
|
+
const newest = pending.at(-1);
|
|
3638
|
+
if (newest !== void 0) this.choice = this.browser.activeTabOf(newest.conversationId);
|
|
1471
3639
|
this.sendState();
|
|
1472
|
-
|
|
3640
|
+
this.ping();
|
|
1473
3641
|
return;
|
|
1474
3642
|
}
|
|
1475
3643
|
switch (m.t) {
|
|
@@ -1482,39 +3650,64 @@ var ViewerSession = class {
|
|
|
1482
3650
|
});
|
|
1483
3651
|
return;
|
|
1484
3652
|
case "frame-ack":
|
|
1485
|
-
if (typeof m.seq === "number"
|
|
3653
|
+
if (typeof m.seq === "number") this.onAck(Math.min(m.seq, this.seq));
|
|
1486
3654
|
this.pump();
|
|
1487
3655
|
return;
|
|
3656
|
+
case "pong": {
|
|
3657
|
+
const sentAt = typeof m.id === "number" ? this.pingsSent.get(m.id) : void 0;
|
|
3658
|
+
if (sentAt !== void 0) {
|
|
3659
|
+
this.pingsSent.delete(m.id);
|
|
3660
|
+
this.pacer.pinged(this.clock.now() - sentAt);
|
|
3661
|
+
}
|
|
3662
|
+
return;
|
|
3663
|
+
}
|
|
1488
3664
|
case "takeover":
|
|
1489
|
-
this.state.takeover();
|
|
3665
|
+
this.state.takeover(this.browser.owningConversations());
|
|
1490
3666
|
return;
|
|
1491
3667
|
case "handback":
|
|
1492
3668
|
this.inputGen++;
|
|
1493
3669
|
this.state.handback();
|
|
1494
3670
|
return;
|
|
1495
3671
|
case "mouse":
|
|
1496
|
-
|
|
3672
|
+
if (m.kind === "move") this.move(m);
|
|
3673
|
+
else this.input(() => this.mouse(m));
|
|
1497
3674
|
return;
|
|
1498
3675
|
case "key":
|
|
1499
3676
|
this.input(() => this.key(m));
|
|
1500
3677
|
return;
|
|
1501
3678
|
case "nav":
|
|
1502
|
-
this.input(
|
|
1503
|
-
|
|
3679
|
+
this.input(async () => {
|
|
3680
|
+
let page = this.shownPage();
|
|
3681
|
+
if (page === void 0) {
|
|
3682
|
+
if (typeof m.url !== "string") return;
|
|
3683
|
+
page = await this.openOwnTab();
|
|
3684
|
+
if (page === void 0) return;
|
|
3685
|
+
}
|
|
3686
|
+
this.concern(this.browser.tabIdOf(page));
|
|
3687
|
+
await this.browser.viewerNav(page, {
|
|
1504
3688
|
...typeof m.url === "string" ? { url: m.url } : {},
|
|
1505
3689
|
...m.action === void 0 ? {} : { action: m.action }
|
|
1506
|
-
})
|
|
1507
|
-
);
|
|
3690
|
+
});
|
|
3691
|
+
});
|
|
3692
|
+
return;
|
|
3693
|
+
case "show":
|
|
3694
|
+
if (typeof m.tabId === "string" && this.inTree(m.tabId)) {
|
|
3695
|
+
this.choice = m.tabId;
|
|
3696
|
+
this.queueState();
|
|
3697
|
+
}
|
|
1508
3698
|
return;
|
|
1509
3699
|
case "tab":
|
|
3700
|
+
if (m.action === "adopt") {
|
|
3701
|
+
this.adopt(m.tabId);
|
|
3702
|
+
return;
|
|
3703
|
+
}
|
|
1510
3704
|
this.input(async () => {
|
|
1511
3705
|
try {
|
|
1512
|
-
if (m.action === "open") await this.
|
|
1513
|
-
else if (m.action === "switch" && m.tabId !== void 0)
|
|
1514
|
-
|
|
1515
|
-
|
|
3706
|
+
if (m.action === "open") await this.openOwnTab();
|
|
3707
|
+
else if (m.action === "switch" && m.tabId !== void 0) this.switchTo(m.tabId);
|
|
3708
|
+
else if (m.action === "close" && m.tabId !== void 0 && this.inTree(m.tabId)) {
|
|
3709
|
+
this.concern(m.tabId);
|
|
1516
3710
|
await this.browser.tabById(m.tabId).close();
|
|
1517
|
-
await this.browser.activePage();
|
|
1518
3711
|
}
|
|
1519
3712
|
} catch {
|
|
1520
3713
|
}
|
|
@@ -1522,26 +3715,206 @@ var ViewerSession = class {
|
|
|
1522
3715
|
return;
|
|
1523
3716
|
}
|
|
1524
3717
|
}
|
|
1525
|
-
/**
|
|
3718
|
+
/** Whether a tab belongs to the viewer's tree. */
|
|
3719
|
+
inTree(tabId) {
|
|
3720
|
+
return this.browser.ownerOf(tabId)?.root === this.root && this.browser.pageById(tabId) !== void 0;
|
|
3721
|
+
}
|
|
3722
|
+
/** The shown tab's page, if the tree has one. */
|
|
3723
|
+
shownPage() {
|
|
3724
|
+
return this.browser.pageById(this.shown);
|
|
3725
|
+
}
|
|
3726
|
+
/** The person used a tab during the takeover: its owner gets the hand back note. */
|
|
3727
|
+
concern(tabId) {
|
|
3728
|
+
if (tabId === void 0) return;
|
|
3729
|
+
this.state.concern(this.browser.ownerOf(tabId)?.owner);
|
|
3730
|
+
}
|
|
3731
|
+
/**
|
|
3732
|
+
* A tab the person opens: owned by the viewer's conversation, made its active tab and shown
|
|
3733
|
+
* (the caps apply; a refusal opens nothing).
|
|
3734
|
+
*/
|
|
3735
|
+
async openOwnTab() {
|
|
3736
|
+
try {
|
|
3737
|
+
const page = this.browser.countOf(this.conv) === 0 ? await this.browser.pageFor(this.conv, this.root) : await this.browser.openTab(this.conv, this.root);
|
|
3738
|
+
this.state.concern(this.conv);
|
|
3739
|
+
this.choice = void 0;
|
|
3740
|
+
this.queueState();
|
|
3741
|
+
return page;
|
|
3742
|
+
} catch {
|
|
3743
|
+
return void 0;
|
|
3744
|
+
}
|
|
3745
|
+
}
|
|
3746
|
+
/**
|
|
3747
|
+
* Shows a tab of the tree and brings it to the front (a viewer in control decides what is
|
|
3748
|
+
* front). A tab of the viewer's own conversation also becomes its active tab (the person chose
|
|
3749
|
+
* it); another conversation's tab changes only the shown tab, never that agent's active tab.
|
|
3750
|
+
*/
|
|
3751
|
+
switchTo(tabId) {
|
|
3752
|
+
if (!this.inTree(tabId)) return;
|
|
3753
|
+
if (this.browser.ownerOf(tabId)?.owner === this.conv) {
|
|
3754
|
+
this.browser.setActive(this.conv, tabId);
|
|
3755
|
+
this.choice = void 0;
|
|
3756
|
+
} else this.choice = tabId;
|
|
3757
|
+
void this.browser.bringToFront(tabId);
|
|
3758
|
+
this.queueState();
|
|
3759
|
+
}
|
|
3760
|
+
/**
|
|
3761
|
+
* Moves another tree's tab (or an unowned one) to the viewer's conversation, as the tool's adopt;
|
|
3762
|
+
* a tab of the viewer's own tree is ignored (inside the tree the person drives tabs without
|
|
3763
|
+
* moving them). A tab whose owner is in use answers the `tab_in_use` notice.
|
|
3764
|
+
*/
|
|
3765
|
+
adopt(tabId) {
|
|
3766
|
+
if (typeof tabId !== "string" || this.browser.pageById(tabId) === void 0) return;
|
|
3767
|
+
if (this.browser.ownerOf(tabId)?.root === this.root) return;
|
|
3768
|
+
let result;
|
|
3769
|
+
try {
|
|
3770
|
+
result = this.browser.adopt(this.conv, this.root, tabId);
|
|
3771
|
+
} catch {
|
|
3772
|
+
return;
|
|
3773
|
+
}
|
|
3774
|
+
if (result === "in_use") this.send({ t: "notice", code: "tab_in_use" });
|
|
3775
|
+
else if (result === "cap") this.send({ t: "notice", code: "tab_cap" });
|
|
3776
|
+
else if (result === "ok") {
|
|
3777
|
+
this.choice = void 0;
|
|
3778
|
+
this.queueState();
|
|
3779
|
+
}
|
|
3780
|
+
}
|
|
3781
|
+
/**
|
|
3782
|
+
* Runs viewer input in arrival order, apart from the screencast chain, and only while the person
|
|
3783
|
+
* holds control: input from a viewer in the watch state (the agent drives) is dropped, both when
|
|
3784
|
+
* it arrives and when its turn comes.
|
|
3785
|
+
*/
|
|
1526
3786
|
input(fn) {
|
|
3787
|
+
if (this.state.control !== "user") return;
|
|
3788
|
+
this.moveSlot = void 0;
|
|
1527
3789
|
const gen = this.inputGen;
|
|
1528
|
-
const guarded = () => gen === this.inputGen && !this.closed ? fn() : Promise.resolve();
|
|
3790
|
+
const guarded = () => gen === this.inputGen && !this.closed && this.state.control === "user" ? fn() : Promise.resolve();
|
|
1529
3791
|
const run = this.inputChain.then(guarded, guarded);
|
|
1530
3792
|
this.inputChain = run.catch(() => void 0);
|
|
1531
3793
|
}
|
|
1532
|
-
/**
|
|
3794
|
+
/** A pointer move: coalesced while one waits (the newest position wins), then the cursor. */
|
|
3795
|
+
move(m) {
|
|
3796
|
+
if (this.state.control !== "user") return;
|
|
3797
|
+
const p = point(m);
|
|
3798
|
+
if (p === null) return;
|
|
3799
|
+
if (this.moveSlot !== void 0) {
|
|
3800
|
+
this.moveSlot.x = p.x;
|
|
3801
|
+
this.moveSlot.y = p.y;
|
|
3802
|
+
return;
|
|
3803
|
+
}
|
|
3804
|
+
const slot = { ...p };
|
|
3805
|
+
this.input(async () => {
|
|
3806
|
+
if (this.moveSlot === slot) this.moveSlot = void 0;
|
|
3807
|
+
const page = this.shownPage();
|
|
3808
|
+
if (page === void 0) return;
|
|
3809
|
+
try {
|
|
3810
|
+
await page.mouse.move(slot.x, slot.y);
|
|
3811
|
+
} catch {
|
|
3812
|
+
return;
|
|
3813
|
+
}
|
|
3814
|
+
this.wantCursor(slot.x, slot.y);
|
|
3815
|
+
});
|
|
3816
|
+
this.moveSlot = slot;
|
|
3817
|
+
}
|
|
3818
|
+
/**
|
|
3819
|
+
* Asks for the page's cursor at (x, y): resolved off the input chain (a click never waits for
|
|
3820
|
+
* it), the newest position wins while one resolution runs, and an answer later than
|
|
3821
|
+
* CURSOR_TIMEOUT_MS is dropped.
|
|
3822
|
+
*/
|
|
3823
|
+
wantCursor(x, y) {
|
|
3824
|
+
this.cursorPoint = { x, y };
|
|
3825
|
+
const resolver = this.cursorResolver;
|
|
3826
|
+
if (resolver === void 0 || this.cursorLoop === resolver) return;
|
|
3827
|
+
this.cursorLoop = resolver;
|
|
3828
|
+
void (async () => {
|
|
3829
|
+
try {
|
|
3830
|
+
while (!this.closed && this.cursorResolver === resolver) {
|
|
3831
|
+
const p = this.cursorPoint;
|
|
3832
|
+
this.cursorPoint = void 0;
|
|
3833
|
+
if (p === void 0) return;
|
|
3834
|
+
const started = this.clock.now();
|
|
3835
|
+
const cursor = await resolver.at(p.x, p.y).catch(() => void 0);
|
|
3836
|
+
if (cursor === void 0 || this.clock.now() - started > CURSOR_TIMEOUT_MS) continue;
|
|
3837
|
+
if (this.cursorPoint !== void 0) continue;
|
|
3838
|
+
if (cursor === this.cursor || this.closed || this.state.control !== "user") continue;
|
|
3839
|
+
this.cursor = cursor;
|
|
3840
|
+
this.send({ t: "cursor", cursor });
|
|
3841
|
+
}
|
|
3842
|
+
} finally {
|
|
3843
|
+
if (this.cursorLoop === resolver) this.cursorLoop = void 0;
|
|
3844
|
+
}
|
|
3845
|
+
})();
|
|
3846
|
+
}
|
|
3847
|
+
/**
|
|
3848
|
+
* Releases the keys and buttons this viewer still holds (straight, not on the input chain and
|
|
3849
|
+
* not through the control gate): the agent must not inherit a held Shift or a drag.
|
|
3850
|
+
*/
|
|
3851
|
+
async releaseHeld() {
|
|
3852
|
+
if (this.heldKeys.size === 0 && this.heldButtons.size === 0) return;
|
|
3853
|
+
const keys = [...this.heldKeys];
|
|
3854
|
+
const buttons = [...this.heldButtons];
|
|
3855
|
+
this.heldKeys.clear();
|
|
3856
|
+
this.heldButtons.clear();
|
|
3857
|
+
for (const [key2, page] of keys) await page.keyboard.up(key2).catch(() => void 0);
|
|
3858
|
+
for (const [button, page] of buttons) {
|
|
3859
|
+
await page.mouse.move(-1, -1).catch(() => void 0);
|
|
3860
|
+
await page.mouse.up({ button }).catch(() => void 0);
|
|
3861
|
+
}
|
|
3862
|
+
}
|
|
3863
|
+
/** Whether input this viewer applied should stay applied (still in control, not closed). */
|
|
3864
|
+
get driving() {
|
|
3865
|
+
return !this.closed && this.state.control === "user";
|
|
3866
|
+
}
|
|
3867
|
+
/** Ends the viewer: stops its screencast and its subscriptions, and lets go of its pins. */
|
|
1533
3868
|
async close() {
|
|
1534
3869
|
if (this.closed) return;
|
|
1535
3870
|
this.closed = true;
|
|
1536
3871
|
this.inputGen++;
|
|
3872
|
+
this.state.unpin(this.conv);
|
|
3873
|
+
if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
|
|
3874
|
+
this.pinnedOwner = void 0;
|
|
3875
|
+
await this.releaseHeld();
|
|
1537
3876
|
for (const u of this.unsubscribe.splice(0)) u();
|
|
1538
|
-
|
|
3877
|
+
for (const t of [this.pumpTimer, this.pingTimer, this.encodeTimer])
|
|
3878
|
+
if (t !== void 0) this.clock.cancel(t);
|
|
1539
3879
|
await this.serial(() => this.detach());
|
|
1540
3880
|
}
|
|
1541
3881
|
setSize(w, h) {
|
|
1542
3882
|
this.maxWidth = clampDim(w, VIEWPORT.width);
|
|
1543
3883
|
this.maxHeight = clampDim(h, VIEWPORT.height);
|
|
1544
|
-
|
|
3884
|
+
}
|
|
3885
|
+
/** Pings the viewer every VIEWER_PING_MS (its pong measures the path, see the pacing). */
|
|
3886
|
+
ping() {
|
|
3887
|
+
if (this.closed) return;
|
|
3888
|
+
const id = ++this.pingSeq;
|
|
3889
|
+
this.pingsSent.set(id, this.clock.now());
|
|
3890
|
+
for (const old of this.pingsSent.keys()) if (old < id - 4) this.pingsSent.delete(old);
|
|
3891
|
+
this.send({ t: "ping", id });
|
|
3892
|
+
this.pingTimer = this.clock.schedule(() => this.ping(), VIEWER_PING_MS);
|
|
3893
|
+
}
|
|
3894
|
+
/**
|
|
3895
|
+
* Control or handoffs changed: a new state; input of the old control dropped; a new handoff of
|
|
3896
|
+
* the tree shows its conversation's active tab.
|
|
3897
|
+
*/
|
|
3898
|
+
onControl() {
|
|
3899
|
+
const pending = this.state.handoffs(this.root);
|
|
3900
|
+
const fresh = pending.filter((h) => !this.seenHandoffs.has(handoffKey(h))).at(-1);
|
|
3901
|
+
this.seenHandoffs = new Set(pending.map(handoffKey));
|
|
3902
|
+
if (fresh !== void 0) {
|
|
3903
|
+
const tab = this.browser.activeTabOf(fresh.conversationId);
|
|
3904
|
+
if (tab !== void 0) this.choice = tab;
|
|
3905
|
+
}
|
|
3906
|
+
const control = this.state.control;
|
|
3907
|
+
if (control !== this.lastControl) {
|
|
3908
|
+
this.lastControl = control;
|
|
3909
|
+
this.moveSlot = void 0;
|
|
3910
|
+
this.cursor = void 0;
|
|
3911
|
+
this.cursorPoint = void 0;
|
|
3912
|
+
if (control === "agent") {
|
|
3913
|
+
this.inputGen++;
|
|
3914
|
+
void this.releaseHeld();
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
this.queueState();
|
|
1545
3918
|
}
|
|
1546
3919
|
serial(fn) {
|
|
1547
3920
|
const run = this.chain.then(fn, fn);
|
|
@@ -1555,45 +3928,58 @@ var ViewerSession = class {
|
|
|
1555
3928
|
*/
|
|
1556
3929
|
fitted(m) {
|
|
1557
3930
|
const fits = (x) => Buffer.byteLength(JSON.stringify(x)) <= this.frameMaxBytes;
|
|
1558
|
-
if (
|
|
3931
|
+
if (fits(m)) return m;
|
|
1559
3932
|
let small;
|
|
1560
3933
|
if (m.t === "state") {
|
|
1561
|
-
const
|
|
3934
|
+
const plain = { ...m, tabs: m.tabs.map(({ favicon: _icon, ...t }) => t) };
|
|
3935
|
+
if (fits(plain)) return plain;
|
|
3936
|
+
m = plain;
|
|
1562
3937
|
small = {
|
|
1563
3938
|
...m,
|
|
1564
|
-
tabs: m.tabs.map((t) => ({
|
|
1565
|
-
|
|
3939
|
+
tabs: m.tabs.map((t) => ({
|
|
3940
|
+
...t,
|
|
3941
|
+
title: clip(t.title, 200),
|
|
3942
|
+
url: clip(t.url, 200),
|
|
3943
|
+
...t.blocker === void 0 ? {} : { blocker: { ...t.blocker, url: clip(t.blocker.url, 200) } }
|
|
3944
|
+
})),
|
|
3945
|
+
otherTabs: m.otherTabs.map((t) => ({
|
|
3946
|
+
...t,
|
|
3947
|
+
title: clip(t.title, 200),
|
|
3948
|
+
url: clip(t.url, 200)
|
|
3949
|
+
})),
|
|
3950
|
+
handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) }))
|
|
1566
3951
|
};
|
|
1567
3952
|
} else if (m.t === "dialog") {
|
|
1568
3953
|
small = { ...m, message: clip(m.message, 200) };
|
|
1569
|
-
} else {
|
|
3954
|
+
} else if (m.t === "blocked") {
|
|
1570
3955
|
small = { ...m, url: clip(m.url, 200) };
|
|
1571
|
-
}
|
|
3956
|
+
} else return null;
|
|
1572
3957
|
return fits(small) ? small : null;
|
|
1573
3958
|
}
|
|
3959
|
+
/** Sends a JSON message at once: it never waits behind a held frame. */
|
|
1574
3960
|
send(raw) {
|
|
1575
3961
|
if (this.closed) return;
|
|
1576
3962
|
const m = this.fitted(raw);
|
|
1577
3963
|
if (m === null) return;
|
|
1578
|
-
if (!this.out.send(m)
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
3964
|
+
if (!this.out.send(m)) this.awaitDrain();
|
|
3965
|
+
}
|
|
3966
|
+
awaitDrain() {
|
|
3967
|
+
if (this.draining) return;
|
|
3968
|
+
this.draining = true;
|
|
3969
|
+
this.out.whenDrained().then(() => {
|
|
3970
|
+
this.draining = false;
|
|
3971
|
+
this.pump();
|
|
3972
|
+
});
|
|
1585
3973
|
}
|
|
1586
3974
|
onSession(e) {
|
|
1587
3975
|
if (e.type === "state") this.queueState();
|
|
1588
3976
|
else if (e.type === "active") {
|
|
3977
|
+
if (e.conversationId === this.conv) this.choice = void 0;
|
|
3978
|
+
else if (this.shown !== void 0 && this.browser.ownerOf(this.shown)?.owner === e.conversationId)
|
|
3979
|
+
this.choice = this.browser.activeTabOf(e.conversationId);
|
|
1589
3980
|
this.queueState();
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
if (page === this.page) return;
|
|
1593
|
-
await this.detach();
|
|
1594
|
-
await this.attach();
|
|
1595
|
-
});
|
|
1596
|
-
} else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
|
|
3981
|
+
} else if (e.root !== this.root) return;
|
|
3982
|
+
else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
|
|
1597
3983
|
else this.send({ t: "dialog", kind: e.kind, message: e.message });
|
|
1598
3984
|
}
|
|
1599
3985
|
/** Coalesces bursts of changes into one state message. */
|
|
@@ -1605,40 +3991,119 @@ var ViewerSession = class {
|
|
|
1605
3991
|
this.sendState();
|
|
1606
3992
|
});
|
|
1607
3993
|
}
|
|
3994
|
+
/**
|
|
3995
|
+
* The tab to show: the chosen one while it is in the tree; else the viewer's conversation's
|
|
3996
|
+
* active tab; else the active tab of the tree's conversation that acted last; else the tree's
|
|
3997
|
+
* first tab; none when the tree owns no tab.
|
|
3998
|
+
*/
|
|
3999
|
+
computeShown(tree) {
|
|
4000
|
+
if (this.choice !== void 0 && tree.some((t) => t.id === this.choice)) return this.choice;
|
|
4001
|
+
this.choice = void 0;
|
|
4002
|
+
const own = this.browser.activeTabOf(this.conv);
|
|
4003
|
+
if (own !== void 0) return own;
|
|
4004
|
+
let best;
|
|
4005
|
+
for (const owner of new Set(tree.map((t) => t.owner))) {
|
|
4006
|
+
if (owner === void 0) continue;
|
|
4007
|
+
const tab = this.browser.activeTabOf(owner);
|
|
4008
|
+
const order = this.browser.actedOrder(owner);
|
|
4009
|
+
if (tab !== void 0 && (best === void 0 || order > best.order)) best = { tab, order };
|
|
4010
|
+
}
|
|
4011
|
+
return best?.tab ?? tree[0]?.id;
|
|
4012
|
+
}
|
|
4013
|
+
/** Pins the owner of the shown tab (besides the viewer's own conversation). */
|
|
4014
|
+
pinShownOwner() {
|
|
4015
|
+
const owner = this.shown === void 0 ? void 0 : this.browser.ownerOf(this.shown);
|
|
4016
|
+
const next = owner === void 0 || owner.owner === this.conv ? void 0 : owner.owner;
|
|
4017
|
+
if (next === this.pinnedOwner) return;
|
|
4018
|
+
if (next !== void 0 && owner !== void 0) this.state.pin(next, owner.root);
|
|
4019
|
+
if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
|
|
4020
|
+
this.pinnedOwner = next;
|
|
4021
|
+
}
|
|
4022
|
+
groupOf(owner) {
|
|
4023
|
+
if (owner === this.conv || owner === void 0) return "own";
|
|
4024
|
+
let g = this.groups.get(owner);
|
|
4025
|
+
if (g === void 0) {
|
|
4026
|
+
g = `sub${this.groups.size + 1}`;
|
|
4027
|
+
this.groups.set(owner, g);
|
|
4028
|
+
}
|
|
4029
|
+
return g;
|
|
4030
|
+
}
|
|
1608
4031
|
sendState() {
|
|
1609
|
-
|
|
1610
|
-
const
|
|
1611
|
-
const
|
|
4032
|
+
if (this.closed) return;
|
|
4033
|
+
const all = this.browser.tabs();
|
|
4034
|
+
const tree = all.filter((t) => t.root === this.root);
|
|
4035
|
+
this.shown = this.computeShown(tree);
|
|
4036
|
+
this.pinShownOwner();
|
|
4037
|
+
if (this.browser.pageById(this.shown) !== this.page) {
|
|
4038
|
+
void this.serial(async () => {
|
|
4039
|
+
if (this.browser.pageById(this.shown) === this.page) return;
|
|
4040
|
+
await this.detach();
|
|
4041
|
+
await this.attach();
|
|
4042
|
+
});
|
|
4043
|
+
}
|
|
4044
|
+
const order = /* @__PURE__ */ new Map([["own", 0]]);
|
|
4045
|
+
const tabs = tree.map((t) => {
|
|
4046
|
+
const group = this.groupOf(t.owner);
|
|
4047
|
+
if (!order.has(group)) order.set(group, order.size);
|
|
4048
|
+
return {
|
|
4049
|
+
id: t.id,
|
|
4050
|
+
title: t.title,
|
|
4051
|
+
url: t.url,
|
|
4052
|
+
active: t.id === this.shown,
|
|
4053
|
+
group,
|
|
4054
|
+
...t.blocker === void 0 ? {} : { blocker: t.blocker },
|
|
4055
|
+
...t.favicon === void 0 ? {} : { favicon: t.favicon },
|
|
4056
|
+
...t.loading === true ? { loading: true } : {}
|
|
4057
|
+
};
|
|
4058
|
+
});
|
|
4059
|
+
tabs.sort((a, b) => (order.get(a.group) ?? 0) - (order.get(b.group) ?? 0));
|
|
4060
|
+
const shownTab = tree.find((t) => t.id === this.shown);
|
|
4061
|
+
const last = this.browser.lastClickOf(this.shown);
|
|
1612
4062
|
this.send({
|
|
1613
4063
|
t: "state",
|
|
1614
4064
|
tabs,
|
|
1615
|
-
|
|
1616
|
-
|
|
4065
|
+
...this.shown === void 0 ? {} : { shown: this.shown },
|
|
4066
|
+
otherTabs: all.filter((t) => t.root !== this.root && !isStartBlank(t)).map((t) => ({ id: t.id, title: t.title, url: t.url })),
|
|
4067
|
+
loading: this.browser.isLoading(this.shown),
|
|
4068
|
+
secure: shownTab?.url.startsWith("https:") ?? false,
|
|
1617
4069
|
control: this.state.control,
|
|
1618
4070
|
...last === void 0 ? {} : { lastClick: last },
|
|
1619
|
-
|
|
4071
|
+
handoffs: this.state.handoffs(this.root).map((h) => ({
|
|
4072
|
+
callId: h.callId,
|
|
4073
|
+
conversationId: h.conversationId,
|
|
4074
|
+
message: h.message,
|
|
4075
|
+
tabIds: this.browser.tabsOf(h.conversationId)
|
|
4076
|
+
}))
|
|
1620
4077
|
});
|
|
1621
4078
|
}
|
|
1622
4079
|
get scale() {
|
|
1623
|
-
return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.shrink;
|
|
4080
|
+
return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.frameQuality.shrink;
|
|
1624
4081
|
}
|
|
1625
|
-
/** Room for the JPEG
|
|
4082
|
+
/** Room for the JPEG in one frame message. */
|
|
1626
4083
|
get jpegBudget() {
|
|
1627
|
-
return
|
|
4084
|
+
return this.frameMaxBytes - FRAME_HEADER_BYTES;
|
|
1628
4085
|
}
|
|
1629
4086
|
async attach() {
|
|
1630
4087
|
if (this.closed) return;
|
|
1631
|
-
const page =
|
|
4088
|
+
const page = this.shownPage();
|
|
4089
|
+
if (page === void 0) return;
|
|
1632
4090
|
const cdp = await this.browser.context.newCDPSession(page);
|
|
1633
4091
|
this.page = page;
|
|
1634
4092
|
this.cdp = cdp;
|
|
1635
4093
|
cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
|
|
4094
|
+
this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
|
|
1636
4095
|
const first = await captureFitting(cdp, {
|
|
1637
4096
|
maxBytes: this.jpegBudget,
|
|
1638
4097
|
maxScale: this.scale
|
|
1639
4098
|
}).catch(() => null);
|
|
1640
4099
|
if (first !== null && this.cdp === cdp) {
|
|
1641
|
-
this.
|
|
4100
|
+
this.pending = {
|
|
4101
|
+
cdp,
|
|
4102
|
+
jpeg: Buffer.from(first.data, "base64"),
|
|
4103
|
+
width: first.width,
|
|
4104
|
+
height: first.height
|
|
4105
|
+
};
|
|
4106
|
+
this.pump();
|
|
1642
4107
|
}
|
|
1643
4108
|
await this.startScreencast(cdp);
|
|
1644
4109
|
}
|
|
@@ -1646,7 +4111,7 @@ var ViewerSession = class {
|
|
|
1646
4111
|
if (this.closed || this.cdp !== cdp) return;
|
|
1647
4112
|
await cdp.send("Page.startScreencast", {
|
|
1648
4113
|
format: "jpeg",
|
|
1649
|
-
quality: this.quality,
|
|
4114
|
+
quality: this.frameQuality.quality,
|
|
1650
4115
|
maxWidth: Math.max(16, Math.floor(VIEWPORT.width * this.scale)),
|
|
1651
4116
|
maxHeight: Math.max(16, Math.floor(VIEWPORT.height * this.scale)),
|
|
1652
4117
|
everyNthFrame: 1
|
|
@@ -1657,93 +4122,163 @@ var ViewerSession = class {
|
|
|
1657
4122
|
this.cdp = void 0;
|
|
1658
4123
|
this.page = void 0;
|
|
1659
4124
|
this.pending = void 0;
|
|
4125
|
+
this.encodeAck = void 0;
|
|
4126
|
+
this.cursorResolver?.dispose();
|
|
4127
|
+
this.cursorResolver = void 0;
|
|
1660
4128
|
if (cdp === void 0) return;
|
|
1661
4129
|
await cdp.send("Page.stopScreencast").catch(() => void 0);
|
|
1662
4130
|
await cdp.detach().catch(() => void 0);
|
|
1663
4131
|
}
|
|
1664
4132
|
sendFrame(jpeg, width, height) {
|
|
1665
4133
|
this.seq++;
|
|
1666
|
-
this.
|
|
1667
|
-
this.
|
|
4134
|
+
this.pacer.sent(this.seq, this.clock.now());
|
|
4135
|
+
if (!this.out.sendFrame(encodeFrame({ seq: this.seq, width, height, jpeg }))) this.awaitDrain();
|
|
4136
|
+
}
|
|
4137
|
+
/** The viewer acked frames up to `seq`: the link time adapts quality and scale. */
|
|
4138
|
+
onAck(seq) {
|
|
4139
|
+
const sample = this.pacer.acked(seq, this.clock.now());
|
|
4140
|
+
if (sample === void 0) return;
|
|
4141
|
+
if (this.clock.now() - this.lastRestartAt < RESTART_MIN_MS) return;
|
|
4142
|
+
if (this.frameQuality.observe(this.pacer.linkMs ?? sample)) this.restart();
|
|
4143
|
+
}
|
|
4144
|
+
/** Restarts the screencast at the current quality and scale. */
|
|
4145
|
+
restart() {
|
|
4146
|
+
const cdp = this.cdp;
|
|
4147
|
+
if (cdp === void 0) return;
|
|
4148
|
+
this.lastRestartAt = this.clock.now();
|
|
4149
|
+
this.pacer.reset();
|
|
4150
|
+
void this.serial(async () => {
|
|
4151
|
+
if (this.cdp !== cdp) return;
|
|
4152
|
+
await cdp.send("Page.stopScreencast").catch(() => void 0);
|
|
4153
|
+
this.pending = void 0;
|
|
4154
|
+
this.encodeAck = void 0;
|
|
4155
|
+
await this.startScreencast(cdp);
|
|
4156
|
+
});
|
|
1668
4157
|
}
|
|
1669
4158
|
onFrame(cdp, f) {
|
|
1670
4159
|
if (this.closed || this.cdp !== cdp) return;
|
|
1671
4160
|
const bytes = Buffer.from(f.data, "base64");
|
|
1672
4161
|
if (bytes.length > this.jpegBudget) {
|
|
1673
4162
|
cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => void 0);
|
|
1674
|
-
if (this.
|
|
1675
|
-
else this.shrink *= 0.75;
|
|
1676
|
-
void this.serial(async () => {
|
|
1677
|
-
if (this.cdp !== cdp) return;
|
|
1678
|
-
await cdp.send("Page.stopScreencast").catch(() => void 0);
|
|
1679
|
-
await this.startScreencast(cdp);
|
|
1680
|
-
});
|
|
4163
|
+
if (this.frameQuality.tooLarge()) this.restart();
|
|
1681
4164
|
return;
|
|
1682
4165
|
}
|
|
1683
4166
|
const { width, height } = jpegSize(bytes);
|
|
1684
|
-
this.pending = { cdp,
|
|
4167
|
+
this.pending = { cdp, jpeg: bytes, width, height };
|
|
4168
|
+
this.encodeAck = { cdp, sessionId: f.sessionId };
|
|
1685
4169
|
this.pump();
|
|
4170
|
+
this.scheduleEncodeAck();
|
|
4171
|
+
}
|
|
4172
|
+
/**
|
|
4173
|
+
* Lets Chromium encode its next frame (screencastFrameAck): at most at the viewer's frame rate
|
|
4174
|
+
* while frames flow, and while one waits for the viewer only every ENCODE_MAX_INTERVAL_MS, so
|
|
4175
|
+
* the frame sent when room comes is a recent one without encoding frames nobody gets.
|
|
4176
|
+
*/
|
|
4177
|
+
scheduleEncodeAck() {
|
|
4178
|
+
if (this.encodeTimer !== void 0) this.clock.cancel(this.encodeTimer);
|
|
4179
|
+
this.encodeTimer = void 0;
|
|
4180
|
+
const ack = this.encodeAck;
|
|
4181
|
+
if (ack === void 0 || this.closed) return;
|
|
4182
|
+
const gap = this.pending === void 0 ? 1e3 / VIEWER_MAX_FPS : ENCODE_MAX_INTERVAL_MS;
|
|
4183
|
+
const wait = this.lastEncodeAckAt + gap - this.clock.now();
|
|
4184
|
+
if (wait > 0) {
|
|
4185
|
+
this.encodeTimer = this.clock.schedule(() => {
|
|
4186
|
+
this.encodeTimer = void 0;
|
|
4187
|
+
this.scheduleEncodeAck();
|
|
4188
|
+
}, wait);
|
|
4189
|
+
return;
|
|
4190
|
+
}
|
|
4191
|
+
this.encodeAck = void 0;
|
|
4192
|
+
if (this.cdp !== ack.cdp) return;
|
|
4193
|
+
this.lastEncodeAckAt = this.clock.now();
|
|
4194
|
+
ack.cdp.send("Page.screencastFrameAck", { sessionId: ack.sessionId }).catch(() => void 0);
|
|
1686
4195
|
}
|
|
1687
4196
|
/**
|
|
1688
|
-
* Sends the
|
|
1689
|
-
*
|
|
1690
|
-
* the previous one sooner than 1000 / VIEWER_MAX_FPS ms, the first after an attach included.
|
|
4197
|
+
* Sends the newest screencast frame once the pacer allows (viewer acks, link time, rate cap)
|
|
4198
|
+
* and the transport is not backed up.
|
|
1691
4199
|
*/
|
|
1692
4200
|
pump() {
|
|
1693
4201
|
const pending = this.pending;
|
|
1694
4202
|
if (pending === void 0 || this.closed || this.draining) return;
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
if (this.pumpTimer === void 0) {
|
|
4203
|
+
const d = this.pacer.decide(this.clock.now());
|
|
4204
|
+
if (!d.ok) {
|
|
4205
|
+
if (d.waitMs !== void 0 && this.pumpTimer === void 0) {
|
|
1699
4206
|
this.pumpTimer = this.clock.schedule(() => {
|
|
1700
4207
|
this.pumpTimer = void 0;
|
|
1701
4208
|
this.pump();
|
|
1702
|
-
},
|
|
4209
|
+
}, d.waitMs);
|
|
1703
4210
|
}
|
|
1704
4211
|
return;
|
|
1705
4212
|
}
|
|
1706
4213
|
this.pending = void 0;
|
|
1707
4214
|
if (this.cdp !== pending.cdp) return;
|
|
1708
|
-
this.sendFrame(pending.
|
|
1709
|
-
|
|
4215
|
+
this.sendFrame(pending.jpeg, pending.width, pending.height);
|
|
4216
|
+
this.scheduleEncodeAck();
|
|
1710
4217
|
}
|
|
1711
4218
|
async mouse(m) {
|
|
1712
|
-
const page =
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
4219
|
+
const page = this.shownPage();
|
|
4220
|
+
const p = point(m);
|
|
4221
|
+
if (p === null || page === void 0) return;
|
|
4222
|
+
this.concern(this.browser.tabIdOf(page));
|
|
4223
|
+
const { x, y } = p;
|
|
1716
4224
|
const button = m.button === "right" ? "right" : "left";
|
|
1717
4225
|
try {
|
|
1718
|
-
if (m.kind === "
|
|
1719
|
-
else if (m.kind === "down") {
|
|
4226
|
+
if (m.kind === "down") {
|
|
1720
4227
|
await page.mouse.move(x, y);
|
|
1721
4228
|
await page.mouse.down({ button });
|
|
4229
|
+
if (this.driving) this.heldButtons.set(button, page);
|
|
4230
|
+
else await page.mouse.up({ button });
|
|
1722
4231
|
} else if (m.kind === "up") {
|
|
4232
|
+
this.heldButtons.delete(button);
|
|
1723
4233
|
await page.mouse.move(x, y);
|
|
1724
4234
|
await page.mouse.up({ button });
|
|
1725
4235
|
} else if (m.kind === "wheel") {
|
|
1726
4236
|
await page.mouse.move(x, y);
|
|
1727
4237
|
await page.mouse.wheel(Number(m.dx) || 0, Number(m.dy) || 0);
|
|
1728
|
-
}
|
|
4238
|
+
} else return;
|
|
1729
4239
|
} catch {
|
|
4240
|
+
return;
|
|
1730
4241
|
}
|
|
4242
|
+
if (m.kind !== "down") this.wantCursor(x, y);
|
|
1731
4243
|
}
|
|
1732
4244
|
async key(m) {
|
|
1733
|
-
const page =
|
|
4245
|
+
const page = this.shownPage();
|
|
4246
|
+
if (page === void 0) return;
|
|
4247
|
+
this.concern(this.browser.tabIdOf(page));
|
|
1734
4248
|
try {
|
|
1735
4249
|
if (m.kind === "char") {
|
|
1736
4250
|
const text = m.text ?? m.key;
|
|
1737
|
-
if (typeof text === "string" && text !== "")
|
|
1738
|
-
|
|
1739
|
-
else if (m.kind === "
|
|
4251
|
+
if (typeof text === "string" && text !== "")
|
|
4252
|
+
await page.keyboard.insertText(clipCodePoints(text, VIEWER_TEXT_MAX_CHARS));
|
|
4253
|
+
} else if (m.kind === "down") {
|
|
4254
|
+
await page.keyboard.down(m.key);
|
|
4255
|
+
if (this.driving) this.heldKeys.set(m.key, page);
|
|
4256
|
+
else await page.keyboard.up(m.key);
|
|
4257
|
+
} else if (m.kind === "up") {
|
|
4258
|
+
this.heldKeys.delete(m.key);
|
|
4259
|
+
await page.keyboard.up(m.key);
|
|
4260
|
+
}
|
|
1740
4261
|
} catch {
|
|
1741
4262
|
}
|
|
1742
4263
|
}
|
|
1743
4264
|
};
|
|
4265
|
+
var handoffKey = (h) => `${h.conversationId}\0${h.callId}`;
|
|
4266
|
+
function point(m) {
|
|
4267
|
+
const x = Number(m.x);
|
|
4268
|
+
const y = Number(m.y);
|
|
4269
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
|
|
4270
|
+
return {
|
|
4271
|
+
x: Math.max(0, Math.min(VIEWPORT.width - 1, x)),
|
|
4272
|
+
y: Math.max(0, Math.min(VIEWPORT.height - 1, y))
|
|
4273
|
+
};
|
|
4274
|
+
}
|
|
1744
4275
|
|
|
1745
4276
|
// daemon/main.ts
|
|
4277
|
+
var SEALED_EXIT_GRACE_MS = 2e3;
|
|
1746
4278
|
var SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
|
|
4279
|
+
var BROWSER_CLOSE_GRACE_MS = 3e3;
|
|
4280
|
+
var PROCESS_POLL_MS = 10;
|
|
4281
|
+
var COOKIE_SAVE_MS = 500;
|
|
1747
4282
|
var enc = new TextEncoder();
|
|
1748
4283
|
var dec = new TextDecoder();
|
|
1749
4284
|
var REQUEST_OPS = /* @__PURE__ */ new Set([
|
|
@@ -1781,6 +4316,10 @@ function parse(raw) {
|
|
|
1781
4316
|
return void 0;
|
|
1782
4317
|
}
|
|
1783
4318
|
}
|
|
4319
|
+
var HANDOFF_HOLDS_ROLL_MS = 30 * 6e4;
|
|
4320
|
+
function isRollCheck(body) {
|
|
4321
|
+
return typeof body === "object" && body !== null && body.capybara === JSON.parse(ROLL_CHECK_REQUEST).capybara;
|
|
4322
|
+
}
|
|
1784
4323
|
function write(sock, value, tooLarge) {
|
|
1785
4324
|
if (sock.destroyed) return false;
|
|
1786
4325
|
let framed;
|
|
@@ -1812,78 +4351,168 @@ async function startDaemon(opts) {
|
|
|
1812
4351
|
let closing = false;
|
|
1813
4352
|
const sessionFile = new SessionFile(opts.stateDir, clock);
|
|
1814
4353
|
const saved = sessionFile.read();
|
|
4354
|
+
let live;
|
|
1815
4355
|
const state = new DaemonState({
|
|
1816
4356
|
clock,
|
|
1817
4357
|
...opts.idleMs === void 0 ? {} : { idleMs: opts.idleMs },
|
|
4358
|
+
...opts.conversationIdleMs === void 0 ? {} : { conversationIdleMs: opts.conversationIdleMs },
|
|
1818
4359
|
onIdle: () => {
|
|
1819
4360
|
sessionFile.forget();
|
|
1820
4361
|
opts.onIdle?.();
|
|
4362
|
+
},
|
|
4363
|
+
onConversationIdle: (conversationId) => {
|
|
4364
|
+
void live?.closeConversation(conversationId);
|
|
1821
4365
|
}
|
|
1822
4366
|
});
|
|
1823
|
-
if (saved
|
|
1824
|
-
state.noticeHandoff(saved.handoff.callId, saved.handoff.message);
|
|
4367
|
+
if (saved !== void 0) sessionFile.restoreState(state, saved);
|
|
1825
4368
|
const launch = opts.launch ?? launchChromium;
|
|
4369
|
+
const closeGraceMs = opts.browserCloseGraceMs ?? BROWSER_CLOSE_GRACE_MS;
|
|
1826
4370
|
let current;
|
|
4371
|
+
let running;
|
|
1827
4372
|
let restored = false;
|
|
4373
|
+
function within2(value, ms) {
|
|
4374
|
+
let timer;
|
|
4375
|
+
return Promise.race([
|
|
4376
|
+
value,
|
|
4377
|
+
new Promise((r) => {
|
|
4378
|
+
timer = clock.schedule(() => r(void 0), ms);
|
|
4379
|
+
})
|
|
4380
|
+
]).finally(() => clock.cancel(timer));
|
|
4381
|
+
}
|
|
1828
4382
|
function browser() {
|
|
1829
4383
|
if (current !== void 0) return current;
|
|
4384
|
+
if (closing) return Promise.reject(new Error("The browser daemon is stopping."));
|
|
1830
4385
|
const starting = launch(plan).then(async (ctx) => {
|
|
4386
|
+
let pid;
|
|
4387
|
+
let failed = false;
|
|
4388
|
+
try {
|
|
4389
|
+
return await sessionOn(
|
|
4390
|
+
ctx,
|
|
4391
|
+
(id) => {
|
|
4392
|
+
pid = id;
|
|
4393
|
+
},
|
|
4394
|
+
() => failed
|
|
4395
|
+
);
|
|
4396
|
+
} catch (e) {
|
|
4397
|
+
failed = true;
|
|
4398
|
+
await closeOrKill(ctx.close(), () => pid);
|
|
4399
|
+
throw e;
|
|
4400
|
+
}
|
|
4401
|
+
});
|
|
4402
|
+
current = starting;
|
|
4403
|
+
starting.catch(() => {
|
|
4404
|
+
if (current === starting) current = void 0;
|
|
4405
|
+
live = void 0;
|
|
4406
|
+
if (running?.launch === starting) running = void 0;
|
|
4407
|
+
});
|
|
4408
|
+
return starting;
|
|
4409
|
+
async function sessionOn(ctx, setPid, failed) {
|
|
4410
|
+
let gone = false;
|
|
1831
4411
|
ctx.on("close", () => {
|
|
1832
|
-
|
|
4412
|
+
gone = true;
|
|
4413
|
+
if (running?.launch === starting) running = void 0;
|
|
4414
|
+
if (!closing && !failed()) opts.onBrowserGone?.();
|
|
1833
4415
|
});
|
|
4416
|
+
const pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
|
|
4417
|
+
setPid(pid);
|
|
4418
|
+
if (!gone) running = { launch: starting, pid, ctx };
|
|
1834
4419
|
const workspace = opts.env[SERVICE_WORKSPACE_ENV];
|
|
1835
4420
|
const session = new BrowserSession(ctx, {
|
|
1836
4421
|
proxy: plan.proxy,
|
|
1837
4422
|
clock,
|
|
4423
|
+
usage: state,
|
|
1838
4424
|
workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
|
|
1839
4425
|
downloadsTmp: plan.downloadsTmp,
|
|
1840
4426
|
downloadMaxBytes: downloadMaxBytes(opts.env),
|
|
1841
|
-
...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
|
|
4427
|
+
...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs },
|
|
4428
|
+
...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
|
|
1842
4429
|
});
|
|
1843
|
-
if (
|
|
4430
|
+
if (plan.shippedDir !== void 0)
|
|
4431
|
+
session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
|
|
4432
|
+
if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
|
|
4433
|
+
session.note(HEADLESS_SHELL_NOTE);
|
|
4434
|
+
if (!closing) await restoreCookies(ctx, opts.stateDir);
|
|
4435
|
+
if (!restored && !closing) {
|
|
1844
4436
|
restored = true;
|
|
1845
4437
|
if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
|
|
1846
4438
|
}
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
4439
|
+
if (!closing) {
|
|
4440
|
+
const save = () => sessionFile.save(session, state);
|
|
4441
|
+
session.on(save);
|
|
4442
|
+
state.onChange(save);
|
|
4443
|
+
}
|
|
4444
|
+
if (!failed()) live = session;
|
|
1850
4445
|
return session;
|
|
1851
|
-
}
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
4446
|
+
}
|
|
4447
|
+
}
|
|
4448
|
+
async function closeOrKill(closingBrowser, pid) {
|
|
4449
|
+
const done = closingBrowser.then(
|
|
4450
|
+
() => true,
|
|
4451
|
+
() => true
|
|
4452
|
+
);
|
|
4453
|
+
if (await within2(done, closeGraceMs) === true) return;
|
|
4454
|
+
const id = pid();
|
|
4455
|
+
if (id === void 0) return;
|
|
4456
|
+
killChromium(id);
|
|
4457
|
+
await within2(done, closeGraceMs);
|
|
1857
4458
|
}
|
|
1858
4459
|
async function launchFailure(e) {
|
|
4460
|
+
if (e instanceof BrowserInstalledError)
|
|
4461
|
+
return { ok: false, error: "restart", message: e.message, blockedHosts: [] };
|
|
4462
|
+
if (plan.unavailable !== void 0) return fail(plan.unavailable);
|
|
1859
4463
|
const cause = e instanceof Error ? e.message.split("\n")[0] : String(e);
|
|
1860
4464
|
const proxy = plan.proxy;
|
|
1861
4465
|
const refused = proxy === void 0 ? [] : (await Promise.all(
|
|
1862
|
-
playwrightDownloadHosts(opts.env).map(
|
|
1863
|
-
|
|
1864
|
-
|
|
4466
|
+
playwrightDownloadHosts(opts.env).map(async (host) => {
|
|
4467
|
+
const layer = await proxyRefusal(proxy, host, 443);
|
|
4468
|
+
return layer === null ? void 0 : { host, layer };
|
|
4469
|
+
})
|
|
1865
4470
|
)).filter((h) => h !== void 0);
|
|
1866
4471
|
if (refused.length > 0)
|
|
1867
4472
|
return {
|
|
1868
4473
|
ok: false,
|
|
1869
4474
|
error: "blocked",
|
|
1870
|
-
message: `${DOWNLOAD_BLOCKED_PREFIX}${refused.join(", ")}.`,
|
|
4475
|
+
message: `${DOWNLOAD_BLOCKED_PREFIX}${refused.map((r) => r.host).join(", ")}.`,
|
|
1871
4476
|
blockedHosts: refused
|
|
1872
4477
|
};
|
|
1873
4478
|
return fail(
|
|
1874
4479
|
`The browser could not start in the device: ${cause}. The next browser call tries again.`
|
|
1875
4480
|
);
|
|
1876
4481
|
}
|
|
4482
|
+
async function stopBrowser() {
|
|
4483
|
+
const starting = current;
|
|
4484
|
+
if (starting === void 0) return;
|
|
4485
|
+
const r = running?.launch === starting ? running : void 0;
|
|
4486
|
+
const pid = r?.pid;
|
|
4487
|
+
if (r !== void 0) await within2(saveCookies(r.ctx, opts.stateDir), COOKIE_SAVE_MS);
|
|
4488
|
+
await closeOrKill(
|
|
4489
|
+
starting.then(
|
|
4490
|
+
async (session) => {
|
|
4491
|
+
await session.close();
|
|
4492
|
+
if (pid !== void 0) await processGone(pid);
|
|
4493
|
+
},
|
|
4494
|
+
() => void 0
|
|
4495
|
+
),
|
|
4496
|
+
() => pid
|
|
4497
|
+
);
|
|
4498
|
+
}
|
|
4499
|
+
async function processGone(pid) {
|
|
4500
|
+
while (processAlive(pid)) await new Promise((r) => clock.schedule(r, PROCESS_POLL_MS));
|
|
4501
|
+
}
|
|
1877
4502
|
const ready = browser().then(() => void 0);
|
|
1878
|
-
ready.catch(() =>
|
|
4503
|
+
ready.catch((e) => {
|
|
4504
|
+
if (e instanceof BrowserInstalledError)
|
|
4505
|
+
clock.schedule(() => opts.onSealed?.(), SEALED_EXIT_GRACE_MS);
|
|
4506
|
+
});
|
|
1879
4507
|
async function handoffOp(req) {
|
|
1880
4508
|
if (typeof req.callId !== "string" || req.callId === "")
|
|
1881
4509
|
return fail("The handoff needs a callId.");
|
|
4510
|
+
const conv = req.conversationId;
|
|
1882
4511
|
if (req.op === "handoff_notice") {
|
|
1883
4512
|
if (typeof req.message !== "string") return fail("The handoff notice needs a message.");
|
|
1884
|
-
state.noticeHandoff(req.callId, req.message);
|
|
4513
|
+
state.noticeHandoff(conv, req.rootConversationId, req.callId, req.message);
|
|
1885
4514
|
} else {
|
|
1886
|
-
state.clearHandoff(req.callId);
|
|
4515
|
+
state.clearHandoff(conv, req.callId);
|
|
1887
4516
|
if (req.handback === true) state.handback();
|
|
1888
4517
|
}
|
|
1889
4518
|
let session;
|
|
@@ -1892,15 +4521,38 @@ async function startDaemon(opts) {
|
|
|
1892
4521
|
} catch (e) {
|
|
1893
4522
|
return launchFailure(e);
|
|
1894
4523
|
}
|
|
1895
|
-
|
|
4524
|
+
const page = session.currentPage(conv);
|
|
4525
|
+
return {
|
|
4526
|
+
ok: true,
|
|
4527
|
+
...page === void 0 ? {} : { page: await session.pageInfo(page) },
|
|
4528
|
+
blockedHosts: []
|
|
4529
|
+
};
|
|
1896
4530
|
}
|
|
4531
|
+
const namesConversation = (raw) => {
|
|
4532
|
+
const r = raw;
|
|
4533
|
+
return typeof r.conversationId === "string" && r.conversationId !== "" && typeof r.rootConversationId === "string" && r.rootConversationId !== "";
|
|
4534
|
+
};
|
|
1897
4535
|
async function handleRequest(raw) {
|
|
1898
4536
|
if (typeof raw !== "object" || raw === null || !REQUEST_OPS.has(String(raw.op))) {
|
|
1899
4537
|
return fail("Unknown browser request.");
|
|
1900
4538
|
}
|
|
4539
|
+
if (!namesConversation(raw)) return fail(NO_CONVERSATION_MESSAGE);
|
|
1901
4540
|
const req = raw;
|
|
4541
|
+
const conv = req.conversationId;
|
|
4542
|
+
state.requestArrived(conv, req.rootConversationId);
|
|
4543
|
+
let reply;
|
|
4544
|
+
try {
|
|
4545
|
+
reply = await conversationRequest(req);
|
|
4546
|
+
} catch (e) {
|
|
4547
|
+
reply = fail(e instanceof ActionError ? e.message : String(e));
|
|
4548
|
+
} finally {
|
|
4549
|
+
state.requestFinished(conv);
|
|
4550
|
+
}
|
|
4551
|
+
return { ...reply, tabs: { open: live?.countOf(conv) ?? 0, max: MAX_TABS_PER_CONVERSATION } };
|
|
4552
|
+
}
|
|
4553
|
+
async function conversationRequest(req) {
|
|
1902
4554
|
if (req.op === "handoff_notice" || req.op === "handoff_clear") return handoffOp(req);
|
|
1903
|
-
state.dropHandoff();
|
|
4555
|
+
state.dropHandoff(req.conversationId);
|
|
1904
4556
|
if (state.control === "user" && req.op !== "wait") {
|
|
1905
4557
|
return { ok: false, error: "taken_over", message: TAKEN_OVER_MESSAGE, blockedHosts: [] };
|
|
1906
4558
|
}
|
|
@@ -1912,7 +4564,7 @@ async function startDaemon(opts) {
|
|
|
1912
4564
|
}
|
|
1913
4565
|
const reply = await session.run(req, { takenOver: () => state.control === "user" });
|
|
1914
4566
|
if (reply.ok) {
|
|
1915
|
-
const since = state.takeHandbackNote();
|
|
4567
|
+
const since = state.takeHandbackNote(req.conversationId);
|
|
1916
4568
|
if (since !== void 0) reply.userControlledSince = since;
|
|
1917
4569
|
}
|
|
1918
4570
|
return reply;
|
|
@@ -1922,6 +4574,7 @@ async function startDaemon(opts) {
|
|
|
1922
4574
|
sockets.add(sock);
|
|
1923
4575
|
const decoder = new ServiceMessageDecoder();
|
|
1924
4576
|
let kind;
|
|
4577
|
+
let context;
|
|
1925
4578
|
let handled = false;
|
|
1926
4579
|
let viewer;
|
|
1927
4580
|
let opened = false;
|
|
@@ -1944,42 +4597,68 @@ async function startDaemon(opts) {
|
|
|
1944
4597
|
if (kind === void 0) {
|
|
1945
4598
|
const first = parse(raw);
|
|
1946
4599
|
if (first?.kind === "request") kind = "request";
|
|
1947
|
-
else if (first?.kind === "stream")
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
4600
|
+
else if (first?.kind === "stream") kind = "stream";
|
|
4601
|
+
else sock.destroy();
|
|
4602
|
+
return;
|
|
4603
|
+
}
|
|
4604
|
+
if (kind === "stream" && context === void 0) {
|
|
4605
|
+
const ctx = parseViewerContext(raw);
|
|
4606
|
+
if (ctx === null) {
|
|
4607
|
+
sock.destroy();
|
|
4608
|
+
return;
|
|
4609
|
+
}
|
|
4610
|
+
context = {
|
|
4611
|
+
conversationId: ctx.conversationId,
|
|
4612
|
+
rootConversationId: ctx.rootConversationId
|
|
4613
|
+
};
|
|
4614
|
+
const viewerContext = context;
|
|
4615
|
+
opened = true;
|
|
4616
|
+
state.viewerOpened();
|
|
4617
|
+
browser().then(
|
|
4618
|
+
(session) => {
|
|
4619
|
+
if (sock.destroyed) return;
|
|
4620
|
+
viewer = new ViewerSession({
|
|
4621
|
+
browser: session,
|
|
4622
|
+
state,
|
|
4623
|
+
conversationId: viewerContext.conversationId,
|
|
4624
|
+
rootConversationId: viewerContext.rootConversationId,
|
|
4625
|
+
clock,
|
|
4626
|
+
frameMaxBytes: frameCap,
|
|
4627
|
+
transport: {
|
|
4628
|
+
send: (m) => {
|
|
4629
|
+
let dropped = false;
|
|
4630
|
+
const ok = write(sock, m, () => {
|
|
4631
|
+
dropped = true;
|
|
4632
|
+
});
|
|
4633
|
+
return ok || dropped || sock.destroyed;
|
|
4634
|
+
},
|
|
4635
|
+
sendFrame: (frame) => {
|
|
4636
|
+
if (sock.destroyed) return true;
|
|
4637
|
+
return sock.write(encodeServiceMessage(frame));
|
|
4638
|
+
},
|
|
4639
|
+
whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
|
|
4640
|
+
}
|
|
4641
|
+
});
|
|
4642
|
+
},
|
|
4643
|
+
() => sock.destroy()
|
|
4644
|
+
);
|
|
1974
4645
|
return;
|
|
1975
4646
|
}
|
|
1976
4647
|
if (kind === "request") {
|
|
1977
4648
|
if (handled) return;
|
|
1978
4649
|
handled = true;
|
|
4650
|
+
const body = parse(raw);
|
|
4651
|
+
if (isRollCheck(body)) {
|
|
4652
|
+
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;
|
|
4653
|
+
write(sock, reason === void 0 ? { busy: false } : { busy: true, reason });
|
|
4654
|
+
sock.end();
|
|
4655
|
+
return;
|
|
4656
|
+
}
|
|
1979
4657
|
state.requestStarted();
|
|
1980
|
-
handleRequest(
|
|
4658
|
+
handleRequest(body).catch((e) => fail(e instanceof ActionError ? e.message : String(e))).then((reply) => {
|
|
1981
4659
|
write(sock, reply, () => write(sock, fail(REPLY_TOO_LARGE_MESSAGE), () => void 0));
|
|
1982
4660
|
sock.end();
|
|
4661
|
+
if (!reply.ok && reply.error === "restart") sock.once("close", () => opts.onSealed?.());
|
|
1983
4662
|
}).catch(() => sock.destroy()).finally(() => state.requestEnded());
|
|
1984
4663
|
return;
|
|
1985
4664
|
}
|
|
@@ -1998,7 +4677,7 @@ async function startDaemon(opts) {
|
|
|
1998
4677
|
for (const m of msgs) onMessage(m);
|
|
1999
4678
|
});
|
|
2000
4679
|
}
|
|
2001
|
-
if (existsSync2(opts.socketPath))
|
|
4680
|
+
if (existsSync2(opts.socketPath)) unlinkSync2(opts.socketPath);
|
|
2002
4681
|
const server = createServer(onConnection);
|
|
2003
4682
|
await new Promise((resolve, reject) => {
|
|
2004
4683
|
server.once("error", reject);
|
|
@@ -2019,11 +4698,10 @@ async function startDaemon(opts) {
|
|
|
2019
4698
|
server.close(() => r());
|
|
2020
4699
|
for (const s of sockets) s.destroy();
|
|
2021
4700
|
});
|
|
2022
|
-
|
|
2023
|
-
await session?.close();
|
|
4701
|
+
await stopBrowser();
|
|
2024
4702
|
if (existsSync2(opts.socketPath)) {
|
|
2025
4703
|
try {
|
|
2026
|
-
|
|
4704
|
+
unlinkSync2(opts.socketPath);
|
|
2027
4705
|
} catch {
|
|
2028
4706
|
}
|
|
2029
4707
|
}
|
|
@@ -2059,7 +4737,9 @@ async function main() {
|
|
|
2059
4737
|
stateDir,
|
|
2060
4738
|
env: process.env,
|
|
2061
4739
|
onIdle: () => stop(0, "idle"),
|
|
2062
|
-
onBrowserGone: () => stop(1, "Chromium exited")
|
|
4740
|
+
onBrowserGone: () => stop(1, "Chromium exited"),
|
|
4741
|
+
// installed and sealed: the next start runs the browser read only
|
|
4742
|
+
onSealed: () => stop(0, "browser installed and sealed; restart to run it")
|
|
2063
4743
|
});
|
|
2064
4744
|
process.stderr.write(`browser daemon: listening on ${socketPath}
|
|
2065
4745
|
`);
|