xcodebug 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * the same surface Xcode's debug console shows. No jailbreak, no debugger.
8
8
  */
9
9
  import { readdir, readFile } from "node:fs/promises";
10
- import { basename, dirname, join } from "node:path";
10
+ import { basename, dirname, join, resolve } from "node:path";
11
11
  // `import type` is erased at compile time, so this specifier never reaches the
12
12
  // runtime: it only has to name a module the loader can resolve for typechecking.
13
13
  // `@earendil-works/pi-coding-agent` is the official one the engine documents for
@@ -16,12 +16,12 @@ import { basename, dirname, join } from "node:path";
16
16
  // one distribution of the engine.
17
17
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
18
18
  import { Type } from "typebox";
19
- import { Capture, type LogLine } from "./capture.ts";
20
- import { describeDevices, findProcessPid, listDevices, lookupProcess, resolveDevice, type DeviceInfo } from "./devices.ts";
19
+ import { Capture, matchesFilter, type FoundLine } from "./capture.ts";
20
+ import { describeDevices, findProcessPid, listDevices, lookupProcess, pullCrashReport, resolveDevice, type DeviceInfo } from "./devices.ts";
21
21
  import { lastLines, runCommand, timestamp } from "./exec.ts";
22
- import { buildForDevice, consoleLaunchArgs, installApp, terminateApp, type BuildTarget } from "./xcode.ts";
23
- import { checkPodLockSync, describeChanges, detectChanges, runPodInstall, type ChangeReport } from "./changes.ts";
24
- import { clearArchives } from "./archive.ts";
22
+ import { buildForDevice, consoleLaunchArgs, installApp, terminateApp, type BuildOutcome, type BuildTarget } from "./xcode.ts";
23
+ import { checkPodLockSync, describeChanges, detectChanges, directorySignature, runPodInstall, type ChangeReport } from "./changes.ts";
24
+ import { clearArchives, pruneLogs } from "./archive.ts";
25
25
 
26
26
  const CAPTURE_PREFIX = "xcodebug";
27
27
  const PUSH_INTERVAL_MS = 4_000;
@@ -36,6 +36,31 @@ const SILENCE_NOTICE_MS = 60_000;
36
36
  * producing lines, so only the syslog side needs this.
37
37
  */
38
38
  const SYSLOG_SILENCE_MS = 30_000;
39
+ /**
40
+ * When to look for a crash report after a console bridge goes down, each
41
+ * counted from the attempt before. The device needs a few seconds to write one:
42
+ * 8s after a watchdog kill, measured.
43
+ */
44
+ const CRASH_REPORT_DELAYS_MS = [2_000, 4_000, 8_000, 16_000];
45
+ /**
46
+ * A report is dated by the phone's clock and a bridge's end by this machine's.
47
+ * Without some slack, a phone running slightly behind would date the report of
48
+ * the crash that took the bridge down to before it went.
49
+ */
50
+ const DEVICE_CLOCK_SKEW_MS = 5_000;
51
+ /**
52
+ * How long a log outlives its last write. Every run leaves a build log of
53
+ * several megabytes and a capture log beside it, and nothing else removes them.
54
+ */
55
+ const LOG_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
56
+ /**
57
+ * Actions that work whatever state `.xcodebug.json` is in: `doctor` reports it,
58
+ * and reading or stopping a capture never uses it. Every other action refuses a
59
+ * config that does not parse, because running as if there were none uses the
60
+ * defaults the file was written to override. Listed as exemptions so that an
61
+ * action added later refuses too.
62
+ */
63
+ const CONFIG_FREE_ACTIONS = new Set(["doctor", "devices", "logs", "wait", "status", "stop", "await"]);
39
64
 
