@parcha/agentrun-computer 0.1.0-beta.35 → 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 +423 -323
- package/box/Dockerfile +3 -1
- package/box/agentrun-archil +59 -7
- package/box/build-agent37.mjs +177 -0
- package/box/build-daytona.py +20 -4
- 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/browser.d.ts +61 -10
- package/dist/browser.js +125 -3
- package/dist/browserbase.d.ts +46 -23
- package/dist/browserbase.js +162 -17
- package/dist/chrome.d.ts +3 -4
- package/dist/chrome.js +6 -11
- 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/daytona.d.ts +4 -0
- package/dist/conformance/daytona.js +5 -0
- 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 +15 -5
- package/dist/daytona.js +58 -38
- package/dist/descriptor.d.ts +29 -2
- package/dist/descriptor.js +13 -0
- package/dist/descriptors/agent37.d.ts +41 -0
- package/dist/descriptors/agent37.js +28 -0
- package/dist/descriptors/browserbase.d.ts +1 -0
- package/dist/descriptors/browserbase.js +2 -0
- package/dist/descriptors/daytona.d.ts +23 -2
- package/dist/descriptors/daytona.js +34 -2
- package/dist/descriptors/index.d.ts +66 -3
- package/dist/descriptors/index.js +5 -3
- package/dist/descriptors/kernel.d.ts +1 -0
- package/dist/descriptors/kernel.js +2 -0
- package/dist/descriptors/modal.d.ts +4 -0
- package/dist/descriptors/modal.js +11 -1
- package/dist/descriptors/orgo.d.ts +13 -1
- package/dist/descriptors/orgo.js +9 -3
- package/dist/descriptors/phone-harness.d.ts +6 -1
- package/dist/descriptors/phone-harness.js +5 -2
- package/dist/docker/egress.d.ts +4 -3
- package/dist/docker/egress.js +7 -6
- package/dist/docker.d.ts +7 -4
- package/dist/docker.js +278 -34
- 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 +11 -7
- package/dist/index.js +10 -7
- package/dist/janitor.d.ts +5 -4
- package/dist/janitor.js +1 -1
- package/dist/kernel.d.ts +17 -27
- package/dist/kernel.js +94 -18
- package/dist/kinds.d.ts +17 -5
- package/dist/kinds.js +20 -4
- package/dist/labels.d.ts +10 -2
- package/dist/labels.js +30 -7
- package/dist/local-chrome.d.ts +5 -5
- package/dist/local-chrome.js +10 -5
- package/dist/modal.d.ts +23 -181
- package/dist/modal.js +273 -1232
- package/dist/mount-archil.d.ts +25 -3
- package/dist/mount-archil.js +39 -8
- package/dist/orgo-channel.d.ts +3 -2
- package/dist/orgo-channel.js +5 -2
- package/dist/orgo-desktop.d.ts +23 -9
- package/dist/orgo-desktop.js +328 -66
- package/dist/orgo-names.d.ts +129 -3
- package/dist/orgo-names.js +211 -8
- package/dist/orgo-workspaces.d.ts +47 -0
- package/dist/orgo-workspaces.js +94 -0
- package/dist/orgo.d.ts +27 -10
- package/dist/orgo.js +411 -81
- package/dist/phone-harness.d.ts +31 -21
- package/dist/phone-harness.js +510 -681
- package/dist/png.d.ts +4 -0
- package/dist/png.js +27 -0
- package/dist/protocol.d.ts +338 -30
- package/dist/protocol.js +96 -3
- package/dist/provider.d.ts +97 -7
- package/dist/provider.js +24 -3
- 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,11 +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 {
|
|
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";
|
|
17
20
|
import { PHONE_GROUPS, PHONE_HARNESS } from "./descriptors/phone-harness.js";
|
|
18
|
-
import {
|
|
21
|
+
import { PROTOCOL_VERSION } from "./protocol.js";
|
|
19
22
|
import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
|
|
20
23
|
import { failFor, ok, vendorFail } from "./result.js";
|
|
21
24
|
import { daemonWatch, redactWords } from "./screen-watch.js";
|
|
@@ -38,14 +41,51 @@ const DEFAULT_REQUEST_MS = 30_000;
|
|
|
38
41
|
const ADB_TIMEOUT_MS = 30_000;
|
|
39
42
|
/** The user every shell command on an Android runs as: shell, 2000. */
|
|
40
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
|
+
}
|
|
41
68
|
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
42
69
|
/** The ledger's id for a create not answered yet. */
|
|
43
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
|
+
}
|
|
44
83
|
/** A ledger in this process's memory: the default, and enough for one process that makes and ends its phones. */
|
|
45
84
|
export function memoryLedger() {
|
|
46
85
|
const entries = new Map();
|
|
47
86
|
return {
|
|
48
87
|
put: (entry) => void entries.set(entry.id, structuredClone(entry)),
|
|
88
|
+
claim: (entry) => !entries.has(entry.id) && (entries.set(entry.id, structuredClone(entry)), true),
|
|
49
89
|
get: (id) => structuredClone(entries.get(id)),
|
|
50
90
|
list: () => [...entries.values()].map((entry) => structuredClone(entry)),
|
|
51
91
|
remove: (id) => void entries.delete(id),
|
|
@@ -66,6 +106,7 @@ function guardedLedger(ledger) {
|
|
|
66
106
|
};
|
|
67
107
|
return {
|
|
68
108
|
put: guard("written", (entry) => ledger.put(entry)),
|
|
109
|
+
claim: guard("written", (entry) => ledger.claim(entry)),
|
|
69
110
|
get: guard("read", (id) => ledger.get(id)),
|
|
70
111
|
list: guard("read", () => ledger.list()),
|
|
71
112
|
remove: guard("written", (id) => ledger.remove(id)),
|
|
@@ -118,15 +159,22 @@ export function adbCli(path = "adb", { port = ADB_SERVER_PORT, env } = {}) {
|
|
|
118
159
|
child.stdin?.end(input ?? "");
|
|
119
160
|
});
|
|
120
161
|
let started;
|
|
121
|
-
|
|
122
|
-
|
|
162
|
+
/** The adb server, started once: a failed start is tried again by the next request. */
|
|
163
|
+
const serverUp = async (timeoutMs) => {
|
|
123
164
|
started ??= run(["start-server"], { timeoutMs });
|
|
124
165
|
const start = await started;
|
|
125
166
|
if (!start.ok || start.value.exitCode !== 0) {
|
|
126
167
|
started = undefined;
|
|
127
168
|
return start.ok ? vendorFail("phone-harness", `adb start-server failed: ${start.value.stderr.trim().split("\n")[0] || `exit code ${start.value.exitCode}`}`) : start;
|
|
128
169
|
}
|
|
129
|
-
|
|
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;
|
|
130
178
|
return new Promise((resolve) => {
|
|
131
179
|
let buffer = Buffer.alloc(0);
|
|
132
180
|
let settled = false;
|
|
@@ -165,7 +213,69 @@ export function adbCli(path = "adb", { port = ADB_SERVER_PORT, env } = {}) {
|
|
|
165
213
|
});
|
|
166
214
|
});
|
|
167
215
|
};
|
|
168
|
-
|
|
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 };
|
|
169
279
|
}
|
|
170
280
|
/** A service as error words name it: its kind and first word, never the rest (a shell command's code, an endpoint). */
|
|
171
281
|
export function serviceWords(service) {
|
|
@@ -210,6 +320,12 @@ export class PhoneHarnessProvider {
|
|
|
210
320
|
#fetch;
|
|
211
321
|
#adb;
|
|
212
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();
|
|
213
329
|
#maxLifetimeMs;
|
|
214
330
|
#readyMs;
|
|
215
331
|
#pollMs;
|
|
@@ -222,6 +338,21 @@ export class PhoneHarnessProvider {
|
|
|
222
338
|
#holders = new Map();
|
|
223
339
|
/** Each endpoint's host:disconnect still on its way: a connect to that endpoint waits for it before its own. */
|
|
224
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();
|
|
225
356
|
constructor(options) {
|
|
226
357
|
const { apiKey, platform = "android" } = options ?? {};
|
|
227
358
|
if (typeof apiKey !== "string" || apiKey === "")
|
|
@@ -234,9 +365,14 @@ export class PhoneHarnessProvider {
|
|
|
234
365
|
this.#baseUrl = (options.baseUrl ?? PHONE_HARNESS_URL).replace(/\/+$/, "");
|
|
235
366
|
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
236
367
|
const adb = options.adb;
|
|
237
|
-
if (adb !== undefined && typeof adb !== "string" && !(typeof adb?.run === "function" && typeof adb?.server === "function")) {
|
|
238
|
-
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()");
|
|
239
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];
|
|
240
376
|
this.#adb = adb === undefined || typeof adb === "string" ? adbCli(adb ?? "adb") : adb;
|
|
241
377
|
this.#ledger = guardedLedger(options.ledger ?? memoryLedger());
|
|
242
378
|
this.#maxLifetimeMs = options.maxLifetimeMs ?? DEFAULT_MAX_LIFETIME_MS;
|
|
@@ -377,12 +513,102 @@ export class PhoneHarnessProvider {
|
|
|
377
513
|
await this.#ledger.remove(id);
|
|
378
514
|
return ok(undefined);
|
|
379
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
|
+
}
|
|
380
524
|
#deadlineOf(session, fallback) {
|
|
381
525
|
return new Date(typeof session.expires_at === "number" && Number.isFinite(session.expires_at) ? session.expires_at * 1000 : fallback).toISOString();
|
|
382
526
|
}
|
|
383
527
|
// --- the provider ----------------------------------------------------------------------------------------------
|
|
384
|
-
|
|
385
|
-
|
|
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
|
+
}
|
|
386
612
|
}
|
|
387
613
|
attach(ref, context = {}) {
|
|
388
614
|
return ledgerSafe(() => this.#attach(ref, context));
|
|
@@ -407,18 +633,40 @@ export class PhoneHarnessProvider {
|
|
|
407
633
|
watch(ref, handlers, options) {
|
|
408
634
|
return daemonWatch(this, ref, handlers, options);
|
|
409
635
|
}
|
|
410
|
-
async #create(spec,
|
|
411
|
-
const refusals = this.check(spec);
|
|
412
|
-
if (refusals.length > 0)
|
|
413
|
-
return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
|
|
636
|
+
async #create(spec, name, requestKey, signal) {
|
|
414
637
|
if (signal?.aborted)
|
|
415
638
|
return fail("aborted", "create was aborted before the phone harness was asked");
|
|
416
|
-
const
|
|
417
|
-
const requestKey = randomBytes(16).toString("hex");
|
|
639
|
+
const looked = this.#now();
|
|
418
640
|
const body = { platform: "android", kind: "emulator", timeout_seconds: Math.ceil(runLifetimeMs(spec) / 1000) };
|
|
419
|
-
// 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.
|
|
420
647
|
const pending = pendingId(requestKey);
|
|
421
|
-
|
|
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();
|
|
422
670
|
const posted = await this.#api("POST", "/sessions", { body, headers: { "Idempotency-Key": requestKey }, ...(signal ? { signal } : {}) });
|
|
423
671
|
const cancelled = !posted.ok && posted.error.code === "aborted";
|
|
424
672
|
let first = posted.ok ? sessionOf(posted.value.json, "POST /sessions") : undefined;
|
|
@@ -440,6 +688,7 @@ export class PhoneHarnessProvider {
|
|
|
440
688
|
else if (!posted.ok) {
|
|
441
689
|
// The phone harness refused the request: nothing was made, and the key is forgotten.
|
|
442
690
|
await this.#ledger.remove(pending);
|
|
691
|
+
this.#claimed.delete(requestKey);
|
|
443
692
|
return posted;
|
|
444
693
|
}
|
|
445
694
|
if (first === undefined || !first.ok)
|
|
@@ -459,54 +708,43 @@ export class PhoneHarnessProvider {
|
|
|
459
708
|
}
|
|
460
709
|
};
|
|
461
710
|
const named = await record(async () => {
|
|
462
|
-
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)) });
|
|
463
712
|
await this.#ledger.remove(pending);
|
|
713
|
+
this.#claimed.delete(requestKey);
|
|
464
714
|
});
|
|
465
715
|
if (!named.ok)
|
|
466
716
|
return named;
|
|
467
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);
|
|
468
720
|
const gone = await this.#end(id);
|
|
469
721
|
return fail(code, `${words}; ${gone.ok ? "it was ended" : `it could not be ended (${gone.error.message})`}`);
|
|
470
722
|
};
|
|
471
723
|
if (cancelled)
|
|
472
724
|
return ended("aborted", `create was aborted during POST /sessions, after the service made the phone ${id}`);
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
// A read takes no longer than readyMs has left, so a stalled one cannot hold create past it.
|
|
478
|
-
const left = this.#readyMs - (this.#now() - from);
|
|
479
|
-
const bound = Math.max(1, Math.min(this.#requestMs, left));
|
|
480
|
-
const read = await this.#session(id, signal, bound);
|
|
481
|
-
if (!read.ok && read.error.code === "timeout") {
|
|
482
|
-
// A read cut off by its own bound (requestMs) while readyMs has time left is one slow answer, not the deadline:
|
|
483
|
-
// ask again. Only a read bounded by what readyMs had left, or the deadline check below, ends the phone.
|
|
484
|
-
if (bound < left && this.#now() - from < this.#readyMs) {
|
|
485
|
-
await this.#sleep(this.#pollMs);
|
|
486
|
-
continue;
|
|
487
|
-
}
|
|
488
|
-
return ended("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s: ${read.error.message}`);
|
|
489
|
-
}
|
|
490
|
-
if (!read.ok)
|
|
491
|
-
return ended(read.error.code === "gone" ? "vendor" : read.error.code, `the phone ${id} did not start: ${read.error.message}`);
|
|
492
|
-
session = read.value;
|
|
493
|
-
if (session.state === "ready")
|
|
494
|
-
break;
|
|
495
|
-
if (session.state !== "provisioning")
|
|
496
|
-
return ended("vendor", `the phone ${id} did not start: ${this.#clean(session.error ?? session.state)}`);
|
|
497
|
-
if (this.#now() - from >= this.#readyMs)
|
|
498
|
-
return ended("timeout", `the phone ${id} was not ready within ${this.#readyMs / 1000} s`);
|
|
499
|
-
await this.#sleep(this.#pollMs);
|
|
500
|
-
}
|
|
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;
|
|
501
729
|
const deadline = this.#deadlineOf(session, from + runLifetimeMs(spec));
|
|
502
|
-
|
|
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
|
+
});
|
|
503
739
|
if (!kept.ok)
|
|
504
740
|
return kept;
|
|
741
|
+
if (released)
|
|
742
|
+
return fail("exists", endedWords(name));
|
|
505
743
|
const took = this.#now() - from;
|
|
506
744
|
if (this.#now() >= Date.parse(deadline)) {
|
|
507
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)`);
|
|
508
746
|
}
|
|
509
|
-
return ok({ id, name
|
|
747
|
+
return ok({ id, name });
|
|
510
748
|
}
|
|
511
749
|
async #attach(ref, { signal } = {}) {
|
|
512
750
|
let entry;
|
|
@@ -531,13 +769,13 @@ export class PhoneHarnessProvider {
|
|
|
531
769
|
const session = await this.#session(id, signal);
|
|
532
770
|
if (!session.ok) {
|
|
533
771
|
if (session.error.code === "gone")
|
|
534
|
-
await this.#
|
|
772
|
+
await this.#forget(entry);
|
|
535
773
|
return session;
|
|
536
774
|
}
|
|
537
775
|
if (session.value.state !== "ready" && session.value.state !== "provisioning")
|
|
538
776
|
return fail("gone", `${id} is ${session.value.state}`);
|
|
539
777
|
const deadline = new Date(this.#deadlineOf(session.value, Date.parse(entry.deadline)));
|
|
540
|
-
return ok({ id, name:
|
|
778
|
+
return ok({ id, name: entry.name, spec: { image: entry.image, user: SHELL_USER, network: "open", deadline, kind: "android" } });
|
|
541
779
|
}
|
|
542
780
|
/**
|
|
543
781
|
* Settings' test: one GET /sessions, the account's sessions joined to the ledger, and a GET of any phone of the
|
|
@@ -579,7 +817,7 @@ export class PhoneHarnessProvider {
|
|
|
579
817
|
await this.#ledger.remove(listed.id);
|
|
580
818
|
continue;
|
|
581
819
|
}
|
|
582
|
-
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)) };
|
|
583
821
|
await this.#ledger.put(entry);
|
|
584
822
|
await this.#ledger.remove(listed.id);
|
|
585
823
|
}
|
|
@@ -587,11 +825,11 @@ export class PhoneHarnessProvider {
|
|
|
587
825
|
// Released, and being ended: never listed. Forgotten once the listing leaves it out and its own GET is a 404,
|
|
588
826
|
// or once its deadline has passed.
|
|
589
827
|
if (this.#now() > Date.parse(entry.deadline))
|
|
590
|
-
await this.#
|
|
828
|
+
await this.#forget(entry);
|
|
591
829
|
else if (!live.has(entry.id)) {
|
|
592
830
|
const read = await this.#session(entry.id, signal);
|
|
593
831
|
if (!read.ok && read.error.code === "gone")
|
|
594
|
-
await this.#
|
|
832
|
+
await this.#forget(entry);
|
|
595
833
|
}
|
|
596
834
|
continue;
|
|
597
835
|
}
|
|
@@ -600,7 +838,7 @@ export class PhoneHarnessProvider {
|
|
|
600
838
|
// Not in the listing: its own GET says whether the service ended it (404), and only then is it forgotten.
|
|
601
839
|
const read = await this.#session(entry.id, signal);
|
|
602
840
|
if (!read.ok && read.error.code === "gone") {
|
|
603
|
-
await this.#
|
|
841
|
+
await this.#forget(entry);
|
|
604
842
|
continue;
|
|
605
843
|
}
|
|
606
844
|
if (!read.ok)
|
|
@@ -610,7 +848,7 @@ export class PhoneHarnessProvider {
|
|
|
610
848
|
if (!carries(entry.labels, labels) || out.some((info) => info.ref.id === entry.id))
|
|
611
849
|
continue;
|
|
612
850
|
out.push({
|
|
613
|
-
ref: { id: entry.id, name: entry.
|
|
851
|
+
ref: { id: entry.id, name: entry.name },
|
|
614
852
|
labels: { ...entry.labels },
|
|
615
853
|
deadline: new Date(this.#deadlineOf(session, Date.parse(entry.deadline))),
|
|
616
854
|
state: session.state === "ready" || session.state === "provisioning" ? "running" : "stopped",
|
|
@@ -635,6 +873,9 @@ export class PhoneHarnessProvider {
|
|
|
635
873
|
if (how !== "delete")
|
|
636
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`);
|
|
637
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);
|
|
638
879
|
if (entry?.released !== undefined) {
|
|
639
880
|
// Released already, and the service may still be ending it: ok. Its own GET says whether it is gone, and then it is
|
|
640
881
|
// forgotten; a phone the service still holds running is sent its DELETE again.
|
|
@@ -725,7 +966,15 @@ export class PhoneHarnessProvider {
|
|
|
725
966
|
if (left > 0)
|
|
726
967
|
return void this.#holders.set(endpoint, left);
|
|
727
968
|
this.#holders.delete(endpoint);
|
|
728
|
-
|
|
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}`))
|
|
729
978
|
.catch(() => undefined)
|
|
730
979
|
.finally(() => {
|
|
731
980
|
if (this.#leaving.get(endpoint) === leaving)
|
|
@@ -776,647 +1025,227 @@ export class PhoneHarnessProvider {
|
|
|
776
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}`));
|
|
777
1026
|
}
|
|
778
1027
|
}
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
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);
|
|
784
1040
|
}
|
|
785
|
-
const
|
|
786
|
-
if (
|
|
787
|
-
|
|
788
|
-
|
|
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);
|
|
789
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);
|
|
790
1053
|
return ok({ client, hello, close: () => client.closed() });
|
|
791
1054
|
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
// --- the client: the protocol over adb ---------------------------------------------------------------------------
|
|
802
|
-
/** Android's keycode for each key name in KEYS. */
|
|
803
|
-
const KEYCODES = {
|
|
804
|
-
enter: "ENTER",
|
|
805
|
-
tab: "TAB",
|
|
806
|
-
space: "SPACE",
|
|
807
|
-
backspace: "DEL",
|
|
808
|
-
delete: "FORWARD_DEL",
|
|
809
|
-
escape: "ESCAPE",
|
|
810
|
-
insert: "INSERT",
|
|
811
|
-
up: "DPAD_UP",
|
|
812
|
-
down: "DPAD_DOWN",
|
|
813
|
-
left: "DPAD_LEFT",
|
|
814
|
-
right: "DPAD_RIGHT",
|
|
815
|
-
home: "MOVE_HOME",
|
|
816
|
-
end: "MOVE_END",
|
|
817
|
-
pageup: "PAGE_UP",
|
|
818
|
-
pagedown: "PAGE_DOWN",
|
|
819
|
-
shift: "SHIFT_LEFT",
|
|
820
|
-
ctrl: "CTRL_LEFT",
|
|
821
|
-
alt: "ALT_LEFT",
|
|
822
|
-
super: "META_LEFT",
|
|
823
|
-
capslock: "CAPS_LOCK",
|
|
824
|
-
...Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`f${i + 1}`, `F${i + 1}`])),
|
|
825
|
-
};
|
|
826
|
-
const BUTTON_KEYS = { back: "BACK", home: "HOME", app_switch: "APP_SWITCH" };
|
|
827
|
-
const refuse = (code, message) => fail(code, message);
|
|
828
|
-
/** The in-process client of one cloud Android: each protocol method is one or more adb commands. */
|
|
829
|
-
class AdbClient {
|
|
830
|
-
transport;
|
|
831
|
-
adb;
|
|
832
|
-
disconnect;
|
|
833
|
-
sleep;
|
|
834
|
-
now;
|
|
835
|
-
#closed = false;
|
|
836
|
-
#hello;
|
|
837
|
-
#size = [0, 0];
|
|
838
|
-
#scale = 1;
|
|
839
|
-
/** The shot held for screen.read, until read to its end or the next shot. */
|
|
840
|
-
#held;
|
|
841
|
-
/** The newest watch frame's rest, held apart from the shot's (as computerd's is), so neither evicts the other. */
|
|
842
|
-
#watchHeld;
|
|
843
|
-
/**
|
|
844
|
-
* screen.watch's state: the newest frame's seq, what it was read from (a digest of the pixels), the frame, and when
|
|
845
|
-
* the screen was last read (read, by now()).
|
|
846
|
-
*/
|
|
847
|
-
#watch = {
|
|
848
|
-
seq: 0,
|
|
849
|
-
digest: "",
|
|
850
|
-
read: Number.NEGATIVE_INFINITY,
|
|
851
|
-
};
|
|
852
|
-
/** One screen.watch at a time on this connection. */
|
|
853
|
-
#watching = Promise.resolve();
|
|
854
|
-
/** One input.actions batch at a time on this connection: a second waits for the first, whole. */
|
|
855
|
-
#inputs = Promise.resolve();
|
|
856
|
-
/** Fires on close: every adb run and wait in flight ends with it, so a close never waits for the phone. */
|
|
857
|
-
#closing = new AbortController();
|
|
858
|
-
/** The disconnect close started, which the connection's close waits for. */
|
|
859
|
-
#gone = Promise.resolve();
|
|
860
|
-
constructor(
|
|
861
|
-
/** The adb server's transport id of the phone: no secret, so it may be in an argv. */
|
|
862
|
-
transport, adb,
|
|
863
|
-
/** Lets the adb server drop the phone's transport, by its endpoint over the server's socket. */
|
|
864
|
-
disconnect, sleep, now) {
|
|
865
|
-
this.transport = transport;
|
|
866
|
-
this.adb = adb;
|
|
867
|
-
this.disconnect = disconnect;
|
|
868
|
-
this.sleep = sleep;
|
|
869
|
-
this.now = now;
|
|
870
|
-
}
|
|
871
|
-
/** What the phone is: its ABI, its screen's size and density; then the hello it answers. */
|
|
872
|
-
async open(version) {
|
|
873
|
-
const abi = await this.#shell("getprop ro.product.cpu.abi");
|
|
874
|
-
if (!abi.ok)
|
|
875
|
-
return abi;
|
|
876
|
-
const size = await this.#shell("wm size");
|
|
877
|
-
if (!size.ok)
|
|
878
|
-
return size;
|
|
879
|
-
const density = await this.#shell("wm density");
|
|
880
|
-
if (!density.ok)
|
|
881
|
-
return density;
|
|
882
|
-
const sizes = [...size.value.matchAll(/(\d+)x(\d+)/g)];
|
|
883
|
-
const last = sizes.at(-1);
|
|
884
|
-
if (!last)
|
|
885
|
-
return vendorFail("phone-harness", `the phone (adb transport ${this.transport}) did not say its screen's size: ${size.value.trim().slice(0, 100)}`);
|
|
886
|
-
this.#size = [Number(last[1]), Number(last[2])];
|
|
887
|
-
const dpi = [...density.value.matchAll(/(\d+)/g)].at(-1);
|
|
888
|
-
this.#scale = dpi ? Number(dpi[1]) / 160 : 1;
|
|
889
|
-
const reported = abi.value.trim();
|
|
890
|
-
this.#hello = { protocol: PROTOCOL_VERSION, version, os: "android", kind: "android", arch: ARCH[reported] ?? reported, groups: [...PHONE_GROUPS] };
|
|
891
|
-
return ok(this.#hello);
|
|
892
|
-
}
|
|
893
|
-
close() {
|
|
894
|
-
if (this.#closed)
|
|
895
|
-
return;
|
|
896
|
-
this.#closed = true;
|
|
897
|
-
this.#held = undefined;
|
|
898
|
-
this.#watchHeld = undefined;
|
|
899
|
-
this.#closing.abort();
|
|
900
|
-
this.#gone = this.disconnect().catch(() => undefined);
|
|
901
|
-
}
|
|
902
|
-
/** Closes, and waits until the adb server has let the phone's transport go. */
|
|
903
|
-
async closed() {
|
|
904
|
-
this.close();
|
|
905
|
-
await this.#gone;
|
|
906
|
-
}
|
|
907
|
-
/** The caller's signal and the connection's close, as one signal. */
|
|
908
|
-
#either(signal) {
|
|
909
|
-
return signal ? AbortSignal.any([signal, this.#closing.signal]) : this.#closing.signal;
|
|
910
|
-
}
|
|
911
|
-
/** One shell command on the phone: its stdout, or the failure in words (adb's, redacted: it names the endpoint). */
|
|
912
|
-
async #shell(command, signal, timeoutMs) {
|
|
913
|
-
const ran = await this.adb(["shell", command], { signal: this.#either(signal), ...(timeoutMs === undefined ? {} : { timeoutMs }) });
|
|
914
|
-
if (!ran.ok)
|
|
915
|
-
return ran;
|
|
916
|
-
if (ran.value.exitCode !== 0) {
|
|
917
|
-
const why = (ran.value.stderr.trim() || ran.value.stdout.toString("utf8").trim()).split("\n")[0] || `exit code ${ran.value.exitCode}`;
|
|
918
|
-
return vendorFail("phone-harness", `${command.split(" ").slice(0, 2).join(" ")} on the phone failed: ${redactWords(why)}`);
|
|
919
|
-
}
|
|
920
|
-
return ok(ran.value.stdout.toString("utf8"));
|
|
921
|
-
}
|
|
922
|
-
async #execOut(command, signal) {
|
|
923
|
-
const ran = await this.adb(["exec-out", command], { timeoutMs: 60_000, signal: this.#either(signal) });
|
|
924
|
-
if (!ran.ok)
|
|
925
|
-
return ran;
|
|
926
|
-
if (ran.value.exitCode !== 0)
|
|
927
|
-
return vendorFail("phone-harness", `${command.split(" ")[0]} on the phone failed: ${redactWords(ran.value.stderr.trim().split("\n")[0] || `exit code ${ran.value.exitCode}`)}`);
|
|
928
|
-
return ok(ran.value.stdout);
|
|
929
|
-
}
|
|
930
|
-
async call(method, params, options = {}) {
|
|
931
|
-
if (this.#closed)
|
|
932
|
-
return fail("gone", "the connection to the phone is closed");
|
|
933
|
-
if (options.signal?.aborted)
|
|
934
|
-
return fail("aborted", `${method} was aborted`);
|
|
935
|
-
return (await this.#answer(method, (params ?? {}), options.signal));
|
|
936
|
-
}
|
|
937
|
-
async #answer(method, params, signal) {
|
|
938
|
-
switch (method) {
|
|
939
|
-
case "hello":
|
|
940
|
-
return ok(this.#hello);
|
|
941
|
-
case "ping":
|
|
942
|
-
return ok({});
|
|
943
|
-
case "screen.shot":
|
|
944
|
-
return this.#shot(params.region);
|
|
945
|
-
case "screen.read":
|
|
946
|
-
return this.#read(params.id, params.offset);
|
|
947
|
-
case "screen.watch": {
|
|
948
|
-
const turn = this.#watching.then(() => this.#screenWatch(params, this.#either(signal)));
|
|
949
|
-
this.#watching = turn.catch(() => undefined);
|
|
950
|
-
return turn;
|
|
951
|
-
}
|
|
952
|
-
case "input.actions":
|
|
953
|
-
return this.#inTurn(params.actions, this.#either(signal));
|
|
954
|
-
case "apps.list":
|
|
955
|
-
return this.#appsList();
|
|
956
|
-
case "apps.launch":
|
|
957
|
-
return this.#launch(params.id);
|
|
958
|
-
case "apps.terminate":
|
|
959
|
-
return this.#terminate(params.id);
|
|
960
|
-
case "apps.ui_tree":
|
|
961
|
-
return this.#tree();
|
|
962
|
-
}
|
|
963
|
-
const group = method.split(".")[0];
|
|
964
|
-
if (["exec", "files", "process", "tar"].includes(group))
|
|
965
|
-
return refuse("unsupported", `${method}: a phone has no shell in the computer protocol, so it offers no exec, files or processes`);
|
|
966
|
-
if (method === "apps.install")
|
|
967
|
-
return refuse("unsupported", "apps.install: this phone takes no files to install from");
|
|
968
|
-
if (method === "deadline.extend")
|
|
969
|
-
return refuse("unsupported", "deadline.extend: a cloud phone's session ends when the phone harness says; it has no extend");
|
|
970
|
-
return refuse("unsupported", `${method} is not a method this phone answers`);
|
|
971
|
-
}
|
|
972
|
-
// --- screen --------------------------------------------------------------------------------------------------
|
|
973
|
-
async #shot(region) {
|
|
974
|
-
const raw = await this.#execOut("screencap");
|
|
975
|
-
if (!raw.ok)
|
|
976
|
-
return raw;
|
|
977
|
-
const frame = decodeScreencap(raw.value);
|
|
978
|
-
if (!frame.ok)
|
|
979
|
-
return frame;
|
|
980
|
-
const { width, height, rgba } = frame.value;
|
|
981
|
-
this.#size = [width, height];
|
|
982
|
-
let rect = [0, 0, width, height];
|
|
983
|
-
if (region !== undefined) {
|
|
984
|
-
const r = region;
|
|
985
|
-
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)) {
|
|
986
|
-
return refuse("invalid", `region ${show(region)} is not [x, y, w, h] inside the ${width}x${height} screen`);
|
|
987
|
-
}
|
|
988
|
-
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);
|
|
989
1064
|
}
|
|
990
|
-
|
|
991
|
-
const id = randomBytes(6).toString("hex");
|
|
992
|
-
this.#held = { id, bytes };
|
|
993
|
-
const data = bytes.subarray(0, MAX_CHUNK_BYTES);
|
|
994
|
-
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;
|
|
995
1066
|
}
|
|
996
1067
|
/**
|
|
997
|
-
*
|
|
998
|
-
*
|
|
999
|
-
* 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
|
|
1000
|
-
* newest waits for a change until waitMs passes. maxWidth scales the frame (nearest pixel); width and height stay the
|
|
1001
|
-
* screen's, the input space. quality is checked and has no effect on a PNG. The signal (the caller's cancel and the
|
|
1002
|
-
* 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.
|
|
1003
1070
|
*/
|
|
1004
|
-
async #
|
|
1005
|
-
const
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
if (!
|
|
1012
|
-
return
|
|
1013
|
-
if (
|
|
1014
|
-
return
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
const
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
return aborted();
|
|
1028
|
-
watch.read = this.now();
|
|
1029
|
-
const raw = await this.#execOut("screencap", signal);
|
|
1030
|
-
if (signal.aborted || this.#closed)
|
|
1031
|
-
return aborted();
|
|
1032
|
-
if (!raw.ok)
|
|
1033
|
-
return raw;
|
|
1034
|
-
const read = decodeScreencap(raw.value);
|
|
1035
|
-
if (!read.ok)
|
|
1036
|
-
return read;
|
|
1037
|
-
const { width, height, rgba } = read.value;
|
|
1038
|
-
this.#size = [width, height];
|
|
1039
|
-
// The size is in the digest: a phone turned to landscape may give the same pixels, the other way round.
|
|
1040
|
-
const digest = createHash("sha256").update(`${width}x${height}|`).update(rgba).digest("hex");
|
|
1041
|
-
if (watch.seq === 0 || digest !== watch.digest) {
|
|
1042
|
-
const frameWidth = Math.min(width, maxWidth);
|
|
1043
|
-
const frameHeight = Math.max(1, Math.floor((height * frameWidth) / width));
|
|
1044
|
-
const pixels = frameWidth === width ? rgba : scaleRgba(rgba, width, height, frameWidth, frameHeight);
|
|
1045
|
-
watch.seq += 1;
|
|
1046
|
-
watch.digest = digest;
|
|
1047
|
-
watch.frame = { bytes: encodePng(pixels, frameWidth, [0, 0, frameWidth, frameHeight]), frameWidth, frameHeight, width, height };
|
|
1048
|
-
return ok(this.#frameAnswer());
|
|
1049
|
-
}
|
|
1050
|
-
const left = deadline - this.now();
|
|
1051
|
-
if (left < WATCH_POLL_MS) {
|
|
1052
|
-
// Not another read before the wait is over: answer no change when it is.
|
|
1053
|
-
if (left > 0)
|
|
1054
|
-
await this.#pause(left, signal);
|
|
1055
|
-
if (signal.aborted || this.#closed)
|
|
1056
|
-
return aborted();
|
|
1057
|
-
return ok({ seq: watch.seq, changed: false, width, height });
|
|
1058
|
-
}
|
|
1059
|
-
}
|
|
1060
|
-
}
|
|
1061
|
-
/** The newest frame as screen.watch answers it: its first chunk, the rest held for screen.read. */
|
|
1062
|
-
#frameAnswer() {
|
|
1063
|
-
const { seq, frame } = this.#watch;
|
|
1064
|
-
const { bytes, frameWidth, frameHeight, width, height } = frame;
|
|
1065
|
-
const data = bytes.subarray(0, MAX_CHUNK_BYTES);
|
|
1066
|
-
const eof = data.length === bytes.length;
|
|
1067
|
-
const id = randomBytes(6).toString("hex");
|
|
1068
|
-
if (!eof)
|
|
1069
|
-
this.#watchHeld = { id, bytes };
|
|
1070
|
-
return { seq, changed: true, ...(eof ? {} : { id }), size: bytes.length, data: data.toString("base64"), eof, format: "png", frameWidth, frameHeight, width, height };
|
|
1071
|
-
}
|
|
1072
|
-
/** The rest of the shot or the watch frame held by id, from offset: each is dropped once read to its end. */
|
|
1073
|
-
#read(id, offset) {
|
|
1074
|
-
const frame = this.#watchHeld !== undefined && this.#watchHeld.id === id;
|
|
1075
|
-
const held = frame ? this.#watchHeld : this.#held;
|
|
1076
|
-
if (held === undefined || held.id !== id)
|
|
1077
|
-
return refuse("not_found", `no shot ${show(id)} is held: take one with screen.shot`);
|
|
1078
|
-
if (!(Number.isSafeInteger(offset) && offset >= 0 && offset <= held.bytes.length))
|
|
1079
|
-
return refuse("invalid", `offset ${show(offset)} is not inside the shot's ${held.bytes.length} bytes`);
|
|
1080
|
-
const data = held.bytes.subarray(offset, offset + MAX_CHUNK_BYTES);
|
|
1081
|
-
const eof = offset + data.length >= held.bytes.length;
|
|
1082
|
-
if (eof && frame)
|
|
1083
|
-
this.#watchHeld = undefined;
|
|
1084
|
-
else if (eof)
|
|
1085
|
-
this.#held = undefined;
|
|
1086
|
-
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);
|
|
1087
1094
|
}
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
gone = by;
|
|
1116
|
-
steps.push(`input motionevent MOVE ${point(p)}`);
|
|
1117
|
-
}
|
|
1118
|
-
steps.push(`input motionevent UP ${point(last)}`);
|
|
1119
|
-
return { commands: [steps.join(";")], busyMs: gone };
|
|
1120
|
-
}
|
|
1121
|
-
case "button":
|
|
1122
|
-
return { commands: [`input keyevent KEYCODE_${BUTTON_KEYS[action.name]}`] };
|
|
1123
|
-
case "type": {
|
|
1124
|
-
if (/[^\x20-\x7e\n]/.test(action.text))
|
|
1125
|
-
return { kind: "unsupported", message: "type: adb's input text takes printable ASCII and line breaks only" };
|
|
1126
|
-
const commands = [];
|
|
1127
|
-
for (const [i, line] of action.text.split("\n").entries()) {
|
|
1128
|
-
if (i > 0)
|
|
1129
|
-
commands.push("input keyevent KEYCODE_ENTER");
|
|
1130
|
-
// input text reads a % followed by s as a space, and nothing else. A space is sent as %s; a literal %s
|
|
1131
|
-
// is split across two calls, so its % ends one and its s starts the next and the two never meet.
|
|
1132
|
-
const pieces = line.split("%s");
|
|
1133
|
-
for (const [j, piece] of pieces.entries()) {
|
|
1134
|
-
const part = `${j > 0 ? "s" : ""}${piece}${j < pieces.length - 1 ? "%" : ""}`;
|
|
1135
|
-
if (part !== "")
|
|
1136
|
-
commands.push(`input text ${quote(part.replaceAll(" ", "%s"))}`);
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
return { commands };
|
|
1140
|
-
}
|
|
1141
|
-
case "key": {
|
|
1142
|
-
if (action.keys.length !== 1)
|
|
1143
|
-
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` };
|
|
1144
|
-
const key = action.keys[0];
|
|
1145
|
-
const press = KEYCODES[key] ? `input keyevent KEYCODE_${KEYCODES[key]}` : /^[a-z0-9]$/.test(key) ? `input keyevent KEYCODE_${key.toUpperCase()}` : `input text ${quote(key)}`;
|
|
1146
|
-
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"}`);
|
|
1147
1122
|
}
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
return { kind: "unsupported", message: "hold: adb's input keyevent cannot keep a key down" };
|
|
1154
|
-
default:
|
|
1155
|
-
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] ?? "")}`);
|
|
1156
1128
|
}
|
|
1129
|
+
return ok(undefined);
|
|
1157
1130
|
}
|
|
1158
|
-
/**
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
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`);
|
|
1172
1179
|
}
|
|
1173
|
-
|
|
1174
|
-
|
|
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`);
|
|
1175
1184
|
}
|
|
1185
|
+
return ok({ client, hello: hello.value, end });
|
|
1176
1186
|
}
|
|
1177
1187
|
/**
|
|
1178
|
-
*
|
|
1179
|
-
*
|
|
1180
|
-
*
|
|
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.
|
|
1181
1191
|
*/
|
|
1182
|
-
#
|
|
1183
|
-
const
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
resolve(waitedOut());
|
|
1194
|
-
};
|
|
1195
|
-
signal.addEventListener("abort", stop, { once: true });
|
|
1196
|
-
if (signal.aborted)
|
|
1197
|
-
stop();
|
|
1198
|
-
turn.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
|
|
1199
|
-
});
|
|
1200
|
-
}
|
|
1201
|
-
async #actions(actions, signal) {
|
|
1202
|
-
const refused = checkActions(actions, PHONE_GROUPS);
|
|
1203
|
-
if (refused !== undefined)
|
|
1204
|
-
return ok({ done: 0, failed: refused });
|
|
1205
|
-
const list = actions;
|
|
1206
|
-
const plans = [];
|
|
1207
|
-
for (const [index, action] of list.entries()) {
|
|
1208
|
-
const plan = this.#commands(action);
|
|
1209
|
-
if ("kind" in plan)
|
|
1210
|
-
return ok({ done: 0, failed: { index, kind: plan.kind, message: `action ${index}: ${plan.message}` } });
|
|
1211
|
-
for (const at of pointsOf(action)) {
|
|
1212
|
-
if (at[0] < 0 || at[1] < 0 || at[0] >= this.#size[0] || at[1] >= this.#size[1]) {
|
|
1213
|
-
return ok({ done: 0, failed: { index, kind: "invalid", message: `action ${index}: ${show(at)} is off the ${this.#size[0]}x${this.#size[1]} screen` } });
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
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`);
|
|
1217
1203
|
}
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
return cancelled(index);
|
|
1223
|
-
if (plan.waitMs !== undefined) {
|
|
1224
|
-
await this.#pause(plan.waitMs, signal);
|
|
1225
|
-
// A wait the cancel cut short is not done.
|
|
1226
|
-
if (signal?.aborted)
|
|
1227
|
-
return cancelled(index);
|
|
1228
|
-
}
|
|
1229
|
-
for (const command of plan.commands) {
|
|
1230
|
-
if (signal?.aborted)
|
|
1231
|
-
return cancelled(index);
|
|
1232
|
-
const ran = await this.#shell(command, signal, ADB_TIMEOUT_MS + (plan.busyMs ?? 0));
|
|
1233
|
-
if (!ran.ok) {
|
|
1234
|
-
const kind = ran.error.code === "timeout" || ran.error.code === "aborted" || ran.error.code === "not_found" ? ran.error.code : "invalid";
|
|
1235
|
-
return ok({ done: index, failed: { index, kind, message: `action ${index}: ${ran.error.message}` } });
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
return ok({ done: plans.length });
|
|
1240
|
-
}
|
|
1241
|
-
// --- apps ----------------------------------------------------------------------------------------------------
|
|
1242
|
-
async #foreground() {
|
|
1243
|
-
const out = await this.#shell("dumpsys activity activities");
|
|
1244
|
-
if (!out.ok)
|
|
1245
|
-
return out;
|
|
1246
|
-
const found = /topResumedActivity=ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(out.value) ?? /mResumedActivity: ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(out.value);
|
|
1247
|
-
return ok(found ? found[1] : null);
|
|
1248
|
-
}
|
|
1249
|
-
async #appsList() {
|
|
1250
|
-
const out = await this.#shell("pm list packages");
|
|
1251
|
-
if (!out.ok)
|
|
1252
|
-
return out;
|
|
1253
|
-
const apps = out.value
|
|
1254
|
-
.split("\n")
|
|
1255
|
-
.filter((line) => line.startsWith("package:"))
|
|
1256
|
-
.map((line) => ({ id: line.slice("package:".length).trim() }))
|
|
1257
|
-
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
1258
|
-
const foreground = await this.#foreground();
|
|
1259
|
-
if (!foreground.ok)
|
|
1260
|
-
return foreground;
|
|
1261
|
-
return ok({ apps, foreground: foreground.value });
|
|
1262
|
-
}
|
|
1263
|
-
async #launch(id) {
|
|
1264
|
-
if (typeof id !== "string" || !APP_ID.test(id))
|
|
1265
|
-
return refuse("invalid", `id ${show(id)} is not an Android package id`);
|
|
1266
|
-
const resolved = await this.#shell(`cmd package resolve-activity --brief -c android.intent.category.LAUNCHER ${id}`);
|
|
1267
|
-
if (!resolved.ok)
|
|
1268
|
-
return resolved;
|
|
1269
|
-
const component = resolved.value
|
|
1270
|
-
.split("\n")
|
|
1271
|
-
.map((line) => line.trim())
|
|
1272
|
-
.reverse()
|
|
1273
|
-
.find((line) => COMPONENT.test(line));
|
|
1274
|
-
if (component === undefined)
|
|
1275
|
-
return refuse("not_found", `${id} has no activity to launch: is it installed?`);
|
|
1276
|
-
// The app named comes to the front, not whatever its task last held: on Android 15 Settings' task keeps search (another
|
|
1277
|
-
// package) on top, and a plain start resumes it there. A cleared task starts the app itself (phone probe 2).
|
|
1278
|
-
const started = await this.#shell(`am start -W --activity-clear-task -n ${component}`);
|
|
1279
|
-
if (!started.ok)
|
|
1280
|
-
return started;
|
|
1281
|
-
if (/Error:|Exception/.test(started.value))
|
|
1282
|
-
return vendorFail("phone-harness", `am start of ${component}: ${redactWords(started.value.trim().split("\n").at(-1) ?? "")}`);
|
|
1283
|
-
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);
|
|
1284
1208
|
}
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
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;
|
|
1290
1225
|
}
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
const start = text.indexOf("<?xml");
|
|
1297
|
-
if (start < 0)
|
|
1298
|
-
return refuse("unsupported", `uiautomator gave no tree for this screen: ${redactWords(text.trim().split("\n")[0] || "nothing")}`);
|
|
1299
|
-
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 });
|
|
1300
1231
|
}
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
if (action.type === "swipe")
|
|
1307
|
-
return action.path;
|
|
1308
|
-
return [];
|
|
1309
|
-
}
|
|
1310
|
-
/** The frame `adb exec-out screencap` gives: a header (width, height, format, and a color space on newer Androids), then the pixels. */
|
|
1311
|
-
export function decodeScreencap(raw) {
|
|
1312
|
-
if (raw.length < 12)
|
|
1313
|
-
return vendorFail("phone-harness", `screencap gave ${raw.length} bytes, not a frame`);
|
|
1314
|
-
const width = raw.readUInt32LE(0);
|
|
1315
|
-
const height = raw.readUInt32LE(4);
|
|
1316
|
-
const format = raw.readUInt32LE(8);
|
|
1317
|
-
const pixels = width * height * 4;
|
|
1318
|
-
const header = raw.length - pixels;
|
|
1319
|
-
if (!(width > 0 && height > 0 && (header === 12 || header === 16)))
|
|
1320
|
-
return vendorFail("phone-harness", `screencap gave ${raw.length} bytes for a ${width}x${height} frame`);
|
|
1321
|
-
const rgba = Buffer.from(raw.subarray(header));
|
|
1322
|
-
// 1 is RGBA_8888, 2 RGBX_8888 (alpha unset), 5 BGRA_8888.
|
|
1323
|
-
if (format === 2)
|
|
1324
|
-
for (let i = 3; i < rgba.length; i += 4)
|
|
1325
|
-
rgba[i] = 255;
|
|
1326
|
-
else if (format === 5)
|
|
1327
|
-
for (let i = 0; i < rgba.length; i += 4)
|
|
1328
|
-
[rgba[i], rgba[i + 2]] = [rgba[i + 2], rgba[i]];
|
|
1329
|
-
else if (format !== 1)
|
|
1330
|
-
return fail("unsupported", `screencap gave pixel format ${format}, which this provider does not read`);
|
|
1331
|
-
return ok({ width, height, rgba });
|
|
1332
|
-
}
|
|
1333
|
-
/** How often a waiting screen.watch reads a phone's screen: about once a second (the user-approved decision, 2026-11-09). */
|
|
1334
|
-
const WATCH_POLL_MS = 1_000;
|
|
1335
|
-
/** A width x height RGBA frame scaled to toWidth x toHeight by the nearest pixel. */
|
|
1336
|
-
function scaleRgba(rgba, width, height, toWidth, toHeight) {
|
|
1337
|
-
const out = Buffer.alloc(toWidth * toHeight * 4);
|
|
1338
|
-
for (let y = 0; y < toHeight; y++) {
|
|
1339
|
-
const sy = Math.floor((y * height) / toHeight);
|
|
1340
|
-
for (let x = 0; x < toWidth; x++) {
|
|
1341
|
-
const sx = Math.floor((x * width) / toWidth);
|
|
1342
|
-
rgba.copy(out, (y * toWidth + x) * 4, (sy * width + sx) * 4, (sy * width + sx) * 4 + 4);
|
|
1343
|
-
}
|
|
1232
|
+
close() {
|
|
1233
|
+
if (this.#closing.signal.aborted)
|
|
1234
|
+
return;
|
|
1235
|
+
this.#closing.abort();
|
|
1236
|
+
this.#gone = this.release().catch(() => undefined);
|
|
1344
1237
|
}
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
const rows = Buffer.alloc((w * 4 + 1) * h);
|
|
1350
|
-
for (let row = 0; row < h; row++) {
|
|
1351
|
-
const from = ((y + row) * width + x) * 4;
|
|
1352
|
-
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;
|
|
1353
1242
|
}
|
|
1354
|
-
const chunk = (type, data) => {
|
|
1355
|
-
const length = Buffer.alloc(4);
|
|
1356
|
-
length.writeUInt32BE(data.length);
|
|
1357
|
-
const typed = Buffer.concat([Buffer.from(type, "latin1"), data]);
|
|
1358
|
-
const crc = Buffer.alloc(4);
|
|
1359
|
-
crc.writeUInt32BE(crc32(typed) >>> 0);
|
|
1360
|
-
return Buffer.concat([length, typed, crc]);
|
|
1361
|
-
};
|
|
1362
|
-
const ihdr = Buffer.alloc(13);
|
|
1363
|
-
ihdr.writeUInt32BE(w, 0);
|
|
1364
|
-
ihdr.writeUInt32BE(h, 4);
|
|
1365
|
-
ihdr.set([8, 6, 0, 0, 0], 8);
|
|
1366
|
-
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(rows)), chunk("IEND", Buffer.alloc(0))]);
|
|
1367
1243
|
}
|
|
1368
|
-
|
|
1369
|
-
const
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
let truncated = false;
|
|
1376
|
-
let dropped = 0;
|
|
1377
|
-
for (const tag of xml.matchAll(/<(\/?)node\b([^>]*?)(\/?)>/g)) {
|
|
1378
|
-
const [, closing, body, selfClosing] = tag;
|
|
1379
|
-
if (closing) {
|
|
1380
|
-
if (dropped > 0)
|
|
1381
|
-
dropped--;
|
|
1382
|
-
else
|
|
1383
|
-
stack.pop();
|
|
1384
|
-
continue;
|
|
1385
|
-
}
|
|
1386
|
-
if (dropped > 0 || nodes >= MAX_UI_NODES) {
|
|
1387
|
-
truncated = true;
|
|
1388
|
-
if (!selfClosing)
|
|
1389
|
-
dropped++;
|
|
1390
|
-
continue;
|
|
1391
|
-
}
|
|
1392
|
-
const attrs = {};
|
|
1393
|
-
for (const [, key, value] of body.matchAll(/([\w:-]+)="([^"]*)"/g))
|
|
1394
|
-
attrs[key] = unescape(value);
|
|
1395
|
-
const box = /^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$/.exec(attrs.bounds ?? "");
|
|
1396
|
-
const [x1, y1, x2, y2] = box ? box.slice(1).map(Number) : [0, 0, 0, 0];
|
|
1397
|
-
const bool = (key) => attrs[key] === "true";
|
|
1398
|
-
const node = {
|
|
1399
|
-
role: attrs.class || "node",
|
|
1400
|
-
...(attrs["resource-id"] ? { id: attrs["resource-id"] } : {}),
|
|
1401
|
-
...(attrs.text ? { text: attrs.text } : {}),
|
|
1402
|
-
...(attrs["content-desc"] ? { label: attrs["content-desc"] } : {}),
|
|
1403
|
-
bounds: [x1, y1, Math.max(0, x2 - x1), Math.max(0, y2 - y1)],
|
|
1404
|
-
enabled: bool("enabled"),
|
|
1405
|
-
clickable: bool("clickable"),
|
|
1406
|
-
focused: bool("focused"),
|
|
1407
|
-
selected: bool("selected"),
|
|
1408
|
-
checked: bool("checked"),
|
|
1409
|
-
scrollable: bool("scrollable"),
|
|
1410
|
-
children: [],
|
|
1411
|
-
};
|
|
1412
|
-
nodes++;
|
|
1413
|
-
(stack.at(-1)?.children ?? top).push(node);
|
|
1414
|
-
if (!selfClosing)
|
|
1415
|
-
stack.push(node);
|
|
1416
|
-
}
|
|
1417
|
-
if (top.length === 0)
|
|
1418
|
-
return vendorFail("phone-harness", "uiautomator's dump held no node");
|
|
1419
|
-
if (top.length === 1)
|
|
1420
|
-
return ok({ root: top[0], nodes, truncated });
|
|
1421
|
-
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);
|
|
1422
1251
|
}
|