emd-agents 0.15.0 → 0.16.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.
@@ -1,18 +1,33 @@
1
1
  import { axeBackend } from "./device/axe.js";
2
- import { detectEnvironment, directions, firstWorking, } from "./device/backend.js";
2
+ import { detectEnvironment, directions, firstWorking, readScreen, secondsTo, } from "./device/backend.js";
3
3
  import { maestroBackend } from "./device/maestro.js";
4
+ import { typeUntilShown } from "./device/typing.js";
4
5
  import { firstLine } from "./log.js";
5
6
  import { resolveRun } from "./run.js";
6
7
  // Taps, typing and swipes on a launched app (decision 0009). Each acts once
7
8
  // and says which backend did it; whether the app reacted is for `check`.
8
- async function act(what, { jobId }, gesture) {
9
+ const backends = [axeBackend, maestroBackend];
10
+ const until = (seconds) => Date.now() + seconds * 1000;
11
+ // Runs `run` against the launched app. `run` returns extra result fields, or
12
+ // a `reason` when it failed.
13
+ async function act(what, { jobId }, run) {
9
14
  const resolved = resolveRun({ jobId });
10
15
  if ("reason" in resolved)
11
16
  return { verdict: "failed", reason: resolved.reason };
12
- const where = { device: resolved.run.device, appId: resolved.run.appId };
17
+ const { device, appId } = resolved.run;
18
+ let first = {};
13
19
  try {
14
- const { backend, fellBack } = await firstWorking(what, await detectEnvironment(), [axeBackend, maestroBackend], (b, bin) => gesture(b, where, bin));
15
- return { verdict: "ok", backend, ...(fellBack ? { fellBack } : {}) };
20
+ const env = await detectEnvironment();
21
+ const extra = await run({
22
+ send: async (gesture) => {
23
+ const { backend, fellBack } = await firstWorking(what, env, backends, (b, bin) => gesture(b, { device, appId }, bin));
24
+ if (!first.backend) {
25
+ first = { backend, ...(fellBack ? { fellBack } : {}) };
26
+ }
27
+ },
28
+ read: (seconds) => readScreen(device, env, backends, until(seconds)).then((r) => r.nodes),
29
+ });
30
+ return { verdict: extra.reason ? "failed" : "ok", ...first, ...extra };
16
31
  }
17
32
  catch (error) {
18
33
  return { verdict: "failed", reason: firstLine(error) };
@@ -38,7 +53,7 @@ export function tap(options) {
38
53
  });
39
54
  }
40
55
  const started = Date.now();
41
- const done = act("tap", options, (b, where, bin) => b.tap(where, bin, target));
56
+ const done = act("tap", options, ({ send }) => send((b, where, bin) => b.tap(where, bin, target)).then(() => ({})));
42
57
  if ("x" in target)
43
58
  return done;
44
59
  // The backends wait for an element: AXe up to 10 s, Maestro its own limit.
@@ -52,7 +67,29 @@ export function typeText(options) {
52
67
  if (text.length === 0) {
53
68
  return Promise.resolve({ verdict: "failed", reason: "Give text to type." });
54
69
  }
55
- return act("type", options, (b, where, bin) => b.type(where, bin, text));
70
+ // `ok` means the text shows on screen (issue 163, decision 0013). Tap and
71
+ // swipe cannot say that.
72
+ return act("type", options, async ({ send, read }) => {
73
+ const typed = await typeUntilShown({
74
+ type: (part, seconds) => {
75
+ const end = until(seconds);
76
+ return send((b, where, bin) => b.type(where, bin, part, secondsTo(end)));
77
+ },
78
+ read,
79
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
80
+ now: Date.now,
81
+ }, text);
82
+ return {
83
+ seconds: typed.seconds,
84
+ ...(typed.retyped ? { retyped: typed.retyped } : {}),
85
+ ...(typed.verdict === "failed" ? { reason: typed.reason } : {}),
86
+ ...(typed.verdict === "secure"
87
+ ? {
88
+ note: "Secure field: bullets grew by the text length; the text itself cannot be read.",
89
+ }
90
+ : {}),
91
+ };
92
+ });
56
93
  }
57
94
  const isDirection = (value) => directions.includes(value);
58
95
  export function swipe(options) {
@@ -63,5 +100,5 @@ export function swipe(options) {
63
100
  reason: `Give a direction: ${directions.join(", ")}.`,
64
101
  });
65
102
  }
