emd-agents 0.16.2 → 0.17.0

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.
Files changed (52) hide show
  1. package/README.md +31 -21
  2. package/dist/adapters/expo/index.js +17 -5
  3. package/dist/adapters/gradle/index.d.ts +3 -0
  4. package/dist/adapters/gradle/index.js +63 -0
  5. package/dist/adapters/xcode/index.d.ts +16 -0
  6. package/dist/adapters/xcode/index.js +116 -0
  7. package/dist/cli/main.js +17 -2
  8. package/dist/core/adapter.d.ts +12 -5
  9. package/dist/core/adapter.js +1 -1
  10. package/dist/core/buildrecord.d.ts +5 -0
  11. package/dist/core/buildrecord.js +22 -0
  12. package/dist/core/check.d.ts +4 -2
  13. package/dist/core/check.js +22 -9
  14. package/dist/core/device/adb.d.ts +23 -0
  15. package/dist/core/device/adb.js +128 -0
  16. package/dist/core/device/backend.d.ts +1 -1
  17. package/dist/core/device/backend.js +18 -2
  18. package/dist/core/doctor.d.ts +6 -1
  19. package/dist/core/doctor.js +100 -19
  20. package/dist/core/emulator.d.ts +29 -0
  21. package/dist/core/emulator.js +144 -0
  22. package/dist/core/gc.d.ts +1 -0
  23. package/dist/core/gc.js +6 -0
  24. package/dist/core/index.d.ts +2 -0
  25. package/dist/core/index.js +2 -0
  26. package/dist/core/input.d.ts +3 -0
  27. package/dist/core/input.js +7 -2
  28. package/dist/core/launch.d.ts +5 -0
  29. package/dist/core/launch.js +332 -69
  30. package/dist/core/log.d.ts +2 -0
  31. package/dist/core/log.js +20 -9
  32. package/dist/core/logs.d.ts +1 -0
  33. package/dist/core/logs.js +32 -17
  34. package/dist/core/owned.d.ts +1 -1
  35. package/dist/core/probe.d.ts +1 -0
  36. package/dist/core/probe.js +22 -8
  37. package/dist/core/process.d.ts +1 -0
  38. package/dist/core/process.js +30 -1
  39. package/dist/core/registry.js +2 -0
  40. package/dist/core/reload.d.ts +1 -1
  41. package/dist/core/reload.js +14 -7
  42. package/dist/core/result.d.ts +23 -0
  43. package/dist/core/result.js +7 -0
  44. package/dist/core/run.d.ts +2 -0
  45. package/dist/core/run.js +2 -0
  46. package/dist/core/setup.d.ts +1 -0
  47. package/dist/core/setup.js +9 -3
  48. package/dist/core/tool.d.ts +1 -0
  49. package/dist/core/tool.js +5 -0
  50. package/dist/mcp/server.js +21 -5
  51. package/package.json +2 -2
  52. package/skills/emd/SKILL.md +8 -3