40
65
  interface ProjectConfig {
41
66
  workspace?: string;
@@ -57,8 +82,15 @@ interface SessionState {
57
82
  activeCaptureId?: string;
58
83
  pushTimers: Map<string, ReturnType<typeof setInterval>>;
59
84
  pushCursors: Map<string, number>;
60
- /** Fingerprint of the working tree at the last successful build in this session. */
61
- lastBuiltFingerprint?: string;
85
+ /**
86
+ * What this session built, per target and device: the tree each build was made
87
+ * from, and its product as the build left it. A map, because one session
88
+ * debugs several apps and the build of one says nothing about another. The
89
+ * last entry is the most recent build.
90
+ */
91
+ builds: Map<string, { fingerprint: string; appPath: string; product: string; bundleId?: string; executable?: string }>;
92
+ /** Old logs are cleared once per session, by its first run. */
93
+ logsPruned?: boolean;
62
94
  /** Key of the new-component-file set pod install has already handled. */
63
95
  installedPodsFingerprint?: string;
64
96
  /** console capture id -> parallel syslog capture id. */
@@ -211,13 +243,23 @@ function archiveWorkDir(ctx: ExtensionContext): string {
211
243
  * disk. A new build is the natural boundary: whatever happened before it
212
244
  * belongs to a different binary.
213
245
  */
214
- async function clearArchiveBeforeNewRun(ctx: ExtensionContext): Promise<string> {
246
+ async function clearArchiveBeforeNewRun(ctx: ExtensionContext): Promise<string | undefined> {
215
247
  const { removed, freedBytes } = await clearArchives(archiveWorkDir(ctx));
216
- if (removed === 0) return "archive: nothing to clear";
248
+ // Archiving is off, so there is normally nothing here; only say so when a
249
+ // snapshot from an older version was actually removed.
250
+ if (removed === 0) return undefined;
217
251
  const mb = (freedBytes / 1024 / 1024).toFixed(0);
218
252
  return `archive: cleared ${removed} snapshot(s), freed ${mb} MB`;
219
253
  }
220
254
 
255
+ /** A build is another run's only when target, configuration and device all match. */
256
+ function buildKeyOf(target: BuildTarget, device: DeviceInfo): string {
257
+ return JSON.stringify([
258
+ target.workspace, target.project, target.scheme, target.configuration, target.derivedDataPath,
259
+ device.udid ?? device.id,
260
+ ]);
261
+ }
262
+
221
263
  async function readBundleExecutable(appPath: string): Promise<string | undefined> {
222
264
  const result = await runCommand(
223
265
  "/usr/libexec/PlistBuddy",
@@ -240,11 +282,20 @@ async function readBundleIdentifier(appPath: string): Promise<string | undefined
240
282
  }
241
283
 
242
284
  async function readConfig(cwd: string): Promise<ProjectConfig> {
285
+ const path = join(cwd, ".xcodebug.json");
286
+ let text: string;
243
287
  try {
244
- return JSON.parse(await readFile(join(cwd, ".xcodebug.json"), "utf8")) as ProjectConfig;
288
+ text = await readFile(path, "utf8");
245
289
  } catch {
246
290
  return {};
247
291
  }
292
+ try {
293
+ return JSON.parse(text) as ProjectConfig;
294
+ } catch (error) {
295
+ // Reading a config that does not parse as "no config" runs with the very
296
+ // defaults it was written to override - another scheme, another device.
297
+ throw new Error(`${path} is not valid JSON: ${(error as Error).message}`);
298
+ }
248
299
  }
249
300
 
250
301
  /**
@@ -503,26 +554,102 @@ function resolveBuildTarget(config: ProjectConfig, params: {
503
554
  };
504
555
  }
505
556
 
506
- function formatLogLines(capture: Capture, since: number, limit: number, grep?: string): {
507
- text: string;
508
- cursor: number;
509
- total: number;
510
- } {
511
- const read = capture.read({ since, limit, grep });
557
+ /**
558
+ * `match`/`grep` as the reads take them: a substring, or a pattern when the
559
+ * caller set `regex`. A pattern is what lets one wait cover both outcomes
560
+ * ("sync (done|failed)"), where a substring can only ever name one.
561
+ */
562
+ function toFilter(text: string | undefined, regex: boolean | undefined): string | RegExp | undefined {
563
+ if (!text || !regex) return text;
564
+ try {
565
+ return new RegExp(text);
566
+ } catch (error) {
567
+ throw new Error(`"${text}" is not a valid regular expression: ${(error as Error).message}`);
568
+ }
569
+ }
570
+
571
+ /**
572
+ * What a reply owes its reader when the lines asked for start before the buffer
573
+ * does: without it "no match" reads as "never logged" when the line was only
574
+ * evicted. `missing` is absent for a read that did not look on disk.
575
+ */
576
+ function evictedNote(read: { evicted: number; missing?: number }, logFile: string): string {
577
+ if (read.evicted === 0) return "";
578
+ if (read.missing === undefined) {
579
+ return `\nnote: ${read.evicted} older line(s) are no longer in memory; read them from ${logFile}`;
580
+ }
581
+ const found = read.evicted - read.missing;
582
+ const parts = [
583
+ found > 0 ? `${found} line(s) no longer in memory were searched in ${logFile}` : "",
584
+ // Overwritten by rotation, or never written: either way this read cannot speak for them.
585
+ read.missing > 0 ? `${read.missing} line(s) are in neither memory nor the log files and were not searched` : "",
586
+ ];
587
+ return `\nnote: ${parts.filter(Boolean).join("; ")}`;
588
+ }
589
+
590
+ /**
591
+ * The last thing a capture logged that xcodebug did not write itself.
592
+ *
593
+ * devicectl reports a death in its own words ("App terminated due to signal 9.")
594
+ * as it exits; when it said nothing, the app's last line is the next best lead.
595
+ */
596
+ function lastWords(capture: Capture): string | undefined {
597
+ const lines = capture.read({ limit: 20 }).lines.filter((line) => !line.text.startsWith("[xcodebug]"));
598
+ return lines.at(-1)?.text.slice(0, 200);
599
+ }
600
+
601
+ /**
602
+ * What is settled about a capture that ended on its own: why, and the crash
603
+ * report its app left on the device. Empty while neither is known.
604
+ */
605
+ function endedNote(capture: Capture): string {
606
+ const reason = capture.endReason ? ` · ${capture.endReason}` : "";
607
+ return `${reason}${capture.crashReport ? ` · crash report: ${capture.crashReport}` : ""}`;
608
+ }
609
+
610
+ /**
611
+ * The same for a reply that finds a console bridge already down. Whether the app
612
+ * died or only the bridge dropped is settled a moment after the bridge goes;
613
+ * until then the capture's last line is what there is to go on.
614
+ */
615
+ function whyEnded(capture: Capture): string {
616
+ const last = capture.endReason ? undefined : lastWords(capture);
617
+ return `${last ? ` · last line: "${last}"` : ""}${endedNote(capture)}`;
618
+ }
619
+
620
+ /** Host time of a line, for lining a log up with a test runner's own output. */
621
+ function clock(at: number): string {
622
+ const date = new Date(at);
623
+ const pad = (value: number, width = 2): string => String(value).padStart(width, "0");
624
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)} `;
625
+ }
626
+
627
+ async function formatLogLines(
628
+ capture: Capture,
629
+ options: { since: number; limit: number; grep?: string | RegExp; times?: boolean; signal?: AbortSignal },
630
+ ): Promise<{ text: string; cursor: number; total: number }> {
631
+ const { since, limit, grep } = options;
632
+ // A filtered read looks on disk for what the buffer dropped. An unfiltered one
633
+ // returns the newest lines anyway, so the dropped ones only add to "omitted".
634
+ const read = grep ? await capture.search({ since, limit, grep, signal: options.signal }) : capture.read({ since, limit });
635
+ const total = grep ? read.total : read.total + read.evicted;
636
+ const note = evictedNote(read, capture.logFile);
512
637
  if (read.lines.length === 0) {
513
- return { text: `(no new lines since ${since}; capture cursor is ${read.cursor})`, cursor: read.cursor, total: 0 };
638
+ const what = grep ? `no line matching ${typeof grep === "string" ? `"${grep}"` : grep}` : "no new lines";
639
+ return { text: `(${what} since ${since}; capture cursor is ${read.cursor})${note}`, cursor: read.cursor, total: 0 };
514
640
  }
515
- const body = read.lines
641
+ const lines: FoundLine[] = read.lines;
642
+ const body = lines
516
643
  .map((line) => {
517
644
  // In console mode devicectl's own status lines arrive on stdout while the
518
645
  // app's output arrives on stderr, so only stdout needs a label.
519
646
  const tag = capture.mode === "console" && line.stream === "out" ? "[devicectl] " : "";
520
- return `${String(line.index).padStart(6, " ")} ${tag}${line.text}`;
647
+ return `${String(line.index).padStart(6, " ")} ${options.times ? clock(line.at) : ""}${tag}${line.text}`;
521
648
  })
522
649
  .join("\n");
523
- const omitted = read.total - read.lines.length;
524
- const header = `${read.lines.length} line(s)${omitted > 0 ? ` (${omitted} older omitted)` : ""} · cursor ${read.cursor}`;
525
- return { text: `${header}\n${body}`, cursor: read.cursor, total: read.total };
650
+ const omitted = total - lines.length;
651
+ const header = `${lines.length} line(s)${omitted > 0 ? ` (${omitted} older omitted)` : ""} · cursor ${read.cursor}`;
652
+ return { text: `${header}\n${body}${note}`, cursor: read.cursor, total };
526
653
  }
527
654
 
528
655
  /** Fill in the container when the caller and the config both omit it. */
@@ -653,7 +780,7 @@ function parseCommandArgs(raw: string): ToolParams {
653
780
  const params: Record<string, unknown> = {};
654
781
  const free: string[] = [];
655
782
  const numberKeys = ["limit", "since", "timeoutSeconds"];
656
- const boolKeys = ["force", "installPods", "dualChannel", "keepApp", "terminateExisting", "build"];
783
+ const boolKeys = ["force", "installPods", "dualChannel", "keepApp", "terminateExisting", "build", "regex", "times"];
657
784
 
658
785
  const assign = (key: string, value: string): void => {
659
786
  if (numberKeys.includes(key)) {
@@ -736,6 +863,10 @@ type ToolParams = {
736
863
  limit?: number;
737
864
  grep?: string;
738
865
  match?: string;
866
+ /** `match`/`grep` are regular expressions rather than substrings. */
867
+ regex?: boolean;
868
+ /** Prefix returned lines with the host time they arrived. */
869
+ times?: boolean;
739
870
  timeoutSeconds?: number;
740
871
  push?: "off" | "context" | "wake";
741
872
  force?: boolean;
@@ -757,6 +888,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
757
888
  endedCaptures: new Set(),
758
889
  pushTimers: new Map(),
759
890
  pushCursors: new Map(),
891
+ builds: new Map(),
760
892
  companions: new Map(),
761
893
  lastLineAt: new Map(),
762
894
  silenceNotified: new Set(),
@@ -948,6 +1080,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
948
1080
  if (![...state.captures.values()].some((c) => c !== capture && c.running)) stopStatusTicker();
949
1081
  refreshStatus();
950
1082
  capture.stop(terminateApp);
1083
+ if (!capture.running) releaseCapture(capture);
951
1084
  if (state.activeCaptureId === capture.id) state.activeCaptureId = undefined;
952
1085
  };
953
1086
 
@@ -1053,6 +1186,81 @@ export default function xcodebug(pi: ExtensionAPI): void {
1053
1186
  await new Promise((resolve) => setTimeout(resolve, Math.min(250, deadline - Date.now())));
1054
1187
  }
1055
1188
  };
1189
+ /**
1190
+ * Record the pid of the instance a console bridge has just launched.
1191
+ *
1192
+ * `replaced` is the instance that launch terminated. It stays in the process
1193
+ * table for a moment afterwards, so the first answer can still be the one that
1194
+ * is about to die - and a pid that names the wrong process makes `terminate`
1195
+ * miss, and makes a later bridge drop look like someone else restarted the app.
1196
+ */
1197
+ const discoverAppPid = async (capture: Capture, device: DeviceInfo, replaced: number | undefined, signal = capture.signal): Promise<void> => {
1198
+ if (!capture.processName) return;
1199
+ const launch = capture.relaunches;
1200
+ const deadline = Date.now() + 20_000;
1201
+ while (!signal.aborted && Date.now() < deadline && capture.running && capture.relaunches === launch) {
1202
+ const { pid } = await lookupProcess(device, capture.processName, { attempts: 1, signal });
1203
+ if (pid !== undefined && pid !== replaced) {
1204
+ if (capture.relaunches === launch) capture.appPid = pid;
1205
+ return;
1206
+ }
1207
+ await new Promise((resolve) => setTimeout(resolve, 500));
1208
+ }
1209
+ };
1210
+
1211
+ /** Captures a crash report is being looked for, so two bridge drops close together search once. */
1212
+ const crashSearches = new Set<string>();
1213
+
1214
+ /**
1215
+ * Look for the crash report of an app whose console bridge went down.
1216
+ *
1217
+ * The device writes one a few seconds after the process died, so this tries a
1218
+ * few times. An app that was only terminated, or that is still running, leaves
1219
+ * none, and then nothing more is said. It runs apart from the capture: a
1220
+ * `stop` a moment later must not call it off, since that is exactly how a run
1221
+ * that ends in a crash is wrapped up.
1222
+ */
1223
+ const fetchCrashReport = async (capture: Capture, device: DeviceInfo): Promise<void> => {
1224
+ const executable = capture.processName;
1225
+ if (!executable || crashSearches.has(capture.id)) return;
1226
+ crashSearches.add(capture.id);
1227
+ // The instance whose bridge has just gone; a reattach will soon record another.
1228
+ const pid = capture.appPid;
1229
+ // A report is written after the process is gone, so one dated before the
1230
+ // bridge went down belongs to an earlier run of the app.
1231
+ const since = Date.now() - DEVICE_CLOCK_SKEW_MS;
1232
+ try {
1233
+ for (const delay of CRASH_REPORT_DELAYS_MS) {
1234
+ // Unreferenced: a search still waiting must not hold a finished host open.
1235
+ await new Promise((resolve) => {
1236
+ setTimeout(resolve, delay).unref?.();
1237
+ });
1238
+ // The session ended, or has since let go of this capture.
1239
+ if (state.captures.get(capture.id) !== capture) return;
1240
+ const path = await pullCrashReport(device, executable, { since, pid, directory: dirname(capture.logFile) });
1241
+ if (path) {
1242
+ capture.crashReport = path;
1243
+ capture.pushLine("err", `[xcodebug] crash report: ${path}`);
1244
+ return;
1245
+ }
1246
+ }
1247
+ } finally {
1248
+ crashSearches.delete(capture.id);
1249
+ }
1250
+ };
1251
+
1252
+ /**
1253
+ * End a console capture whose app is no longer the process it launched, and
1254
+ * say why where a later read will find it: a capture that just stops looks
1255
+ * the same as an app that went quiet.
1256
+ */
1257
+ const endCapture = (capture: Capture, reason: string): void => {
1258
+ const last = lastWords(capture);
1259
+ capture.endReason = last ? `${reason}; last line before the bridge ended: "${last}"` : reason;
1260
+ capture.pushLine("err", `[xcodebug] ${capture.endReason}; stopping capture`);
1261
+ releaseCapture(capture);
1262
+ };
1263
+
1056
1264
  /**
1057
1265
  * Keep a capture alive for as long as the run lasts.
1058
1266
  *
@@ -1091,18 +1299,36 @@ export default function xcodebug(pi: ExtensionAPI): void {
1091
1299
  // Only the console channel is bound to the app's lifetime, so only it
1092
1300
  // consults the process table. A syslog bridge outlives the app and its
1093
1301
  // drops say nothing about whether the app is still running.
1302
+ // `listed` is the app's pid as the table has it now, when it could be read.
1303
+ let listed: number | undefined;
1094
1304
  if (capture.mode === "console" && capture.processName) {
1095
1305
  const lookup = await lookupProcess(device, capture.processName, {
1096
1306
  attempts: 1,
1097
1307
  signal: capture.signal,
1098
1308
  });
1099
- if (!lookup.queryFailed && lookup.pid === undefined) {
1100
- capture.pushLine("err", "[xcodebug] app process is gone; stopping capture");
1101
- releaseCapture(capture);
1102
- return;
1103
- }
1309
+ // A stop that lands during the probe aborts it, which reads as a
1310
+ // failed query; carrying on would relaunch an app the user has let go.
1311
+ if (capture.stoppedByUser) return;
1104
1312
  if (lookup.queryFailed) {
1105
1313
  capture.pushLine("err", "[xcodebug] could not read the process table; still retrying");
1314
+ continue;
1315
+ } else if (lookup.pid === undefined) {
1316
+ endCapture(capture, "the app exited");
1317
+ return;
1318
+ } else if (capture.appPid !== undefined && lookup.pid !== capture.appPid) {
1319
+ // The console attaches only by launching, so reattaching here would
1320
+ // kill whatever started this instance - another session's capture,
1321
+ // which would then do the same to this one, or a test runner's app.
1322
+ endCapture(
1323
+ capture,
1324
+ `the app was restarted outside this capture (pid ${capture.appPid} -> ${lookup.pid}) and is left running`,
1325
+ );
1326
+ return;
1327
+ } else if (capture.appPid === undefined && capture.launchArgs.includes("--terminate-existing")) {
1328
+ endCapture(capture, "cannot verify ownership of the running app; it is left running");
1329
+ return;
1330
+ } else {
1331
+ listed = lookup.pid;
1106
1332
  }
1107
1333
  }
1108
1334
 
@@ -1110,6 +1336,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1110
1336
  capture.resetForReconnect();
1111
1337
  try {
1112
1338
  await capture.start();
1339
+ if (capture.stoppedByUser) return;
1113
1340
  attempts = 0;
1114
1341
  onReconnect?.(1);
1115
1342
  // Resume pushing for whichever channel this is. The active-id check
@@ -1117,7 +1344,21 @@ export default function xcodebug(pi: ExtensionAPI): void {
1117
1344
  if (capture.pushMode && state.pushTimers.get(capture.id) === undefined) {
1118
1345
  startPush(capture, capture.pushMode, capture.pushMatch, { resume: true });
1119
1346
  }
1120
- capture.pushLine("err", `[xcodebug] ${label} bridge reattached`);
1347
+ // devicectl attaches a console only by launching, and this launch
1348
+ // terminates the instance that was running.
1349
+ if (capture.mode === "console" && capture.launchArgs.includes("--terminate-existing")) {
1350
+ capture.relaunches += 1;
1351
+ // Without a reading of the table the new pid cannot be told from
1352
+ // the old one, and none is better than one that may be wrong.
1353
+ capture.appPid = undefined;
1354
+ if (listed !== undefined) void discoverAppPid(capture, device, listed);
1355
+ capture.pushLine(
1356
+ "err",
1357
+ `[xcodebug] console bridge reattached - this relaunched the app (relaunch ${capture.relaunches}), so the state it had is gone`,
1358
+ );
1359
+ } else {
1360
+ capture.pushLine("err", `[xcodebug] ${label} bridge reattached`);
1361
+ }
1121
1362
  return;
1122
1363
  } catch (error) {
1123
1364
  capture.pushLine("err", `[xcodebug] reconnect failed: ${(error as Error).message}`);
@@ -1141,6 +1382,10 @@ export default function xcodebug(pi: ExtensionAPI): void {
1141
1382
  releaseCapture(capture);
1142
1383
  return;
1143
1384
  }
1385
+ // An app that dies takes its console with it. Looking for its report
1386
+ // starts here rather than once the reconnect below has settled what
1387
+ // happened, because a `stop` can arrive before it does.
1388
+ if (capture.mode === "console") void fetchCrashReport(capture, device);
1144
1389
  // Always hand off. If a reconnect loop is already running it returns at
1145
1390
  // once and keeps retrying on its own; if none is running, this starts it.
1146
1391
  // An earlier version skipped this while the watchdog was restarting, which
@@ -1275,8 +1520,11 @@ export default function xcodebug(pi: ExtensionAPI): void {
1275
1520
  onUpdate?: (text: string) => void;
1276
1521
  /** The .xcworkspace/.xcodeproj this run targets; anchors the Podfile lookup. */
1277
1522
  containerPath?: string;
1278
- }): Promise<{ report: ChangeReport; needsBuild: boolean; podInstall?: string; podInstallFailed: boolean; notes: string[] }> => {
1279
- let report = await detectChanges(options.root);
1523
+ /** Which of this session's builds would be reused; without one, a build is always needed. */
1524
+ buildKey?: string;
1525
+ preview?: boolean;
1526
+ }): Promise<{ report: ChangeReport; needsBuild: boolean; podInstall?: string; podInstallNeeded?: boolean; podInstallFailed: boolean; notes: string[] }> => {
1527
+ let report = await detectChanges(options.root, options.containerPath);
1280
1528
  const notes: string[] = [];
1281
1529
  let podInstallNote: string | undefined;
1282
1530
  let podInstallFailed = false;
@@ -1301,13 +1549,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1301
1549
  const lockCheck =
1302
1550
  options.installPods === false || !options.containerPath
1303
1551
  ? undefined
1304
- : await checkPodLockSync(options.containerPath);
1552
+ : await checkPodLockSync(resolve(options.root, options.containerPath));
1305
1553
  const lockNeedsInstall = lockCheck !== undefined && !lockCheck.synced;
1306
1554
 
1307
1555
  if (newFilesNeedInstall || lockNeedsInstall) {
1308
1556
  // pod install only runs in the directory that owns this container's
1309
1557
  // Podfile. Searching elsewhere risks reinstalling another project's pods.
1310
1558
  const podfileDir = lockCheck?.podfileDir;
1559
+ if (options.preview && podfileDir) {
1560
+ return { report, needsBuild: true, podInstallNeeded: true, podInstallFailed: false, notes };
1561
+ }
1311
1562
  if (!podfileDir) {
1312
1563
  notes.push(
1313
1564
  `pod install skipped: no Podfile beside ${options.containerPath ?? "the container"} ` +
@@ -1330,7 +1581,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1330
1581
  // pod install rewrites Podfile.lock and the Pods project, so re-read the
1331
1582
  // tree: storing the pre-install fingerprint would make the next launch
1332
1583
  // think the pods are still stale and install them again.
1333
- report = await detectChanges(options.root);
1584
+ report = await detectChanges(options.root, options.containerPath);
1334
1585
  // Record the key derived from the post-install tree, not the one that
1335
1586
  // triggered this install: pod install can change the new-file set, and a
1336
1587
  // stale key would make the next run skip an install it still needs.
@@ -1339,7 +1590,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1339
1590
  // The install is only meaningful if the lock actually converged. Re-check
1340
1591
  // rather than trusting the pre-install verdict.
1341
1592
  if (options.containerPath) {
1342
- const after = await checkPodLockSync(options.containerPath);
1593
+ const after = await checkPodLockSync(resolve(options.root, options.containerPath));
1343
1594
  if (after && !after.synced) {
1344
1595
  podInstallNote += `\nwarning: Podfile.lock is still out of sync after pod install (${after.reason})`;
1345
1596
  }
@@ -1347,15 +1598,51 @@ export default function xcodebug(pi: ExtensionAPI): void {
1347
1598
  }
1348
1599
  }
1349
1600
 
1601
+ // A build is reused only when it was made of this target, from this tree,
1602
+ // and its product is still what the build left behind: Xcode, or a raw
1603
+ // xcodebuild in another terminal, writes the same DerivedData path.
1604
+ const built = options.buildKey === undefined ? undefined : state.builds.get(options.buildKey);
1350
1605
  const needsBuild =
1351
1606
  options.force === true ||
1352
1607
  report.unavailable ||
1353
- state.lastBuiltFingerprint === undefined ||
1354
- state.lastBuiltFingerprint !== report.fingerprint;
1608
+ built?.fingerprint !== report.fingerprint ||
1609
+ (await directorySignature(built.appPath)) !== built.product;
1355
1610
 
1356
1611
  return { report, needsBuild, podInstall: podInstallNote, podInstallFailed, notes };
1357
1612
  };
1358
1613
 
1614
+ /**
1615
+ * Remember a successful build so the next run of the same target can reuse it.
1616
+ *
1617
+ * `before` is the tree the build started from. If the tree is different once
1618
+ * the build is over, something changed while it ran, and whether that change
1619
+ * made it into the product is unknowable - so the build is not remembered, the
1620
+ * next run builds again, and the returned note says why.
1621
+ */
1622
+ const rememberBuild = async (
1623
+ key: string,
1624
+ before: string,
1625
+ root: string,
1626
+ containerPath: string | undefined,
1627
+ outcome: BuildOutcome,
1628
+ ): Promise<string | undefined> => {
1629
+ if (!outcome.appPath) return undefined;
1630
+ const after = (await detectChanges(root, containerPath)).fingerprint;
1631
+ if (after !== before) {
1632
+ return "the working tree changed while this was building, so the next run builds again instead of reusing it";
1633
+ }
1634
+ const product = await directorySignature(outcome.appPath);
1635
+ if (product === undefined) return undefined;
1636
+ state.builds.set(key, {
1637
+ fingerprint: after,
1638
+ appPath: outcome.appPath,
1639
+ product,
1640
+ bundleId: outcome.bundleId,
1641
+ executable: outcome.executable,
1642
+ });
1643
+ return undefined;
1644
+ };
1645
+
1359
1646
  /**
1360
1647
  * Run a shell command to completion, then stop the capture it was watching
1361
1648
  * and report what the run produced.
@@ -1397,6 +1684,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1397
1684
 
1398
1685
  const since = target?.status().cursor ?? 0;
1399
1686
  const linesAtStart = target?.status().lineCount ?? 0;
1687
+ const relaunchesAtStart = target?.relaunches ?? 0;
1400
1688
  const result = await runCommand(bin, argv, {
1401
1689
  cwd,
1402
1690
  timeoutMs,
@@ -1412,11 +1700,24 @@ export default function xcodebug(pi: ExtensionAPI): void {
1412
1700
  // the screen stays where the case left it.
1413
1701
  let captureNote = "no capture was running; nothing to stop";
1414
1702
  if (target) {
1703
+ // A bridge that is already down went down by itself, and the reply has to
1704
+ // say so: "the case ran" and "the app died under the case" must not read
1705
+ // alike. Stopping still matters then - it calls off a pending reattach,
1706
+ // which would relaunch the app now that the case is over.
1707
+ const how = target.running
1708
+ ? `stopped ${target.id}`
1709
+ : target.stoppedByUser
1710
+ ? `${target.id} was already stopped`
1711
+ : `warning: ${target.id} was no longer capturing when the command finished${whyEnded(target)}`;
1415
1712
  stopCapture(target, false);
1416
1713
  await target.waitForExit(5_000);
1417
1714
  const status = target.status();
1418
1715
  const added = Math.max(0, status.lineCount - linesAtStart);
1419
- captureNote = `stopped ${status.id} · ${added} new line(s) · ${status.logFile}`;
1716
+ captureNote = `${how} · ${added} new line(s) · ${status.logFile}`;
1717
+ const relaunched = target.relaunches - relaunchesAtStart;
1718
+ if (relaunched > 0) {
1719
+ captureNote += `\nwarning: a console reattach relaunched the app ${relaunched} time(s) during this run; lines after a relaunch come from a fresh instance`;
1720
+ }
1420
1721
  }
1421
1722
 
1422
1723
  const verdict = result.timedOut
@@ -1463,8 +1764,20 @@ export default function xcodebug(pi: ExtensionAPI): void {
1463
1764
  // lookup below (config, change detection, container discovery, the command's
1464
1765
  // working directory) must agree on one root or they disagree about the project.
1465
1766
  const projectRoot = resolveProjectRoot(pi, ctx);
1466
- const config = await readConfig(projectRoot);
1767
+ const configRead = await readConfig(projectRoot).then(
1768
+ (value) => ({ value, error: undefined }),
1769
+ (error: Error) => ({ value: {} as ProjectConfig, error }),
1770
+ );
1771
+ const config = configRead.value;
1467
1772
  const action = params.action;
1773
+ if (configRead.error && !CONFIG_FREE_ACTIONS.has(action)) throw configRead.error;
1774
+
1775
+ // The first run of a session clears out the logs nothing has written to in
1776
+ // a while, before it adds its own.
1777
+ if (!state.logsPruned && (action === "build" || action === "launch" || action === "syslog")) {
1778
+ state.logsPruned = true;
1779
+ await pruneLogs(logDir(ctx), LOG_RETENTION_MS);
1780
+ }
1468
1781
 
1469
1782
  if (action === "doctor") {
1470
1783
  const checks = await Promise.all([
@@ -1472,28 +1785,50 @@ export default function xcodebug(pi: ExtensionAPI): void {
1472
1785
  runCommand("xcrun", ["devicectl", "--version"], { timeoutMs: 30_000 }),
1473
1786
  runCommand("idevicesyslog", ["--version"], { timeoutMs: 20_000 }),
1474
1787
  ]);
1788
+ const configLine = configRead.error
1789
+ ? configRead.error.message
1790
+ : Object.keys(config).length > 0 ? join(projectRoot, ".xcodebug.json") : "(none)";
1475
1791
  const lines = [
1476
1792
  `xcodebuild: ${checks[0].code === 0 ? checks[0].stdout.split("\n")[0] : "missing"}`,
1477
1793
  `devicectl: ${checks[1].code === 0 ? (checks[1].stdout || checks[1].stderr).trim().split("\n")[0] : "missing"}`,
1478
1794
  `idevicesyslog: ${checks[2].code === 0 ? (checks[2].stdout || checks[2].stderr).trim().split("\n")[0] : "missing (optional, syslog action only)"}`,
1479
- `config: ${Object.keys(config).length > 0 ? join(projectRoot, ".xcodebug.json") : "(none)"}`,
1795
+ `config: ${configLine}`,
1480
1796
  `log dir: ${logDir(ctx)}`,
1481
1797
  ];
1482
1798
  return { content: [{ type: "text", text: lines.join("\n") }], details: {} };
1483
1799
  }
1484
1800
 
1485
1801
  if (action === "changes") {
1486
- const report = await detectChanges(projectRoot);
1802
+ let buildKey: string | undefined;
1803
+ let containerPath: string | undefined;
1804
+ let unresolved: string | undefined;
1805
+ try {
1806
+ const target = await withContainer(projectRoot, config, params);
1807
+ containerPath = target.workspace ?? target.project;
1808
+ buildKey = buildKeyOf(target, await resolveDeviceParam(params.device, projectRoot));
1809
+ } catch (error) {
1810
+ unresolved = (error as Error).message;
1811
+ const detected = await detectContainer(projectRoot);
1812
+ containerPath ??= params.workspace ?? params.project ?? config.workspace ?? config.project ?? detected.workspace ?? detected.project;
1813
+ }
1814
+ const gate = await prepareRun(ctx, {
1815
+ root: projectRoot, containerPath: containerPath && resolve(projectRoot, containerPath),
1816
+ buildKey, force: params.force, installPods: params.installPods, preview: true,
1817
+ });
1818
+ const { report } = gate;
1819
+ const lastBuilt = buildKey === undefined ? undefined : state.builds.get(buildKey)?.fingerprint;
1487
1820
  const lines = [
1488
1821
  describeChanges(report),
1489
1822
  `fingerprint: ${report.fingerprint}`,
1490
- `last build in this session: ${state.lastBuiltFingerprint ?? "(none)"}`,
1491
- `rebuild needed: ${report.needsBuild || state.lastBuiltFingerprint !== report.fingerprint ? "yes" : "no"}`,
1492
- `pod install needed: ${report.podsNeedingInstall.length > 0 ? report.podsNeedingInstall.join(", ") : "no"}`,
1823
+ `last build for this target: ${lastBuilt ?? "(none)"}`,
1824
+ `rebuild needed: ${gate.needsBuild ? "yes" : "no"}`,
1825
+ `pod install needed: ${gate.podInstallNeeded ? "yes" : "no"}`,
1826
+ ...gate.notes,
1493
1827
  ];
1828
+ if (unresolved) lines.push(`no reusable target resolved: ${unresolved}`);
1494
1829
  return {
1495
1830
  content: [{ type: "text", text: lines.join("\n") }],
1496
- details: { report, lastBuiltFingerprint: state.lastBuiltFingerprint },
1831
+ details: { report, lastBuiltFingerprint: lastBuilt },
1497
1832
  };
1498
1833
  }
1499
1834
 
@@ -1508,13 +1843,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1508
1843
  setRunPhase("resolving the project…");
1509
1844
  const device = await resolveDeviceParam(params.device, projectRoot);
1510
1845
  const target = await withContainer(projectRoot, config, params);
1846
+ const buildKey = buildKeyOf(target, device);
1847
+ const containerPath = target.workspace ?? target.project;
1511
1848
  const gate = await prepareRun(ctx, {
1512
1849
  root: projectRoot,
1513
1850
  force: params.force,
1514
1851
  installPods: params.installPods,
1515
1852
  timeoutSeconds: params.timeoutSeconds,
1516
1853
  signal,
1517
- containerPath: target.workspace ?? target.project,
1854
+ containerPath,
1855
+ buildKey,
1518
1856
  onUpdate: (text) => onUpdate?.({ content: [{ type: "text", text }], details: {} }),
1519
1857
  });
1520
1858
  if (gate.podInstallFailed) {
@@ -1527,14 +1865,17 @@ export default function xcodebug(pi: ExtensionAPI): void {
1527
1865
  if (!gate.needsBuild) {
1528
1866
  const summary =
1529
1867
  gate.report.changed.length === 0
1530
- ? "no build-relevant changes"
1531
- : `${gate.report.changed.length} changed file(s), but they are unchanged since the last successful build`;
1868
+ ? "nothing changed"
1869
+ : `${gate.report.changed.length} changed file(s), but they are unchanged`;
1532
1870
  return {
1533
- content: [{ type: "text", text: `build skipped: ${summary} (fingerprint ${gate.report.fingerprint}; pass force=true to rebuild)` }],
1871
+ content: [{ type: "text", text: `build skipped: ${summary} since this session's last successful build (fingerprint ${gate.report.fingerprint}; pass force=true to rebuild)` }],
1534
1872
  details: { report: gate.report, skipped: true },
1535
1873
  };
1536
1874
  }
1537
1875
  setRunPhase(`building ${target.scheme} for ${device.name}`);
1876
+ // Forgotten before the build, not after: one that fails can leave the
1877
+ // product half rewritten, which is no longer the build that was remembered.
1878
+ state.builds.delete(buildKey);
1538
1879
  const outcome = await buildForDevice(target, device, {
1539
1880
  logDir: logDir(ctx),
1540
1881
  cwd: projectRoot,
@@ -1544,13 +1885,14 @@ export default function xcodebug(pi: ExtensionAPI): void {
1544
1885
  signal,
1545
1886
  });
1546
1887
  clearRunPhase();
1888
+ let notRemembered: string | undefined;
1547
1889
  if (outcome.ok) {
1548
- state.lastBuiltFingerprint = (await detectChanges(projectRoot)).fingerprint;
1890
+ notRemembered = await rememberBuild(buildKey, gate.report.fingerprint, projectRoot, containerPath, outcome);
1549
1891
  await clearArchiveBeforeNewRun(ctx);
1550
1892
  }
1551
1893
  const prefix = gate.podInstall ? `${gate.podInstall}\n` : "";
1552
1894
  return {
1553
- content: [{ type: "text", text: `${prefix}${outcome.summary}\nlog: ${outcome.logFile}` }],
1895
+ content: [{ type: "text", text: `${prefix}${outcome.summary}${notRemembered ? `\nnote: ${notRemembered}` : ""}\nlog: ${outcome.logFile}` }],
1554
1896
  details: { ...outcome, report: gate.report },
1555
1897
  isError: !outcome.ok,
1556
1898
  };
@@ -1641,13 +1983,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1641
1983
  // Resolve the container up front: the Podfile that governs this run lives
1642
1984
  // beside it, so the pod gate must not search from an arbitrary cwd.
1643
1985
  const launchTarget = explicitApp && !wantsBuild ? undefined : await withContainer(projectRoot, config, params);
1986
+ const buildKey = launchTarget ? buildKeyOf(launchTarget, device) : undefined;
1987
+ const containerPath = launchTarget ? (launchTarget.workspace ?? launchTarget.project) : undefined;
1644
1988
  const gate = await prepareRun(ctx, {
1645
1989
  root: projectRoot,
1646
1990
  force: params.force,
1647
1991
  installPods: explicitApp && !wantsBuild ? false : params.installPods,
1648
1992
  timeoutSeconds: params.timeoutSeconds,
1649
1993
  signal,
1650
- containerPath: launchTarget ? (launchTarget.workspace ?? launchTarget.project) : undefined,
1994
+ containerPath,
1995
+ buildKey,
1651
1996
  onUpdate: (text) => onUpdate?.({ content: [{ type: "text", text }], details: {} }),
1652
1997
  });
1653
1998
  const notes = [...gate.notes];
@@ -1661,13 +2006,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1661
2006
  };
1662
2007
  }
1663
2008
 
1664
- // Rebuild when the tree changed, when no build happened yet in this
1665
- // session, when the caller asked for a build, or when force is set.
1666
- const mustBuild = explicitApp && !wantsBuild ? false : gate.needsBuild || wantsBuild || !appPath;
2009
+ // Rebuild when the tree changed, when this session has not built this
2010
+ // target yet, when the caller asked for a build, or when force is set.
2011
+ // `needsBuild` false means the gate found this target's build still good.
2012
+ const reused = buildKey === undefined || gate.needsBuild || wantsBuild ? undefined : state.builds.get(buildKey);
2013
+ const mustBuild = launchTarget !== undefined && buildKey !== undefined && reused === undefined;
1667
2014
  if (mustBuild) {
1668
- const target = launchTarget ?? (await withContainer(projectRoot, config, params));
1669
- setRunPhase(`building ${target.scheme} for ${device.name}`);
1670
- const build = await buildForDevice(target, device, {
2015
+ setRunPhase(`building ${launchTarget.scheme} for ${device.name}`);
2016
+ // Forgotten before the build, for the reason `build` gives.
2017
+ state.builds.delete(buildKey);
2018
+ const build = await buildForDevice(launchTarget, device, {
1671
2019
  logDir: logDir(ctx),
1672
2020
  cwd: projectRoot,
1673
2021
  onProgress: (text) => setRunPhase(text),
@@ -1682,19 +2030,39 @@ export default function xcodebug(pi: ExtensionAPI): void {
1682
2030
  isError: true,
1683
2031
  };
1684
2032
  }
1685
- state.lastBuiltFingerprint = (await detectChanges(projectRoot)).fingerprint;
1686
- notes.push(await clearArchiveBeforeNewRun(ctx));
2033
+ const notRemembered = await rememberBuild(buildKey, gate.report.fingerprint, projectRoot, containerPath, build);
2034
+ const cleared = await clearArchiveBeforeNewRun(ctx);
2035
+ if (cleared) notes.push(cleared);
1687
2036
  appPath = build.appPath;
1688
2037
  bundleId = build.bundleId ?? bundleId;
1689
2038
  executable = build.executable;
1690
2039
  notes.push(build.summary);
2040
+ if (notRemembered) notes.push(`note: ${notRemembered}`);
1691
2041
  if (!appPath) throw new Error(`Build succeeded but the product path is unknown.\nlog: ${build.logFile}`);
1692
- } else {
1693
- notes.push(`reusing this session's build (no changes since fingerprint ${gate.report.fingerprint})`);
2042
+ } else if (reused) {
2043
+ appPath = reused.appPath;
2044
+ bundleId = reused.bundleId ?? bundleId;
2045
+ executable = reused.executable;
2046
+ notes.push(`reusing this session's build (nothing changed since fingerprint ${gate.report.fingerprint}; force=true rebuilds)\napp: ${appPath}`);
1694
2047
  }
1695
2048
 
1696
2049
  if (!appPath) throw new Error("launch requires appPath, or a scheme to build.");
1697
2050
  executable ??= params.processName ?? (await readBundleExecutable(appPath));
2051
+
2052
+ // The instance this launch is about to replace, read before the install
2053
+ // because installing over a running app can end it already. The pid
2054
+ // recorded further down must not be this one, so when the table cannot be
2055
+ // read none is recorded.
2056
+ const before =
2057
+ executable && params.terminateExisting !== false
2058
+ ? await lookupProcess(device, executable, { attempts: 1, signal })
2059
+ : { queryFailed: false, pid: undefined };
2060
+ // Another session's capture, or the user's own running app: its state is
2061
+ // gone once this launch goes through, which is worth a line.
2062
+ if (before.pid !== undefined && ![...state.captures.values()].some((c) => c.appPid === before.pid)) {
2063
+ notes.push(`note: ${executable} was already running (pid ${before.pid}), not started by this session; this launch terminated it`);
2064
+ }
2065
+
1698
2066
  setRunPhase(`installing on ${device.name}`);
1699
2067
  const install = await installApp(device, appPath, { timeoutMs: 180_000, signal });
1700
2068
  if (!install.ok) {
@@ -1734,7 +2102,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1734
2102
  environment: { ...(config.environment ?? {}), ...(params.environment ?? {}) },
1735
2103
  }),
1736
2104
  });
1737
- await capture.start();
2105
+ await capture.start(signal);
1738
2106
  state.captures.set(capture.id, capture);
1739
2107
  state.activeCaptureId = capture.id;
1740
2108
  watchExit(capture, device);
@@ -1782,7 +2150,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1782
2150
  args: ["-u", device.udid ?? device.id, "-p", executable, "--no-colors"],
1783
2151
  });