66
- return act("swipe", options, (b, where, bin) => b.swipe(where, bin, direction));
103
+ return act("swipe", options, ({ send }) => send((b, where, bin) => b.swipe(where, bin, direction)).then(() => ({})));
67
104
  }
@@ -22,13 +22,15 @@ export async function pickPort(taken) {
22
22
  // matching `/Developer/Xcode/DerivedData/<name>/Build/Products/`.
23
23
  export const derivedDataPath = (root) => join(homeDir(), "derived", worktreeKey(root), "Developer/Xcode/DerivedData", basename(root));
24
24
  // Expo's build has no DerivedData option, so a directory placed first on PATH
25
- // holds an xcodebuild that adds it. Returns that directory.
25
+ // holds an xcodebuild that adds it. It also asks for xcodebuild's timing summary
26
+ // (#208) and, with ShowBuildOperationDuration, the total on the "** BUILD
27
+ // SUCCEEDED **" line; both land in Expo's raw log. Returns that directory.
26
28
  export function xcodebuildShim(root, derivedData) {
27
29
  const dir = join(homeDir(), "bin", worktreeKey(root));
28
30
  mkdirSync(dir, { recursive: true });
29
31
  const path = join(dir, "xcodebuild");
30
32
  const quoted = `'${derivedData.replaceAll("'", "'\\''")}'`;
31
- writeFileSync(path, `#!/bin/sh\nexec /usr/bin/xcodebuild -derivedDataPath ${quoted} "$@"\n`, { mode: 0o755 });
33
+ writeFileSync(path, `#!/bin/sh\nexec /usr/bin/xcodebuild -derivedDataPath ${quoted} -showBuildTimingSummary -ShowBuildOperationDuration=YES "$@"\n`, { mode: 0o755 });
32
34
  return dir;
33
35
  }
34
36
  // Disk use of a folder in MB; absent counts as 0.
@@ -17,6 +17,7 @@ export type Handlers = {
17
17
  };
18
18
  export declare function createJob<K extends JobKind>(kind: K, input: Inputs[K]): Job;
19
19
  export declare function startJob<K extends JobKind>(kind: K, input: Inputs[K], worker?: string): JobView;
20
+ export declare function launchInline(input: LaunchOptions, run?: Handlers): Promise<LaunchResult>;
20
21
  export declare function runJob(id: string, run?: Handlers): Promise<void>;
21
22
  export declare function jobStatus(id: string): JobView | undefined;
22
- export declare function waitForJob(id: string, waitSeconds: number): Promise<JobView | undefined>;
23
+ export declare function waitForJob(id: string, waitSeconds: number, read?: (id: string) => JobView | undefined, signal?: AbortSignal): Promise<JobView | undefined>;
package/dist/core/jobs.js CHANGED
@@ -72,6 +72,13 @@ export function startJob(kind, input, worker = defaultWorker) {
72
72
  child.unref();
73
73
  return view(job);
74
74
  }
75
+ // Runs a launch in this process and leaves the same job record as a started
76
+ // job, so a later launch finds its dev server and log stream.
77
+ export async function launchInline(input, run = handlers) {
78
+ const { id } = createJob("launch", input);
79
+ await runJob(id, run);
80
+ return readJob(id)?.result;
81
+ }
75
82
  const execute = (job, run, report) => job.kind === "launch"
76
83
  ? run.launch(job.input, report)
77
84
  : run.check(job.input, report);
@@ -114,14 +121,25 @@ export function jobStatus(id) {
114
121
  }
115
122
  // Like jobStatus, but when the job is queued or running, reads it again every
116
123
  // half second until it ends or `waitSeconds` pass. A wait of 0 answers at once.
117
- export async function waitForJob(id, waitSeconds) {
124
+ // No read starts after the deadline, so a slow read can't push the answer past
125
+ // it (#198). An aborted `signal` (the caller cancelled) ends the wait at once.
126
+ export async function waitForJob(id, waitSeconds, read = jobStatus, signal) {
118
127
  const deadline = Date.now() + waitSeconds * 1000;
119
- let job = jobStatus(id);
120
- while (job &&
121
- (job.status === "queued" || job.status === "running") &&
122
- Date.now() < deadline) {
123
- await new Promise((resolve) => setTimeout(resolve, 500));
124
- job = jobStatus(id);
128
+ let job = read(id);
129
+ while (job && (job.status === "queued" || job.status === "running")) {
130
+ const left = deadline - Date.now();
131
+ await new Promise((resolve) => {
132
+ const done = () => {
133
+ clearTimeout(timer);
134
+ signal?.removeEventListener("abort", done);
135
+ resolve();
136
+ };
137
+ const timer = setTimeout(done, Math.min(500, left));
138
+ signal?.addEventListener("abort", done, { once: true });
139
+ });
140
+ if (signal?.aborted || Date.now() >= deadline)
141
+ break;
142
+ job = read(id);
125
143
  }
126
144
  return job;
127
145
  }
@@ -5,4 +5,5 @@ export type LaunchOptions = {
5
5
  timeoutSeconds?: number;
6
6
  };
7
7
  export declare function stopEarlierServer(root: string, port: number): Promise<void>;
8
+ export declare function recordTiming(root: string, buildLog: string, since: number): Promise<number | undefined>;
8
9
  export declare function launch(options?: LaunchOptions, report?: (step: string) => void): Promise<LaunchResult>;
@@ -1,19 +1,20 @@
1
- import { mkdir, readFile } from "node:fs/promises";
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 { readBuildRecord, whyBuild, writeBuildRecord } from "./buildrecord.js";
4
+ import { builtApp, readBuildRecord, whyBuild, writeBuildRecord, } from "./buildrecord.js";
5
5
  import { detect } from "./detect.js";
6
6
  import { axeBackend } from "./device/axe.js";
7
7
  import { detectEnvironment, untilReadable } from "./device/backend.js";
8
8
  import { derivedDataPath, diskMB, pickPort, xcodebuildShim, } from "./isolate.js";
9
9
  import { launchesIn } from "./jobstore.js";
10
- import { firstErrors, knownFix, onlyOpenFailed } from "./log.js";
10
+ import { buildTiming, firstErrors, knownFix, onlyOpenFailed } from "./log.js";
11
11
  import { startCapture, stopCaptures } from "./logs.js";
12
12
  import { confirm, reserve, worktreeKey } from "./owned.js";
13
13
  import { startLogged } from "./process.js";
14
14
  import { inspectProject } from "./project.js";
15
15
  import { loadAdapter } from "./registry.js";
16
- import { appAccessibilityOn, appInstalled, boot, cloneDevice, enableAppAccessibility, launchApp, listDevices, newerThan, pickDevice, removeSimulator, simulatorSdk, terminateApp, } from "./simulator.js";
16
+ import { bundlesServed, earlierLaunch, runningPid, sendReload, untilBundled, } from "./reload.js";
17
+ import { appAccessibilityOn, appInstalled, boot, cloneDevice, enableAppAccessibility, installApp, launchApp, listDevices, newerThan, pickDevice, plainKeyboard, removeSimulator, simulatorSdk, terminateApp, } from "./simulator.js";
17
18
  import { stateDir } from "./state.js";
18
19
  import { runTool } from "./tool.js";
19
20
  const metroStartSeconds = 120;
@@ -25,6 +26,8 @@ const defaultTimeoutSeconds = 900;
25
26
  const screenReadSeconds = 180;
26
27
  // An empty tree this long after the app started means accessibility is off.
27
28
  const emptyTreeSeconds = 5;
29
+ // How long a reload may take to show a new bundle request in the dev server log.
30
+ const bundleSeconds = 60;
28
31
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29
32
  async function metroRunning(port) {
30
33
  try {
@@ -125,10 +128,49 @@ async function runBuild(command, cwd, logPath, env, options) {
125
128
  }
126
129
  return { reason, errors: firstErrors(text) };
127
130
  }
131
+ // After a build, xcodebuild's timing from the raw log Expo writes to
132
+ // <app>/.expo/xcodebuild.log (#208): appends the slowest steps to build.log and
133
+ // returns xcodebuild's total. A log older than the build gives nothing.
134
+ export async function recordTiming(root, buildLog, since) {
135
+ const raw = join(root, ".expo", "xcodebuild.log");
136
+ try {
137
+ if ((await stat(raw)).mtimeMs < since)
138
+ return undefined;
139
+ const timing = buildTiming(await readFile(raw, "utf8"));
140
+ if (!timing)
141
+ return undefined;
142
+ const lines = [
143
+ `EMD: xcodebuild took ${timing.seconds ?? "an unknown number of"} s. Its slowest steps:`,
144
+ ...timing.slowest.map((s) => `EMD: ${s.step} (${s.tasks} tasks): ${s.seconds} s`),
145
+ ];
146
+ await appendFile(buildLog, `\n${lines.join("\n")}\n`);
147
+ return timing.seconds;
148
+ }
149
+ catch {
150
+ return undefined;
151
+ }
152
+ }
128
153
  export async function launch(options = {}, report = () => { }) {
129
154
  const started = Date.now();
130
- const seconds = () => Math.round((Date.now() - started) / 100) / 10;
131
- report("checking the project");
155
+ const tenths = (ms) => Math.round(ms / 100) / 10;
156
+ const seconds = () => tenths(Date.now() - started);
157
+ // Seconds each phase took, in order, under a short name (#203). A phase ends
158
+ // when the next one starts or the launch returns. A phase that runs twice adds up.
159
+ const phases = {};
160
+ let current;
161
+ const endPhase = () => {
162
+ if (current) {
163
+ phases[current.name] = tenths((phases[current.name] ?? 0) * 1000 + Date.now() - current.at);
164
+ }
165
+ current = undefined;
166
+ return phases;
167
+ };
168
+ const phase = (name, step) => {
169
+ endPhase();
170
+ current = { name, at: Date.now() };
171
+ report(step);
172
+ };
173
+ phase("project", "checking the project");
132
174
  const detected = await detect(options.dir);
133
175
  const { root } = detected;
134
176
  const unsupported = (reason) => ({
@@ -136,17 +178,25 @@ export async function launch(options = {}, report = () => { }) {
136
178
  root,
137
179
  reason,
138
180
  });
139
- const failed = (reason, rest = {}) => ({ verdict: "failed", root, reason, seconds: seconds(), ...rest });
181
+ const failed = (reason, rest = {}) => ({
182
+ verdict: "failed",
183
+ root,
184
+ reason,
185
+ seconds: seconds(),
186
+ phases: endPhase(),
187
+ ...rest,
188
+ });
140
189
  if (detected.verdict !== "detected" || !detected.stack) {
141
190
  return unsupported("No supported mobile project found here.");
142
191
  }
143
192
  if (!detected.platforms?.includes("ios")) {
144
193
  return unsupported("The project does not target iOS.");
145
194
  }
146
- const appId = detected.appIds?.ios;
147
- if (!appId) {
148
- return unsupported("No iOS app ID found; install the app's dependencies and set ios.bundleIdentifier in the app config.");
149
- }
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
+ if (detected.problem)
198
+ return unsupported(detected.problem);
199
+ let appId = detected.appIds?.ios;
150
200
  if (process.platform !== "darwin") {
151
201
  return unsupported("iOS simulators need macOS.");
152
202
  }
@@ -166,7 +216,7 @@ export async function launch(options = {}, report = () => { }) {
166
216
  // A clone on a runtime newer than the selected Xcode's SDK does not build
167
217
  // (#122). It is EMD's own, so it is replaced, not reused.
168
218
  if (device && sdk && newerThan(device, sdk)) {
169
- report(`replacing the simulator: iOS ${device.version.join(".")} is newer than Xcode's iOS ${sdk.join(".")} SDK`);
219
+ phase("replace", `replacing the simulator: iOS ${device.version.join(".")} is newer than Xcode's iOS ${sdk.join(".")} SDK`);
170
220
  await removeSimulator(device);
171
221
  device = undefined;
172
222
  }
@@ -177,7 +227,7 @@ export async function launch(options = {}, report = () => { }) {
177
227
  ? `No shut-down simulator matches "${options.device}" to clone.`
178
228
  : "No shut-down iPhone simulator is available to clone.");
179
229
  }
180
- report("cloning a simulator");
230
+ phase("clone", "cloning a simulator");
181
231
  const id = await cloneDevice(base, name);
182
232
  device = {
183
233
  id,
@@ -219,7 +269,7 @@ export async function launch(options = {}, report = () => { }) {
219
269
  diskMB: await sizes(),
220
270
  ...rest,
221
271
  });
222
- report("booting the simulator");
272
+ phase("boot", "booting the simulator");
223
273
  try {
224
274
  await boot(device);
225
275
  }
@@ -228,18 +278,99 @@ export async function launch(options = {}, report = () => { }) {
228
278
  errors: String(error).split("\n").slice(0, 3),
229
279
  });
230
280
  }
281
+ // Reuse the installed build when nothing native changed. A fingerprint that
282
+ // cannot be computed means a normal build.
283
+ let fingerprint;
284
+ let why;
285
+ try {
286
+ fingerprint = await (await loadAdapter(detected.stack)).fingerprint(root, "ios");
287
+ }
288
+ catch (error) {
289
+ why = `fingerprint failed: ${String(error).split("\n")[0]}`;
290
+ }
291
+ // A running app, a running dev server of this worktree and an unchanged
292
+ // fingerprint: reload the app. Without a new bundle request in the log the
293
+ // reload did not happen, and the launch goes on as a relaunch.
294
+ let reloadFailed;
295
+ const earlier = fingerprint === undefined
296
+ ? undefined
297
+ : earlierLaunch(root, port, await listeningGroups(port));
298
+ if (earlier?.appId &&
299
+ earlier.logDir &&
300
+ fingerprint !== undefined &&
301
+ whyBuild(readBuildRecord(derivedData), { fingerprint, port }, true) ===
302
+ undefined &&
303
+ (await metroRunning(port))) {
304
+ const pid = await runningPid(device, earlier.appId);
305
+ if (pid !== undefined) {
306
+ phase("reload", "reloading the app");
307
+ const before = await bundlesServed(earlier.logDir);
308
+ // The reload starts a new run, as a relaunch does: its own folder and log
309
+ // window, open before the message so no line of the reloaded app is missed.
310
+ let reloadCapture;
311
+ try {
312
+ await mkdir(logDir, { recursive: true });
313
+ await stopCaptures(root);
314
+ reloadCapture = await startCapture(device.id, earlier.appId, logDir);
315
+ await symlink(await realpath(join(earlier.logDir, "metro.log")), metroLog);
316
+ await sendReload(port);
317
+ if (await untilBundled(earlier.logDir, before, bundleSeconds)) {
318
+ const axe = (await detectEnvironment()).axe;
319
+ phase("screen", "waiting for the screen");
320
+ const screen = axe
321
+ ? await untilReadable(() => axeBackend.readScreen(device.id, axe), screenReadSeconds)
322
+ : undefined;
323
+ return {
324
+ verdict: "launched",
325
+ root,
326
+ ...where,
327
+ appId: earlier.appId,
328
+ ...(screen && { screen }),
329
+ appPid: pid,
330
+ build: { action: "reloaded" },
331
+ ...(earlier.metro && { metro: earlier.metro }),
332
+ logStream: { pid: reloadCapture.pid },
333
+ derivedData,
334
+ diskMB: await sizes(),
335
+ seconds: seconds(),
336
+ phases: endPhase(),
337
+ };
338
+ }
339
+ reloadFailed = `no new bundle request ${bundleSeconds}s after the reload message`;
340
+ }
341
+ catch (error) {
342
+ reloadFailed = `the reload message failed: ${String(error).split("\n")[0]}`;
343
+ }
344
+ reloadCapture?.kill();
345
+ }
346
+ }
347
+ if (reloadFailed !== undefined) {
348
+ // The relaunch writes its own dev server log in the same folder.
349
+ await rm(metroLog, { force: true });
350
+ await rm(join(logDir, "app.ndjson"), { force: true });
351
+ }
231
352
  await stopEarlierServer(root, port);
232
353
  if (await metroRunning(port)) {
233
354
  return stuck(`Port ${port} already serves a dev server. Stop it and retry.`);
234
355
  }
235
356
  await stopCaptures(root);
236
- report("starting the dev server");
357
+ // Runs while the dev server starts, so it costs no time, and ends before the
358
+ // app starts. A failed write is not a launch failure: `type` still checks
359
+ // its text.
360
+ const keyboard = plainKeyboard(device).catch(() => { });
361
+ phase("server", "starting the dev server");
237
362
  const env = {
238
363
  CI: "1",
239
364
  RCT_METRO_PORT: String(port),
240
365
  PATH: `${shimDir}:${process.env.PATH}`,
241
366
  };
242
- const metro = startLogged(plan.server, { cwd: root, logPath: metroLog, env });
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
+ });
243
374
  const metroState = await untilReady(() => metroRunning(port), metro.exited, metroStartSeconds);
244
375
  if (metroState !== "ready") {
245
376
  metro.kill();
@@ -247,27 +378,19 @@ export async function launch(options = {}, report = () => { }) {
247
378
  ? "The dev server exited before it was ready."
248
379
  : `The dev server was not ready after ${metroStartSeconds}s.`, { errors: await logTail(metroLog) });
249
380
  }
381
+ await keyboard;
250
382
  confirm(root, "port");
251
- // Reuse the installed build when nothing native changed. A fingerprint that
252
- // cannot be computed means a normal build.
253
- let fingerprint;
254
- let why;
255
- try {
256
- fingerprint = await (await loadAdapter(detected.stack)).fingerprint(root, "ios");
257
- }
258
- catch (error) {
259
- why = `fingerprint failed: ${String(error).split("\n")[0]}`;
260
- }
261
383
  if (fingerprint !== undefined) {
262
- why = whyBuild(readBuildRecord(derivedData), { fingerprint, port }, await appInstalled(device, appId));
384
+ why = whyBuild(readBuildRecord(derivedData), { fingerprint, port }, appId !== undefined && (await appInstalled(device, appId)));
263
385
  }
264
386
  const reused = why === undefined;
265
- if (reused) {
266
- report("reusing the installed build");
267
- }
268
- else {
269
- report("building and installing the app");
387
+ // Builds and installs the app; returns the launch result when it fails.
388
+ let xcodebuildSeconds;
389
+ const buildApp = async () => {
390
+ phase("build", "building and installing the app");
391
+ const buildStarted = Date.now();
270
392
  const failure = await runBuild(plan.build, root, buildLog, env, options);
393
+ xcodebuildSeconds = await recordTiming(root, buildLog, buildStarted);
271
394
  if (failure) {
272
395
  metro.kill();
273
396
  return stuck(failure.reason, { errors: failure.errors });
@@ -278,35 +401,94 @@ export async function launch(options = {}, report = () => { }) {
278
401
  }
279
402
  catch { }
280
403
  }
404
+ };
405
+ // The fingerprint and port match but the app is gone from the simulator: the
406
+ // build in DerivedData installs in seconds. Build only if that is not possible.
407
+ let installedAgain = false;
408
+ if (reused) {
409
+ phase("reuse", "reusing the installed build");
410
+ }
411
+ else {
412
+ const earlierApp = why === "app not installed" && appId !== undefined
413
+ ? builtApp(derivedData)
414
+ : undefined;
415
+ if (earlierApp) {
416
+ phase("install", "installing the earlier build");
417
+ try {
418
+ await installApp(device, earlierApp);
419
+ installedAgain = true;
420
+ }
421
+ catch (error) {
422
+ why = `app not installed; install failed: ${String(error).split("\n")[0]}`;
423
+ }
424
+ }
425
+ if (!installedAgain) {
426
+ const failure = await buildApp();
427
+ if (failure)
428
+ return failure;
429
+ }
281
430
  }
282
- report("launching the app");
431
+ let appIdSet;
432
+ if (appId === undefined) {
433
+ appId = (await detect(root)).appIds?.ios;
434
+ 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) });
437
+ }
438
+ appIdSet = appId;
439
+ // The config changed, so the fingerprint did too. A failure here only costs
440
+ // one rebuild on the next launch.
441
+ try {
442
+ fingerprint = await (await loadAdapter(detected.stack)).fingerprint(root, "ios");
443
+ writeBuildRecord(derivedData, { fingerprint, port });
444
+ }
445
+ catch { }
446
+ }
447
+ const captureFailed = (error) => {
448
+ metro.kill();
449
+ return stuck("Built, but could not capture the app's log.", {
450
+ errors: String(error).split("\n").slice(0, 3),
451
+ });
452
+ };
453
+ phase("open", "launching the app");
283
454
  let capture;
