@parcha/agentrun-computer 0.1.0-beta.36 → 0.1.0-beta.37
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/NOTICE +2 -0
- package/README.md +321 -308
- package/box/build-agent37.mjs +177 -0
- package/dist/agent37.d.ts +165 -0
- package/dist/agent37.js +759 -0
- package/dist/attach.d.ts +146 -0
- package/dist/attach.js +469 -0
- package/dist/browserbase.d.ts +2 -4
- package/dist/browserbase.js +2 -1
- package/dist/client.d.ts +33 -1
- package/dist/client.js +53 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/conformance/agent37.d.ts +96 -0
- package/dist/conformance/agent37.js +154 -0
- package/dist/conformance/cases/apps.d.ts +5 -0
- package/dist/conformance/cases/apps.js +160 -73
- package/dist/conformance/cases/health.js +14 -0
- package/dist/conformance/cases/index.js +2 -0
- package/dist/conformance/cases/provider.js +27 -1
- package/dist/conformance/cases/screen.d.ts +3 -0
- package/dist/conformance/cases/screen.js +18 -0
- package/dist/conformance/cases/settings.d.ts +29 -23
- package/dist/conformance/cases/settings.js +76 -58
- package/dist/conformance/cases/touch.js +19 -17
- package/dist/conformance/cases/ui.d.ts +2 -0
- package/dist/conformance/cases/ui.js +475 -0
- package/dist/conformance/cli.d.ts +9 -0
- package/dist/conformance/cli.js +28 -3
- package/dist/conformance/e2b.d.ts +6 -0
- package/dist/conformance/e2b.js +9 -2
- package/dist/conformance/fixture.d.ts +1 -1
- package/dist/conformance/fixture.js +25 -1
- package/dist/conformance/modal.d.ts +17 -13
- package/dist/conformance/modal.js +18 -9
- package/dist/conformance/orgo.d.ts +3 -3
- package/dist/conformance/orgo.js +6 -8
- package/dist/conformance/phone-harness.d.ts +6 -2
- package/dist/conformance/phone-harness.js +21 -4
- package/dist/conformance/report.js +1 -1
- package/dist/conformance/runner.js +23 -4
- package/dist/conformance/sweep.d.ts +50 -0
- package/dist/conformance/sweep.js +187 -0
- package/dist/conformance/types.d.ts +11 -3
- package/dist/conformance/ui-fixture.d.ts +56 -0
- package/dist/conformance/ui-fixture.js +43 -0
- package/dist/create-requests.d.ts +51 -0
- package/dist/create-requests.js +121 -0
- package/dist/daytona.d.ts +2 -4
- package/dist/daytona.js +3 -2
- package/dist/descriptor.d.ts +5 -0
- package/dist/descriptor.js +2 -0
- package/dist/descriptors/agent37.d.ts +41 -0
- package/dist/descriptors/agent37.js +28 -0
- package/dist/descriptors/index.d.ts +38 -2
- package/dist/descriptors/index.js +4 -2
- package/dist/descriptors/orgo.d.ts +2 -1
- package/dist/descriptors/orgo.js +3 -2
- package/dist/descriptors/phone-harness.d.ts +1 -1
- package/dist/descriptors/phone-harness.js +2 -2
- package/dist/docker.d.ts +7 -4
- package/dist/docker.js +271 -29
- package/dist/e2b.d.ts +9 -165
- package/dist/e2b.js +282 -1342
- package/dist/fake-ui-driver.d.ts +97 -0
- package/dist/fake-ui-driver.js +717 -0
- package/dist/host.d.ts +182 -0
- package/dist/host.js +1 -0
- package/dist/hosted/process.d.ts +67 -0
- package/dist/hosted/process.js +228 -0
- package/dist/hosted/provider.d.ts +146 -0
- package/dist/hosted/provider.js +1364 -0
- package/dist/hosted/scripts.d.ts +76 -0
- package/dist/{child.js → hosted/scripts.js} +93 -12
- package/dist/index.d.ts +7 -3
- package/dist/index.js +7 -4
- package/dist/kernel.d.ts +2 -4
- package/dist/kernel.js +2 -1
- package/dist/kinds.d.ts +8 -1
- package/dist/kinds.js +20 -4
- package/dist/local-chrome.d.ts +2 -4
- package/dist/local-chrome.js +2 -1
- package/dist/modal.d.ts +23 -181
- package/dist/modal.js +271 -1244
- package/dist/orgo-channel.d.ts +3 -2
- package/dist/orgo-channel.js +5 -2
- package/dist/orgo-desktop.d.ts +9 -4
- package/dist/orgo-desktop.js +33 -13
- package/dist/orgo-workspaces.d.ts +47 -0
- package/dist/orgo-workspaces.js +94 -0
- package/dist/orgo.d.ts +10 -4
- package/dist/orgo.js +30 -12
- package/dist/phone-harness.d.ts +31 -22
- package/dist/phone-harness.js +510 -698
- package/dist/png.d.ts +4 -0
- package/dist/png.js +27 -0
- package/dist/protocol.d.ts +335 -32
- package/dist/protocol.js +96 -3
- package/dist/provider.d.ts +34 -6
- package/dist/provider.js +16 -0
- package/dist/result.d.ts +1 -1
- package/dist/surface/api.d.ts +248 -0
- package/dist/surface/api.js +1 -0
- package/dist/surface/core.d.ts +42 -0
- package/dist/surface/core.js +393 -0
- package/dist/surface/index.d.ts +5 -0
- package/dist/surface/index.js +3 -0
- package/dist/surface/outline.d.ts +8 -0
- package/dist/surface/outline.js +50 -0
- package/dist/surface/script.d.ts +10 -0
- package/dist/surface/script.js +92 -0
- package/dist/ui-engine.d.ts +114 -0
- package/dist/ui-engine.js +798 -0
- package/package.json +17 -1
- package/dist/child.d.ts +0 -42
- package/dist/conformance/e2b-diagnose.d.ts +0 -16
- package/dist/conformance/e2b-diagnose.js +0 -61
- package/dist/conformance/e2b-sweep.d.ts +0 -18
- package/dist/conformance/e2b-sweep.js +0 -132
- package/dist/conformance/modal-sweep.d.ts +0 -22
- package/dist/conformance/modal-sweep.js +0 -213
package/dist/phone-harness.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// The phone kind on the phone harness's cloud phones (phone-harness.com): a cloud Android rented by the minute through
|
|
2
|
-
// its HTTPS API, and driven over adb.
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// refused for now.
|
|
2
|
+
// its HTTPS API, and driven over adb. connect() pushes phoned (daemon-android/, the phone's driver: one dex jar) to the
|
|
3
|
+
// phone when it lacks it, starts it as the shell user through app_process, and speaks the protocol to it over adb's
|
|
4
|
+
// exec: service: phoned answers the phone groups (exec, screen, input.touch, input.keys, apps, ui) on the phone itself.
|
|
5
|
+
// A cloud iPhone (driven by the API's control URL) is a later change: platform "ios" is refused for now.
|
|
6
6
|
//
|
|
7
7
|
// The library reads no environment: the API key and every setting are options (serve passes PHONE_HARNESS_API_KEY as
|
|
8
8
|
// apiKey). The vendor keeps no labels on a session, so the provider keeps its own in a ledger (an option: serve's store,
|
|
@@ -11,12 +11,14 @@
|
|
|
11
11
|
import { execFile } from "node:child_process";
|
|
12
12
|
import { createHash, randomBytes } from "node:crypto";
|
|
13
13
|
import { readFileSync } from "node:fs";
|
|
14
|
+
import { readFile } from "node:fs/promises";
|
|
14
15
|
import { createConnection } from "node:net";
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
16
|
+
import { basename } from "node:path";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
import { DaemonClient } from "./client.js";
|
|
19
|
+
import { CreateRequests, endedWords, labelsDiffer, otherSpecWords } from "./create-requests.js";
|
|
18
20
|
import { PHONE_GROUPS, PHONE_HARNESS } from "./descriptors/phone-harness.js";
|
|
19
|
-
import {
|
|
21
|
+
import { PROTOCOL_VERSION } from "./protocol.js";
|
|
20
22
|
import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
|
|
21
23
|
import { failFor, ok, vendorFail } from "./result.js";
|
|
22
24
|
import { daemonWatch, redactWords } from "./screen-watch.js";
|
|
@@ -39,14 +41,51 @@ const DEFAULT_REQUEST_MS = 30_000;
|
|
|
39
41
|
const ADB_TIMEOUT_MS = 30_000;
|
|
40
42
|
/** The user every shell command on an Android runs as: shell, 2000. */
|
|
41
43
|
const SHELL_USER = "2000:2000";
|
|
44
|
+
/** phoned's jar in this package, built by npm run build:phoned beside the compiled modules. */
|
|
45
|
+
const DEFAULT_PHONED_PATH = fileURLToPath(new URL("./phoned.jar", import.meta.url));
|
|
46
|
+
/** Where phoned's jars and logs go on a phone: the shell user's own directory. */
|
|
47
|
+
const PHONE_TMP = "/data/local/tmp";
|
|
48
|
+
/** How long a jar push may take: about 70 KB, over a link to a cloud phone. */
|
|
49
|
+
const PUSH_TIMEOUT_MS = 120_000;
|
|
50
|
+
/** How long phoned may take to start and answer hello: app_process starts a runtime first. */
|
|
51
|
+
const HELLO_TIMEOUT_MS = 30_000;
|
|
52
|
+
/**
|
|
53
|
+
* How long a phoned whose connection closed has to exit before the next phoned on its phone kills it: once its stdin
|
|
54
|
+
* ends it gives its running requests 3 s, lets go of the phone's accessibility and exits.
|
|
55
|
+
*/
|
|
56
|
+
const PHONED_EXIT_S = 10;
|
|
57
|
+
/** How long a killed phoned has to be gone. */
|
|
58
|
+
const PHONED_KILL_S = 2;
|
|
59
|
+
/**
|
|
60
|
+
* A shell command for the phone that waits until the process is gone (a zombie counts: it holds nothing; so does
|
|
61
|
+
* another process that took its pid), up to PHONED_EXIT_S; then kills it and waits PHONED_KILL_S more. Its last line is
|
|
62
|
+
* exited, killed or running. /proc/<pid>/stat less its "<pid> (<name>) " gives the state as $1 and the start time as ${20}.
|
|
63
|
+
*/
|
|
64
|
+
function untilGone({ pid, start }) {
|
|
65
|
+
const wait = (seconds) => `n=0; while alive && [ $n -lt ${seconds * 10} ]; do sleep 0.1; n=$((n+1)); done`;
|
|
66
|
+
return `p=${pid}; t=${start}; alive() { s=$(cat /proc/$p/stat 2>/dev/null) || return 1; s=\${s##*") "}; set -- $s; [ "$1" != Z ] && [ "\${20}" = "$t" ]; }; ${wait(PHONED_EXIT_S)}; alive || { echo exited; exit 0; }; kill -9 $p 2>/dev/null; ${wait(PHONED_KILL_S)}; alive && echo running || echo killed`;
|
|
67
|
+
}
|
|
42
68
|
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
43
69
|
/** The ledger's id for a create not answered yet. */
|
|
44
70
|
const pendingId = (requestKey) => `pending-${requestKey}`;
|
|
71
|
+
/** The Idempotency-Key of a request: every create of one request id sends the same key, so the service can tell them one. */
|
|
72
|
+
const requestKeyOf = (requestId) => createHash("sha256").update(requestId, "utf8").digest("hex");
|
|
73
|
+
/**
|
|
74
|
+
* How a spec differs from a phone of its request, as the ledger reads it back: its labels and its image, every field of
|
|
75
|
+
* a spec check() lets a phone ask for but its network (always open) and its lifetime (each create counts its own).
|
|
76
|
+
*/
|
|
77
|
+
function phoneDiffer(spec, labels, image, seen) {
|
|
78
|
+
const differ = labelsDiffer(spec.labels ?? {}, labels, seen);
|
|
79
|
+
if (spec.image !== image)
|
|
80
|
+
differ.push(`image: asked ${spec.image}, ${seen} ${image}`);
|
|
81
|
+
return differ;
|
|
82
|
+
}
|
|
45
83
|
/** A ledger in this process's memory: the default, and enough for one process that makes and ends its phones. */
|
|
46
84
|
export function memoryLedger() {
|
|
47
85
|
const entries = new Map();
|
|
48
86
|
return {
|
|
49
87
|
put: (entry) => void entries.set(entry.id, structuredClone(entry)),
|
|
88
|
+
claim: (entry) => !entries.has(entry.id) && (entries.set(entry.id, structuredClone(entry)), true),
|
|
50
89
|
get: (id) => structuredClone(entries.get(id)),
|
|
51
90
|
list: () => [...entries.values()].map((entry) => structuredClone(entry)),
|
|
52
91
|
remove: (id) => void entries.delete(id),
|
|
@@ -67,6 +106,7 @@ function guardedLedger(ledger) {
|
|
|
67
106
|
};
|
|
68
107
|
return {
|
|
69
108
|
put: guard("written", (entry) => ledger.put(entry)),
|
|
109
|
+
claim: guard("written", (entry) => ledger.claim(entry)),
|
|
70
110
|
get: guard("read", (id) => ledger.get(id)),
|
|
71
111
|
list: guard("read", () => ledger.list()),
|
|
72
112
|
remove: guard("written", (id) => ledger.remove(id)),
|
|
@@ -119,15 +159,22 @@ export function adbCli(path = "adb", { port = ADB_SERVER_PORT, env } = {}) {
|
|
|
119
159
|
child.stdin?.end(input ?? "");
|
|
120
160
|
});
|
|
121
161
|
let started;
|
|
122
|
-
|
|
123
|
-
|
|
162
|
+
/** The adb server, started once: a failed start is tried again by the next request. */
|
|
163
|
+
const serverUp = async (timeoutMs) => {
|
|
124
164
|
started ??= run(["start-server"], { timeoutMs });
|
|
125
165
|
const start = await started;
|
|
126
166
|
if (!start.ok || start.value.exitCode !== 0) {
|
|
127
167
|
started = undefined;
|
|
128
168
|
return start.ok ? vendorFail("phone-harness", `adb start-server failed: ${start.value.stderr.trim().split("\n")[0] || `exit code ${start.value.exitCode}`}`) : start;
|
|
129
169
|
}
|
|
130
|
-
|
|
170
|
+
return ok(undefined);
|
|
171
|
+
};
|
|
172
|
+
const frame = (request) => `${Buffer.byteLength(request).toString(16).padStart(4, "0")}${request}`;
|
|
173
|
+
const server = async (service, { timeoutMs, transport }) => {
|
|
174
|
+
const what = serviceWords(service);
|
|
175
|
+
const up = await serverUp(timeoutMs);
|
|
176
|
+
if (!up.ok)
|
|
177
|
+
return up;
|
|
131
178
|
return new Promise((resolve) => {
|
|
132
179
|
let buffer = Buffer.alloc(0);
|
|
133
180
|
let settled = false;
|
|
@@ -166,7 +213,69 @@ export function adbCli(path = "adb", { port = ADB_SERVER_PORT, env } = {}) {
|
|
|
166
213
|
});
|
|
167
214
|
});
|
|
168
215
|
};
|
|
169
|
-
|
|
216
|
+
const open = async (service, { timeoutMs, transport }) => {
|
|
217
|
+
const what = serviceWords(service);
|
|
218
|
+
const up = await serverUp(timeoutMs);
|
|
219
|
+
if (!up.ok)
|
|
220
|
+
return up;
|
|
221
|
+
return new Promise((resolve) => {
|
|
222
|
+
let buffer = Buffer.alloc(0);
|
|
223
|
+
let settled = false;
|
|
224
|
+
// First host:transport-id, whose OKAY binds the socket to the phone; then the service, whose OKAY hands the
|
|
225
|
+
// socket over to it.
|
|
226
|
+
let asking = `host:transport-id:${transport}`;
|
|
227
|
+
const socket = createConnection({ host: "127.0.0.1", port });
|
|
228
|
+
/** The adb server's refusal: its answer is never OKAY here, so it is always a failure. */
|
|
229
|
+
const refused = (raw, of) => {
|
|
230
|
+
const answer = adbAnswer(raw, of);
|
|
231
|
+
return answer.ok ? vendorFail("phone-harness", `the adb server answered ${of} without OKAY`) : answer;
|
|
232
|
+
};
|
|
233
|
+
const done = (result) => {
|
|
234
|
+
if (settled)
|
|
235
|
+
return;
|
|
236
|
+
settled = true;
|
|
237
|
+
clearTimeout(timer);
|
|
238
|
+
socket.off("data", onData);
|
|
239
|
+
socket.off("error", onError);
|
|
240
|
+
socket.off("close", onClose);
|
|
241
|
+
if (!result.ok)
|
|
242
|
+
socket.destroy();
|
|
243
|
+
resolve(result);
|
|
244
|
+
};
|
|
245
|
+
const onData = (chunk) => {
|
|
246
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
247
|
+
while (!settled && buffer.length >= 4) {
|
|
248
|
+
const status = buffer.subarray(0, 4).toString("latin1");
|
|
249
|
+
// FAIL is followed by its hex length and words: wait for them, or for the close that ends them.
|
|
250
|
+
if (status !== "OKAY") {
|
|
251
|
+
const length = buffer.length >= 8 ? Number.parseInt(buffer.subarray(4, 8).toString("latin1"), 16) : Number.NaN;
|
|
252
|
+
if (status === "FAIL" && !(buffer.length >= 8 + length))
|
|
253
|
+
return;
|
|
254
|
+
return done(refused(buffer, asking === service ? what : asking));
|
|
255
|
+
}
|
|
256
|
+
buffer = buffer.subarray(4);
|
|
257
|
+
if (asking !== service) {
|
|
258
|
+
asking = service;
|
|
259
|
+
socket.write(frame(service));
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
// The service's stream from here on: what came after its OKAY is the first of it.
|
|
263
|
+
socket.pause();
|
|
264
|
+
if (buffer.length > 0)
|
|
265
|
+
socket.unshift(buffer);
|
|
266
|
+
return done(ok(socket));
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
const onError = (error) => done(vendorFail("phone-harness", `the adb server on 127.0.0.1:${port} could not be reached for ${what}: ${error.message}`));
|
|
270
|
+
const onClose = () => done(buffer.length >= 4 ? refused(buffer, asking === service ? what : asking) : vendorFail("phone-harness", `the adb server closed ${asking === service ? what : asking} before it answered`));
|
|
271
|
+
const timer = setTimeout(() => done(fail("timeout", `the adb server did not answer ${what} within ${timeoutMs / 1000} s`)), timeoutMs);
|
|
272
|
+
socket.on("connect", () => socket.write(frame(asking)));
|
|
273
|
+
socket.on("data", onData);
|
|
274
|
+
socket.on("error", onError);
|
|
275
|
+
socket.on("close", onClose);
|
|
276
|
+
});
|
|
277
|
+
};
|
|
278
|
+
return { run, server, open };
|
|
170
279
|
}
|
|
171
280
|
/** A service as error words name it: its kind and first word, never the rest (a shell command's code, an endpoint). */
|
|
172
281
|
export function serviceWords(service) {
|
|
@@ -211,6 +320,12 @@ export class PhoneHarnessProvider {
|
|
|
211
320
|
#fetch;
|
|
212
321
|
#adb;
|
|
213
322
|
#ledger;
|
|
323
|
+
/** Each create in flight, and the names of the phones this provider ended (create-requests.ts). Past this process, the
|
|
324
|
+
* ledger's released entry is what holds, until the service has ended the phone. */
|
|
325
|
+
#requests = new CreateRequests();
|
|
326
|
+
/** The Idempotency-Keys whose pending entry a create here claimed, kept until it is removed: a pending entry of one is
|
|
327
|
+
* this provider's own (no create of it is in flight, CreateRequests shares those), so a retry here sends the POST. */
|
|
328
|
+
#claimed = new Set();
|
|
214
329
|
#maxLifetimeMs;
|
|
215
330
|
#readyMs;
|
|
216
331
|
#pollMs;
|
|
@@ -223,6 +338,21 @@ export class PhoneHarnessProvider {
|
|
|
223
338
|
#holders = new Map();
|
|
224
339
|
/** Each endpoint's host:disconnect still on its way: a connect to that endpoint waits for it before its own. */
|
|
225
340
|
#leaving = new Map();
|
|
341
|
+
/**
|
|
342
|
+
* Each endpoint's phoned, started by its first connection and shared by all of them, as its adb transport is: a phone
|
|
343
|
+
* has one accessibility connection to give. The last holder's release ends it before the disconnect.
|
|
344
|
+
*/
|
|
345
|
+
#daemons = new Map();
|
|
346
|
+
/**
|
|
347
|
+
* Each endpoint's last phoned, by its process on the phone, until it is seen gone: the next phoned there starts only
|
|
348
|
+
* once it is (#lastGone), since it holds the phone's one accessibility connection until it exits, after its
|
|
349
|
+
* connection closed.
|
|
350
|
+
*/
|
|
351
|
+
#lastPhoned = new Map();
|
|
352
|
+
#phonedPath;
|
|
353
|
+
#apks;
|
|
354
|
+
/** Each file the provider puts on its phones (phoned's jar, the APKs), read once: its bytes' sha256 names it there. */
|
|
355
|
+
#files = new Map();
|
|
226
356
|
constructor(options) {
|
|
227
357
|
const { apiKey, platform = "android" } = options ?? {};
|
|
228
358
|
if (typeof apiKey !== "string" || apiKey === "")
|
|
@@ -235,9 +365,14 @@ export class PhoneHarnessProvider {
|
|
|
235
365
|
this.#baseUrl = (options.baseUrl ?? PHONE_HARNESS_URL).replace(/\/+$/, "");
|
|
236
366
|
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
237
367
|
const adb = options.adb;
|
|
238
|
-
if (adb !== undefined && typeof adb !== "string" && !(typeof adb?.run === "function" && typeof adb?.server === "function")) {
|
|
239
|
-
throw new Error("options.adb is the adb CLI's path, or a transport with run() and
|
|
368
|
+
if (adb !== undefined && typeof adb !== "string" && !(typeof adb?.run === "function" && typeof adb?.server === "function" && typeof adb?.open === "function")) {
|
|
369
|
+
throw new Error("options.adb is the adb CLI's path, or a transport with run(), server() and open()");
|
|
240
370
|
}
|
|
371
|
+
this.#phonedPath = options.phoned ?? DEFAULT_PHONED_PATH;
|
|
372
|
+
const apks = options.apks ?? [];
|
|
373
|
+
if (!Array.isArray(apks) || !apks.every((path) => typeof path === "string" && path !== ""))
|
|
374
|
+
throw new Error(`options.apks ${show(options.apks)} is not a list of APK paths`);
|
|
375
|
+
this.#apks = [...apks];
|
|
241
376
|
this.#adb = adb === undefined || typeof adb === "string" ? adbCli(adb ?? "adb") : adb;
|
|
242
377
|
this.#ledger = guardedLedger(options.ledger ?? memoryLedger());
|
|
243
378
|
this.#maxLifetimeMs = options.maxLifetimeMs ?? DEFAULT_MAX_LIFETIME_MS;
|
|
@@ -378,12 +513,102 @@ export class PhoneHarnessProvider {
|
|
|
378
513
|
await this.#ledger.remove(id);
|
|
379
514
|
return ok(undefined);
|
|
380
515
|
}
|
|
516
|
+
/**
|
|
517
|
+
* Forgets a phone the service ended: its request is spent first, so a retry of it is refused exists (endedWords),
|
|
518
|
+
* never a second POST /sessions, and then its entry goes.
|
|
519
|
+
*/
|
|
520
|
+
async #forget(entry) {
|
|
521
|
+
this.#requests.end(entry.name);
|
|
522
|
+
await this.#ledger.remove(entry.id);
|
|
523
|
+
}
|
|
381
524
|
#deadlineOf(session, fallback) {
|
|
382
525
|
return new Date(typeof session.expires_at === "number" && Number.isFinite(session.expires_at) ? session.expires_at * 1000 : fallback).toISOString();
|
|
383
526
|
}
|
|
384
527
|
// --- the provider ----------------------------------------------------------------------------------------------
|
|
385
|
-
|
|
386
|
-
|
|
528
|
+
/**
|
|
529
|
+
* Makes a phone, once per request (provider.md, Idempotent create): context.requestId names it (computerNameFor) and
|
|
530
|
+
* gives the POST's Idempotency-Key. A request whose phone the ledger holds answers that phone once it is ready; one
|
|
531
|
+
* released is refused exists; a create of a request in flight here waits for the first (CreateRequests).
|
|
532
|
+
*/
|
|
533
|
+
create(spec, context) {
|
|
534
|
+
const refusals = this.check(spec);
|
|
535
|
+
return ledgerSafe(() => this.#requests.create(spec, context, {
|
|
536
|
+
refuse: fail,
|
|
537
|
+
...(refusals.length > 0 ? { refused: refusals.map(({ field, message }) => `${field}: ${message}`).join("; ") } : {}),
|
|
538
|
+
make: (name) => this.#create(spec, name, requestKeyOf(context.requestId), context.signal),
|
|
539
|
+
}));
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* The phone the ledger holds for a request, or undefined when it holds none: one whose create's answer was lost is
|
|
543
|
+
* asked for by its key first, and recorded when the service made it. One released, or ended, is refused exists; one
|
|
544
|
+
* of another spec is refused exists; one still starting is waited for, within readyMs.
|
|
545
|
+
*/
|
|
546
|
+
async #held(spec, name, requestKey, signal) {
|
|
547
|
+
const entries = await this.#ledger.list();
|
|
548
|
+
let entry = entries.find((one) => one.name === name && one.request === undefined);
|
|
549
|
+
const pending = entries.find((one) => one.id === pendingId(requestKey));
|
|
550
|
+
if (entry === undefined && pending !== undefined) {
|
|
551
|
+
const recovered = await this.#api("GET", `/sessions/requests/${requestKey}`);
|
|
552
|
+
if (!recovered.ok)
|
|
553
|
+
return recovered.error.code === "not_found" ? undefined : recovered;
|
|
554
|
+
const session = sessionOf(recovered.value.json, `GET /sessions/requests/${requestKey}`);
|
|
555
|
+
if (!session.ok)
|
|
556
|
+
return session;
|
|
557
|
+
// Claimed, never put over an entry another create recorded while the service answered: that one, and its release
|
|
558
|
+
// marker, stand. One already forgotten was released and is gone.
|
|
559
|
+
const found = { id: session.value.id, name, labels: { ...pending.labels }, image: pending.image, deadline: this.#deadlineOf(session.value, Date.parse(pending.deadline)) };
|
|
560
|
+
entry = (await this.#ledger.claim(found)) ? found : await this.#ledger.get(found.id);
|
|
561
|
+
await this.#ledger.remove(pending.id);
|
|
562
|
+
if (entry === undefined)
|
|
563
|
+
return fail("exists", endedWords(name));
|
|
564
|
+
}
|
|
565
|
+
if (entry === undefined)
|
|
566
|
+
return undefined;
|
|
567
|
+
if (entry.released !== undefined || this.#now() >= Date.parse(entry.deadline))
|
|
568
|
+
return fail("exists", endedWords(name));
|
|
569
|
+
const differ = phoneDiffer(spec, entry.labels, entry.image, "read back");
|
|
570
|
+
if (differ.length > 0)
|
|
571
|
+
return fail("exists", otherSpecWords(name, "was made", differ));
|
|
572
|
+
// The same wait a fresh create makes, within readyMs; a phone that ended, or reached its deadline as it started, is
|
|
573
|
+
// spent. One not ready in time is left to the create that made it, which ends it.
|
|
574
|
+
const ready = await this.#ready(entry.id, this.#now(), signal);
|
|
575
|
+
if (!ready.ok)
|
|
576
|
+
return ready.error.code === "gone" ? fail("exists", endedWords(name)) : ready;
|
|
577
|
+
if (this.#now() >= Date.parse(this.#deadlineOf(ready.value, Date.parse(entry.deadline))))
|
|
578
|
+
return fail("exists", endedWords(name));
|
|
579
|
+
return ok({ id: entry.id, name });
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Waits until the phone id is ready, within readyMs counted from `from`, each read bounded by what readyMs has left so
|
|
583
|
+
* a stalled one cannot hold the wait past it: the ready session, or why not. gone: the service ended the phone, or it
|
|
584
|
+
* did not start; timeout: readyMs passed; aborted: the signal fired.
|
|
585
|
+
*/
|
|
586
|
+
async #ready(id, from, signal) {
|
|
587
|
+
for (;;) {
|
|
588
|
+
if (signal?.aborted)
|
|
589
|
+
return fail("aborted", `create was aborted while the phone ${id} started`);
|
|
590
|
+
const left = this.#readyMs - (this.#now() - from);
|
|
591
|
+
const bound = Math.max(1, Math.min(this.#requestMs, left));
|
|
592
|
+
const read = await this.#session(id, signal, bound);
|
|
593
|
+
if (!read.ok && read.error.code === "timeout") {
|
|
594
|
+
// A read cut off by its own bound (requestMs) while readyMs has time left is one slow answer, not the deadline:
|
|
595
|
+
// ask again. Only a read bounded by what readyMs had left, or the check below, ends the wait.
|
|
596
|
+
if (bound < left && this.#now() - from < this.#readyMs) {
|
|
597
|
+
await this.#sleep(this.#pollMs);
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
return fail("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s: ${read.error.message}`);
|
|
601
|
+
}
|
|
602
|
+
if (!read.ok)
|
|
603
|
+
return fail(read.error.code, `the phone ${id} did not start: ${read.error.message}`);
|
|
604
|
+
if (read.value.state === "ready")
|
|
605
|
+
return read;
|
|
606
|
+
if (read.value.state !== "provisioning")
|
|
607
|
+
return fail("gone", `the phone ${id} did not start: ${this.#clean(read.value.error ?? read.value.state)}`);
|
|
608
|
+
if (this.#now() - from >= this.#readyMs)
|
|
609
|
+
return fail("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s`);
|
|
610
|
+
await this.#sleep(this.#pollMs);
|
|
611
|
+
}
|
|
387
612
|
}
|
|
388
613
|
attach(ref, context = {}) {
|
|
389
614
|
return ledgerSafe(() => this.#attach(ref, context));
|
|
@@ -408,18 +633,40 @@ export class PhoneHarnessProvider {
|
|
|
408
633
|
watch(ref, handlers, options) {
|
|
409
634
|
return daemonWatch(this, ref, handlers, options);
|
|
410
635
|
}
|
|
411
|
-
async #create(spec,
|
|
412
|
-
const refusals = this.check(spec);
|
|
413
|
-
if (refusals.length > 0)
|
|
414
|
-
return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
|
|
636
|
+
async #create(spec, name, requestKey, signal) {
|
|
415
637
|
if (signal?.aborted)
|
|
416
638
|
return fail("aborted", "create was aborted before the phone harness was asked");
|
|
417
|
-
const
|
|
418
|
-
const requestKey = randomBytes(16).toString("hex");
|
|
639
|
+
const looked = this.#now();
|
|
419
640
|
const body = { platform: "android", kind: "emulator", timeout_seconds: Math.ceil(runLifetimeMs(spec) / 1000) };
|
|
420
|
-
// The key goes into the ledger before the POST: whatever answers are lost, list() can find the phone by it.
|
|
641
|
+
// The key goes into the ledger before the POST: whatever answers are lost, list() can find the phone by it. It is
|
|
642
|
+
// claimed, never put over another's: a create of the request in another provider on the same ledger (another
|
|
643
|
+
// process) holds the request's spec there, and one of another spec is refused before it can POST the same key.
|
|
644
|
+
// One of the same spec waits for that create's phone (#held finds it by the key, and never ends it): only the
|
|
645
|
+
// create that holds the claim owns the phone, to end it if it gives up. A claim older than any create's POST and
|
|
646
|
+
// its recovery (readyMs and twice requestMs from this look) is one whose create ended unrecorded: this one sends.
|
|
421
647
|
const pending = pendingId(requestKey);
|
|
422
|
-
|
|
648
|
+
const stale = looked + this.#readyMs + 2 * this.#requestMs;
|
|
649
|
+
for (;;) {
|
|
650
|
+
const held = await this.#held(spec, name, requestKey, signal);
|
|
651
|
+
if (held !== undefined)
|
|
652
|
+
return held;
|
|
653
|
+
if (await this.#ledger.claim({ id: pending, name, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: new Date(this.#now() + runLifetimeMs(spec)).toISOString(), request: requestKey }))
|
|
654
|
+
break;
|
|
655
|
+
const other = await this.#ledger.get(pending);
|
|
656
|
+
// Gone since: that create has ended, with a phone or none; look again.
|
|
657
|
+
if (other === undefined)
|
|
658
|
+
continue;
|
|
659
|
+
const differ = phoneDiffer(spec, other.labels, other.image, "in flight");
|
|
660
|
+
if (differ.length > 0)
|
|
661
|
+
return fail("exists", otherSpecWords(name, "is being made", differ));
|
|
662
|
+
if (this.#claimed.has(requestKey) || this.#now() >= stale)
|
|
663
|
+
break;
|
|
664
|
+
if (signal?.aborted)
|
|
665
|
+
return fail("aborted", `create was aborted while another create of this request made ${name}`);
|
|
666
|
+
await this.#sleep(this.#pollMs);
|
|
667
|
+
}
|
|
668
|
+
this.#claimed.add(requestKey);
|
|
669
|
+
const from = this.#now();
|
|
423
670
|
const posted = await this.#api("POST", "/sessions", { body, headers: { "Idempotency-Key": requestKey }, ...(signal ? { signal } : {}) });
|
|
424
671
|
const cancelled = !posted.ok && posted.error.code === "aborted";
|
|
425
672
|
let first = posted.ok ? sessionOf(posted.value.json, "POST /sessions") : undefined;
|
|
@@ -441,6 +688,7 @@ export class PhoneHarnessProvider {
|
|
|
441
688
|
else if (!posted.ok) {
|
|
442
689
|
// The phone harness refused the request: nothing was made, and the key is forgotten.
|
|
443
690
|
await this.#ledger.remove(pending);
|
|
691
|
+
this.#claimed.delete(requestKey);
|
|
444
692
|
return posted;
|
|
445
693
|
}
|
|
446
694
|
if (first === undefined || !first.ok)
|
|
@@ -460,54 +708,43 @@ export class PhoneHarnessProvider {
|
|
|
460
708
|
}
|
|
461
709
|
};
|
|
462
710
|
const named = await record(async () => {
|
|
463
|
-
await this.#ledger.put({ id, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: this.#deadlineOf(first.value, from + runLifetimeMs(spec)) });
|
|
711
|
+
await this.#ledger.put({ id, name, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline: this.#deadlineOf(first.value, from + runLifetimeMs(spec)) });
|
|
464
712
|
await this.#ledger.remove(pending);
|
|
713
|
+
this.#claimed.delete(requestKey);
|
|
465
714
|
});
|
|
466
715
|
if (!named.ok)
|
|
467
716
|
return named;
|
|
468
717
|
const ended = async (code, words) => {
|
|
718
|
+
// A phone create gave up on: its request is spent, as one released.
|
|
719
|
+
this.#requests.end(name);
|
|
469
720
|
const gone = await this.#end(id);
|
|
470
721
|
return fail(code, `${words}; ${gone.ok ? "it was ended" : `it could not be ended (${gone.error.message})`}`);
|
|
471
722
|
};
|
|
472
723
|
if (cancelled)
|
|
473
724
|
return ended("aborted", `create was aborted during POST /sessions, after the service made the phone ${id}`);
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
// A read takes no longer than readyMs has left, so a stalled one cannot hold create past it.
|
|
479
|
-
const left = this.#readyMs - (this.#now() - from);
|
|
480
|
-
const bound = Math.max(1, Math.min(this.#requestMs, left));
|
|
481
|
-
const read = await this.#session(id, signal, bound);
|
|
482
|
-
if (!read.ok && read.error.code === "timeout") {
|
|
483
|
-
// A read cut off by its own bound (requestMs) while readyMs has time left is one slow answer, not the deadline:
|
|
484
|
-
// ask again. Only a read bounded by what readyMs had left, or the deadline check below, ends the phone.
|
|
485
|
-
if (bound < left && this.#now() - from < this.#readyMs) {
|
|
486
|
-
await this.#sleep(this.#pollMs);
|
|
487
|
-
continue;
|
|
488
|
-
}
|
|
489
|
-
return ended("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s: ${read.error.message}`);
|
|
490
|
-
}
|
|
491
|
-
if (!read.ok)
|
|
492
|
-
return ended(read.error.code === "gone" ? "vendor" : read.error.code, `the phone ${id} did not start: ${read.error.message}`);
|
|
493
|
-
session = read.value;
|
|
494
|
-
if (session.state === "ready")
|
|
495
|
-
break;
|
|
496
|
-
if (session.state !== "provisioning")
|
|
497
|
-
return ended("vendor", `the phone ${id} did not start: ${this.#clean(session.error ?? session.state)}`);
|
|
498
|
-
if (this.#now() - from >= this.#readyMs)
|
|
499
|
-
return ended("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s`);
|
|
500
|
-
await this.#sleep(this.#pollMs);
|
|
501
|
-
}
|
|
725
|
+
const ready = await this.#ready(id, from, signal);
|
|
726
|
+
if (!ready.ok)
|
|
727
|
+
return ended(ready.error.code === "gone" ? "vendor" : ready.error.code, ready.error.message);
|
|
728
|
+
const session = ready.value;
|
|
502
729
|
const deadline = this.#deadlineOf(session, from + runLifetimeMs(spec));
|
|
503
|
-
|
|
730
|
+
// The entry as kept now: a create of the same request on another provider may have answered this phone while it
|
|
731
|
+
// started (#held), and its caller released it. That release stands: never written over, and the phone not answered.
|
|
732
|
+
let released = false;
|
|
733
|
+
const kept = await record(async () => {
|
|
734
|
+
const now = await this.#ledger.get(id);
|
|
735
|
+
released = now === undefined || now.released !== undefined;
|
|
736
|
+
if (!released)
|
|
737
|
+
await this.#ledger.put({ ...now, id, name, labels: { ...(spec.labels ?? {}) }, image: spec.image, deadline });
|
|
738
|
+
});
|
|
504
739
|
if (!kept.ok)
|
|
505
740
|
return kept;
|
|
741
|
+
if (released)
|
|
742
|
+
return fail("exists", endedWords(name));
|
|
506
743
|
const took = this.#now() - from;
|
|
507
744
|
if (this.#now() >= Date.parse(deadline)) {
|
|
508
745
|
return ended("timeout", `the phone ${id}'s lifetime of ${runLifetimeMs(spec) / 1000} s ended before it was ready (it took ${Math.round(took / 100) / 10} s)`);
|
|
509
746
|
}
|
|
510
|
-
return ok({ id, name
|
|
747
|
+
return ok({ id, name });
|
|
511
748
|
}
|
|
512
749
|
async #attach(ref, { signal } = {}) {
|
|
513
750
|
let entry;
|
|
@@ -532,13 +769,13 @@ export class PhoneHarnessProvider {
|
|
|
532
769
|
const session = await this.#session(id, signal);
|
|
533
770
|
if (!session.ok) {
|
|
534
771
|
if (session.error.code === "gone")
|
|
535
|
-
await this.#
|
|
772
|
+
await this.#forget(entry);
|
|
536
773
|
return session;
|
|
537
774
|
}
|
|
538
775
|
if (session.value.state !== "ready" && session.value.state !== "provisioning")
|
|
539
776
|
return fail("gone", `${id} is ${session.value.state}`);
|
|
540
777
|
const deadline = new Date(this.#deadlineOf(session.value, Date.parse(entry.deadline)));
|
|
541
|
-
return ok({ id, name:
|
|
778
|
+
return ok({ id, name: entry.name, spec: { image: entry.image, user: SHELL_USER, network: "open", deadline, kind: "android" } });
|
|
542
779
|
}
|
|
543
780
|
/**
|
|
544
781
|
* Settings' test: one GET /sessions, the account's sessions joined to the ledger, and a GET of any phone of the
|
|
@@ -580,7 +817,7 @@ export class PhoneHarnessProvider {
|
|
|
580
817
|
await this.#ledger.remove(listed.id);
|
|
581
818
|
continue;
|
|
582
819
|
}
|
|
583
|
-
entry = { id: made.id, labels: { ...entry.labels }, image: entry.image, deadline: this.#deadlineOf(made, Date.parse(entry.deadline)) };
|
|
820
|
+
entry = { id: made.id, name: entry.name, labels: { ...entry.labels }, image: entry.image, deadline: this.#deadlineOf(made, Date.parse(entry.deadline)) };
|
|
584
821
|
await this.#ledger.put(entry);
|
|
585
822
|
await this.#ledger.remove(listed.id);
|
|
586
823
|
}
|
|
@@ -588,11 +825,11 @@ export class PhoneHarnessProvider {
|
|
|
588
825
|
// Released, and being ended: never listed. Forgotten once the listing leaves it out and its own GET is a 404,
|
|
589
826
|
// or once its deadline has passed.
|
|
590
827
|
if (this.#now() > Date.parse(entry.deadline))
|
|
591
|
-
await this.#
|
|
828
|
+
await this.#forget(entry);
|
|
592
829
|
else if (!live.has(entry.id)) {
|
|
593
830
|
const read = await this.#session(entry.id, signal);
|
|
594
831
|
if (!read.ok && read.error.code === "gone")
|
|
595
|
-
await this.#
|
|
832
|
+
await this.#forget(entry);
|
|
596
833
|
}
|
|
597
834
|
continue;
|
|
598
835
|
}
|
|
@@ -601,7 +838,7 @@ export class PhoneHarnessProvider {
|
|
|
601
838
|
// Not in the listing: its own GET says whether the service ended it (404), and only then is it forgotten.
|
|
602
839
|
const read = await this.#session(entry.id, signal);
|
|
603
840
|
if (!read.ok && read.error.code === "gone") {
|
|
604
|
-
await this.#
|
|
841
|
+
await this.#forget(entry);
|
|
605
842
|
continue;
|
|
606
843
|
}
|
|
607
844
|
if (!read.ok)
|
|
@@ -611,7 +848,7 @@ export class PhoneHarnessProvider {
|
|
|
611
848
|
if (!carries(entry.labels, labels) || out.some((info) => info.ref.id === entry.id))
|
|
612
849
|
continue;
|
|
613
850
|
out.push({
|
|
614
|
-
ref: { id: entry.id, name: entry.
|
|
851
|
+
ref: { id: entry.id, name: entry.name },
|
|
615
852
|
labels: { ...entry.labels },
|
|
616
853
|
deadline: new Date(this.#deadlineOf(session, Date.parse(entry.deadline))),
|
|
617
854
|
state: session.state === "ready" || session.state === "provisioning" ? "running" : "stopped",
|
|
@@ -636,6 +873,9 @@ export class PhoneHarnessProvider {
|
|
|
636
873
|
if (how !== "delete")
|
|
637
874
|
return fail("unsupported", `a cloud phone is kept for no agent (the phone harness declares no persistence), so release ${JSON.stringify(how)} is refused and the phone is left as it is: release it with delete`);
|
|
638
875
|
const entry = await this.#ledger.get(ref.id);
|
|
876
|
+
// A released phone's request is spent: the same request id again is refused, never made a second time.
|
|
877
|
+
if (entry !== undefined)
|
|
878
|
+
this.#requests.end(entry.name);
|
|
639
879
|
if (entry?.released !== undefined) {
|
|
640
880
|
// Released already, and the service may still be ending it: ok. Its own GET says whether it is gone, and then it is
|
|
641
881
|
// forgotten; a phone the service still holds running is sent its DELETE again.
|
|
@@ -726,7 +966,15 @@ export class PhoneHarnessProvider {
|
|
|
726
966
|
if (left > 0)
|
|
727
967
|
return void this.#holders.set(endpoint, left);
|
|
728
968
|
this.#holders.delete(endpoint);
|
|
729
|
-
|
|
969
|
+
// The phone's phoned goes with its last holder, in the same critical section: a connect after this starts its own.
|
|
970
|
+
const daemon = this.#daemons.get(endpoint);
|
|
971
|
+
this.#daemons.delete(endpoint);
|
|
972
|
+
const leaving = (async () => {
|
|
973
|
+
const started = await daemon;
|
|
974
|
+
if (started?.ok)
|
|
975
|
+
await started.value.end();
|
|
976
|
+
})()
|
|
977
|
+
.then(() => server(`host:disconnect:${endpoint}`))
|
|
730
978
|
.catch(() => undefined)
|
|
731
979
|
.finally(() => {
|
|
732
980
|
if (this.#leaving.get(endpoint) === leaving)
|
|
@@ -777,663 +1025,227 @@ export class PhoneHarnessProvider {
|
|
|
777
1025
|
return letGo(vendorFail("phone-harness", /\bunlocked\b/.test(unlocked.value) ? `the phone of ${ref.id} stayed locked after its unlock code` : `the phone of ${ref.id} refused its unlock code: ${words}`));
|
|
778
1026
|
}
|
|
779
1027
|
}
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
1028
|
+
let started = this.#daemons.get(endpoint);
|
|
1029
|
+
if (started === undefined) {
|
|
1030
|
+
const starting = this.#startPhoned(endpoint, id, adb, onPhone, () => {
|
|
1031
|
+
// phoned ended on its own (the phone killed it, or it failed): the next connect starts another, once this start
|
|
1032
|
+
// is done, so its pid is kept before that start waits on it.
|
|
1033
|
+
void starting.then(() => {
|
|
1034
|
+
if (this.#daemons.get(endpoint) === starting)
|
|
1035
|
+
this.#daemons.delete(endpoint);
|
|
1036
|
+
});
|
|
1037
|
+
});
|
|
1038
|
+
started = starting;
|
|
1039
|
+
this.#daemons.set(endpoint, starting);
|
|
785
1040
|
}
|
|
786
|
-
const
|
|
787
|
-
if (
|
|
788
|
-
|
|
789
|
-
|
|
1041
|
+
const daemon = await started;
|
|
1042
|
+
if (!daemon.ok) {
|
|
1043
|
+
if (this.#daemons.get(endpoint) === started)
|
|
1044
|
+
this.#daemons.delete(endpoint);
|
|
1045
|
+
return letGo(daemon);
|
|
790
1046
|
}
|
|
1047
|
+
const { hello } = daemon.value;
|
|
1048
|
+
if (hello.version !== this.#daemonVersion)
|
|
1049
|
+
return letGo(fail("refused", `hello: the daemon reports version ${hello.version}, expected ${this.#daemonVersion}`));
|
|
1050
|
+
if (hello.protocol !== PROTOCOL_VERSION)
|
|
1051
|
+
return letGo(fail("refused", `hello: phoned speaks protocol ${hello.protocol}, and this provider ${PROTOCOL_VERSION}`));
|
|
1052
|
+
const client = new PhoneClient(daemon.value.client, release);
|
|
791
1053
|
return ok({ client, hello, close: () => client.closed() });
|
|
792
1054
|
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
// --- the client: the protocol over adb ---------------------------------------------------------------------------
|
|
803
|
-
/** Android's keycode for each key name in KEYS. */
|
|
804
|
-
const KEYCODES = {
|
|
805
|
-
enter: "ENTER",
|
|
806
|
-
tab: "TAB",
|
|
807
|
-
space: "SPACE",
|
|
808
|
-
backspace: "DEL",
|
|
809
|
-
delete: "FORWARD_DEL",
|
|
810
|
-
escape: "ESCAPE",
|
|
811
|
-
insert: "INSERT",
|
|
812
|
-
up: "DPAD_UP",
|
|
813
|
-
down: "DPAD_DOWN",
|
|
814
|
-
left: "DPAD_LEFT",
|
|
815
|
-
right: "DPAD_RIGHT",
|
|
816
|
-
home: "MOVE_HOME",
|
|
817
|
-
end: "MOVE_END",
|
|
818
|
-
pageup: "PAGE_UP",
|
|
819
|
-
pagedown: "PAGE_DOWN",
|
|
820
|
-
shift: "SHIFT_LEFT",
|
|
821
|
-
ctrl: "CTRL_LEFT",
|
|
822
|
-
alt: "ALT_LEFT",
|
|
823
|
-
super: "META_LEFT",
|
|
824
|
-
capslock: "CAPS_LOCK",
|
|
825
|
-
...Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`f${i + 1}`, `F${i + 1}`])),
|
|
826
|
-
};
|
|
827
|
-
const BUTTON_KEYS = { back: "BACK", home: "HOME", app_switch: "APP_SWITCH" };
|
|
828
|
-
const refuse = (code, message) => fail(code, message);
|
|
829
|
-
/** The in-process client of one cloud Android: each protocol method is one or more adb commands. */
|
|
830
|
-
class AdbClient {
|
|
831
|
-
transport;
|
|
832
|
-
adb;
|
|
833
|
-
disconnect;
|
|
834
|
-
sleep;
|
|
835
|
-
now;
|
|
836
|
-
#closed = false;
|
|
837
|
-
#hello;
|
|
838
|
-
#size = [0, 0];
|
|
839
|
-
#scale = 1;
|
|
840
|
-
/** The shot held for screen.read, until read to its end or the next shot. */
|
|
841
|
-
#held;
|
|
842
|
-
/** The newest watch frame's rest, held apart from the shot's (as computerd's is), so neither evicts the other. */
|
|
843
|
-
#watchHeld;
|
|
844
|
-
/**
|
|
845
|
-
* screen.watch's state: the newest frame's seq, what it was read from (a digest of the pixels), the frame, and when
|
|
846
|
-
* the screen was last read (read, by now()).
|
|
847
|
-
*/
|
|
848
|
-
#watch = {
|
|
849
|
-
seq: 0,
|
|
850
|
-
digest: "",
|
|
851
|
-
read: Number.NEGATIVE_INFINITY,
|
|
852
|
-
};
|
|
853
|
-
/** One screen.watch at a time on this connection. */
|
|
854
|
-
#watching = Promise.resolve();
|
|
855
|
-
/** One input.actions batch at a time on this connection: a second waits for the first, whole. */
|
|
856
|
-
#inputs = Promise.resolve();
|
|
857
|
-
/** Fires on close: every adb run and wait in flight ends with it, so a close never waits for the phone. */
|
|
858
|
-
#closing = new AbortController();
|
|
859
|
-
/** The disconnect close started, which the connection's close waits for. */
|
|
860
|
-
#gone = Promise.resolve();
|
|
861
|
-
constructor(
|
|
862
|
-
/** The adb server's transport id of the phone: no secret, so it may be in an argv. */
|
|
863
|
-
transport, adb,
|
|
864
|
-
/** Lets the adb server drop the phone's transport, by its endpoint over the server's socket. */
|
|
865
|
-
disconnect, sleep, now) {
|
|
866
|
-
this.transport = transport;
|
|
867
|
-
this.adb = adb;
|
|
868
|
-
this.disconnect = disconnect;
|
|
869
|
-
this.sleep = sleep;
|
|
870
|
-
this.now = now;
|
|
871
|
-
}
|
|
872
|
-
/** What the phone is: its ABI, its Android release, its screen's size and density; then the hello it answers. */
|
|
873
|
-
async open(version) {
|
|
874
|
-
const abi = await this.#shell("getprop ro.product.cpu.abi");
|
|
875
|
-
if (!abi.ok)
|
|
876
|
-
return abi;
|
|
877
|
-
const release = await this.#shell("getprop ro.build.version.release");
|
|
878
|
-
if (!release.ok)
|
|
879
|
-
return release;
|
|
880
|
-
const size = await this.#shell("wm size");
|
|
881
|
-
if (!size.ok)
|
|
882
|
-
return size;
|
|
883
|
-
const density = await this.#shell("wm density");
|
|
884
|
-
if (!density.ok)
|
|
885
|
-
return density;
|
|
886
|
-
const sizes = [...size.value.matchAll(/(\d+)x(\d+)/g)];
|
|
887
|
-
const last = sizes.at(-1);
|
|
888
|
-
if (!last)
|
|
889
|
-
return vendorFail("phone-harness", `the phone (adb transport ${this.transport}) did not say its screen's size: ${size.value.trim().slice(0, 100)}`);
|
|
890
|
-
this.#size = [Number(last[1]), Number(last[2])];
|
|
891
|
-
const dpi = [...density.value.matchAll(/(\d+)/g)].at(-1);
|
|
892
|
-
this.#scale = dpi ? Number(dpi[1]) / 160 : 1;
|
|
893
|
-
const reported = abi.value.trim();
|
|
894
|
-
// An empty answer says no release: the hello then carries none.
|
|
895
|
-
const osVersion = release.value.trim();
|
|
896
|
-
this.#hello = { protocol: PROTOCOL_VERSION, version, os: "android", ...(osVersion ? { osVersion } : {}), kind: "android", arch: ARCH[reported] ?? reported, groups: [...PHONE_GROUPS] };
|
|
897
|
-
return ok(this.#hello);
|
|
898
|
-
}
|
|
899
|
-
close() {
|
|
900
|
-
if (this.#closed)
|
|
901
|
-
return;
|
|
902
|
-
this.#closed = true;
|
|
903
|
-
this.#held = undefined;
|
|
904
|
-
this.#watchHeld = undefined;
|
|
905
|
-
this.#closing.abort();
|
|
906
|
-
this.#gone = this.disconnect().catch(() => undefined);
|
|
907
|
-
}
|
|
908
|
-
/** Closes, and waits until the adb server has let the phone's transport go. */
|
|
909
|
-
async closed() {
|
|
910
|
-
this.close();
|
|
911
|
-
await this.#gone;
|
|
912
|
-
}
|
|
913
|
-
/** The caller's signal and the connection's close, as one signal. */
|
|
914
|
-
#either(signal) {
|
|
915
|
-
return signal ? AbortSignal.any([signal, this.#closing.signal]) : this.#closing.signal;
|
|
916
|
-
}
|
|
917
|
-
/** One shell command on the phone: its stdout, or the failure in words (adb's, redacted: it names the endpoint). */
|
|
918
|
-
async #shell(command, signal, timeoutMs) {
|
|
919
|
-
const ran = await this.adb(["shell", command], { signal: this.#either(signal), ...(timeoutMs === undefined ? {} : { timeoutMs }) });
|
|
920
|
-
if (!ran.ok)
|
|
921
|
-
return ran;
|
|
922
|
-
if (ran.value.exitCode !== 0) {
|
|
923
|
-
const why = (ran.value.stderr.trim() || ran.value.stdout.toString("utf8").trim()).split("\n")[0] || `exit code ${ran.value.exitCode}`;
|
|
924
|
-
return vendorFail("phone-harness", `${command.split(" ").slice(0, 2).join(" ")} on the phone failed: ${redactWords(why)}`);
|
|
925
|
-
}
|
|
926
|
-
return ok(ran.value.stdout.toString("utf8"));
|
|
927
|
-
}
|
|
928
|
-
async #execOut(command, signal) {
|
|
929
|
-
const ran = await this.adb(["exec-out", command], { timeoutMs: 60_000, signal: this.#either(signal) });
|
|
930
|
-
if (!ran.ok)
|
|
931
|
-
return ran;
|
|
932
|
-
if (ran.value.exitCode !== 0)
|
|
933
|
-
return vendorFail("phone-harness", `${command.split(" ")[0]} on the phone failed: ${redactWords(ran.value.stderr.trim().split("\n")[0] || `exit code ${ran.value.exitCode}`)}`);
|
|
934
|
-
return ok(ran.value.stdout);
|
|
935
|
-
}
|
|
936
|
-
async call(method, params, options = {}) {
|
|
937
|
-
if (this.#closed)
|
|
938
|
-
return fail("gone", "the connection to the phone is closed");
|
|
939
|
-
if (options.signal?.aborted)
|
|
940
|
-
return fail("aborted", `${method} was aborted`);
|
|
941
|
-
return (await this.#answer(method, (params ?? {}), options.signal));
|
|
942
|
-
}
|
|
943
|
-
async #answer(method, params, signal) {
|
|
944
|
-
switch (method) {
|
|
945
|
-
case "hello":
|
|
946
|
-
return ok(this.#hello);
|
|
947
|
-
case "ping":
|
|
948
|
-
return ok({});
|
|
949
|
-
case "screen.shot":
|
|
950
|
-
return this.#shot(params.region);
|
|
951
|
-
case "screen.read":
|
|
952
|
-
return this.#read(params.id, params.offset);
|
|
953
|
-
case "screen.watch": {
|
|
954
|
-
const turn = this.#watching.then(() => this.#screenWatch(params, this.#either(signal)));
|
|
955
|
-
this.#watching = turn.catch(() => undefined);
|
|
956
|
-
return turn;
|
|
957
|
-
}
|
|
958
|
-
case "input.actions":
|
|
959
|
-
return this.#inTurn(params.actions, this.#either(signal));
|
|
960
|
-
case "apps.list":
|
|
961
|
-
return this.#appsList();
|
|
962
|
-
case "apps.launch":
|
|
963
|
-
return this.#launch(params.id);
|
|
964
|
-
case "apps.terminate":
|
|
965
|
-
return this.#terminate(params.id);
|
|
966
|
-
case "apps.ui_tree":
|
|
967
|
-
return this.#tree();
|
|
968
|
-
}
|
|
969
|
-
const group = method.split(".")[0];
|
|
970
|
-
if (["exec", "files", "process", "tar"].includes(group))
|
|
971
|
-
return refuse("unsupported", `${method}: a phone has no shell in the computer protocol, so it offers no exec, files or processes`);
|
|
972
|
-
if (method === "apps.install")
|
|
973
|
-
return refuse("unsupported", "apps.install: this phone takes no files to install from");
|
|
974
|
-
if (method === "deadline.extend")
|
|
975
|
-
return refuse("unsupported", "deadline.extend: a cloud phone's session ends when the phone harness says; it has no extend");
|
|
976
|
-
return refuse("unsupported", `${method} is not a method this phone answers`);
|
|
977
|
-
}
|
|
978
|
-
// --- screen --------------------------------------------------------------------------------------------------
|
|
979
|
-
async #shot(region) {
|
|
980
|
-
const raw = await this.#execOut("screencap");
|
|
981
|
-
if (!raw.ok)
|
|
982
|
-
return raw;
|
|
983
|
-
const frame = decodeScreencap(raw.value);
|
|
984
|
-
if (!frame.ok)
|
|
985
|
-
return frame;
|
|
986
|
-
const { width, height, rgba } = frame.value;
|
|
987
|
-
this.#size = [width, height];
|
|
988
|
-
let rect = [0, 0, width, height];
|
|
989
|
-
if (region !== undefined) {
|
|
990
|
-
const r = region;
|
|
991
|
-
if (!(Array.isArray(r) && r.length === 4 && r.every((v) => Number.isSafeInteger(v)) && r[0] >= 0 && r[1] >= 0 && r[2] > 0 && r[3] > 0 && r[0] + r[2] <= width && r[1] + r[3] <= height)) {
|
|
992
|
-
return refuse("invalid", `region ${show(region)} is not [x, y, w, h] inside the ${width}x${height} screen`);
|
|
993
|
-
}
|
|
994
|
-
rect = r;
|
|
1055
|
+
/** A file the provider puts on its phones, and its sha256, read once; not_found in the words missing gives. */
|
|
1056
|
+
#fileAt(path, missing) {
|
|
1057
|
+
let read = this.#files.get(path);
|
|
1058
|
+
if (read === undefined) {
|
|
1059
|
+
read = readFile(path).then((bytes) => ok({ path, sha256: createHash("sha256").update(bytes).digest("hex") }), (error) => {
|
|
1060
|
+
this.#files.delete(path);
|
|
1061
|
+
return fail("not_found", missing(error.code ?? error.message));
|
|
1062
|
+
});
|
|
1063
|
+
this.#files.set(path, read);
|
|
995
1064
|
}
|
|
996
|
-
|
|
997
|
-
// close() may have run while the frame was deflating: hold nothing for a closed connection.
|
|
998
|
-
if (this.#closed)
|
|
999
|
-
return fail("gone", "the connection to the phone is closed");
|
|
1000
|
-
const id = randomBytes(6).toString("hex");
|
|
1001
|
-
this.#held = { id, bytes };
|
|
1002
|
-
const data = bytes.subarray(0, MAX_CHUNK_BYTES);
|
|
1003
|
-
return ok({ id, size: bytes.length, data: data.toString("base64"), eof: data.length === bytes.length, width: rect[2], height: rect[3], scale: this.#scale });
|
|
1065
|
+
return read;
|
|
1004
1066
|
}
|
|
1005
1067
|
/**
|
|
1006
|
-
*
|
|
1007
|
-
*
|
|
1008
|
-
* than an idle one is polled. after is the caller's ack; an older one gets the newest frame at once, and one at the
|
|
1009
|
-
* newest waits for a change until waitMs passes. maxWidth scales the frame (nearest pixel); width and height stay the
|
|
1010
|
-
* screen's, the input space. quality is checked and has no effect on a PNG. The signal (the caller's cancel and the
|
|
1011
|
-
* connection's close) ends a screencap and a wait in flight.
|
|
1068
|
+
* Puts file on the phone at remote, a name that holds its sha256, only when the phone lacks it there: pushed beside
|
|
1069
|
+
* that name and then moved to it, so a file of that name is always whole. what names it in the errors.
|
|
1012
1070
|
*/
|
|
1013
|
-
async #
|
|
1014
|
-
const
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
if (!
|
|
1021
|
-
return
|
|
1022
|
-
if (
|
|
1023
|
-
return
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
const
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
return aborted();
|
|
1037
|
-
watch.read = this.now();
|
|
1038
|
-
const raw = await this.#execOut("screencap", signal);
|
|
1039
|
-
if (signal.aborted || this.#closed)
|
|
1040
|
-
return aborted();
|
|
1041
|
-
if (!raw.ok)
|
|
1042
|
-
return raw;
|
|
1043
|
-
const read = decodeScreencap(raw.value);
|
|
1044
|
-
if (!read.ok)
|
|
1045
|
-
return read;
|
|
1046
|
-
const { width, height, rgba } = read.value;
|
|
1047
|
-
this.#size = [width, height];
|
|
1048
|
-
// The size is in the digest: a phone turned to landscape may give the same pixels, the other way round.
|
|
1049
|
-
const digest = createHash("sha256").update(`${width}x${height}|`).update(rgba).digest("hex");
|
|
1050
|
-
if (watch.seq === 0 || digest !== watch.digest) {
|
|
1051
|
-
const frameWidth = Math.min(width, maxWidth);
|
|
1052
|
-
const frameHeight = Math.max(1, Math.floor((height * frameWidth) / width));
|
|
1053
|
-
const pixels = frameWidth === width ? rgba : scaleRgba(rgba, width, height, frameWidth, frameHeight);
|
|
1054
|
-
// Encoded before the frame is published: a watch that reads the seq while this one encodes never gets an older
|
|
1055
|
-
// frame under the newer seq.
|
|
1056
|
-
const bytes = await encodePng(pixels, frameWidth, [0, 0, frameWidth, frameHeight]);
|
|
1057
|
-
if (signal.aborted || this.#closed)
|
|
1058
|
-
return aborted();
|
|
1059
|
-
watch.seq += 1;
|
|
1060
|
-
watch.digest = digest;
|
|
1061
|
-
watch.frame = { bytes, frameWidth, frameHeight, width, height };
|
|
1062
|
-
return ok(this.#frameAnswer());
|
|
1063
|
-
}
|
|
1064
|
-
const left = deadline - this.now();
|
|
1065
|
-
if (left < WATCH_POLL_MS) {
|
|
1066
|
-
// Not another read before the wait is over: answer no change when it is.
|
|
1067
|
-
if (left > 0)
|
|
1068
|
-
await this.#pause(left, signal);
|
|
1069
|
-
if (signal.aborted || this.#closed)
|
|
1070
|
-
return aborted();
|
|
1071
|
-
return ok({ seq: watch.seq, changed: false, width, height });
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
/** The newest frame as screen.watch answers it: its first chunk, the rest held for screen.read. */
|
|
1076
|
-
#frameAnswer() {
|
|
1077
|
-
const { seq, frame } = this.#watch;
|
|
1078
|
-
const { bytes, frameWidth, frameHeight, width, height } = frame;
|
|
1079
|
-
const data = bytes.subarray(0, MAX_CHUNK_BYTES);
|
|
1080
|
-
const eof = data.length === bytes.length;
|
|
1081
|
-
const id = randomBytes(6).toString("hex");
|
|
1082
|
-
if (!eof)
|
|
1083
|
-
this.#watchHeld = { id, bytes };
|
|
1084
|
-
return { seq, changed: true, ...(eof ? {} : { id }), size: bytes.length, data: data.toString("base64"), eof, format: "png", frameWidth, frameHeight, width, height };
|
|
1085
|
-
}
|
|
1086
|
-
/** The rest of the shot or the watch frame held by id, from offset: each is dropped once read to its end. */
|
|
1087
|
-
#read(id, offset) {
|
|
1088
|
-
const frame = this.#watchHeld !== undefined && this.#watchHeld.id === id;
|
|
1089
|
-
const held = frame ? this.#watchHeld : this.#held;
|
|
1090
|
-
if (held === undefined || held.id !== id)
|
|
1091
|
-
return refuse("not_found", `no shot ${show(id)} is held: take one with screen.shot`);
|
|
1092
|
-
if (!(Number.isSafeInteger(offset) && offset >= 0 && offset <= held.bytes.length))
|
|
1093
|
-
return refuse("invalid", `offset ${show(offset)} is not inside the shot's ${held.bytes.length} bytes`);
|
|
1094
|
-
const data = held.bytes.subarray(offset, offset + MAX_CHUNK_BYTES);
|
|
1095
|
-
const eof = offset + data.length >= held.bytes.length;
|
|
1096
|
-
if (eof && frame)
|
|
1097
|
-
this.#watchHeld = undefined;
|
|
1098
|
-
else if (eof)
|
|
1099
|
-
this.#held = undefined;
|
|
1100
|
-
return ok({ data: data.toString("base64"), eof });
|
|
1071
|
+
async #place(transport, adb, onPhone, file, remote, what) {
|
|
1072
|
+
const have = await onPhone(`shell:sha256sum ${remote} 2>/dev/null`, transport);
|
|
1073
|
+
if (!have.ok)
|
|
1074
|
+
return have;
|
|
1075
|
+
if (have.value.startsWith(file.sha256))
|
|
1076
|
+
return ok(undefined);
|
|
1077
|
+
const pushed = await adb(["push", file.path, `${remote}.part`], { timeoutMs: PUSH_TIMEOUT_MS });
|
|
1078
|
+
if (!pushed.ok)
|
|
1079
|
+
return pushed;
|
|
1080
|
+
if (pushed.value.exitCode !== 0)
|
|
1081
|
+
return vendorFail("phone-harness", `adb push of ${what} to the phone failed: ${redactWords(pushed.value.stderr.trim().split("\n")[0] || `exit code ${pushed.value.exitCode}`)}`);
|
|
1082
|
+
// Checked before it takes its name: a file under that name is always whole.
|
|
1083
|
+
const landed = await onPhone(`shell:sha256sum ${remote}.part`, transport);
|
|
1084
|
+
if (!landed.ok)
|
|
1085
|
+
return landed;
|
|
1086
|
+
if (!landed.value.startsWith(file.sha256))
|
|
1087
|
+
return vendorFail("phone-harness", `${what} reached the phone changed: its sha256 there is not the file's (${redactWords(landed.value.trim().split("\n")[0] ?? "")})`);
|
|
1088
|
+
const moved = await onPhone(`shell:mv ${remote}.part ${remote} && echo moved`, transport);
|
|
1089
|
+
if (!moved.ok)
|
|
1090
|
+
return moved;
|
|
1091
|
+
if (moved.value.trim() !== "moved")
|
|
1092
|
+
return vendorFail("phone-harness", `${what} could not be put in place on the phone: ${redactWords(moved.value.trim().split("\n")[0] ?? "")}`);
|
|
1093
|
+
return ok(undefined);
|
|
1101
1094
|
}
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
gone = by;
|
|
1130
|
-
steps.push(`input motionevent MOVE ${point(p)}`);
|
|
1131
|
-
}
|
|
1132
|
-
steps.push(`input motionevent UP ${point(last)}`);
|
|
1133
|
-
return { commands: [steps.join(";")], busyMs: gone };
|
|
1134
|
-
}
|
|
1135
|
-
case "button":
|
|
1136
|
-
return { commands: [`input keyevent KEYCODE_${BUTTON_KEYS[action.name]}`] };
|
|
1137
|
-
case "type": {
|
|
1138
|
-
if (/[^\x20-\x7e\n]/.test(action.text))
|
|
1139
|
-
return { kind: "unsupported", message: "type: adb's input text takes printable ASCII and line breaks only" };
|
|
1140
|
-
const commands = [];
|
|
1141
|
-
for (const [i, line] of action.text.split("\n").entries()) {
|
|
1142
|
-
if (i > 0)
|
|
1143
|
-
commands.push("input keyevent KEYCODE_ENTER");
|
|
1144
|
-
// input text reads a % followed by s as a space, and nothing else. A space is sent as %s; a literal %s
|
|
1145
|
-
// is split across two calls, so its % ends one and its s starts the next and the two never meet.
|
|
1146
|
-
const pieces = line.split("%s");
|
|
1147
|
-
for (const [j, piece] of pieces.entries()) {
|
|
1148
|
-
const part = `${j > 0 ? "s" : ""}${piece}${j < pieces.length - 1 ? "%" : ""}`;
|
|
1149
|
-
if (part !== "")
|
|
1150
|
-
commands.push(`input text ${quote(part.replaceAll(" ", "%s"))}`);
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
return { commands };
|
|
1154
|
-
}
|
|
1155
|
-
case "key": {
|
|
1156
|
-
if (action.keys.length !== 1)
|
|
1157
|
-
return { kind: "unsupported", message: `key ${show(action.keys)}: a combo of keys is not something adb's input keyevent can press; send one key at a time` };
|
|
1158
|
-
const key = action.keys[0];
|
|
1159
|
-
const press = KEYCODES[key] ? `input keyevent KEYCODE_${KEYCODES[key]}` : /^[a-z0-9]$/.test(key) ? `input keyevent KEYCODE_${key.toUpperCase()}` : `input text ${quote(key)}`;
|
|
1160
|
-
return { commands: Array.from({ length: action.repeat ?? 1 }, () => press) };
|
|
1095
|
+
/**
|
|
1096
|
+
* The apks option's APKs, each put on the phone like phoned's jar and installed there with `pm install -r`, once per
|
|
1097
|
+
* phone: a marker beside it on the phone (<apk>.installed) says that phone installed those bytes, so a later connect,
|
|
1098
|
+
* which starts phoned afresh, installs nothing again.
|
|
1099
|
+
*/
|
|
1100
|
+
async #install(transport, adb, onPhone) {
|
|
1101
|
+
for (const path of this.#apks) {
|
|
1102
|
+
const what = `the APK ${basename(path)}`;
|
|
1103
|
+
const apk = await this.#fileAt(path, (why) => `${what}, which the provider's apks option names, is not at ${path} (${why})`);
|
|
1104
|
+
if (!apk.ok)
|
|
1105
|
+
return apk;
|
|
1106
|
+
const remote = `${PHONE_TMP}/apk-${apk.value.sha256.slice(0, 16)}.apk`;
|
|
1107
|
+
const done = await onPhone(`shell:test -e ${remote}.installed && echo installed`, transport);
|
|
1108
|
+
if (!done.ok)
|
|
1109
|
+
return done;
|
|
1110
|
+
if (done.value.trim() === "installed")
|
|
1111
|
+
continue;
|
|
1112
|
+
const placed = await this.#place(transport, adb, onPhone, apk.value, remote, what);
|
|
1113
|
+
if (!placed.ok)
|
|
1114
|
+
return placed;
|
|
1115
|
+
const installed = await onPhone(`shell:pm install -r ${remote} 2>&1`, transport);
|
|
1116
|
+
if (!installed.ok)
|
|
1117
|
+
return installed;
|
|
1118
|
+
// pm says Success on a line of its own, else Failure [INSTALL_FAILED_…: why].
|
|
1119
|
+
if (!/^Success$/m.test(installed.value)) {
|
|
1120
|
+
const said = installed.value.split("\n").find((line) => /Failure|Error|Exception/.test(line)) ?? installed.value.trim().split("\n")[0] ?? "";
|
|
1121
|
+
return vendorFail("phone-harness", `${what} did not install on the phone: ${redactWords(said.trim()) || "pm install answered nothing"}`);
|
|
1161
1122
|
}
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
return { kind: "unsupported", message: "hold: adb's input keyevent cannot keep a key down" };
|
|
1168
|
-
default:
|
|
1169
|
-
return { kind: "unsupported", message: `${action.type} is not an action this phone takes` };
|
|
1123
|
+
const marked = await onPhone(`shell:touch ${remote}.installed && echo marked`, transport);
|
|
1124
|
+
if (!marked.ok)
|
|
1125
|
+
return marked;
|
|
1126
|
+
if (marked.value.trim() !== "marked")
|
|
1127
|
+
return vendorFail("phone-harness", `${what} installed, and its marker could not be written on the phone: ${redactWords(marked.value.trim().split("\n")[0] ?? "")}`);
|
|
1170
1128
|
}
|
|
1129
|
+
return ok(undefined);
|
|
1171
1130
|
}
|
|
1172
|
-
/**
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1131
|
+
/**
|
|
1132
|
+
* Starts phoned on the phone and says hello, after installing the apks option's APKs. The jar goes to the phone under
|
|
1133
|
+
* its sha256 (#place). phoned runs as the shell user through app_process (scrcpy's way in), on adb's exec: service,
|
|
1134
|
+
* whose socket carries its stdin and stdout raw; its stderr goes to a log beside the jar. It starts once the
|
|
1135
|
+
* endpoint's last phoned is gone (#lastGone), and its pid is kept for the next start's wait.
|
|
1136
|
+
*/
|
|
1137
|
+
async #startPhoned(endpoint, transport, adb, onPhone, ended) {
|
|
1138
|
+
const installed = await this.#install(transport, adb, onPhone);
|
|
1139
|
+
if (!installed.ok)
|
|
1140
|
+
return installed;
|
|
1141
|
+
const jar = await this.#fileAt(this.#phonedPath, (why) => `phoned, the phone's driver, is not at ${this.#phonedPath} (${why}): build it with npm run build:phoned, or give the provider's phoned option`);
|
|
1142
|
+
if (!jar.ok)
|
|
1143
|
+
return jar;
|
|
1144
|
+
const remote = `${PHONE_TMP}/phoned-${jar.value.sha256.slice(0, 16)}.jar`;
|
|
1145
|
+
const placed = await this.#place(transport, adb, onPhone, jar.value, remote, "phoned");
|
|
1146
|
+
if (!placed.ok)
|
|
1147
|
+
return placed;
|
|
1148
|
+
const gone = await this.#lastGone(endpoint, transport, onPhone);
|
|
1149
|
+
if (!gone.ok)
|
|
1150
|
+
return gone;
|
|
1151
|
+
// sh writes its pid and start time, which app_process keeps as it takes sh's place by exec, to a file of this start's
|
|
1152
|
+
// own (the 22nd field of /proc/<pid>/stat is ${20} once its "<pid> (<name>) " is cut), read back after hello.
|
|
1153
|
+
const base = remote.slice(0, -".jar".length);
|
|
1154
|
+
const pidFile = `${base}-${randomBytes(4).toString("hex")}.pid`;
|
|
1155
|
+
const stream = await this.#adb.open(`exec:s=$(cat /proc/$$/stat); s=\${s##*") "}; set -- $s; echo $$ \${20} >${pidFile}; CLASSPATH=${remote} exec app_process / ai.agentrun.phoned.android.Main 2>${base}.log`, { timeoutMs: ADB_TIMEOUT_MS, transport });
|
|
1156
|
+
if (!stream.ok)
|
|
1157
|
+
return stream;
|
|
1158
|
+
const socket = stream.value;
|
|
1159
|
+
socket.once("close", ended);
|
|
1160
|
+
const client = new DaemonClient({ readable: socket, writable: socket });
|
|
1161
|
+
socket.resume();
|
|
1162
|
+
const end = async () => {
|
|
1163
|
+
if (socket.destroyed)
|
|
1164
|
+
return;
|
|
1165
|
+
const closed = new Promise((resolve) => socket.once("close", () => resolve()));
|
|
1166
|
+
client.close();
|
|
1167
|
+
await closed;
|
|
1168
|
+
};
|
|
1169
|
+
const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: this.#timeout(HELLO_TIMEOUT_MS) });
|
|
1170
|
+
// Read whether or not it said hello: one that did not may still run, and the next phoned here waits for it as well.
|
|
1171
|
+
const read = await onPhone(`shell:cat ${pidFile} && rm -f ${pidFile}`, transport);
|
|
1172
|
+
const said = read.ok ? read.value.trim() : "";
|
|
1173
|
+
const fields = /^([1-9][0-9]*) ([0-9]+)$/.exec(said);
|
|
1174
|
+
if (fields)
|
|
1175
|
+
this.#lastPhoned.set(endpoint, { pid: Number(fields[1]), start: fields[2] });
|
|
1176
|
+
if (!hello.ok) {
|
|
1177
|
+
await end();
|
|
1178
|
+
return vendorFail("phone-harness", `phoned did not say hello on the phone (${hello.error.code}: ${redactWords(hello.error.message)}); its log on the phone is ${base}.log`);
|
|
1186
1179
|
}
|
|
1187
|
-
|
|
1188
|
-
|
|
1180
|
+
if (!fields) {
|
|
1181
|
+
await end();
|
|
1182
|
+
const why = read.ok ? `it read ${show(redactWords(said.split("\n")[0] ?? ""))}` : redactWords(read.error.message);
|
|
1183
|
+
return vendorFail("phone-harness", `phoned said hello, and its process id could not be read back from the phone (${why}): without it the next phoned could start before this one lets go of the phone's accessibility`);
|
|
1189
1184
|
}
|
|
1185
|
+
return ok({ client, hello: hello.value, end });
|
|
1190
1186
|
}
|
|
1191
1187
|
/**
|
|
1192
|
-
*
|
|
1193
|
-
*
|
|
1194
|
-
*
|
|
1188
|
+
* Waits until the endpoint's last phoned is gone from the phone, and kills it when it outstays PHONED_EXIT_S. A phone
|
|
1189
|
+
* has one accessibility connection to give, and phoned holds it until it exits: a phoned started before then finds it
|
|
1190
|
+
* taken ("already registered" at its first ui call), so none starts while the last one runs.
|
|
1195
1191
|
*/
|
|
1196
|
-
#
|
|
1197
|
-
const
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
resolve(waitedOut());
|
|
1208
|
-
};
|
|
1209
|
-
signal.addEventListener("abort", stop, { once: true });
|
|
1210
|
-
if (signal.aborted)
|
|
1211
|
-
stop();
|
|
1212
|
-
turn.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
|
|
1213
|
-
});
|
|
1214
|
-
}
|
|
1215
|
-
async #actions(actions, signal) {
|
|
1216
|
-
const refused = checkActions(actions, PHONE_GROUPS);
|
|
1217
|
-
if (refused !== undefined)
|
|
1218
|
-
return ok({ done: 0, failed: refused });
|
|
1219
|
-
const list = actions;
|
|
1220
|
-
const plans = [];
|
|
1221
|
-
for (const [index, action] of list.entries()) {
|
|
1222
|
-
const plan = this.#commands(action);
|
|
1223
|
-
if ("kind" in plan)
|
|
1224
|
-
return ok({ done: 0, failed: { index, kind: plan.kind, message: `action ${index}: ${plan.message}` } });
|
|
1225
|
-
for (const at of pointsOf(action)) {
|
|
1226
|
-
if (at[0] < 0 || at[1] < 0 || at[0] >= this.#size[0] || at[1] >= this.#size[1]) {
|
|
1227
|
-
return ok({ done: 0, failed: { index, kind: "invalid", message: `action ${index}: ${show(at)} is off the ${this.#size[0]}x${this.#size[1]} screen` } });
|
|
1228
|
-
}
|
|
1229
|
-
}
|
|
1230
|
-
plans.push(plan);
|
|
1192
|
+
async #lastGone(endpoint, transport, onPhone) {
|
|
1193
|
+
const last = this.#lastPhoned.get(endpoint);
|
|
1194
|
+
if (last === undefined)
|
|
1195
|
+
return ok(undefined);
|
|
1196
|
+
const { pid } = last;
|
|
1197
|
+
const waited = await onPhone(`shell:${untilGone(last)}`, transport);
|
|
1198
|
+
if (!waited.ok)
|
|
1199
|
+
return waited;
|
|
1200
|
+
const said = waited.value.trim().split("\n").at(-1) ?? "";
|
|
1201
|
+
if (said === "running") {
|
|
1202
|
+
return vendorFail("phone-harness", `the phoned of this phone's last connection (pid ${pid}) did not exit within ${PHONED_EXIT_S} s, nor ${PHONED_KILL_S} s after a kill, and it holds the phone's accessibility: no phoned starts beside it; release this phone and create another`);
|
|
1231
1203
|
}
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
return cancelled(index);
|
|
1237
|
-
if (plan.waitMs !== undefined) {
|
|
1238
|
-
await this.#pause(plan.waitMs, signal);
|
|
1239
|
-
// A wait the cancel cut short is not done.
|
|
1240
|
-
if (signal?.aborted)
|
|
1241
|
-
return cancelled(index);
|
|
1242
|
-
}
|
|
1243
|
-
for (const command of plan.commands) {
|
|
1244
|
-
if (signal?.aborted)
|
|
1245
|
-
return cancelled(index);
|
|
1246
|
-
const ran = await this.#shell(command, signal, ADB_TIMEOUT_MS + (plan.busyMs ?? 0));
|
|
1247
|
-
if (!ran.ok) {
|
|
1248
|
-
const kind = ran.error.code === "timeout" || ran.error.code === "aborted" || ran.error.code === "not_found" ? ran.error.code : "invalid";
|
|
1249
|
-
return ok({ done: index, failed: { index, kind, message: `action ${index}: ${ran.error.message}` } });
|
|
1250
|
-
}
|
|
1251
|
-
}
|
|
1252
|
-
}
|
|
1253
|
-
return ok({ done: plans.length });
|
|
1254
|
-
}
|
|
1255
|
-
// --- apps ----------------------------------------------------------------------------------------------------
|
|
1256
|
-
async #foreground() {
|
|
1257
|
-
const out = await this.#shell("dumpsys activity activities");
|
|
1258
|
-
if (!out.ok)
|
|
1259
|
-
return out;
|
|
1260
|
-
const found = /topResumedActivity=ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(out.value) ?? /mResumedActivity: ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(out.value);
|
|
1261
|
-
return ok(found ? found[1] : null);
|
|
1262
|
-
}
|
|
1263
|
-
async #appsList() {
|
|
1264
|
-
const out = await this.#shell("pm list packages");
|
|
1265
|
-
if (!out.ok)
|
|
1266
|
-
return out;
|
|
1267
|
-
const apps = out.value
|
|
1268
|
-
.split("\n")
|
|
1269
|
-
.filter((line) => line.startsWith("package:"))
|
|
1270
|
-
.map((line) => ({ id: line.slice("package:".length).trim() }))
|
|
1271
|
-
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
1272
|
-
const foreground = await this.#foreground();
|
|
1273
|
-
if (!foreground.ok)
|
|
1274
|
-
return foreground;
|
|
1275
|
-
return ok({ apps, foreground: foreground.value });
|
|
1276
|
-
}
|
|
1277
|
-
async #launch(id) {
|
|
1278
|
-
if (typeof id !== "string" || !APP_ID.test(id))
|
|
1279
|
-
return refuse("invalid", `id ${show(id)} is not an Android package id`);
|
|
1280
|
-
const resolved = await this.#shell(`cmd package resolve-activity --brief -c android.intent.category.LAUNCHER ${id}`);
|
|
1281
|
-
if (!resolved.ok)
|
|
1282
|
-
return resolved;
|
|
1283
|
-
const component = resolved.value
|
|
1284
|
-
.split("\n")
|
|
1285
|
-
.map((line) => line.trim())
|
|
1286
|
-
.reverse()
|
|
1287
|
-
.find((line) => COMPONENT.test(line));
|
|
1288
|
-
if (component === undefined)
|
|
1289
|
-
return refuse("not_found", `${id} has no activity to launch: is it installed?`);
|
|
1290
|
-
// The app named comes to the front, not whatever its task last held: on Android 15 Settings' task keeps search (another
|
|
1291
|
-
// package) on top, and a plain start resumes it there. A cleared task starts the app itself (phone probe 2).
|
|
1292
|
-
const started = await this.#shell(`am start -W --activity-clear-task -n ${component}`);
|
|
1293
|
-
if (!started.ok)
|
|
1294
|
-
return started;
|
|
1295
|
-
if (/Error:|Exception/.test(started.value))
|
|
1296
|
-
return vendorFail("phone-harness", `am start of ${component}: ${redactWords(started.value.trim().split("\n").at(-1) ?? "")}`);
|
|
1297
|
-
return ok({});
|
|
1204
|
+
if (said !== "exited" && said !== "killed")
|
|
1205
|
+
return vendorFail("phone-harness", `the wait for the last phoned on the phone (pid ${pid}) to exit answered ${show(redactWords(said))}`);
|
|
1206
|
+
this.#lastPhoned.delete(endpoint);
|
|
1207
|
+
return ok(undefined);
|
|
1298
1208
|
}
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* One connection's client of the phone's shared phoned: calls go to phoned, and close lets this connection's hold of
|
|
1212
|
+
* the phone go. A call still running when its connection closes is cancelled (phoned gets $/cancelRequest); a later
|
|
1213
|
+
* one fails with gone.
|
|
1214
|
+
*/
|
|
1215
|
+
class PhoneClient {
|
|
1216
|
+
daemon;
|
|
1217
|
+
release;
|
|
1218
|
+
#closing = new AbortController();
|
|
1219
|
+
#gone = Promise.resolve();
|
|
1220
|
+
constructor(daemon,
|
|
1221
|
+
/** Lets this connection's hold of the phone go: the last one ends phoned and drops the adb transport. */
|
|
1222
|
+
release) {
|
|
1223
|
+
this.daemon = daemon;
|
|
1224
|
+
this.release = release;
|
|
1304
1225
|
}
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
const start = text.indexOf("<?xml");
|
|
1311
|
-
if (start < 0)
|
|
1312
|
-
return refuse("unsupported", `uiautomator gave no tree for this screen: ${redactWords(text.trim().split("\n")[0] || "nothing")}`);
|
|
1313
|
-
return parseUiTree(text.slice(start, text.lastIndexOf(">") + 1), this.#size);
|
|
1226
|
+
call(method, params, options = {}) {
|
|
1227
|
+
if (this.#closing.signal.aborted)
|
|
1228
|
+
return Promise.resolve(fail("gone", "the connection to the phone is closed"));
|
|
1229
|
+
const signal = options.signal ? AbortSignal.any([options.signal, this.#closing.signal]) : this.#closing.signal;
|
|
1230
|
+
return this.daemon.call(method, params, { signal });
|
|
1314
1231
|
}
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
if (action.type === "swipe")
|
|
1321
|
-
return action.path;
|
|
1322
|
-
return [];
|
|
1323
|
-
}
|
|
1324
|
-
/** The frame `adb exec-out screencap` gives: a header (width, height, format, and a color space on newer Androids), then the pixels. */
|
|
1325
|
-
export function decodeScreencap(raw) {
|
|
1326
|
-
if (raw.length < 12)
|
|
1327
|
-
return vendorFail("phone-harness", `screencap gave ${raw.length} bytes, not a frame`);
|
|
1328
|
-
const width = raw.readUInt32LE(0);
|
|
1329
|
-
const height = raw.readUInt32LE(4);
|
|
1330
|
-
const format = raw.readUInt32LE(8);
|
|
1331
|
-
const pixels = width * height * 4;
|
|
1332
|
-
const header = raw.length - pixels;
|
|
1333
|
-
if (!(width > 0 && height > 0 && (header === 12 || header === 16)))
|
|
1334
|
-
return vendorFail("phone-harness", `screencap gave ${raw.length} bytes for a ${width}x${height} frame`);
|
|
1335
|
-
const rgba = Buffer.from(raw.subarray(header));
|
|
1336
|
-
// 1 is RGBA_8888, 2 RGBX_8888 (alpha unset), 5 BGRA_8888.
|
|
1337
|
-
if (format === 2)
|
|
1338
|
-
for (let i = 3; i < rgba.length; i += 4)
|
|
1339
|
-
rgba[i] = 255;
|
|
1340
|
-
else if (format === 5)
|
|
1341
|
-
for (let i = 0; i < rgba.length; i += 4)
|
|
1342
|
-
[rgba[i], rgba[i + 2]] = [rgba[i + 2], rgba[i]];
|
|
1343
|
-
else if (format !== 1)
|
|
1344
|
-
return fail("unsupported", `screencap gave pixel format ${format}, which this provider does not read`);
|
|
1345
|
-
return ok({ width, height, rgba });
|
|
1346
|
-
}
|
|
1347
|
-
/** How often a waiting screen.watch reads a phone's screen: about once a second (the user-approved decision, 2026-11-09). */
|
|
1348
|
-
const WATCH_POLL_MS = 1_000;
|
|
1349
|
-
/** A width x height RGBA frame scaled to toWidth x toHeight by the nearest pixel. */
|
|
1350
|
-
function scaleRgba(rgba, width, height, toWidth, toHeight) {
|
|
1351
|
-
const out = Buffer.alloc(toWidth * toHeight * 4);
|
|
1352
|
-
for (let y = 0; y < toHeight; y++) {
|
|
1353
|
-
const sy = Math.floor((y * height) / toHeight);
|
|
1354
|
-
for (let x = 0; x < toWidth; x++) {
|
|
1355
|
-
const sx = Math.floor((x * width) / toWidth);
|
|
1356
|
-
rgba.copy(out, (y * toWidth + x) * 4, (sy * width + sx) * 4, (sy * width + sx) * 4 + 4);
|
|
1357
|
-
}
|
|
1232
|
+
close() {
|
|
1233
|
+
if (this.#closing.signal.aborted)
|
|
1234
|
+
return;
|
|
1235
|
+
this.#closing.abort();
|
|
1236
|
+
this.#gone = this.release().catch(() => undefined);
|
|
1358
1237
|
}
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
/** An 8-bit RGBA PNG, non-interlaced, of rect of a width-wide RGBA frame. The rows are deflated off the event loop: a
|
|
1364
|
-
* 1080x2400 screen took about 170 ms, every request of the server this harness runs in waiting on it. */
|
|
1365
|
-
export async function encodePng(rgba, width, [x, y, w, h]) {
|
|
1366
|
-
const rows = Buffer.alloc((w * 4 + 1) * h);
|
|
1367
|
-
for (let row = 0; row < h; row++) {
|
|
1368
|
-
const from = ((y + row) * width + x) * 4;
|
|
1369
|
-
rgba.copy(rows, row * (w * 4 + 1) + 1, from, from + w * 4);
|
|
1238
|
+
/** Closes, and waits until the phone's hold is let go (phoned ended and the transport dropped, when it was the last). */
|
|
1239
|
+
async closed() {
|
|
1240
|
+
this.close();
|
|
1241
|
+
await this.#gone;
|
|
1370
1242
|
}
|
|
1371
|
-
const chunk = (type, data) => {
|
|
1372
|
-
const length = Buffer.alloc(4);
|
|
1373
|
-
length.writeUInt32BE(data.length);
|
|
1374
|
-
const typed = Buffer.concat([Buffer.from(type, "latin1"), data]);
|
|
1375
|
-
const crc = Buffer.alloc(4);
|
|
1376
|
-
crc.writeUInt32BE(crc32(typed) >>> 0);
|
|
1377
|
-
return Buffer.concat([length, typed, crc]);
|
|
1378
|
-
};
|
|
1379
|
-
const ihdr = Buffer.alloc(13);
|
|
1380
|
-
ihdr.writeUInt32BE(w, 0);
|
|
1381
|
-
ihdr.writeUInt32BE(h, 4);
|
|
1382
|
-
ihdr.set([8, 6, 0, 0, 0], 8);
|
|
1383
|
-
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", await deflateAsync(rows)), chunk("IEND", Buffer.alloc(0))]);
|
|
1384
1243
|
}
|
|
1385
|
-
|
|
1386
|
-
const
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
let truncated = false;
|
|
1393
|
-
let dropped = 0;
|
|
1394
|
-
for (const tag of xml.matchAll(/<(\/?)node\b([^>]*?)(\/?)>/g)) {
|
|
1395
|
-
const [, closing, body, selfClosing] = tag;
|
|
1396
|
-
if (closing) {
|
|
1397
|
-
if (dropped > 0)
|
|
1398
|
-
dropped--;
|
|
1399
|
-
else
|
|
1400
|
-
stack.pop();
|
|
1401
|
-
continue;
|
|
1402
|
-
}
|
|
1403
|
-
if (dropped > 0 || nodes >= MAX_UI_NODES) {
|
|
1404
|
-
truncated = true;
|
|
1405
|
-
if (!selfClosing)
|
|
1406
|
-
dropped++;
|
|
1407
|
-
continue;
|
|
1408
|
-
}
|
|
1409
|
-
const attrs = {};
|
|
1410
|
-
for (const [, key, value] of body.matchAll(/([\w:-]+)="([^"]*)"/g))
|
|
1411
|
-
attrs[key] = unescape(value);
|
|
1412
|
-
const box = /^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(attrs.bounds ?? "");
|
|
1413
|
-
const [x1, y1, x2, y2] = box ? box.slice(1).map(Number) : [0, 0, 0, 0];
|
|
1414
|
-
const bool = (key) => attrs[key] === "true";
|
|
1415
|
-
const node = {
|
|
1416
|
-
role: attrs.class || "node",
|
|
1417
|
-
...(attrs["resource-id"] ? { id: attrs["resource-id"] } : {}),
|
|
1418
|
-
...(attrs.text ? { text: attrs.text } : {}),
|
|
1419
|
-
...(attrs["content-desc"] ? { label: attrs["content-desc"] } : {}),
|
|
1420
|
-
bounds: [x1, y1, Math.max(0, x2 - x1), Math.max(0, y2 - y1)],
|
|
1421
|
-
enabled: bool("enabled"),
|
|
1422
|
-
clickable: bool("clickable"),
|
|
1423
|
-
focused: bool("focused"),
|
|
1424
|
-
selected: bool("selected"),
|
|
1425
|
-
checked: bool("checked"),
|
|
1426
|
-
scrollable: bool("scrollable"),
|
|
1427
|
-
children: [],
|
|
1428
|
-
};
|
|
1429
|
-
nodes++;
|
|
1430
|
-
(stack.at(-1)?.children ?? top).push(node);
|
|
1431
|
-
if (!selfClosing)
|
|
1432
|
-
stack.push(node);
|
|
1433
|
-
}
|
|
1434
|
-
if (top.length === 0)
|
|
1435
|
-
return vendorFail("phone-harness", "uiautomator's dump held no node");
|
|
1436
|
-
if (top.length === 1)
|
|
1437
|
-
return ok({ root: top[0], nodes, truncated });
|
|
1438
|
-
return ok({ root: { role: "hierarchy", bounds: [0, 0, width, height], enabled: true, children: top }, nodes: nodes + 1, truncated });
|
|
1244
|
+
/** Whether labels carries every one of wanted. */
|
|
1245
|
+
const carries = (labels, wanted) => Object.entries(wanted ?? {}).every(([key, value]) => labels[key] === value);
|
|
1246
|
+
function sessionOf(json, where) {
|
|
1247
|
+
const s = json;
|
|
1248
|
+
if (typeof s !== "object" || s === null || typeof s.id !== "string" || typeof s.state !== "string")
|
|
1249
|
+
return vendorFail("phone-harness", `${where} answered ${show(json).slice(0, 200)}, not a session`);
|
|
1250
|
+
return ok(s);
|
|
1439
1251
|
}
|