1784
2152
  try {
1785
- await syslogCapture.start();
2153
+ await syslogCapture.start(signal);
1786
2154
  state.captures.set(syslogCapture.id, syslogCapture);
1787
2155
  state.companions.set(capture.id, syslogCapture.id);
1788
2156
  watchExit(syslogCapture, device);
@@ -1794,12 +2162,11 @@ export default function xcodebug(pi: ExtensionAPI): void {
1794
2162
 
1795
2163
  // The app pid is not part of --console's output; discover it from the
1796
2164
  // process table so terminate can target the app rather than the bridge.
1797
- if (executable) {
1798
- const deadline = Date.now() + 20_000;
1799
- while (Date.now() < deadline && capture.appPid === undefined && capture.running) {
1800
- capture.appPid = await findProcessPid(device, executable, { attempts: 1 });
1801
- if (capture.appPid === undefined) await new Promise((resolve) => setTimeout(resolve, 500));
1802
- }
2165
+ if (!before.queryFailed) await discoverAppPid(capture, device, before.pid, signal);
2166
+ if (signal?.aborted) {
2167
+ stopCapture(capture, false);
2168
+ await capture.waitForExit(3_000);
2169
+ signal.throwIfAborted();
1803
2170
  }
1804
2171
 
1805
2172
  return {
@@ -1836,7 +2203,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1836
2203
  command: "idevicesyslog",
1837
2204
  args,
1838
2205
  });
1839
- await capture.start();
2206
+ await capture.start(signal);
1840
2207
  state.captures.set(capture.id, capture);
1841
2208
  state.activeCaptureId = capture.id;
1842
2209
  watchExit(capture, device);
@@ -1859,11 +2226,20 @@ export default function xcodebug(pi: ExtensionAPI): void {
1859
2226
  if (action === "logs") {
1860
2227
  const capture = requireCapture(params.captureId);
1861
2228
  const since = params.since ?? 0;
1862
- const formatted = formatLogLines(capture, since, params.limit ?? 200, params.grep);
2229
+ const formatted = await formatLogLines(capture, {
2230
+ since,
2231
+ limit: params.limit ?? 200,
2232
+ grep: toFilter(params.grep, params.regex),
2233
+ times: params.times,
2234
+ signal,
2235
+ });
1863
2236
  const companionId = state.companions.get(capture.id);
1864
2237
  if (!capture.running && companionId) {
1865
2238
  formatted.text += `\n\n[this channel has ended; system-level logs continue in ${companionId} - pass captureId=${companionId}]`;
1866
2239
  }
2240
+ // The lines that say so are in the log, but a filtered read leaves them out.
2241
+ if (capture.endReason) formatted.text += `\n\n[this capture ended on its own · ${capture.endReason}]`;
2242
+ if (capture.crashReport) formatted.text += `\n[crash report: ${capture.crashReport}]`;
1867
2243
  return {
1868
2244
  content: [{ type: "text", text: formatted.text }],
1869
2245
  details: { captureId: capture.id, cursor: formatted.cursor, total: formatted.total, running: capture.running },
@@ -1872,15 +2248,20 @@ export default function xcodebug(pi: ExtensionAPI): void {
1872
2248
 
1873
2249
  if (action === "wait") {
1874
2250
  const capture = requireCapture(params.captureId);
1875
- const needle = params.match;
1876
- if (!needle) throw new Error("wait requires match (a substring to wait for).");
2251
+ const needle = toFilter(params.match, params.regex);
2252
+ if (!needle) throw new Error("wait requires match (a substring to wait for, or a pattern with regex=true).");
2253
+ const shown = typeof needle === "string" ? `"${needle}"` : String(needle);
1877
2254
  const timeoutMs = Math.min(Math.max(1, params.timeoutSeconds ?? 30), 600) * 1000;
1878
2255
  const since = params.since ?? 0;
1879
2256
 
1880
- const matches: LogLine[] = [];
2257
+ const matches: FoundLine[] = [];
1881
2258
  const seen = new Set<number>();
1882
2259
  let finished = false;
1883
2260
  let cancelled = false;
2261
+ // The backlog is read from disk too, which takes a moment. A line that
2262
+ // arrives meanwhile must not settle the wait ahead of the earlier ones.
2263
+ let backlogRead = false;
2264
+ let note = "";
1884
2265
  let timer: ReturnType<typeof setTimeout> | undefined;
1885
2266
  let unsubscribeLine: () => void = () => {};
1886
2267
  let unsubscribeExit: () => void = () => {};
@@ -1892,16 +2273,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1892
2273
  if (matches.length === 0) {
1893
2274
  // Abort also settles through `finish`, so say what happened instead of
1894
2275
  // reporting a timeout that never elapsed.
1895
- if (cancelled) return `cancelled while waiting for "${needle}" (cursor ${cursor})`;
1896
- return timedOut
1897
- ? `timed out after ${timeoutMs / 1000}s waiting for "${needle}" (cursor ${cursor})`
1898
- : `capture ended before "${needle}" appeared (cursor ${cursor})`;
2276
+ if (cancelled) return `cancelled while waiting for ${shown} (cursor ${cursor})${note}`;
2277
+ if (timedOut) return `timed out after ${timeoutMs / 1000}s waiting for ${shown} (cursor ${cursor})${note}`;
2278
+ return `capture ended before ${shown} appeared (cursor ${cursor})${whyEnded(capture)}${note}`;
1899
2279
  }
1900
2280
  const body = matches
2281
+ .sort((a, b) => a.index - b.index)
1901
2282
  .slice(0, 200)
1902
- .map((line) => `${String(line.index).padStart(6, " ")} ${line.text}`)
2283
+ .map((line) => `${String(line.index).padStart(6, " ")} ${params.times ? clock(line.at) : ""}${line.text}`)
1903
2284
  .join("\n");
1904
- return `matched ${matches.length} line(s) · cursor ${cursor}\n${body}`;
2285
+ return `matched ${matches.length} line(s) · cursor ${cursor}\n${body}${note}`;
1905
2286
  };
1906
2287
 
1907
2288
  const finish = (timedOut: boolean): void => {
@@ -1916,14 +2297,14 @@ export default function xcodebug(pi: ExtensionAPI): void {
1916
2297
  resolveWait(settle(timedOut));
1917
2298
  };
1918
2299
 
1919
- const collect = (line: LogLine): void => {
2300
+ const collect = (line: FoundLine): void => {
1920
2301
  if (finished || line.index <= since || seen.has(line.index)) return;
1921
- if (!line.text.includes(needle)) return;
2302
+ if (!matchesFilter(line.text, needle)) return;
1922
2303
  seen.add(line.index);
1923
2304
  matches.push(line);
1924
2305
  };
1925
2306
 
1926
- const text = await new Promise<string>((resolve) => {
2307
+ const waiting = new Promise<string>((resolve) => {
1927
2308
  resolveWait = resolve;
1928
2309
  // Subscribe first, then scan the backlog: the scan covers
1929
2310
  // [since, cursor] and the listener covers everything after it, so no
@@ -1931,24 +2312,37 @@ export default function xcodebug(pi: ExtensionAPI): void {
1931
2312
  unsubscribeLine = capture.onLine((line) => {
1932
2313
  collect(line);
1933
2314
  // Let the rest of the same chunk land before settling.
1934
- if (matches.length > 0) setTimeout(() => finish(false), 50);
2315
+ if (backlogRead && matches.length > 0) setTimeout(() => finish(false), 50);
1935
2316
  });
1936
- unsubscribeExit = capture.onExit(() => setTimeout(() => finish(false), 0));
1937
- timer = setTimeout(() => finish(true), timeoutMs);
2317
+ unsubscribeExit = capture.onExit(() => setTimeout(() => backlogRead && finish(false), 0));
1938
2318
  onAbort = (): void => {
1939
2319
  cancelled = true;
1940
2320
  finish(true);
1941
2321
  };
1942
2322
  signal?.addEventListener("abort", onAbort, { once: true });
1943
-
1944
- for (const line of capture.read({ since, limit: 500, grep: needle }).lines) collect(line);
1945
-
1946
- // A pattern already present in the backlog must return immediately,
1947
- // not wait out the timeout.
1948
- if (matches.length > 0) finish(false);
1949
- else if (!capture.running) finish(false);
1950
2323
  });
1951
2324
 
2325
+ try {
2326
+ const backlog = await capture.search({ since, limit: 500, grep: needle, signal });
2327
+ for (const line of backlog.lines) collect(line);
2328
+ note = evictedNote(backlog, capture.logFile);
2329
+ backlogRead = true;
2330
+ } catch (error) {
2331
+ if (signal?.aborted) onAbort?.();
2332
+ else {
2333
+ finish(false);
2334
+ throw error;
2335
+ }
2336
+ }
2337
+ // The deadline bounds the wait for a line still to come, so it starts
2338
+ // here: expiring while the lines already logged are being read back would
2339
+ // report a timeout for a line that is sitting on disk.
2340
+ if (!finished) timer = setTimeout(() => finish(true), timeoutMs);
2341
+ // A pattern already present in the backlog must return immediately,
2342
+ // not wait out the timeout.
2343
+ if (matches.length > 0 || !capture.running) finish(false);
2344
+ const text = await waiting;
2345
+
1952
2346
  return {
1953
2347
  content: [{ type: "text", text }],
1954
2348
  details: { captureId: capture.id, cursor: capture.status().cursor, matched: matches.length },
@@ -1968,7 +2362,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
1968
2362
  : [...state.companions.values()].includes(status.id)
1969
2363
  ? " · companion"
1970
2364
  : "";
1971
- return `- ${status.id} [${status.mode}] ${stateText}${role} · ${status.lineCount} lines · ${status.bundleId} · ${status.logFile}`;
2365
+ const relaunched = status.relaunches > 0 ? ` · app relaunched ${status.relaunches}×` : "";
2366
+ return `- ${status.id} [${status.mode}] ${stateText}${role}${relaunched}${endedNote(capture)} · ${status.lineCount} lines · ${status.bundleId} · ${status.logFile}`;
1972
2367
  });
1973
2368
  return { content: [{ type: "text", text: lines.join("\n") }], details: { captures: [...state.captures.values()].map((capture) => capture.status()) } };
1974
2369
  }
@@ -1987,7 +2382,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1987
2382
  // an error (requireCapture throws for that).
1988
2383
  const targets = params.captureId
1989
2384
  ? [requireCapture(params.captureId)]
1990
- : [...state.captures.values()].filter((c) => c.running);
2385
+ : [...state.captures.values()].filter((c) => !state.endedCaptures.has(c.id));
1991
2386
  if (targets.length === 0) {
1992
2387
  const known = [...state.captures.values()].map((c) => `${c.id} (${c.mode}, ended)`);
1993
2388
  return {
@@ -2020,14 +2415,17 @@ export default function xcodebug(pi: ExtensionAPI): void {
2020
2415
  const capture = state.activeCaptureId ? state.captures.get(state.activeCaptureId) : undefined;
2021
2416
  const bundleId = params.bundleId ?? capture?.bundleId ?? config.bundleId;
2022
2417
  if (!bundleId) throw new Error("terminate requires bundleId or an active capture.");
2023
- const executable = params.processName ?? capture?.processName ?? config.scheme;
2024
- // Prefer the app pid recorded at launch; the process table can lag a fresh launch.
2025
- const knownPid = capture?.appPid;
2026
- const pid = knownPid ?? (executable ? await findProcessPid(device, executable) : undefined);
2418
+ const sameTarget = capture?.deviceId === device.id && capture.bundleId === bundleId &&
2419
+ (params.processName === undefined || params.processName === capture.processName);
2420
+ const executable = params.processName ?? (sameTarget ? capture.processName : undefined) ??
2421
+ (bundleId === config.bundleId ? config.scheme : undefined);
2422
+ const pid = (sameTarget ? capture.appPid : undefined) ??
2423
+ (executable ? (await lookupProcess(device, executable, { signal })).pid : undefined);
2424
+ signal?.throwIfAborted();
2027
2425
  if (!pid) {
2028
2426
  return { content: [{ type: "text", text: `no running process for ${bundleId} on ${device.name}` }], details: {} };
2029
2427
  }
2030
- const outcome = await terminateApp(device, pid, { timeoutMs: 30_000 });
2428
+ const outcome = await terminateApp(device, pid, { timeoutMs: 30_000, signal });
2031
2429
  return {
2032
2430
  content: [{ type: "text", text: outcome.message }],
2033
2431
  details: { ...outcome, pid },
@@ -2105,14 +2503,14 @@ export default function xcodebug(pi: ExtensionAPI): void {
2105
2503
  promptGuidelines: [
2106
2504
  "Use xcodebug instead of raw xcodebuild/devicectl when debugging on a physical iOS device; it keeps a cursor so xcodebug action=logs returns only new output.",
2107
2505
  "xcodebug action=launch restarts the app; use action=syslog when the app must keep running.",
2108
- "Use xcodebug action=wait to block on an expected log line when verifying a feature end to end.",
2506
+ "Use xcodebug action=wait to block on an expected log line when verifying a feature end to end. With regex=true, match is a pattern, so one wait covers both outcomes: match=\"sync (done|failed)\".",
2109
2507
  "xcodebug action=changes reports whether a rebuild or pod install is pending without running either.",
2110
2508
  "After editing code mid-run, use xcodebug action=restart instead of a full launch: it replays the last launch's app, device, scheme, goal and command, and forces the rebuild.",
2111
2509
  "For an automated run, pass command=\"cd /repo && npm run test:xxx\" to launch: it builds, installs, launches, runs the command to completion, then stops the capture and returns the exit code plus the app-side cursor. Never poll the log for silence to decide a run is done.",
2112
2510
  "The command's runner must not restart the app itself (disable any auto-launch option in the test config), or the launch that xcodebug is capturing dies and the log stops at the restart.",
2113
2511
  "Verification is a loop: run, read the log, stop, edit the code, run again. Once the log has answered the question, call action=stop and report the conclusion - keeping the capture alive only floods the session.",
2114
2512
  "The one case where you must NOT stop: the user has not touched the app yet, so the log is silent because nothing happened. Wait, tell them what to do on the phone, and keep capturing.",
2115
- "A capture also ends on its own when the app process exits; do not reconnect a run whose app the user deliberately closed.",
2513
+ "A capture also ends on its own when the app process exits, or when something else relaunched the app; status and logs then say why, and name the crash report if the device wrote one. Do not reconnect a run whose app the user deliberately closed.",
2116
2514
  ],
2117
2515
  executionMode: "sequential",
2118
2516
  parameters: Type.Object({
@@ -2146,6 +2544,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
2146
2544
  limit: Type.Optional(Type.Number({ description: "Max lines to return (default 200)" })),
2147
2545
  grep: Type.Optional(Type.String({ description: "Only return lines containing this text" })),
2148
2546
  match: Type.Optional(Type.String({ description: "wait: substring to wait for; also filters pushed lines" })),
2547
+ regex: Type.Optional(Type.Boolean({ description: "logs/wait: treat grep and match as regular expressions instead of substrings, e.g. match=\"sync (done|failed)\"." })),
2548
+ times: Type.Optional(Type.Boolean({ description: "logs/wait: prefix each line with the host time it arrived (HH:MM:SS.mmm), to line it up with a test runner's output." })),
2149
2549
  timeoutSeconds: Type.Optional(Type.Number({ description: "wait/build timeout in seconds; await: max run time (default 1800)" })),
2150
2550
  command: Type.Optional(Type.String({ description: "await/launch/restart: shell command line to run to completion after the app is up, e.g. \"cd /repo && npm run test:xxx\". Only /bin/sh -lc runs it, so the cd into the repo that owns the runner is part of the line. Quoted in the slash command (command=\"...\"); restart re-runs the last launch's command unless this overrides it." })),
2151
2551
  push: Type.Optional(Type.Union([Type.Literal("off"), Type.Literal("context"), Type.Literal("wake")], {
@@ -2276,7 +2676,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
2276
2676
  stopStatusTicker();
2277
2677
  state.uiCtx?.ui.setStatus("xcodebug", undefined);
2278
2678
  state.uiCtx?.ui.setWidget("xcodebug", undefined);
2279
- for (const capture of state.captures.values()) {
2679
+ const captures = [...state.captures.values()];
2680
+ for (const capture of captures) {
2280
2681
  stopPush(capture.id);
2281
2682
  stopWatchdog(capture.id);
2282
2683
  capture.stop(false);
@@ -2284,5 +2685,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
2284
2685
  state.captures.clear();
2285
2686
  state.endedCaptures.clear();
2286
2687
  state.activeCaptureId = undefined;
2688
+ // The host exits once this returns, and a log line still in a pipe then is
2689
+ // lost; each capture bounds its own drain.
2690
+ await Promise.all(captures.map((capture) => capture.waitForExit(3_000)));
2287
2691
  });
2288
2692
  }