284
455
  try {
285
456
  capture = await startCapture(device.id, appId, logDir);
286
457
  }
287
458
  catch (error) {
288
- metro.kill();
289
- return stuck(`${reused ? "Reused the build" : "Built"}, but could not capture the app's log.`, {
290
- errors: String(error).split("\n").slice(0, 3),
291
- });
459
+ if (!reused && !installedAgain)
460
+ return captureFailed(error);
461
+ // The reused or installed build's app cannot be read: build once and try again.
462
+ why = "installed app could not be read";
463
+ installedAgain = false;
464
+ const failure = await buildApp();
465
+ if (failure)
466
+ return failure;
467
+ phase("open", "launching the app");
468
+ try {
469
+ capture = await startCapture(device.id, appId, logDir);
470
+ }
471
+ catch (again) {
472
+ return captureFailed(again);
473
+ }
292
474
  }
293
475
  let appPid;
294
476
  try {
295
477
  // A running app still talks to the dev server it started with; a restart
296
478
  // makes it load the new JavaScript from this one.
297
- if (reused)
479
+ if (why === undefined)
298
480
  await terminateApp(device, appId);
299
481
  appPid = await launchApp(device, appId);
300
482
  }
301
483
  catch (error) {
302
484
  capture.kill();
303
485
  metro.kill();
304
- return stuck(`${reused ? "Reused the build" : "Built"}, but launching ${appId} failed.`, {
486
+ return stuck(`${why === undefined ? "Reused the build" : "Built"}, but launching ${appId} failed.`, {
305
487
  errors: String(error).split("\n").slice(0, 3),
306
488
  });
307
489
  }
308
490
  const axe = (await detectEnvironment()).axe;
309
- report("waiting for the screen");
491
+ phase("screen", "waiting for the screen");
310
492
  // This device is EMD's own clone. On some iOS versions AXe reads an empty
311
493
  // tree until application accessibility is on, and only an app that starts
312
494
  // after the write sees it. An AXe error never triggers the write.
@@ -327,13 +509,22 @@ export async function launch(options = {}, report = () => { }) {
327
509
  root,
328
510
  ...where,
329
511
  appId,
512
+ ...(appIdSet && { appIdSet }),
513
+ ...(reloadFailed && { reloadFailed }),
330
514
  ...(screen && { screen }),
331
515
  appPid,
332
- build: reused ? { action: "reused" } : { action: "built", reason: why },
516
+ build: why === undefined
517
+ ? { action: "reused" }
518
+ : {
519
+ action: installedAgain ? "installed" : "built",
520
+ reason: why,
521
+ ...(xcodebuildSeconds !== undefined && { xcodebuildSeconds }),
522
+ },
333
523
  metro: { pid: metro.pid, port },
334
524
  logStream: { pid: capture.pid },
335
525
  derivedData,
336
526
  diskMB: await sizes(),
337
527
  seconds: seconds(),
528
+ phases: endPhase(),
338
529
  };
339
530
  }
@@ -3,3 +3,12 @@ export declare const stripAnsi: (text: string) => string;
3
3
  export declare function firstErrors(log: string, max?: number): string[];
4
4
  export declare function knownFix(log: string): string | undefined;
5
5
  export declare function onlyOpenFailed(log: string): boolean;
6
+ export type BuildTiming = {
7
+ seconds?: number;
8
+ slowest: {
9
+ step: string;
10
+ tasks: number;
11
+ seconds: number;
12
+ }[];
13
+ };
14
+ export declare function buildTiming(log: string, top?: number): BuildTiming | undefined;
package/dist/core/log.js CHANGED
@@ -52,3 +52,25 @@ export function onlyOpenFailed(log) {
52
52
  /^Error: xcrun simctl openurl /m.test(text) &&
53
53
  text.indexOf("\nError: ") === text.indexOf("\nError: xcrun simctl openurl "));
54
54
  }