@@ -1,12 +1,11 @@
1
1
  import { mkdirSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { dropped, readRecord, writeRecord, } from "./checkrecord.js";
4
- import { axeBackend } from "./device/axe.js";
5
4
  import { detectEnvironment, readScreen, } from "./device/backend.js";
6
- import { maestroBackend } from "./device/maestro.js";
7
5
  import { hasElement } from "./device/screen.js";
6
+ import { screenshot as emulatorScreenshot } from "./emulator.js";
8
7
  import { recordCheck, evidence as writeEvidence } from "./evidence.js";
9
- import { swipe, tap, typeText } from "./input.js";
8
+ import { backendsFor, swipe, tap, typeText } from "./input.js";
10
9
  import { firstLine } from "./log.js";
11
10
  import { allLines, tagPattern, } from "./logs.js";
12
11
  import { worktreeKey } from "./owned.js";
@@ -25,12 +24,18 @@ const realDeps = {
25
24
  // Measured by the result's `waited` in the e2e log. A tap through AXe
26
25
  // returns at once, and in 2 of 2 e2e runs the check after it waited 5 s.
27
26
  recheckSeconds: 10,
27
+ // In e2e run 45103213436 a line reached the log more than 2.5 s after the
28
+ // app wrote it, while the screen already showed the change.
29
+ logGraceSeconds: 5,
28
30
  logs: allLines,
29
31
  evidence: (ref) => writeEvidence(ref),
30
32
  act: runAction,
31
- screen: async (device) => readScreen(device, await detectEnvironment(), [axeBackend, maestroBackend]),
32
- screenshot: async (device, path) => {
33
+ screen: async (device, platform) => readScreen(device, await detectEnvironment(), backendsFor(platform)),
34
+ screenshot: async (device, path, platform) => {
33
35
  mkdirSync(dirname(path), { recursive: true });
36
+ if (platform === "android") {
37
+ return emulatorScreenshot(device, path).then(() => undefined, (error) => `adb screencap: ${firstLine(error)}`);
38
+ }
34
39
  const shoot = (extra) => runTool("simctl screenshot", "xcrun", ["simctl", "io", device, "screenshot", ...extra, path], 60);
35
40
  const attempt = (extra) => shoot(extra).then(() => undefined, (error) => String(error));
36
41
  const first = await attempt([]);
@@ -92,7 +97,7 @@ export async function check(options, report = () => { }, deps = realDeps) {
92
97
  const resolved = resolveRun(options);
93
98
  if ("reason" in resolved)
94
99
  return error(resolved.reason);
95
- const { device, root, logDir } = resolved.run;
100
+ const { device, root, logDir, platform } = resolved.run;
96
101
  // Failed checks count per worktree, across relaunches, because a fix
97
102
  // usually means launching again.
98
103
  const key = worktreeKey(root);
@@ -154,7 +159,7 @@ export async function check(options, report = () => { }, deps = realDeps) {
154
159
  let screen;
155
160
  const readTheScreen = async () => {
156
161
  try {
157
- screen = await deps.screen(device);
162
+ screen = await deps.screen(device, platform);
158
163
  }
159
164
  catch (failure) {
160
165
  return `Could not read the screen: ${firstLine(failure)}`;
@@ -176,6 +181,8 @@ export async function check(options, report = () => { }, deps = realDeps) {
176
181
  // Read, then read again what is still missing until the limit, so a check
177
182
  // run a moment after an action doesn't fail on a line still on its way.
178
183
  const started = Date.now();
184
+ let deadline = started + deps.recheckSeconds * 1000;
185
+ let shown = false;
179
186
  let logResults = [];
180
187
  let elementResults = [];
181
188
  for (let first = true;; first = false) {
@@ -194,8 +201,14 @@ export async function check(options, report = () => { }, deps = realDeps) {
194
201
  return error(failure);
195
202
  }
196
203
  ({ logs: logResults, elements: elementResults } = judge());
204
+ if (!shown &&
205
+ elementSpecs.length > 0 &&
206
+ elementResults.every((r) => r.found)) {
207
+ shown = true;
208
+ deadline = Math.max(deadline, Date.now() + deps.logGraceSeconds * 1000);
209
+ }
197
210
  const missing = [...logResults, ...elementResults].some((r) => !r.found);
198
- if (!missing || Date.now() - started >= deps.recheckSeconds * 1000)
211
+ if (!missing || Date.now() >= deadline)
199
212
  break;
200
213
  await timed("wait", () => new Promise((resolve) => setTimeout(resolve, 1000)));
201
214
  }
@@ -205,7 +218,7 @@ export async function check(options, report = () => { }, deps = realDeps) {
205
218
  report("taking a screenshot");
206
219
  const stamp = Date.now();
207
220
  const shotPath = join(logDir, `check-${stamp}.png`);
208
- const shotError = await timed("screenshot", () => deps.screenshot(device, shotPath));
221
+ const shotError = await timed("screenshot", () => deps.screenshot(device, shotPath, platform));
209
222
  const shot = shotError === undefined ? shotPath : undefined;
210
223
  // What the screen reader got, next to the screenshot, for when they disagree.
211
224
  if (screen) {
@@ -0,0 +1,23 @@
1
+ import type { DeviceBackend, Direction } from "./backend.js";
2
+ import type { UiNode } from "./screen.js";
3
+ type Bounds = {
4
+ x1: number;
5
+ y1: number;
6
+ x2: number;
7
+ y2: number;
8
+ };
9
+ type AdbNode = UiNode & {
10
+ bounds?: Bounds;
11
+ };
12
+ export declare function parseDump(xml: string): AdbNode[];
13
+ export declare function inputText(text: string): string;
14
+ export declare function screenSize(stdout: string): {
15
+ width: number;
16
+ height: number;
17
+ };
18
+ export declare function swipeLine({ width, height }: {
19
+ width: number;
20
+ height: number;
21
+ }, direction: Direction): number[];
22
+ export declare const adbBackend: DeviceBackend;
23
+ export {};
@@ -0,0 +1,128 @@
1
+ import { runTool } from "../tool.js";
2
+ const entities = {
3
+ amp: "&",
4
+ lt: "<",
5
+ gt: ">",
6
+ quot: '"',
7
+ apos: "'",
8
+ };
9
+ const decode = (value) => value.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (whole, name) => {
10
+ if (name.startsWith("#x"))
11
+ return String.fromCodePoint(Number.parseInt(name.slice(2), 16));
12
+ if (name.startsWith("#"))
13
+ return String.fromCodePoint(Number(name.slice(1)));
14
+ return entities[name] ?? whole;
15
+ });
16
+ // The nodes of a `uiautomator dump`, with their bounds. A node's id is its
17
+ // resource-id without a "package:id/" prefix: a Compose test tag (with
18
+ // testTagsAsResourceId) or a View's id name. Its texts are text and
19
+ // content-desc.
20
+ export function parseDump(xml) {
21
+ const nodes = [];
22
+ // Quoted values may hold ">", so a tag ends at the first ">" outside quotes.
23
+ for (const [, attrs = ""] of xml.matchAll(/<node\b((?:[^>"]|"[^"]*")*)>/g)) {
24
+ const attr = (name) => decode(attrs.match(new RegExp(`\\s${name}="([^"]*)"`))?.[1] ?? "");
25
+ const id = attr("resource-id").replace(/^[\w.]+:id\//, "");
26
+ const texts = [
27
+ ...new Set([attr("text"), attr("content-desc")].filter(Boolean)),
28
+ ];
29
+ if (id === "" && texts.length === 0)
30
+ continue;
31
+ const box = attr("bounds").match(/^\[(\d+),(\d+)\]\[(\d+),(\d+)\]$/);
32
+ nodes.push({
33
+ id,
34
+ texts,
35
+ ...(box && {
36
+ bounds: {
37
+ x1: Number(box[1]),
38
+ y1: Number(box[2]),
39
+ x2: Number(box[3]),
40
+ y2: Number(box[4]),
41
+ },
42
+ }),
43
+ });
44
+ }
45
+ return nodes;
46
+ }
47
+ const adb = (bin, device, args, seconds) => runTool(`adb ${args.slice(0, 2).join(" ")}`, bin, ["-s", device, ...args], seconds);
48
+ // The dump goes to a file on the device and comes back with cat: printing it to
49
+ // /dev/tty mixes in uiautomator's own status line.
50
+ async function dump(device, bin, seconds = 60) {
51
+ const file = "/data/local/tmp/emd-window.xml";
52
+ await adb(bin, device, ["shell", "uiautomator", "dump", file], seconds);
53
+ const { stdout } = await adb(bin, device, ["exec-out", "cat", file], seconds);
54
+ if (!stdout.includes("<hierarchy"))
55
+ throw new Error("uiautomator wrote no hierarchy");
56
+ return parseDump(stdout);
57
+ }
58
+ // By id or text, a tap waits up to 10 s for the element, as AXe does.
59
+ const elementWaitSeconds = 10;
60
+ async function find(device, bin, target) {
61
+ const until = Date.now() + elementWaitSeconds * 1000;
62
+ for (;;) {
63
+ const node = (await dump(device, bin)).find((n) => "id" in target ? n.id === target.id : n.texts.includes(target.text));
64
+ if (node?.bounds)
65
+ return node.bounds;
66
+ if (Date.now() >= until) {
67
+ throw new Error(`no element with ${"id" in target ? `id "${target.id}"` : `text "${target.text}"`} on screen`);
68
+ }
69
+ await new Promise((resolve) => setTimeout(resolve, 500));
70
+ }
71
+ }
72
+ async function tap({ device }, bin, target) {
73
+ let point = target;
74
+ if (!("x" in target)) {
75
+ const b = await find(device, bin, target);
76
+ point = {
77
+ x: Math.round((b.x1 + b.x2) / 2),
78
+ y: Math.round((b.y1 + b.y2) / 2),
79
+ };
80
+ }
81
+ await adb(bin, device, ["shell", "input", "tap", String(point.x), String(point.y)], 30);
82
+ }
83
+ // `input text` reads %s as a space and runs in the device's shell, so spaces
84
+ // become %s and shell characters are escaped. It types ASCII only; other text
85
+ // throws, so the next backend types it.
86
+ export function inputText(text) {
87
+ if (!/^[\x20-\x7e]*$/.test(text))
88
+ throw new Error("adb input types ASCII text only");
89
+ return text
90
+ .replace(/[\\'"`$&|;<>()*?!#~{}[\]]/g, "\\$&")
91
+ .replaceAll(" ", "%s");
92
+ }
93
+ async function type({ device }, bin, text, seconds = 60) {
94
+ await adb(bin, device, ["shell", "input", "text", inputText(text)], seconds);
95
+ }
96
+ // From `wm size`: the override size when set, else the physical one.
97
+ export function screenSize(stdout) {
98
+ const sizes = [...stdout.matchAll(/(\w+) size: (\d+)x(\d+)/g)];
99
+ const size = sizes.find((m) => m[1] === "Override") ?? sizes[0];
100
+ if (!size)
101
+ throw new Error(`wm size printed no size: ${stdout.trim()}`);
102
+ return { width: Number(size[2]), height: Number(size[3]) };
103
+ }
104
+ // A swipe through the screen's centre over half its height or width, the
105
+ // finger moving the way named, in 300 ms.
106
+ export function swipeLine({ width, height }, direction) {
107
+ const [cx, cy] = [Math.round(width / 2), Math.round(height / 2)];
108
+ const [dx, dy] = [Math.round(width / 4), Math.round(height / 4)];
109
+ const lines = {
110
+ up: [cx, cy + dy, cx, cy - dy],
111
+ down: [cx, cy - dy, cx, cy + dy],
112
+ left: [cx + dx, cy, cx - dx, cy],
113
+ right: [cx - dx, cy, cx + dx, cy],
114
+ };
115
+ return lines[direction];
116
+ }
117
+ async function swipe({ device }, bin, direction) {
118
+ const { stdout } = await adb(bin, device, ["shell", "wm", "size"], 30);
119
+ const line = swipeLine(screenSize(stdout), direction);
120
+ await adb(bin, device, ["shell", "input", "swipe", ...line.map(String), "300"], 30);
121
+ }
122
+ export const adbBackend = {
123
+ id: "adb",
124
+ readScreen: async (device, bin, seconds) => (await dump(device, bin, seconds)).map(({ id, texts }) => ({ id, texts })),
125
+ tap,
126
+ type,
127
+ swipe,
128
+ };
@@ -1,5 +1,5 @@
1
1
  import type { UiNode } from "./screen.js";
2
- export declare const backendIds: readonly ["axe", "maestro"];
2
+ export declare const backendIds: readonly ["axe", "maestro", "adb"];
3
3
  export type BackendId = (typeof backendIds)[number];
4
4
  export type Target = {
5
5
  id: string;
@@ -1,12 +1,13 @@
1
1
  import { accessSync, constants } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { delimiter, join } from "node:path";
3
+ import { delimiter, isAbsolute, join } from "node:path";
4
+ import { sdkTool } from "../emulator.js";
4
5
  import { firstLine } from "../log.js";
5
6
  import { axeDir } from "./axe.js";
6
7
  // Decision 0004: device actions go through backends, and core picks the best
7
8
  // one that is available on this machine, falling back to the next. Tap, type
8
9
  // and swipe joined reading the screen in decision 0009.
9
- export const backendIds = ["axe", "maestro"];
10
+ export const backendIds = ["axe", "maestro", "adb"];
10
11
  // The way the finger moves: "up" shows what is further down.
11
12
  export const directions = ["up", "down", "left", "right"];
12
13
  // Tries the backends in the order given (best first), skipping any that cannot
@@ -123,9 +124,24 @@ function findExecutable(name, extraDirs) {
123
124
  }
124
125
  return undefined;
125
126
  }
127
+ // The adb that starts EMD's emulators (the SDK's), so two adb versions never
128
+ // restart each other's server.
129
+ function sdkAdb() {
130
+ const adb = sdkTool("adb");
131
+ if (!isAbsolute(adb))
132
+ return findExecutable(adb, []);
133
+ try {
134
+ accessSync(adb, constants.X_OK);
135
+ return adb;
136
+ }
137
+ catch {
138
+ return undefined;
139
+ }
140
+ }
126
141
  export async function detectEnvironment() {
127
142
  return {
128
143
  axe: findExecutable("axe", [axeDir()]),
129
144
  maestro: findExecutable("maestro", [join(homedir(), ".maestro", "bin")]),
145
+ adb: sdkAdb(),
130
146
  };
131
147
  }
@@ -1,12 +1,17 @@
1
+ import { type Platform } from "./adapter.js";
1
2
  type Check = {
2
3
  name: string;
4
+ platform?: Platform;
3
5
  status: "ok" | "missing";
4
6
  detail?: string;
5
7
  fix?: string;
6
8
  };
7
9
  export type DoctorResult = {
8
10
  verdict: "ready" | "missing";
11
+ platforms: Partial<Record<Platform, "ready" | "missing">>;
9
12
  checks: Check[];
10
13
  };
11
- export declare function doctor(): Promise<DoctorResult>;
14
+ export declare function doctor(options?: {
15
+ dir?: string;
16
+ }): Promise<DoctorResult>;
12
17
  export {};
@@ -1,21 +1,55 @@
1
+ import { join } from "node:path";
2
+ import { platforms } from "./adapter.js";
3
+ import { detect } from "./detect.js";
1
4
  import { detectEnvironment } from "./device/backend.js";
5
+ import { listAvds, sdkTool } from "./emulator.js";
2
6
  import { firstLine } from "./log.js";
3
7
  import { listDevices } from "./simulator.js";
4
8
  import { runTool } from "./tool.js";
5
9
  const minNode = 22;
6
- // What EMD needs on this machine to launch and check an Expo app on the iOS
7
- // simulator (vision.md). It only reads; it never installs.
8
- export async function doctor() {
9
- const checks = [];
10
+ // The Android Gradle plugin 8 needs JDK 17.
11
+ const minJava = 17;
12
+ // What EMD needs on this machine to launch and check the project in `dir` on
13
+ // each platform it targets, or on both outside a project (vision.md). It only
14
+ // reads; it never installs.
15
+ export async function doctor(options = {}) {
16
+ const detected = await detect(options.dir).catch(() => undefined);
17
+ const targets = detected?.verdict === "detected" && detected.platforms?.length
18
+ ? detected.platforms
19
+ : undefined;
20
+ const wanted = targets ?? [...platforms];
10
21
  const major = Number(process.versions.node.split(".")[0]);
11
- checks.push(major >= minNode
12
- ? { name: "node", status: "ok", detail: process.versions.node }
13
- : {
14
- name: "node",
15
- status: "missing",
16
- detail: process.versions.node,
17
- fix: `Install Node ${minNode} or newer.`,
18
- });
22
+ const checks = [
23
+ major >= minNode
24
+ ? { name: "node", status: "ok", detail: process.versions.node }
25
+ : {
26
+ name: "node",
27
+ status: "missing",
28
+ detail: process.versions.node,
29
+ fix: `Install Node ${minNode} or newer.`,
30
+ },
31
+ ];
32
+ if (wanted.includes("ios"))
33
+ checks.push(...(await iosChecks()));
34
+ if (wanted.includes("android"))
35
+ checks.push(...(await androidChecks()));
36
+ const state = (p) => checks.some((c) => (c.platform ?? p) === p && c.status === "missing")
37
+ ? "missing"
38
+ : "ready";
39
+ const byPlatform = Object.fromEntries(wanted.map((p) => [p, state(p)]));
40
+ const ready = targets
41
+ ? wanted.every((p) => byPlatform[p] === "ready")
42
+ : wanted.some((p) => byPlatform[p] === "ready");
43
+ return {
44
+ verdict: ready ? "ready" : "missing",
45
+ platforms: byPlatform,
46
+ checks,
47
+ };
48
+ }
49
+ // Xcode, an iPhone simulator and a device tool, on macOS.
50
+ async function iosChecks() {
51
+ const checks = [];
52
+ const tagged = () => checks.map((c) => ({ ...c, platform: "ios" }));
19
53
  if (process.platform !== "darwin") {
20
54
  checks.push({
21
55
  name: "macos",
@@ -23,7 +57,7 @@ export async function doctor() {
23
57
  detail: process.platform,
24
58
  fix: "iOS simulators need macOS. `detect` still works here.",
25
59
  });
26
- return done(checks);
60
+ return tagged();
27
61
  }
28
62
  checks.push({ name: "macos", status: "ok" });
29
63
  try {
@@ -37,7 +71,7 @@ export async function doctor() {
37
71
  detail: firstLine(error),
38
72
  fix: "Install Xcode from the App Store, open it once, then run `sudo xcode-select -s /Applications/Xcode.app`.",
39
73
  });
40
- return done(checks);
74
+ return tagged();
41
75
  }
42
76
  const iphones = await listDevices().then((devices) => devices.filter((d) => d.name.startsWith("iPhone")).length, () => 0);
43
77
  checks.push(iphones > 0
@@ -62,9 +96,56 @@ export async function doctor() {
62
96
  detail: "Taps, typing, swipes and element checks need AXe or Maestro.",
63
97
  fix: "Run `emd setup`. It installs AXe.",
64
98
  });
65
- return done(checks);
99
+ return tagged();
100
+ }
101
+ // The SDK's adb, an AVD to run, and the JDK that Gradle builds with.
102
+ async function androidChecks() {
103
+ const platform = "android";
104
+ const checks = [];
105
+ try {
106
+ const { stdout } = await runTool("adb version", sdkTool("adb"), ["version"], 30);
107
+ checks.push({
108
+ name: "adb",
109
+ platform,
110
+ status: "ok",
111
+ detail: firstLine(stdout),
112
+ });
113
+ }
114
+ catch (error) {
115
+ checks.push({
116
+ name: "adb",
117
+ platform,
118
+ status: "missing",
119
+ detail: firstLine(error),
120
+ fix: "Install the Android SDK (Android Studio installs it) and set ANDROID_HOME to its folder.",
121
+ });
122
+ return checks;
123
+ }
124
+ const avds = await listAvds().then((names) => names.length, (error) => firstLine(error));
125
+ checks.push(typeof avds === "number" && avds > 0
126
+ ? { name: "avd", platform, status: "ok", detail: `${avds} AVDs` }
127
+ : {
128
+ name: "avd",
129
+ platform,
130
+ status: "missing",
131
+ ...(typeof avds === "string" && { detail: avds }),
132
+ fix: typeof avds === "string"
133
+ ? "In Android Studio's SDK Manager, install the Android Emulator."
134
+ : "In Android Studio's Device Manager, create a virtual device.",
135
+ });
136
+ // Gradle runs on JAVA_HOME when it is set, else on the java in PATH.
137
+ const home = process.env.JAVA_HOME;
138
+ const java = home ? join(home, "bin", "java") : "java";
139
+ const version = await runTool("java --version", java, ["--version"], 30).then(({ stdout }) => firstLine(stdout), () => undefined);
140
+ const major = Number(version?.match(/\d+/)?.[0]);
141
+ checks.push(major >= minJava
142
+ ? { name: "java", platform, status: "ok", detail: version }
143
+ : {
144
+ name: "java",
145
+ platform,
146
+ status: "missing",
147
+ ...(version && { detail: version }),
148
+ fix: `Install JDK ${minJava} or newer and set JAVA_HOME to it. Android Studio's own JDK (its jbr folder) works.`,
149
+ });
150
+ return checks;
66
151
  }
67
- const done = (checks) => ({
68
- verdict: checks.some((c) => c.status === "missing") ? "missing" : "ready",
69
- checks,
70
- });
@@ -0,0 +1,29 @@
1
+ import { type LoggedProcess } from "./process.js";
2
+ export declare function sdkTool(name: "adb" | "emulator"): string;
3
+ export declare const parseAvds: (stdout: string) => string[];
4
+ export declare const pickAvd: (avds: string[], wanted?: string) => string | undefined;
5
+ export declare const parseAdbDevices: (stdout: string) => {
6
+ serial: string;
7
+ state: string;
8
+ }[];
9
+ export declare function pickEmulatorPort(taken: Set<string>): string;
10
+ export declare const serialOf: (port: string) => string;
11
+ export declare const emulatorPorts: (devices: {
12
+ serial: string;
13
+ }[]) => string[];
14
+ export declare function avdName(serial: string): Promise<string>;
15
+ export declare function installApk(serial: string, apk: string): Promise<void>;
16
+ export declare const parseActivity: (stdout: string) => string | undefined;
17
+ export declare function startApp(serial: string, appId: string): Promise<number>;
18
+ export declare function listAvds(): Promise<string[]>;
19
+ export declare function adbDevices(): Promise<{
20
+ serial: string;
21
+ state: string;
22
+ }[]>;
23
+ export declare function startEmulator(avd: string, port: string, logPath: string): LoggedProcess;
24
+ export declare function untilBooted(serial: string, seconds: number): Promise<void>;
25
+ export declare function stopEmulator(port: string): Promise<void>;
26
+ export declare function deviceAbi(serial: string): Promise<string>;
27
+ export declare function reversePort(serial: string, port: number): Promise<void>;
28
+ export declare function startLogcat(serial: string, logPath: string): Promise<LoggedProcess>;
29
+ export declare function screenshot(serial: string, path: string): Promise<void>;
@@ -0,0 +1,144 @@
1
+ import { dirname, join } from "node:path";
2
+ import { startLogged } from "./process.js";
3
+ import { runTool } from "./tool.js";
4
+ // Android emulators, one per worktree: the base AVD runs read-only on a port
5
+ // EMD reserves, so several worktrees share one AVD and none writes to it
6
+ // (#254). The port is the owned resource (decision 0006).
7
+ // An SDK tool from ANDROID_HOME (or ANDROID_SDK_ROOT), else from PATH.
8
+ export function sdkTool(name) {
9
+ const home = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT;
10
+ const file = process.platform === "win32" ? `${name}.exe` : name;
11
+ if (!home)
12
+ return file;
13
+ return join(home, name === "adb" ? "platform-tools" : "emulator", file);
14
+ }
15
+ const quote = (s) => `'${s.replaceAll("'", "'\\''")}'`;
16
+ // `emulator -list-avds` prints one AVD name a line, after any INFO lines.
17
+ export const parseAvds = (stdout) => stdout
18
+ .split("\n")
19
+ .map((line) => line.trim())
20
+ .filter((line) => line && !/^(INFO|WARNING|ERROR)\b/.test(line));
21
+ // The AVD `wanted` names, else the first one listed.
22
+ export const pickAvd = (avds, wanted) => wanted === undefined ? avds[0] : avds.find((avd) => avd === wanted);
23
+ // `adb devices`: serial and state, one a line after the header.
24
+ export const parseAdbDevices = (stdout) => stdout
25
+ .split("\n")
26
+ .slice(1)
27
+ .map((line) => line.trim().split(/\s+/))
28
+ .filter((parts) => parts.length >= 2)
29
+ .map(([serial, state]) => ({ serial, state }));
30
+ // Emulator console ports are even, from 5554 to 5682; adb uses port + 1.
31
+ export function pickEmulatorPort(taken) {
32
+ for (let port = 5554; port <= 5682; port += 2) {
33
+ if (!taken.has(String(port)))
34
+ return String(port);
35
+ }
36
+ throw new Error("No free emulator port between 5554 and 5682.");
37
+ }
38
+ export const serialOf = (port) => `emulator-${port}`;
39
+ // The console ports of the emulators adb lists, EMD's or not.
40
+ export const emulatorPorts = (devices) => devices.flatMap(({ serial }) => serial.match(/^emulator-(\d+)$/)?.[1] ?? []);
41
+ const adb = (serial, args, seconds) => runTool(`adb ${args.join(" ")}`, sdkTool("adb"), ["-s", serial, ...args], seconds);
42
+ // The AVD an emulator runs: `adb emu avd name` prints it, then OK.
43
+ export async function avdName(serial) {
44
+ const { stdout } = await adb(serial, ["emu", "avd", "name"], 30);
45
+ return stdout.split("\n")[0]?.trim() || serial;
46
+ }
47
+ export async function installApk(serial, apk) {
48
+ await adb(serial, ["install", "-r", apk], 300);
49
+ }
50
+ // `cmd package resolve-activity --brief` prints the activity last, as
51
+ // package/class.
52
+ export const parseActivity = (stdout) => stdout
53
+ .split("\n")
54
+ .map((line) => line.trim())
55
+ .filter((line) => /^[\w.]+\/[\w.$]+$/.test(line))
56
+ .at(-1);
57
+ // Stops the app if it runs, starts its launcher activity, waits until it shows
58
+ // and returns its pid.
59
+ export async function startApp(serial, appId) {
60
+ await adb(serial, ["shell", "am", "force-stop", appId], 30);
61
+ const resolved = await adb(serial, [
62
+ "shell",
63
+ "cmd",
64
+ "package",
65
+ "resolve-activity",
66
+ "--brief",
67
+ "-c",
68
+ "android.intent.category.LAUNCHER",
69
+ appId,
70
+ ], 30);
71
+ const activity = parseActivity(resolved.stdout);
72
+ if (!activity)
73
+ throw new Error(`${appId} has no launcher activity.`);
74
+ // am prints an error and still exits 0 on some Android versions.
75
+ const { stdout } = await adb(serial, ["shell", "am", "start", "-W", "-n", activity], 120);
76
+ if (/^Error/m.test(stdout))
77
+ throw new Error(stdout.trim());
78
+ const pid = await adb(serial, ["shell", "pidof", appId], 30).then((result) => Number(result.stdout.trim().split(/\s+/)[0]), () => Number.NaN);
79
+ if (!(pid > 0))
80
+ throw new Error(`${appId} is not running after the start.`);
81
+ return pid;
82
+ }
83
+ export async function listAvds() {
84
+ const { stdout } = await runTool("emulator -list-avds", sdkTool("emulator"), ["-list-avds"], 30);
85
+ return parseAvds(stdout);
86
+ }
87
+ export async function adbDevices() {
88
+ const { stdout } = await runTool("adb devices", sdkTool("adb"), ["devices"], 30);
89
+ return parseAdbDevices(stdout);
90
+ }
91
+ // Starts `avd` read-only on `port`, with no window. Its output goes to logPath.
92
+ export function startEmulator(avd, port, logPath) {
93
+ return startLogged([
94
+ quote(sdkTool("emulator")),
95
+ `-avd ${quote(avd)}`,
96
+ "-read-only",
97
+ `-port ${port}`,
98
+ // Software rendering: with no window, a host GPU may be missing (CI).
99
+ "-no-window -gpu swiftshader_indirect -no-audio -no-boot-anim -no-snapshot-save",
100
+ ].join(" "), { cwd: process.cwd(), logPath });
101
+ }
102
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
103
+ // Resolves when Android reports the boot complete; throws after `seconds`.
104
+ export async function untilBooted(serial, seconds) {
105
+ const until = Date.now() + seconds * 1000;
106
+ while (Date.now() < until) {
107
+ const done = await runTool("adb getprop", sdkTool("adb"), ["-s", serial, "shell", "getprop", "sys.boot_completed"], 20).then(({ stdout }) => stdout.trim() === "1", () => false);
108
+ if (done)
109
+ return;
110
+ await sleep(2000);
111
+ }
112
+ throw new Error(`${serial} did not finish booting in ${seconds}s.`);
113
+ }
114
+ // Stops the emulator on `port`. One that is not running counts as stopped;
115
+ // any other failure throws, so the port stays owned until a retry works.
116
+ export async function stopEmulator(port) {
117
+ const serial = serialOf(port);
118
+ if (!(await adbDevices()).some((d) => d.serial === serial))
119
+ return;
120
+ await runTool("adb emu kill", sdkTool("adb"), ["-s", serial, "emu", "kill"], 30);
121
+ }
122
+ // The CPU ABI the emulator runs, such as x86_64 or arm64-v8a.
123
+ export async function deviceAbi(serial) {
124
+ const { stdout } = await adb(serial, ["shell", "getprop", "ro.product.cpu.abi"], 30);
125
+ return stdout.trim();
126
+ }
127
+ // Makes `port` on the emulator reach `port` on this machine, so the app finds
128
+ // its dev server at localhost.
129
+ export async function reversePort(serial, port) {
130
+ await adb(serial, ["reverse", `tcp:${port}`, `tcp:${port}`], 30);
131
+ }
132
+ // Streams the app's tagged lines to logPath. The buffer is cleared first, so
133
+ // the file holds only this run: the emulator keeps earlier runs' lines while it
134
+ // runs. logcat's -e keeps only messages that match, so the file stays small.
135
+ export async function startLogcat(serial, logPath) {
136
+ await adb(serial, ["logcat", "-c"], 30);
137
+ return startLogged(`${quote(sdkTool("adb"))} -s ${serial} logcat -v epoch -e EMD:`, { cwd: dirname(logPath), logPath });
138
+ }
139
+ // A PNG of the screen at `path`.
140
+ export async function screenshot(serial, path) {
141
+ const remote = "/data/local/tmp/emd-screenshot.png";
142
+ await adb(serial, ["shell", "screencap", "-p", remote], 60);
143
+ await adb(serial, ["pull", remote, path], 60);
144
+ }
package/dist/core/gc.d.ts CHANGED
@@ -5,6 +5,7 @@ export type GcResult = {
5
5
  key: string;
6
6
  root: string;
7
7
  simulator?: string;
8
+ emulator?: string;
8
9
  derivedData?: string;
9
10
  mb: number;
10
11
  status: "stale" | "removed" | "skipped" | "failed";