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
package/dist/core/gc.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
2
2
  import { join, relative, sep } from "node:path";
3
+ import { serialOf, stopEmulator } from "./emulator.js";
3
4
  import { diskMB } from "./isolate.js";
4
5
  import { firstLine } from "./log.js";
5
6
  import { listLedgers, removeLedger } from "./owned.js";
@@ -108,11 +109,13 @@ export async function gc(options = {}) {
108
109
  const wanted = ledger.resources.find((r) => r.kind === "simulator")?.id;
109
110
  const sim = simulators.find((s) => s.id === wanted || s.name === wanted);
110
111
  const derivedData = ledger.resources.find((r) => r.kind === "derivedData")?.id;
112
+ const emulator = ledger.resources.find((r) => r.kind === "emulator")?.id;
111
113
  const reason = problem(ledger, sim);
112
114
  entries.push({
113
115
  entry: {
114
116
  ...base,
115
117
  ...(sim && { simulator: sim.id }),
118
+ ...(emulator && { emulator: serialOf(emulator) }),
116
119
  ...(derivedData && { derivedData }),
117
120
  mb: (await diskMB(join(homeDir(), "derived", ledger.key))) +
118
121
  (await diskMB(join(homeDir(), "bin", ledger.key))),
@@ -142,6 +145,9 @@ export async function gc(options = {}) {
142
145
  try {
143
146
  if (sim)
144
147
  await removeSimulator(sim);
148
+ const emulator = ledger.resources.find((r) => r.kind === "emulator");
149
+ if (emulator)
150
+ await stopEmulator(emulator.id);
145
151
  rmSync(join(homeDir(), "derived", ledger.key), {
146
152
  recursive: true,
147
153
  force: true,
@@ -1,4 +1,5 @@
1
1
  export type { LaunchPlan, PackageManager, Platform, ProjectInfo, StackAdapter, StackDetection, StackId, } from "./adapter.js";
2
+ export { platforms } from "./adapter.js";
2
3
  export { check } from "./check.js";
3
4
  export { resetChecks } from "./checkrecord.js";
4
5
  export { detect } from "./detect.js";
@@ -9,6 +10,7 @@ export { type GcResult, gc } from "./gc.js";
9
10
  export { swipe, tap, typeText } from "./input.js";
10
11
  export { jobStatus, launchInline, runJob, startJob, waitForJob, } from "./jobs.js";
11
12
  export { logs } from "./logs.js";
13
+ export { xcodeGenerators } from "./probe.js";
12
14
  export { loadedAdapters } from "./registry.js";
13
15
  export { type CheckResult, checkResultSchema, type DetectResult, detectResultSchema, type EvidenceResult, evidenceResultSchema, type InputResult, inputResultSchema, type JobView, jobViewSchema, type LaunchResult, type LogsResult, launchResultSchema, logsResultSchema, } from "./result.js";
14
16
  export { type SetupResult, setup } from "./setup.js";
@@ -1,3 +1,4 @@
1
+ export { platforms } from "./adapter.js";
1
2
  export { check } from "./check.js";
2
3
  export { resetChecks } from "./checkrecord.js";
3
4
  export { detect } from "./detect.js";
@@ -8,6 +9,7 @@ export { gc } from "./gc.js";
8
9
  export { swipe, tap, typeText } from "./input.js";
9
10
  export { jobStatus, launchInline, runJob, startJob, waitForJob, } from "./jobs.js";
10
11
  export { logs } from "./logs.js";
12
+ export { xcodeGenerators } from "./probe.js";
11
13
  export { loadedAdapters } from "./registry.js";
12
14
  export { checkResultSchema, detectResultSchema, evidenceResultSchema, inputResultSchema, jobViewSchema, launchResultSchema, logsResultSchema, } from "./result.js";
13
15
  export { setup } from "./setup.js";
@@ -1,5 +1,8 @@
1
+ import type { Platform } from "./adapter.js";
2
+ import { type DeviceBackend } from "./device/backend.js";
1
3
  import type { InputResult } from "./result.js";
2
4
  import { type RunRef } from "./run.js";
5
+ export declare const backendsFor: (platform: Platform) => DeviceBackend[];
3
6
  export type TapOptions = RunRef & {
4
7
  id?: string;
5
8
  text?: string;
@@ -1,3 +1,4 @@
1
+ import { adbBackend } from "./device/adb.js";
1
2
  import { axeBackend } from "./device/axe.js";
2
3
  import { detectEnvironment, directions, firstWorking, readScreen, secondsTo, } from "./device/backend.js";
3
4
  import { maestroBackend } from "./device/maestro.js";
@@ -6,7 +7,10 @@ import { firstLine } from "./log.js";
6
7
  import { resolveRun } from "./run.js";
7
8
  // Taps, typing and swipes on a launched app (decision 0009). Each acts once
8
9
  // and says which backend did it; whether the app reacted is for `check`.
9
- const backends = [axeBackend, maestroBackend];
10
+ // Best first (decisions 0004, 0005). Maestro works on both platforms.
11
+ export const backendsFor = (platform) => platform === "android"
12
+ ? [adbBackend, maestroBackend]
13
+ : [axeBackend, maestroBackend];
10
14
  const until = (seconds) => Date.now() + seconds * 1000;
11
15
  // Runs `run` against the launched app. `run` returns extra result fields, or
12
16
  // a `reason` when it failed.
@@ -14,7 +18,8 @@ async function act(what, { jobId }, run) {
14
18
  const resolved = resolveRun({ jobId });
15
19
  if ("reason" in resolved)
16
20
  return { verdict: "failed", reason: resolved.reason };
17
- const { device, appId } = resolved.run;
21
+ const { device, appId, platform } = resolved.run;
22
+ const backends = backendsFor(platform);
18
23
  let first = {};
19
24
  try {
20
25
  const env = await detectEnvironment();
@@ -1,6 +1,11 @@
1
+ import { type Platform } from "./adapter.js";
1
2
  import type { LaunchResult } from "./result.js";
2
3
  export type LaunchOptions = {
3
4
  dir?: string;
5
+ platform?: Platform;
6
+ prepare?: string;
7
+ scheme?: string;
8
+ configuration?: string;
4
9
  device?: string;
5
10
  timeoutSeconds?: number;
6
11
  };
@@ -1,16 +1,18 @@
1
1
  import { appendFile, mkdir, readFile, realpath, rm, stat, symlink, } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { basename, join } from "node:path";
4
- import { builtApp, readBuildRecord, whyBuild, writeBuildRecord, } from "./buildrecord.js";
4
+ import { platforms, } from "./adapter.js";
5
+ import { builtApk, builtApp, builtAppId, readBuildRecord, whyBuild, writeBuildRecord, } from "./buildrecord.js";
5
6
  import { detect } from "./detect.js";
6
7
  import { axeBackend } from "./device/axe.js";
7
8
  import { detectEnvironment, untilReadable } from "./device/backend.js";
9
+ import { adbDevices, avdName, deviceAbi, emulatorPorts, installApk, listAvds, pickAvd, pickEmulatorPort, reversePort, serialOf, startApp, startEmulator, startLogcat, untilBooted, } from "./emulator.js";
8
10
  import { derivedDataPath, diskMB, pickPort, xcodebuildShim, } from "./isolate.js";
9
11
  import { launchesIn } from "./jobstore.js";
10
- import { buildTiming, firstErrors, knownFix, onlyOpenFailed } from "./log.js";
12
+ import { buildTiming, errorLines, firstErrors, knownFix, lastLines, onlyOpenFailed, } from "./log.js";
11
13
  import { startCapture, stopCaptures } from "./logs.js";
12
14
  import { confirm, reserve, worktreeKey } from "./owned.js";
13
- import { startLogged } from "./process.js";
15
+ import { startLogged, untilExitOrIdle } from "./process.js";
14
16
  import { inspectProject } from "./project.js";
15
17
  import { loadAdapter } from "./registry.js";
16
18
  import { bundlesServed, earlierLaunch, runningPid, sendReload, untilBundled, } from "./reload.js";
@@ -19,7 +21,10 @@ import { stateDir } from "./state.js";
19
21
  import { runTool } from "./tool.js";
20
22
  const metroStartSeconds = 120;
21
23
  const stopSeconds = 10;
22
- const defaultTimeoutSeconds = 900;
24
+ // A build stops when its log has not grown for buildIdleSeconds (a hang), or
25
+ // after the total limit. A slow build that still prints goes on (decision 0014).
26
+ const defaultTimeoutSeconds = 3600;
27
+ const buildIdleSeconds = 600;
23
28
  // How long AXe may take to read the screen after the app started, about twice
24
29
  // the slowest measurement: first launch 7.8 to 51.4 s on CI iOS 26 and up to
25
30
  // 86 s on iOS 27.1; relaunch 5.9 to 31.3 s.
@@ -28,6 +33,12 @@ const screenReadSeconds = 180;
28
33
  const emptyTreeSeconds = 5;
29
34
  // How long a reload may take to show a new bundle request in the dev server log.
30
35
  const bundleSeconds = 60;
36
+ // How long an Expo app on Android may take to get its first bundle: the dev
37
+ // server builds it on the first request. A hang limit, not a speed target.
38
+ const androidBundleSeconds = 300;
39
+ // How long an emulator may take to boot: a hang limit, not a speed target. A cold
40
+ // boot on a 4-core CI runner took about 75 s (decision 0015).
41
+ const emulatorBootSeconds = 600;
31
42
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
43
  async function metroRunning(port) {
33
44
  try {
@@ -87,40 +98,57 @@ async function untilReady(ready, exited, seconds) {
87
98
  }
88
99
  return "timeout";
89
100
  }
90
- // Resolves with the exit code, or "timeout". Clears its timer so a finished
91
- // build does not keep the process alive.
92
- async function withTimeout(exited, seconds) {
93
- let timer;
94
- const timeout = new Promise((resolve) => {
95
- timer = setTimeout(() => resolve("timeout"), seconds * 1000);
101
+ const errorMessageLines = (error) => String(error).split("\n").slice(0, 3);
102
+ // This launch's folder for its build, server and app logs.
103
+ const runDir = (root) => join(stateDir(), "runs", `${new Date().toISOString().replace(/[:.]/g, "-")}-${basename(root)}`);
104
+ const logTail = async (path) => firstErrors(await readFile(path, "utf8").catch(() => ""));
105
+ // Starts the dev server on `port` and waits until it answers. Returns the
106
+ // process, or why it did not start. With CI set Metro does not watch files, so
107
+ // an edit never reaches the next bundle: the server runs without it. It has no
108
+ // terminal (stdin is closed), so it asks nothing.
109
+ async function startServer(command, root, port, logPath, env) {
110
+ const metro = startLogged(command, {
111
+ cwd: root,
112
+ logPath,
113
+ env: { ...env, CI: undefined },
96
114
  });
97
- try {
98
- return await Promise.race([exited, timeout]);
99
- }
100
- finally {
101
- clearTimeout(timer);
102
- }
115
+ const state = await untilReady(() => metroRunning(port), metro.exited, metroStartSeconds);
116
+ if (state === "ready")
117
+ return metro;
118
+ metro.kill();
119
+ return {
120
+ reason: state === "exited"
121
+ ? "The dev server exited before it was ready."
122
+ : `The dev server was not ready after ${metroStartSeconds}s.`,
123
+ errors: await logTail(logPath),
124
+ };
103
125
  }
104
- const logTail = async (path) => firstErrors(await readFile(path, "utf8").catch(() => ""));
105
126
  // Runs the build and install. Returns why it failed; undefined when the app is
106
127
  // installed.
107
- async function runBuild(command, cwd, logPath, env, options) {
128
+ async function runBuild(command, cwd, logPath, env, options, step = "build") {
108
129
  const seconds = options.timeoutSeconds ?? defaultTimeoutSeconds;
130
+ const idle = Math.min(buildIdleSeconds, seconds);
109
131
  const build = startLogged(command, { cwd, logPath, env });
110
- const outcome = await withTimeout(build.exited, seconds);
132
+ const outcome = await untilExitOrIdle(build.exited, logPath, idle, seconds);
111
133
  if (outcome === 0)
112
134
  return undefined;
113
135
  build.kill();
114
136
  const text = await readFile(logPath, "utf8").catch(() => "");
137
+ if (outcome === "timeout" || outcome === "idle") {
138
+ const errors = errorLines(text);
139
+ return {
140
+ reason: outcome === "timeout"
141
+ ? `The ${step} did not finish in ${seconds}s.`
142
+ : `The ${step} log did not grow for ${idle}s, so the ${step} looked hung and was stopped.`,
143
+ ...(errors.length > 0 ? { errors } : { lastLines: lastLines(text) }),
144
+ };
145
+ }
115
146
  // Expo's own open step timed out after the install; EMD opens the app next.
116
- if (outcome !== "timeout" && onlyOpenFailed(text))
147
+ if (onlyOpenFailed(text))
117
148
  return undefined;
118
149
  const fix = knownFix(text);
119
- let reason = `The build failed (exit ${outcome}).`;
120
- if (outcome === "timeout") {
121
- reason = `The build did not finish in ${seconds}s.`;
122
- }
123
- else if (fix) {
150
+ let reason = `The ${step} failed (exit ${outcome}).`;
151
+ if (fix) {
124
152
  reason = fix;
125
153
  }
126
154
  else if (text.includes("\u203a Build Succeeded")) {
@@ -189,17 +217,53 @@ export async function launch(options = {}, report = () => { }) {
189
217
  if (detected.verdict !== "detected" || !detected.stack) {
190
218
  return unsupported("No supported mobile project found here.");
191
219
  }
192
- if (!detected.platforms?.includes("ios")) {
193
- return unsupported("The project does not target iOS.");
220
+ const adapter = await loadAdapter(detected.stack);
221
+ // Default: the first platform, iOS before Android, that the project targets
222
+ // and EMD launches it on.
223
+ const platform = options.platform ??
224
+ platforms.find((p) => detected.platforms?.includes(p) && adapter.launches.includes(p)) ??
225
+ detected.platforms?.[0] ??
226
+ "ios";
227
+ const name = platform === "ios" ? "iOS" : "Android";
228
+ if (!detected.platforms?.includes(platform)) {
229
+ return unsupported(`The project does not target ${name}.`);
230
+ }
231
+ if (!adapter.launches.includes(platform)) {
232
+ return unsupported(`EMD does not launch ${detected.stack} apps on ${name} yet.`);
194
233
  }
195
- // Without an ID, Expo's own build sets one (ios.bundleIdentifier) and the
196
- // ID is read again after it. EMD writes nothing to the app config.
197
234
  if (detected.problem)
198
235
  return unsupported(detected.problem);
199
- let appId = detected.appIds?.ios;
200
- if (process.platform !== "darwin") {
236
+ if (detected.needsPrepare && !options.prepare) {
237
+ return unsupported(detected.needsPrepare);
238
+ }
239
+ if (platform === "ios" && process.platform !== "darwin") {
201
240
  return unsupported("iOS simulators need macOS.");
202
241
  }
242
+ // The project's own setup step, such as `make`, runs before anything reads
243
+ // the native project it may write.
244
+ const logDir = runDir(root);
245
+ if (options.prepare) {
246
+ phase("prepare", "running the prepare command");
247
+ const failure = await runBuild(options.prepare, root, join(logDir, "prepare.log"), {}, options, "prepare command");
248
+ if (failure) {
249
+ return failed(failure.reason, {
250
+ logDir,
251
+ ...(failure.errors && { errors: failure.errors }),
252
+ ...(failure.lastLines && { lastLines: failure.lastLines }),
253
+ });
254
+ }
255
+ }
256
+ if (platform === "android") {
257
+ return launchAndroid(root, adapter, logDir, options, {
258
+ phase,
259
+ failed,
260
+ unsupported,
261
+ done: () => ({ seconds: seconds(), phases: endPhase() }),
262
+ });
263
+ }
264
+ // Without an ID, Expo's own build sets one (ios.bundleIdentifier) and the
265
+ // ID is read again after it. EMD writes nothing to the app config.
266
+ let appId = detected.appIds?.ios;
203
267
  // Each worktree gets its own simulator, DerivedData and Metro port, recorded
204
268
  // as EMD-owned before they exist (decision 0006).
205
269
  const prefix = "emd-";
@@ -250,13 +314,35 @@ export async function launch(options = {}, report = () => { }) {
250
314
  errors: String(error).split("\n").slice(0, 3),
251
315
  });
252
316
  }
253
- const plan = (await loadAdapter(detected.stack)).launchPlan(await inspectProject(root), { platform: "ios", deviceId: device.id, port });
317
+ let plan;
318
+ try {
319
+ plan = await adapter.launchPlan(await inspectProject(root), {
320
+ dir: root,
321
+ platform: "ios",
322
+ deviceId: device.id,
323
+ port,
324
+ ...(options.scheme && { scheme: options.scheme }),
325
+ ...(options.configuration && { configuration: options.configuration }),
326
+ });
327
+ }
328
+ catch (error) {
329
+ return failed("Could not plan the build.", {
330
+ errors: String(error).split("\n").slice(0, 3),
331
+ });
332
+ }
333
+ if (typeof plan === "string")
334
+ return unsupported(plan);
254
335
  if (!plan)
255
336
  return unsupported(`${detected.stack} cannot launch on iOS.`);
256
- const logDir = join(stateDir(), "runs", `${new Date().toISOString().replace(/[:.]/g, "-")}-${basename(root)}`);
337
+ // Without a dev server the build only builds, and EMD installs the app.
338
+ const { server, build } = plan;
257
339
  const buildLog = join(logDir, "build.log");
258
340
  const metroLog = join(logDir, "metro.log");
259
- const where = { device: { id: device.id, name: device.name }, logDir };
341
+ const where = {
342
+ platform: "ios",
343
+ device: { id: device.id, name: device.name },
344
+ logDir,
345
+ };
260
346
  const sizes = async () => ({
261
347
  derivedData: await diskMB(derivedData),
262
348
  simulator: await diskMB(join(homedir(), "Library/Developer/CoreSimulator/Devices", device.id)),
@@ -279,11 +365,14 @@ export async function launch(options = {}, report = () => { }) {
279
365
  });
280
366
  }
281
367
  // Reuse the installed build when nothing native changed. A fingerprint that
282
- // cannot be computed means a normal build.
368
+ // cannot be computed means a normal build. A stack without one always
369
+ // builds; xcodebuild's own build is incremental.
283
370
  let fingerprint;
284
- let why;
371
+ let why = adapter.fingerprint
372
+ ? undefined
373
+ : "this stack builds on every launch";
285
374
  try {
286
- fingerprint = await (await loadAdapter(detected.stack)).fingerprint(root, "ios");
375
+ fingerprint = await adapter.fingerprint?.(root, "ios");
287
376
  }
288
377
  catch (error) {
289
378
  why = `fingerprint failed: ${String(error).split("\n")[0]}`;
@@ -314,7 +403,8 @@ export async function launch(options = {}, report = () => { }) {
314
403
  reloadCapture = await startCapture(device.id, earlier.appId, logDir);
315
404
  await symlink(await realpath(join(earlier.logDir, "metro.log")), metroLog);
316
405
  await sendReload(port);
317
- if (await untilBundled(earlier.logDir, before, bundleSeconds)) {
406
+ if ((await untilBundled(earlier.logDir, before, bundleSeconds)) ===
407
+ "bundled") {
318
408
  const axe = (await detectEnvironment()).axe;
319
409
  phase("screen", "waiting for the screen");
320
410
  const screen = axe
@@ -350,7 +440,7 @@ export async function launch(options = {}, report = () => { }) {
350
440
  await rm(join(logDir, "app.ndjson"), { force: true });
351
441
  }
352
442
  await stopEarlierServer(root, port);
353
- if (await metroRunning(port)) {
443
+ if (server && (await metroRunning(port))) {
354
444
  return stuck(`Port ${port} already serves a dev server. Stop it and retry.`);
355
445
  }
356
446
  await stopCaptures(root);
@@ -358,25 +448,19 @@ export async function launch(options = {}, report = () => { }) {
358
448
  // app starts. A failed write is not a launch failure: `type` still checks
359
449
  // its text.
360
450
  const keyboard = plainKeyboard(device).catch(() => { });
361
- phase("server", "starting the dev server");
362
451
  const env = {
363
452
  CI: "1",
364
453
  RCT_METRO_PORT: String(port),
365
454
  PATH: `${shimDir}:${process.env.PATH}`,
366
455
  };
367
- // With CI set Metro does not watch files, so an edit never reaches the next
368
- // bundle. The server has no terminal (stdin is closed), so it asks nothing.
369
- const metro = startLogged(plan.server, {
370
- cwd: root,
371
- logPath: metroLog,
372
- env: { ...env, CI: undefined },
373
- });
374
- const metroState = await untilReady(() => metroRunning(port), metro.exited, metroStartSeconds);
375
- if (metroState !== "ready") {
376
- metro.kill();
377
- return stuck(metroState === "exited"
378
- ? "The dev server exited before it was ready."
379
- : `The dev server was not ready after ${metroStartSeconds}s.`, { errors: await logTail(metroLog) });
456
+ let metro;
457
+ if (server) {
458
+ phase("server", "starting the dev server");
459
+ const started = await startServer(server, root, port, metroLog, env);
460
+ if ("reason" in started) {
461
+ return stuck(started.reason, { errors: started.errors });
462
+ }
463
+ metro = started;
380
464
  }
381
465
  await keyboard;
382
466
  confirm(root, "port");
@@ -389,11 +473,27 @@ export async function launch(options = {}, report = () => { }) {
389
473
  const buildApp = async () => {
390
474
  phase("build", "building and installing the app");
391
475
  const buildStarted = Date.now();
392
- const failure = await runBuild(plan.build, root, buildLog, env, options);
476
+ const failure = await runBuild(build, root, buildLog, env, options);
393
477
  xcodebuildSeconds = await recordTiming(root, buildLog, buildStarted);
394
478
  if (failure) {
395
- metro.kill();
396
- return stuck(failure.reason, { errors: failure.errors });
479
+ metro?.kill();
480
+ return stuck(failure.reason, {
481
+ ...(failure.errors && { errors: failure.errors }),
482
+ ...(failure.lastLines && { lastLines: failure.lastLines }),
483
+ });
484
+ }
485
+ if (!server) {
486
+ const app = builtApp(derivedData);
487
+ try {
488
+ if (!app)
489
+ throw new Error("no single .app in DerivedData");
490
+ await installApp(device, app);
491
+ }
492
+ catch (error) {
493
+ return stuck("Built, but installing the app failed.", {
494
+ errors: String(error).split("\n").slice(0, 3),
495
+ });
496
+ }
397
497
  }
398
498
  if (fingerprint !== undefined) {
399
499
  try {
@@ -428,24 +528,27 @@ export async function launch(options = {}, report = () => { }) {
428
528
  return failure;
429
529
  }
430
530
  }
531
+ // An ID the build wrote to the app config (Expo), else the built app's own.
431
532
  let appIdSet;
432
533
  if (appId === undefined) {
433
- appId = (await detect(root)).appIds?.ios;
534
+ appIdSet = (await detect(root)).appIds?.ios;
535
+ appId = appIdSet ?? (await builtAppId(derivedData));
434
536
  if (appId === undefined) {
435
- metro.kill();
436
- return stuck("The build finished, but the app config still has no iOS app ID. Expo may have built from an existing ios/ project.", { errors: await logTail(buildLog) });
537
+ metro?.kill();
538
+ return stuck("The build finished, but neither the app config nor the built app names an iOS app ID.", { errors: await logTail(buildLog) });
437
539
  }
438
- appIdSet = appId;
439
540
  // The config changed, so the fingerprint did too. A failure here only costs
440
541
  // one rebuild on the next launch.
441
- try {
442
- fingerprint = await (await loadAdapter(detected.stack)).fingerprint(root, "ios");
443
- writeBuildRecord(derivedData, { fingerprint, port });
542
+ if (appIdSet && adapter.fingerprint) {
543
+ try {
544
+ fingerprint = await adapter.fingerprint(root, "ios");
545
+ writeBuildRecord(derivedData, { fingerprint, port });
546
+ }
547
+ catch { }
444
548
  }
445
- catch { }
446
549
  }
447
550
  const captureFailed = (error) => {
448
- metro.kill();
551
+ metro?.kill();
449
552
  return stuck("Built, but could not capture the app's log.", {
450
553
  errors: String(error).split("\n").slice(0, 3),
451
554
  });
@@ -476,14 +579,15 @@ export async function launch(options = {}, report = () => { }) {
476
579
  let appPid;
477
580
  try {
478
581
  // A running app still talks to the dev server it started with; a restart
479
- // makes it load the new JavaScript from this one.
480
- if (why === undefined)
582
+ // makes it load the new JavaScript from this one. A native app restarts so
583
+ // the new build runs.
584
+ if (why === undefined || !server)
481
585
  await terminateApp(device, appId);
482
586
  appPid = await launchApp(device, appId);
483
587
  }
484
588
  catch (error) {
485
589
  capture.kill();
486
- metro.kill();
590
+ metro?.kill();
487
591
  return stuck(`${why === undefined ? "Reused the build" : "Built"}, but launching ${appId} failed.`, {
488
592
  errors: String(error).split("\n").slice(0, 3),
489
593
  });
@@ -521,7 +625,7 @@ export async function launch(options = {}, report = () => { }) {
521
625
  reason: why,
522
626
  ...(xcodebuildSeconds !== undefined && { xcodebuildSeconds }),
523
627
  },
524
- metro: { pid: metro.pid, port },
628
+ ...(metro && { metro: { pid: metro.pid, port } }),
525
629
  logStream: { pid: capture.pid },
526
630
  derivedData,
527
631
  diskMB: await sizes(),
@@ -529,3 +633,162 @@ export async function launch(options = {}, report = () => { }) {
529
633
  phases: endPhase(),
530
634
  };
531
635
  }
636
+ // Builds the debug APK, installs it on this worktree's emulator and opens the
637
+ // app. The emulator runs the base AVD read-only on the worktree's own port
638
+ // (decision 0015) and keeps running for the next launch. With a dev server
639
+ // (Expo), the server starts first, the emulator reaches it through adb
640
+ // reverse, and launch waits until the app has its JavaScript. Gradle's own
641
+ // build is incremental, so every launch builds.
642
+ async function launchAndroid(root, adapter, logDir, options, { phase, failed, unsupported, done }) {
643
+ let emulatorPort;
644
+ let port;
645
+ try {
646
+ emulatorPort = (await reserve(root, "emulator", async (taken) => pickEmulatorPort(new Set([...taken, ...emulatorPorts(await adbDevices())])))).id;
647
+ port = Number((await reserve(root, "port", pickPort)).id);
648
+ }
649
+ catch (error) {
650
+ return failed("Could not set up this worktree's emulator.", {
651
+ errors: errorMessageLines(error),
652
+ });
653
+ }
654
+ const metroLog = join(logDir, "metro.log");
655
+ const serial = serialOf(emulatorPort);
656
+ const where = {
657
+ platform: "android",
658
+ device: { id: serial, name: serial },
659
+ logDir,
660
+ };
661
+ const stuck = (reason, error) => failed(reason, {
662
+ ...where,
663
+ ...(error !== undefined && { errors: errorMessageLines(error) }),
664
+ });
665
+ let abi;
666
+ try {
667
+ const state = (await adbDevices()).find((d) => d.serial === serial)?.state;
668
+ if (state !== "device") {
669
+ phase("boot", "booting the emulator");
670
+ if (state === undefined) {
671
+ const avd = pickAvd(await listAvds(), options.device);
672
+ if (!avd) {
673
+ return stuck(options.device
674
+ ? `No Android virtual device (AVD) is named "${options.device}".`
675
+ : "No Android virtual device (AVD) exists. Create one in Android Studio's Device Manager.");
676
+ }
677
+ startEmulator(avd, emulatorPort, join(logDir, "emulator.log"));
678
+ confirm(root, "emulator");
679
+ }
680
+ await untilBooted(serial, emulatorBootSeconds);
681
+ }
682
+ where.device.name = await avdName(serial);
683
+ abi = await deviceAbi(serial);
684
+ }
685
+ catch (error) {
686
+ return stuck("The emulator did not boot.", error);
687
+ }
688
+ let plan;
689
+ try {
690
+ plan = await adapter.launchPlan(await inspectProject(root), {
691
+ dir: root,
692
+ platform: "android",
693
+ deviceId: serial,
694
+ port,
695
+ abi,
696
+ });
697
+ }
698
+ catch (error) {
699
+ return stuck("Could not plan the build.", error);
700
+ }
701
+ if (typeof plan === "string")
702
+ return unsupported(plan);
703
+ const output = plan?.output;
704
+ if (!plan || !output) {
705
+ return unsupported(`${adapter.id} gave no Android build output.`);
706
+ }
707
+ // The server starts before the build, as on iOS: the app asks it for its
708
+ // JavaScript as soon as it opens.
709
+ let metro;
710
+ const stop = () => metro?.kill();
711
+ if (plan.server) {
712
+ await stopEarlierServer(root, port);
713
+ if (await metroRunning(port)) {
714
+ return stuck(`Port ${port} already serves a dev server. Stop it and retry.`);
715
+ }
716
+ phase("server", "starting the dev server");
717
+ const started = await startServer(plan.server, root, port, metroLog, {});
718
+ if ("reason" in started) {
719
+ return failed(started.reason, { ...where, errors: started.errors });
720
+ }
721
+ metro = started;
722
+ confirm(root, "port");
723
+ }
724
+ phase("build", "building the app");
725
+ const failure = await runBuild(plan.build, root, join(logDir, "build.log"), { CI: "1" }, options);
726
+ if (failure) {
727
+ stop();
728
+ return failed(failure.reason, {
729
+ ...where,
730
+ ...(failure.errors && { errors: failure.errors }),
731
+ ...(failure.lastLines && { lastLines: failure.lastLines }),
732
+ });
733
+ }
734
+ let built;
735
+ try {
736
+ built = builtApk(join(root, output));
737
+ }
738
+ catch (error) {
739
+ stop();
740
+ return stuck("Built, but EMD could not find the APK.", error);
741
+ }
742
+ phase("install", "installing the app");
743
+ try {
744
+ await installApk(serial, built.apk);
745
+ if (metro)
746
+ await reversePort(serial, port);
747
+ }
748
+ catch (error) {
749
+ stop();
750
+ return stuck("Built, but installing the APK failed.", error);
751
+ }
752
+ phase("open", "launching the app");
753
+ // The capture starts before the app, so no line of its start is missed.
754
+ let capture;
755
+ try {
756
+ await stopCaptures(root);
757
+ capture = await startLogcat(serial, join(logDir, "app.logcat"));
758
+ }
759
+ catch (error) {
760
+ stop();
761
+ return stuck("Built, but could not capture the app's log.", error);
762
+ }
763
+ let appPid;
764
+ try {
765
+ appPid = await startApp(serial, built.appId);
766
+ }
767
+ catch (error) {
768
+ capture.kill();
769
+ stop();
770
+ return stuck(`Built, but launching ${built.appId} failed.`, error);
771
+ }
772
+ if (metro) {
773
+ phase("bundle", "waiting for the app's JavaScript");
774
+ const bundle = await untilBundled(logDir, 0, androidBundleSeconds, 0);
775
+ if (bundle !== "bundled") {
776
+ capture.kill();
777
+ stop();
778
+ return failed(bundle === "failed"
779
+ ? "The app opened, but the dev server could not build its JavaScript."
780
+ : `The app opened, but did not get its JavaScript from the dev server in ${androidBundleSeconds}s.`, { ...where, errors: await logTail(metroLog) });
781
+ }
782
+ }
783
+ return {
784
+ verdict: "launched",
785
+ root,
786
+ ...where,
787
+ appId: built.appId,
788
+ appPid,
789
+ build: { action: "built", reason: "this stack builds on every launch" },
790
+ ...(metro && { metro: { pid: metro.pid, port } }),
791
+ logStream: { pid: capture.pid },
792
+ ...done(),
793
+ };
794
+ }