55
+ const timingLine = /^(.+?) \((\d+) tasks?\) \| ([\d.]+) seconds?$/;
56
+ const buildEnd = /\*\* BUILD (?:SUCCEEDED|FAILED) \*\* \[([\d.]+) sec\]/;
57
+ export function buildTiming(log, top = 5) {
58
+ const lines = stripAnsi(log)
59
+ .split("\n")
60
+ .map((line) => line.trim());
61
+ const steps = lines.flatMap((line) => {
62
+ const m = line.match(timingLine);
63
+ return m
64
+ ? [{ step: m[1] ?? "", tasks: Number(m[2]), seconds: Number(m[3]) }]
65
+ : [];
66
+ });
67
+ const total = lines
68
+ .map((line) => line.match(buildEnd)?.[1])
69
+ .findLast(Boolean);
70
+ if (steps.length === 0 && total === undefined)
71
+ return undefined;
72
+ return {
73
+ ...(total !== undefined && { seconds: Number(total) }),
74
+ slowest: steps.sort((a, b) => b.seconds - a.seconds).slice(0, top),
75
+ };
76
+ }
@@ -0,0 +1,7 @@
1
+ import type { LaunchResult } from "./result.js";
2
+ import type { Device } from "./simulator.js";
3
+ export declare function sendReload(port: number): Promise<void>;
4
+ export declare function runningPid(device: Device, appId: string): Promise<number | undefined>;
5
+ export declare const earlierLaunch: (root: string, port: number, listening: number[]) => LaunchResult | undefined;
6
+ export declare function untilBundled(logDir: string, before: number, seconds: number): Promise<boolean>;
7
+ export declare const bundlesServed: (logDir: string) => Promise<number>;