xcodebug 1.2.1 → 1.2.3

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,8 @@
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
+ import { setTimeout as sleep } from "node:timers/promises";
11
12
  // `import type` is erased at compile time, so this specifier never reaches the
12
13
  // runtime: it only has to name a module the loader can resolve for typechecking.
13
14
  // `@earendil-works/pi-coding-agent` is the official one the engine documents for
@@ -16,12 +17,12 @@ import { basename, dirname, join } from "node:path";
16
17
  // one distribution of the engine.
17
18
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
18
19
  import { Type } from "typebox";
19
- import { Capture, type LogLine } from "./capture.ts";
20
- import { describeDevices, findProcessPid, listDevices, lookupProcess, resolveDevice, type DeviceInfo } from "./devices.ts";
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";
20
+ import { Capture, matchesFilter, type FoundLine } from "./capture.ts";
21
+ import { describeDevices, findProcessPid, listDevices, lookupProcess, pullCrashReport, resolveDevice, type DeviceInfo } from "./devices.ts";
22
+ import { asRecord, lastLines, runCommand, timestamp } from "./exec.ts";
23
+ import { buildForDevice, consoleLaunchArgs, installApp, terminateApp, type BuildOutcome, type BuildTarget } from "./xcode.ts";
24
+ import { checkPodLockSync, describeChanges, detectChanges, directorySignature, runPodInstall, type ChangeReport } from "./changes.ts";
25
+ import { clearArchives, pruneLogs } from "./archive.ts";
25
26
 
26
27
  const CAPTURE_PREFIX = "xcodebug";
27
28
  const PUSH_INTERVAL_MS = 4_000;
@@ -36,6 +37,31 @@ const SILENCE_NOTICE_MS = 60_000;
36
37
  * producing lines, so only the syslog side needs this.
37
38
  */
38
39
  const SYSLOG_SILENCE_MS = 30_000;
40
+ /**
41
+ * When to look for a crash report after a console bridge goes down, each
42
+ * counted from the attempt before. The device needs a few seconds to write one:
43
+ * 8s after a watchdog kill, measured.
44
+ */
45
+ const CRASH_REPORT_DELAYS_MS = [2_000, 4_000, 8_000, 16_000];
46
+ /**
47
+ * A report is dated by the phone's clock and a bridge's end by this machine's.
48
+ * Without some slack, a phone running slightly behind would date the report of
49
+ * the crash that took the bridge down to before it went.
50
+ */
51
+ const DEVICE_CLOCK_SKEW_MS = 5_000;
52
+ /**
53
+ * How long a log outlives its last write. Every run leaves a build log of
54
+ * several megabytes and a capture log beside it, and nothing else removes them.
55
+ */
56
+ const LOG_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
57
+ /**
58
+ * Actions that work whatever state `.xcodebug.json` is in: `doctor` reports it,
59
+ * and reading or stopping a capture never uses it. Every other action refuses a
60
+ * config that does not parse, because running as if there were none uses the
61
+ * defaults the file was written to override. Listed as exemptions so that an
62
+ * action added later refuses too.
63
+ */
64
+ const CONFIG_FREE_ACTIONS = new Set(["doctor", "devices", "logs", "wait", "status", "stop", "await"]);
39
65
 
40
66
  interface ProjectConfig {
41
67
  workspace?: string;
@@ -57,8 +83,15 @@ interface SessionState {
57
83
  activeCaptureId?: string;
58
84
  pushTimers: Map<string, ReturnType<typeof setInterval>>;
59
85
  pushCursors: Map<string, number>;
60
- /** Fingerprint of the working tree at the last successful build in this session. */
61
- lastBuiltFingerprint?: string;
86
+ /**
87
+ * What this session built, per target and device: the tree each build was made
88
+ * from, and its product as the build left it. A map, because one session
89
+ * debugs several apps and the build of one says nothing about another. The
90
+ * last entry is the most recent build.
91
+ */
92
+ builds: Map<string, { fingerprint: string; appPath: string; product: string; bundleId?: string; executable?: string }>;
93
+ /** Old logs are cleared once per session, by its first run. */
94
+ logsPruned?: boolean;
62
95
  /** Key of the new-component-file set pod install has already handled. */
63
96
  installedPodsFingerprint?: string;
64
97
  /** console capture id -> parallel syslog capture id. */
@@ -211,13 +244,23 @@ function archiveWorkDir(ctx: ExtensionContext): string {
211
244
  * disk. A new build is the natural boundary: whatever happened before it
212
245
  * belongs to a different binary.
213
246
  */
214
- async function clearArchiveBeforeNewRun(ctx: ExtensionContext): Promise<string> {
247
+ async function clearArchiveBeforeNewRun(ctx: ExtensionContext): Promise<string | undefined> {
215
248
  const { removed, freedBytes } = await clearArchives(archiveWorkDir(ctx));
216
- if (removed === 0) return "archive: nothing to clear";
249
+ // Archiving is off, so there is normally nothing here; only say so when a
250
+ // snapshot from an older version was actually removed.
251
+ if (removed === 0) return undefined;
217
252
  const mb = (freedBytes / 1024 / 1024).toFixed(0);
218
253
  return `archive: cleared ${removed} snapshot(s), freed ${mb} MB`;
219
254
  }
220
255
 
256
+ /** A build is another run's only when target, configuration and device all match. */
257
+ function buildKeyOf(target: BuildTarget, device: DeviceInfo): string {
258
+ return JSON.stringify([
259
+ target.workspace, target.project, target.scheme, target.configuration, target.derivedDataPath,
260
+ device.udid ?? device.id,
261
+ ]);
262
+ }
263
+
221
264
  async function readBundleExecutable(appPath: string): Promise<string | undefined> {
222
265
  const result = await runCommand(
223
266
  "/usr/libexec/PlistBuddy",
@@ -240,11 +283,20 @@ async function readBundleIdentifier(appPath: string): Promise<string | undefined
240
283
  }
241
284
 
242
285
  async function readConfig(cwd: string): Promise<ProjectConfig> {
286
+ const path = join(cwd, ".xcodebug.json");
287
+ let text: string;
243
288
  try {
244
- return JSON.parse(await readFile(join(cwd, ".xcodebug.json"), "utf8")) as ProjectConfig;
289
+ text = await readFile(path, "utf8");
245
290
  } catch {
246
291
  return {};
247
292
  }
293
+ try {
294
+ return JSON.parse(text) as ProjectConfig;
295
+ } catch (error) {
296
+ // Reading a config that does not parse as "no config" runs with the very
297
+ // defaults it was written to override - another scheme, another device.
298
+ throw new Error(`${path} is not valid JSON: ${(error as Error).message}`);
299
+ }
248
300
  }
249
301
 
250
302
  /**
@@ -503,26 +555,103 @@ function resolveBuildTarget(config: ProjectConfig, params: {
503
555
  };
504
556
  }
505
557
 
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 });
558
+ /**
559
+ * `match`/`grep` as the reads take them: a substring, or a pattern when the
560
+ * caller set `regex`. A pattern is what lets one wait cover both outcomes
561
+ * ("sync (done|failed)"), where a substring can only ever name one.
562
+ */
563
+ function toFilter(text: string | undefined, regex: boolean | undefined): string | RegExp | undefined {
564
+ if (!text || !regex) return text;
565
+ try {
566
+ return new RegExp(text);
567
+ } catch (error) {
568
+ throw new Error(`"${text}" is not a valid regular expression: ${(error as Error).message}`);
569
+ }
570
+ }
571
+
572
+ /**
573
+ * What a reply owes its reader when the lines asked for start before the buffer
574
+ * does: without it "no match" reads as "never logged" when the line was only
575
+ * evicted. `missing` is absent for a read that did not look on disk.
576
+ */
577
+ function evictedNote(read: { evicted: number; missing?: number }, logFile: string): string {
578
+ if (read.evicted === 0) return "";
579
+ if (read.missing === undefined) {
580
+ return `\nnote: ${read.evicted} older line(s) are no longer in memory; read them from ${logFile}`;
581
+ }
582
+ const found = read.evicted - read.missing;
583
+ const parts = [
584
+ found > 0 ? `${found} line(s) no longer in memory were searched in ${logFile}` : "",
585
+ // Overwritten by rotation, or never written: either way this read cannot speak for them.
586
+ read.missing > 0 ? `${read.missing} line(s) are in neither memory nor the log files and were not searched` : "",
587
+ ];
588
+ return `\nnote: ${parts.filter(Boolean).join("; ")}`;
589
+ }
590
+
591
+ /**
592
+ * The last thing a capture logged that xcodebug did not write itself.
593
+ *
594
+ * devicectl reports a death in its own words ("App terminated due to signal 9.")
595
+ * as it exits; when it said nothing, the app's last line is the next best lead.
596
+ */
597
+ function lastWords(capture: Capture): string | undefined {
598
+ const lines = capture.read({ limit: 20 }).lines.filter((line) => !line.text.startsWith("[xcodebug]"));
599
+ return lines.at(-1)?.text.slice(0, 200);
600
+ }
601
+
602
+ /**
603
+ * What is settled about a capture that ended on its own: why, and the crash
604
+ * report its app left on the device. Empty while neither is known.
605
+ */
606
+ function endedNote(capture: Capture): string {
607
+ const reason = capture.endReason ? ` · ${capture.endReason}` : "";
608
+ const termination = capture.terminationReason ? ` · system termination: ${capture.terminationReason}` : "";
609
+ return `${reason}${termination}${capture.crashReport ? ` · crash report: ${capture.crashReport}` : ""}`;
610
+ }
611
+
612
+ /**
613
+ * The same for a reply that finds a console bridge already down. Whether the app
614
+ * died or only the bridge dropped is settled a moment after the bridge goes;
615
+ * until then the capture's last line is what there is to go on.
616
+ */
617
+ function whyEnded(capture: Capture): string {
618
+ const last = capture.endReason ? undefined : lastWords(capture);
619
+ return `${last ? ` · last line: "${last}"` : ""}${endedNote(capture)}`;
620
+ }
621
+
622
+ /** Host time of a line, for lining a log up with a test runner's own output. */
623
+ function clock(at: number): string {
624
+ const date = new Date(at);
625
+ const pad = (value: number, width = 2): string => String(value).padStart(width, "0");
626
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)} `;
627
+ }
628
+
629
+ async function formatLogLines(
630
+ capture: Capture,
631
+ options: { since: number; limit: number; grep?: string | RegExp; times?: boolean; signal?: AbortSignal },
632
+ ): Promise<{ text: string; cursor: number; total: number }> {
633
+ const { since, limit, grep } = options;
634
+ // A filtered read looks on disk for what the buffer dropped. An unfiltered one
635
+ // returns the newest lines anyway, so the dropped ones only add to "omitted".
636
+ const read = grep ? await capture.search({ since, limit, grep, signal: options.signal }) : capture.read({ since, limit });
637
+ const total = grep ? read.total : read.total + read.evicted;
638
+ const note = evictedNote(read, capture.logFile);
512
639
  if (read.lines.length === 0) {
513
- return { text: `(no new lines since ${since}; capture cursor is ${read.cursor})`, cursor: read.cursor, total: 0 };
640
+ const what = grep ? `no line matching ${typeof grep === "string" ? `"${grep}"` : grep}` : "no new lines";
641
+ return { text: `(${what} since ${since}; capture cursor is ${read.cursor})${note}`, cursor: read.cursor, total: 0 };
514
642
  }
515
- const body = read.lines
643
+ const lines: FoundLine[] = read.lines;
644
+ const body = lines
516
645
  .map((line) => {
517
646
  // In console mode devicectl's own status lines arrive on stdout while the
518
647
  // app's output arrives on stderr, so only stdout needs a label.
519
648
  const tag = capture.mode === "console" && line.stream === "out" ? "[devicectl] " : "";
520
- return `${String(line.index).padStart(6, " ")} ${tag}${line.text}`;
649
+ return `${String(line.index).padStart(6, " ")} ${options.times ? clock(line.at) : ""}${tag}${line.text}`;
521
650
  })
522
651
  .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 };
652
+ const omitted = total - lines.length;
653
+ const header = `${lines.length} line(s)${omitted > 0 ? ` (${omitted} older omitted)` : ""} · cursor ${read.cursor}`;
654
+ return { text: `${header}\n${body}${note}`, cursor: read.cursor, total };
526
655
  }
527
656
 
528
657
  /** Fill in the container when the caller and the config both omit it. */
@@ -653,7 +782,7 @@ function parseCommandArgs(raw: string): ToolParams {
653
782
  const params: Record<string, unknown> = {};
654
783
  const free: string[] = [];
655
784
  const numberKeys = ["limit", "since", "timeoutSeconds"];
656
- const boolKeys = ["force", "installPods", "dualChannel", "keepApp", "terminateExisting", "build"];
785
+ const boolKeys = ["force", "installPods", "dualChannel", "keepApp", "terminateExisting", "build", "regex", "times"];
657
786
 
658
787
  const assign = (key: string, value: string): void => {
659
788
  if (numberKeys.includes(key)) {
@@ -736,6 +865,10 @@ type ToolParams = {
736
865
  limit?: number;
737
866
  grep?: string;
738
867
  match?: string;
868
+ /** `match`/`grep` are regular expressions rather than substrings. */
869
+ regex?: boolean;
870
+ /** Prefix returned lines with the host time they arrived. */
871
+ times?: boolean;
739
872
  timeoutSeconds?: number;
740
873
  push?: "off" | "context" | "wake";
741
874
  force?: boolean;
@@ -757,6 +890,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
757
890
  endedCaptures: new Set(),
758
891
  pushTimers: new Map(),
759
892
  pushCursors: new Map(),
893
+ builds: new Map(),
760
894
  companions: new Map(),
761
895
  lastLineAt: new Map(),
762
896
  silenceNotified: new Set(),
@@ -764,6 +898,35 @@ export default function xcodebug(pi: ExtensionAPI): void {
764
898
  watchdogs: new Map(),
765
899
  };
766
900
 
901
+ // History can evict an ended capture before its launch-result cleanup finishes.
902
+ const ownedCaptures = new Set<Capture>();
903
+ const retiredCleanupWarnings: string[] = [];
904
+ let shuttingDown = false;
905
+ const startCapture = async (capture: Capture, signal?: AbortSignal): Promise<void> => {
906
+ if (shuttingDown) throw new Error("xcodebug session is shutting down");
907
+ ownedCaptures.add(capture);
908
+ const release = (): void => {
909
+ const result = capture.launchResult;
910
+ void capture.waitForLaunchResults().then(() => {
911
+ if (!shuttingDown && !capture.running && !capture.starting && capture.launchResult === result &&
912
+ ownedCaptures.delete(capture)) {
913
+ for (const error of capture.launchResultCleanupErrors ?? []) retiredCleanupWarnings.push(`${capture.id}: ${error}`);
914
+ capture.launchResultCleanupErrors = undefined;
915
+ }
916
+ });
917
+ };
918
+ const unsubscribe = capture.onExit(() => { unsubscribe(); release(); });
919
+ try {
920
+ await capture.start(signal);
921
+ if (shuttingDown) throw new Error("xcodebug session is shutting down");
922
+ } finally {
923
+ if (!capture.running) {
924
+ unsubscribe();
925
+ release();
926
+ }
927
+ }
928
+ };
929
+
767
930
  /**
768
931
  * Paint the live verification state: a footer line that is always visible and
769
932
  * a widget above the editor with the most recent log lines. Both are cleared
@@ -948,6 +1111,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
948
1111
  if (![...state.captures.values()].some((c) => c !== capture && c.running)) stopStatusTicker();
949
1112
  refreshStatus();
950
1113
  capture.stop(terminateApp);
1114
+ if (!capture.running) releaseCapture(capture);
951
1115
  if (state.activeCaptureId === capture.id) state.activeCaptureId = undefined;
952
1116
  };
953
1117
 
@@ -1053,6 +1217,167 @@ export default function xcodebug(pi: ExtensionAPI): void {
1053
1217
  await new Promise((resolve) => setTimeout(resolve, Math.min(250, deadline - Date.now())));
1054
1218
  }
1055
1219
  };
1220
+ const isCurrentBridge = (capture: Capture, launch: number, result: Capture["launchResult"]): boolean =>
1221
+ state.captures.get(capture.id) === capture && capture.relaunches === launch && capture.launchResult === result;
1222
+
1223
+ /**
1224
+ * Record the pid of the instance a console bridge has just launched.
1225
+ *
1226
+ * `replaced` can linger in the table after launch. A table snapshot is only
1227
+ * useful while this bridge is live; after exit, only that launch's command
1228
+ * result can identify the instance that ended.
1229
+ */
1230
+ const discoverAppPid = async (capture: Capture, device: DeviceInfo, replaced: number | undefined, signal = capture.signal): Promise<void> => {
1231
+ if (!capture.processName || capture.processExited) return;
1232
+ const launch = capture.relaunches;
1233
+ const result = capture.launchResult;
1234
+ const deadline = Date.now() + 20_000;
1235
+ const onAbort = (): void => capture.abort.abort(signal.reason);
1236
+ if (signal.aborted) onAbort();
1237
+ else if (signal !== capture.signal) signal.addEventListener("abort", onAbort, { once: true });
1238
+ try {
1239
+ while (!capture.signal.aborted && Date.now() < deadline && capture.running &&
1240
+ !capture.processExited && isCurrentBridge(capture, launch, result)) {
1241
+ const { pid } = await lookupProcess(device, capture.processName, { attempts: 1, signal: capture.signal });
1242
+ if (capture.processExited || capture.naturalExitAt !== undefined || !isCurrentBridge(capture, launch, result)) return;
1243
+ if (pid !== undefined && pid !== replaced) {
1244
+ capture.appPid = pid;
1245
+ return;
1246
+ }
1247
+ await new Promise((resolve) => setTimeout(resolve, 500));
1248
+ }
1249
+ } finally {
1250
+ if (signal !== capture.signal) signal.removeEventListener("abort", onAbort);
1251
+ }
1252
+ };
1253
+
1254
+ /** One identity/report completion job per owned console-launch result. */
1255
+ const crashSearches = new Map<string, {
1256
+ launch: number;
1257
+ result: Capture["launchResult"];
1258
+ identity: Promise<number | undefined>;
1259
+ promise: Promise<void>;
1260
+ }>();
1261
+ const crashSearchAbort = new AbortController();
1262
+
1263
+ /**
1264
+ * Look for the crash report of an app whose console bridge went down.
1265
+ *
1266
+ * The device writes one a few seconds after the process died, so this tries a
1267
+ * few times. A missing report is not proof of a crash. The search runs apart
1268
+ * from the capture:
1269
+ * `stop` a moment later must not call it off, since that is exactly how a run
1270
+ * that ends in a crash is wrapped up.
1271
+ */
1272
+ const fetchCrashReport = async (capture: Capture, device: DeviceInfo, pid: number): Promise<void> => {
1273
+ const executable = capture.processName;
1274
+ if (!executable || capture.naturalExitAt === undefined) return;
1275
+ const launch = capture.relaunches;
1276
+ const result = capture.launchResult;
1277
+ const since = capture.naturalExitAt - DEVICE_CLOCK_SKEW_MS;
1278
+ for (const delay of CRASH_REPORT_DELAYS_MS) {
1279
+ await sleep(delay, undefined, { signal: crashSearchAbort.signal });
1280
+ if (!isCurrentBridge(capture, launch, result)) return;
1281
+ const report = await pullCrashReport(device, executable, { since, pid, directory: dirname(capture.logFile),
1282
+ signal: crashSearchAbort.signal });
1283
+ if (crashSearchAbort.signal.aborted || !isCurrentBridge(capture, launch, result)) return;
1284
+ if (report) {
1285
+ capture.crashReport = report.path;
1286
+ if (!capture.endReason && report.terminationReason) endCapture(capture, "the app exited");
1287
+ capture.terminationReason = report.terminationReason ?? "not recorded in the crash report";
1288
+ capture.pushLine("err", `[xcodebug] system termination: ${capture.terminationReason}`);
1289
+ capture.pushLine("err", `[xcodebug] crash report: ${report.path}`);
1290
+ return;
1291
+ }
1292
+ }
1293
+ if (capture.endReason || capture.stoppedByUser) {
1294
+ capture.terminationReason = "unavailable: the device returned no matching crash report";
1295
+ capture.pushLine("err", `[xcodebug] system termination: ${capture.terminationReason}`);
1296
+ }
1297
+ };
1298
+
1299
+ const startCrashReportSearch = (capture: Capture, device: DeviceInfo): void => {
1300
+ if (capture.mode !== "console" || capture.naturalExitAt === undefined || capture.crashReport ||
1301
+ state.captures.get(capture.id) !== capture) return;
1302
+ const launch = capture.relaunches;
1303
+ const result = capture.launchResult;
1304
+ const existing = crashSearches.get(capture.id);
1305
+ if (existing?.launch === launch && existing.result === result) return;
1306
+ // A live-table PID is not evidence of which instance this ended console owned.
1307
+ capture.appPid = undefined;
1308
+ const identity = (async (): Promise<number | undefined> => {
1309
+ const raw = await result;
1310
+ if (crashSearchAbort.signal.aborted || !isCurrentBridge(capture, launch, result)) return;
1311
+ let pid: unknown;
1312
+ try {
1313
+ const data = asRecord(JSON.parse(raw ?? ""));
1314
+ const info = asRecord(data.info);
1315
+ if (info.commandType === "devicectl.device.process.launch" && info.outcome === "success") {
1316
+ pid = asRecord(asRecord(data.result).process).processIdentifier;
1317
+ }
1318
+ } catch {
1319
+ // Missing or malformed launch output cannot establish instance ownership.
1320
+ }
1321
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) {
1322
+ capture.terminationReason = "unavailable: the app identity was not verified by the console launch";
1323
+ capture.pushLine("err", `[xcodebug] system termination: ${capture.terminationReason}`);
1324
+ return;
1325
+ }
1326
+ capture.appPid = pid;
1327
+ capture.terminationReason = undefined;
1328
+ return pid;
1329
+ })();
1330
+ const promise = (async (): Promise<void> => {
1331
+ try {
1332
+ const pid = await identity;
1333
+ if (pid !== undefined && !crashSearchAbort.signal.aborted && isCurrentBridge(capture, launch, result)) {
1334
+ await fetchCrashReport(capture, device, pid);
1335
+ }
1336
+ } catch (error) {
1337
+ if (!crashSearchAbort.signal.aborted && isCurrentBridge(capture, launch, result)) {
1338
+ capture.terminationReason = "unavailable: exit diagnostics failed";
1339
+ capture.pushLine("err", `[xcodebug] ${capture.terminationReason}: ${error instanceof Error ? error.message : String(error)}`);
1340
+ }
1341
+ } finally {
1342
+ const current = crashSearches.get(capture.id);
1343
+ if (current?.launch === launch && current.result === result) crashSearches.delete(capture.id);
1344
+ }
1345
+ })();
1346
+ crashSearches.set(capture.id, { launch, result, identity, promise });
1347
+ };
1348
+
1349
+ const waitForCrashReport = async (capture: Capture, signal?: AbortSignal): Promise<void> => {
1350
+ const job = crashSearches.get(capture.id);
1351
+ if (!job || !isCurrentBridge(capture, job.launch, job.result) || signal?.aborted) return;
1352
+ const pending = job.promise;
1353
+ if (!signal) {
1354
+ await pending;
1355
+ return;
1356
+ }
1357
+ let onAbort: () => void = () => {};
1358
+ const cancelled = new Promise<void>(resolve => {
1359
+ onAbort = () => resolve();
1360
+ signal.addEventListener("abort", onAbort, { once: true });
1361
+ });
1362
+ try {
1363
+ await Promise.race([pending, cancelled]);
1364
+ } finally {
1365
+ signal.removeEventListener("abort", onAbort);
1366
+ }
1367
+ };
1368
+
1369
+ /**
1370
+ * End a console capture whose app is no longer the process it launched, and
1371
+ * say why where a later read will find it: a capture that just stops looks
1372
+ * the same as an app that went quiet.
1373
+ */
1374
+ const endCapture = (capture: Capture, reason: string): void => {
1375
+ const last = lastWords(capture);
1376
+ capture.endReason = last ? `${reason}; last line before the bridge ended: "${last}"` : reason;
1377
+ capture.pushLine("err", `[xcodebug] ${capture.endReason}; stopping capture`);
1378
+ stopCapture(capture, false);
1379
+ };
1380
+
1056
1381
  /**
1057
1382
  * Keep a capture alive for as long as the run lasts.
1058
1383
  *
@@ -1087,29 +1412,57 @@ export default function xcodebug(pi: ExtensionAPI): void {
1087
1412
  const delay = Math.min(1000 * 2 ** (Math.min(attempts, 5) - 1), 15_000);
1088
1413
  await sleepUnlessStopped(capture, delay);
1089
1414
  if (capture.stoppedByUser) return;
1415
+ const diagnosis = crashSearches.get(capture.id);
1416
+ if (diagnosis && isCurrentBridge(capture, diagnosis.launch, diagnosis.result)) {
1417
+ try {
1418
+ await diagnosis.identity;
1419
+ } catch {
1420
+ // The diagnostic job records the failure; ownership remains unverified.
1421
+ }
1422
+ if (capture.stoppedByUser) return;
1423
+ }
1090
1424
 
1091
1425
  // Only the console channel is bound to the app's lifetime, so only it
1092
1426
  // consults the process table. A syslog bridge outlives the app and its
1093
1427
  // drops say nothing about whether the app is still running.
1428
+ // `listed` is the app's pid as the table has it now, when it could be read.
1429
+ let listed: number | undefined;
1094
1430
  if (capture.mode === "console" && capture.processName) {
1095
1431
  const lookup = await lookupProcess(device, capture.processName, {
1096
1432
  attempts: 1,
1097
1433
  signal: capture.signal,
1098
1434
  });
1099
- if (!lookup.queryFailed && lookup.pid === undefined) {
1100
- capture.pushLine("err", "[xcodebug] app process is gone; stopping capture");
1101
- releaseCapture(capture);
1102
- return;
1103
- }
1435
+ // A stop that lands during the probe aborts it, which reads as a
1436
+ // failed query; carrying on would relaunch an app the user has let go.
1437
+ if (capture.stoppedByUser) return;
1104
1438
  if (lookup.queryFailed) {
1105
1439
  capture.pushLine("err", "[xcodebug] could not read the process table; still retrying");
1440
+ continue;
1441
+ } else if (lookup.pid === undefined) {
1442
+ endCapture(capture, "the app exited");
1443
+ return;
1444
+ } else if (capture.appPid !== undefined && lookup.pid !== capture.appPid) {
1445
+ // The console attaches only by launching, so reattaching here would
1446
+ // kill whatever started this instance - another session's capture,
1447
+ // which would then do the same to this one, or a test runner's app.
1448
+ endCapture(
1449
+ capture,
1450
+ `the app was restarted outside this capture (pid ${capture.appPid} -> ${lookup.pid}) and is left running`,
1451
+ );
1452
+ return;
1453
+ } else if (capture.appPid === undefined && capture.launchArgs.includes("--terminate-existing")) {
1454
+ endCapture(capture, "cannot verify ownership of the running app; it is left running");
1455
+ return;
1456
+ } else {
1457
+ listed = lookup.pid;
1106
1458
  }
1107
1459
  }
1108
1460
 
1109
1461
  capture.pushLine("err", `[xcodebug] reconnecting ${label} bridge (attempt ${attempts})`);
1110
1462
  capture.resetForReconnect();
1111
1463
  try {
1112
- await capture.start();
1464
+ await startCapture(capture);
1465
+ if (capture.stoppedByUser) return;
1113
1466
  attempts = 0;
1114
1467
  onReconnect?.(1);
1115
1468
  // Resume pushing for whichever channel this is. The active-id check
@@ -1117,7 +1470,21 @@ export default function xcodebug(pi: ExtensionAPI): void {
1117
1470
  if (capture.pushMode && state.pushTimers.get(capture.id) === undefined) {
1118
1471
  startPush(capture, capture.pushMode, capture.pushMatch, { resume: true });
1119
1472
  }
1120
- capture.pushLine("err", `[xcodebug] ${label} bridge reattached`);
1473
+ // devicectl attaches a console only by launching, and this launch
1474
+ // terminates the instance that was running.
1475
+ if (capture.mode === "console" && capture.launchArgs.includes("--terminate-existing")) {
1476
+ capture.relaunches += 1;
1477
+ // Without a reading of the table the new pid cannot be told from
1478
+ // the old one, and none is better than one that may be wrong.
1479
+ capture.appPid = undefined;
1480
+ if (listed !== undefined) void discoverAppPid(capture, device, listed);
1481
+ capture.pushLine(
1482
+ "err",
1483
+ `[xcodebug] console bridge reattached - this relaunched the app (relaunch ${capture.relaunches}), so the state it had is gone`,
1484
+ );
1485
+ } else {
1486
+ capture.pushLine("err", `[xcodebug] ${label} bridge reattached`);
1487
+ }
1121
1488
  return;
1122
1489
  } catch (error) {
1123
1490
  capture.pushLine("err", `[xcodebug] reconnect failed: ${(error as Error).message}`);
@@ -1128,6 +1495,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
1128
1495
  }
1129
1496
  };
1130
1497
 
1498
+ capture.onProcessExit(() => startCrashReportSearch(capture, device));
1499
+
1131
1500
  capture.onExit((code, signal) => {
1132
1501
  stopPush(capture.id);
1133
1502
  const reason = signal ? `signal ${signal}` : `exit ${code ?? "?"}`;
@@ -1275,8 +1644,11 @@ export default function xcodebug(pi: ExtensionAPI): void {
1275
1644
  onUpdate?: (text: string) => void;
1276
1645
  /** The .xcworkspace/.xcodeproj this run targets; anchors the Podfile lookup. */
1277
1646
  containerPath?: string;
1278
- }): Promise<{ report: ChangeReport; needsBuild: boolean; podInstall?: string; podInstallFailed: boolean; notes: string[] }> => {
1279
- let report = await detectChanges(options.root);
1647
+ /** Which of this session's builds would be reused; without one, a build is always needed. */
1648
+ buildKey?: string;
1649
+ preview?: boolean;
1650
+ }): Promise<{ report: ChangeReport; needsBuild: boolean; podInstall?: string; podInstallNeeded?: boolean; podInstallFailed: boolean; notes: string[] }> => {
1651
+ let report = await detectChanges(options.root, options.containerPath);
1280
1652
  const notes: string[] = [];
1281
1653
  let podInstallNote: string | undefined;
1282
1654
  let podInstallFailed = false;
@@ -1301,13 +1673,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1301
1673
  const lockCheck =
1302
1674
  options.installPods === false || !options.containerPath
1303
1675
  ? undefined
1304
- : await checkPodLockSync(options.containerPath);
1676
+ : await checkPodLockSync(resolve(options.root, options.containerPath));
1305
1677
  const lockNeedsInstall = lockCheck !== undefined && !lockCheck.synced;
1306
1678
 
1307
1679
  if (newFilesNeedInstall || lockNeedsInstall) {
1308
1680
  // pod install only runs in the directory that owns this container's
1309
1681
  // Podfile. Searching elsewhere risks reinstalling another project's pods.
1310
1682
  const podfileDir = lockCheck?.podfileDir;
1683
+ if (options.preview && podfileDir) {
1684
+ return { report, needsBuild: true, podInstallNeeded: true, podInstallFailed: false, notes };
1685
+ }
1311
1686
  if (!podfileDir) {
1312
1687
  notes.push(
1313
1688
  `pod install skipped: no Podfile beside ${options.containerPath ?? "the container"} ` +
@@ -1330,7 +1705,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1330
1705
  // pod install rewrites Podfile.lock and the Pods project, so re-read the
1331
1706
  // tree: storing the pre-install fingerprint would make the next launch
1332
1707
  // think the pods are still stale and install them again.
1333
- report = await detectChanges(options.root);
1708
+ report = await detectChanges(options.root, options.containerPath);
1334
1709
  // Record the key derived from the post-install tree, not the one that
1335
1710
  // triggered this install: pod install can change the new-file set, and a
1336
1711
  // stale key would make the next run skip an install it still needs.
@@ -1339,7 +1714,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1339
1714
  // The install is only meaningful if the lock actually converged. Re-check
1340
1715
  // rather than trusting the pre-install verdict.
1341
1716
  if (options.containerPath) {
1342
- const after = await checkPodLockSync(options.containerPath);
1717
+ const after = await checkPodLockSync(resolve(options.root, options.containerPath));
1343
1718
  if (after && !after.synced) {
1344
1719
  podInstallNote += `\nwarning: Podfile.lock is still out of sync after pod install (${after.reason})`;
1345
1720
  }
@@ -1347,15 +1722,51 @@ export default function xcodebug(pi: ExtensionAPI): void {
1347
1722
  }
1348
1723
  }
1349
1724
 
1725
+ // A build is reused only when it was made of this target, from this tree,
1726
+ // and its product is still what the build left behind: Xcode, or a raw
1727
+ // xcodebuild in another terminal, writes the same DerivedData path.
1728
+ const built = options.buildKey === undefined ? undefined : state.builds.get(options.buildKey);
1350
1729
  const needsBuild =
1351
1730
  options.force === true ||
1352
1731
  report.unavailable ||
1353
- state.lastBuiltFingerprint === undefined ||
1354
- state.lastBuiltFingerprint !== report.fingerprint;
1732
+ built?.fingerprint !== report.fingerprint ||
1733
+ (await directorySignature(built.appPath)) !== built.product;
1355
1734
 
1356
1735
  return { report, needsBuild, podInstall: podInstallNote, podInstallFailed, notes };
1357
1736
  };
1358
1737
 
1738
+ /**
1739
+ * Remember a successful build so the next run of the same target can reuse it.
1740
+ *
1741
+ * `before` is the tree the build started from. If the tree is different once
1742
+ * the build is over, something changed while it ran, and whether that change
1743
+ * made it into the product is unknowable - so the build is not remembered, the
1744
+ * next run builds again, and the returned note says why.
1745
+ */
1746
+ const rememberBuild = async (
1747
+ key: string,
1748
+ before: string,
1749
+ root: string,
1750
+ containerPath: string | undefined,
1751
+ outcome: BuildOutcome,
1752
+ ): Promise<string | undefined> => {
1753
+ if (!outcome.appPath) return undefined;
1754
+ const after = (await detectChanges(root, containerPath)).fingerprint;
1755
+ if (after !== before) {
1756
+ return "the working tree changed while this was building, so the next run builds again instead of reusing it";
1757
+ }
1758
+ const product = await directorySignature(outcome.appPath);
1759
+ if (product === undefined) return undefined;
1760
+ state.builds.set(key, {
1761
+ fingerprint: after,
1762
+ appPath: outcome.appPath,
1763
+ product,
1764
+ bundleId: outcome.bundleId,
1765
+ executable: outcome.executable,
1766
+ });
1767
+ return undefined;
1768
+ };
1769
+
1359
1770
  /**
1360
1771
  * Run a shell command to completion, then stop the capture it was watching
1361
1772
  * and report what the run produced.
@@ -1397,6 +1808,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1397
1808
 
1398
1809
  const since = target?.status().cursor ?? 0;
1399
1810
  const linesAtStart = target?.status().lineCount ?? 0;
1811
+ const relaunchesAtStart = target?.relaunches ?? 0;
1400
1812
  const result = await runCommand(bin, argv, {
1401
1813
  cwd,
1402
1814
  timeoutMs,
@@ -1412,11 +1824,28 @@ export default function xcodebug(pi: ExtensionAPI): void {
1412
1824
  // the screen stays where the case left it.
1413
1825
  let captureNote = "no capture was running; nothing to stop";
1414
1826
  if (target) {
1827
+ // A bridge that is already down went down by itself, and the reply has to
1828
+ // say so: "the case ran" and "the app died under the case" must not read
1829
+ // alike. Stopping still matters then - it calls off a pending reattach,
1830
+ // which would relaunch the app now that the case is over.
1831
+ const wasRunning = target.running && !target.processExited;
1832
+ const wasUserStopped = target.stoppedByUser && !target.endReason;
1415
1833
  stopCapture(target, false);
1834
+ // Report collection is independent; stop a queued reattach before awaiting it.
1835
+ if (!wasRunning && !wasUserStopped) await waitForCrashReport(target, signal);
1416
1836
  await target.waitForExit(5_000);
1837
+ const how = wasRunning
1838
+ ? `stopped ${target.id}`
1839
+ : wasUserStopped
1840
+ ? `${target.id} was already stopped`
1841
+ : `warning: ${target.id} was no longer capturing when the command finished${whyEnded(target)}`;
1417
1842
  const status = target.status();
1418
1843
  const added = Math.max(0, status.lineCount - linesAtStart);
1419
- captureNote = `stopped ${status.id} · ${added} new line(s) · ${status.logFile}`;
1844
+ captureNote = `${how} · ${added} new line(s) · ${status.logFile}`;
1845
+ const relaunched = target.relaunches - relaunchesAtStart;
1846
+ if (relaunched > 0) {
1847
+ captureNote += `\nwarning: a console reattach relaunched the app ${relaunched} time(s) during this run; lines after a relaunch come from a fresh instance`;
1848
+ }
1420
1849
  }
1421
1850
 
1422
1851
  const verdict = result.timedOut
@@ -1439,6 +1868,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
1439
1868
  elapsedSeconds: elapsedS,
1440
1869
  captureId: target?.id,
1441
1870
  cursor: since,
1871
+ terminationReason: target?.terminationReason,
1872
+ crashReport: target?.crashReport,
1442
1873
  },
1443
1874
  // A non-zero exit is a failed case, and the caller must see it as such
1444
1875
  // rather than as a successful "run finished".
@@ -1463,8 +1894,20 @@ export default function xcodebug(pi: ExtensionAPI): void {
1463
1894
  // lookup below (config, change detection, container discovery, the command's
1464
1895
  // working directory) must agree on one root or they disagree about the project.
1465
1896
  const projectRoot = resolveProjectRoot(pi, ctx);
1466
- const config = await readConfig(projectRoot);
1897
+ const configRead = await readConfig(projectRoot).then(
1898
+ (value) => ({ value, error: undefined }),
1899
+ (error: Error) => ({ value: {} as ProjectConfig, error }),
1900
+ );
1901
+ const config = configRead.value;
1467
1902
  const action = params.action;
1903
+ if (configRead.error && !CONFIG_FREE_ACTIONS.has(action)) throw configRead.error;
1904
+
1905
+ // The first run of a session clears out the logs nothing has written to in
1906
+ // a while, before it adds its own.
1907
+ if (!state.logsPruned && (action === "build" || action === "launch" || action === "syslog")) {
1908
+ state.logsPruned = true;
1909
+ await pruneLogs(logDir(ctx), LOG_RETENTION_MS);
1910
+ }
1468
1911
 
1469
1912
  if (action === "doctor") {
1470
1913
  const checks = await Promise.all([
@@ -1472,28 +1915,50 @@ export default function xcodebug(pi: ExtensionAPI): void {
1472
1915
  runCommand("xcrun", ["devicectl", "--version"], { timeoutMs: 30_000 }),
1473
1916
  runCommand("idevicesyslog", ["--version"], { timeoutMs: 20_000 }),
1474
1917
  ]);
1918
+ const configLine = configRead.error
1919
+ ? configRead.error.message
1920
+ : Object.keys(config).length > 0 ? join(projectRoot, ".xcodebug.json") : "(none)";
1475
1921
  const lines = [
1476
1922
  `xcodebuild: ${checks[0].code === 0 ? checks[0].stdout.split("\n")[0] : "missing"}`,
1477
1923
  `devicectl: ${checks[1].code === 0 ? (checks[1].stdout || checks[1].stderr).trim().split("\n")[0] : "missing"}`,
1478
1924
  `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)"}`,
1925
+ `config: ${configLine}`,
1480
1926
  `log dir: ${logDir(ctx)}`,
1481
1927
  ];
1482
1928
  return { content: [{ type: "text", text: lines.join("\n") }], details: {} };
1483
1929
  }
1484
1930
 
1485
1931
  if (action === "changes") {
1486
- const report = await detectChanges(projectRoot);
1932
+ let buildKey: string | undefined;
1933
+ let containerPath: string | undefined;
1934
+ let unresolved: string | undefined;
1935
+ try {
1936
+ const target = await withContainer(projectRoot, config, params);
1937
+ containerPath = target.workspace ?? target.project;
1938
+ buildKey = buildKeyOf(target, await resolveDeviceParam(params.device, projectRoot));
1939
+ } catch (error) {
1940
+ unresolved = (error as Error).message;
1941
+ const detected = await detectContainer(projectRoot);
1942
+ containerPath ??= params.workspace ?? params.project ?? config.workspace ?? config.project ?? detected.workspace ?? detected.project;
1943
+ }
1944
+ const gate = await prepareRun(ctx, {
1945
+ root: projectRoot, containerPath: containerPath && resolve(projectRoot, containerPath),
1946
+ buildKey, force: params.force, installPods: params.installPods, preview: true,
1947
+ });
1948
+ const { report } = gate;
1949
+ const lastBuilt = buildKey === undefined ? undefined : state.builds.get(buildKey)?.fingerprint;
1487
1950
  const lines = [
1488
1951
  describeChanges(report),
1489
1952
  `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"}`,
1953
+ `last build for this target: ${lastBuilt ?? "(none)"}`,
1954
+ `rebuild needed: ${gate.needsBuild ? "yes" : "no"}`,
1955
+ `pod install needed: ${gate.podInstallNeeded ? "yes" : "no"}`,
1956
+ ...gate.notes,
1493
1957
  ];
1958
+ if (unresolved) lines.push(`no reusable target resolved: ${unresolved}`);
1494
1959
  return {
1495
1960
  content: [{ type: "text", text: lines.join("\n") }],
1496
- details: { report, lastBuiltFingerprint: state.lastBuiltFingerprint },
1961
+ details: { report, lastBuiltFingerprint: lastBuilt },
1497
1962
  };
1498
1963
  }
1499
1964
 
@@ -1508,13 +1973,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1508
1973
  setRunPhase("resolving the project…");
1509
1974
  const device = await resolveDeviceParam(params.device, projectRoot);
1510
1975
  const target = await withContainer(projectRoot, config, params);
1976
+ const buildKey = buildKeyOf(target, device);
1977
+ const containerPath = target.workspace ?? target.project;
1511
1978
  const gate = await prepareRun(ctx, {
1512
1979
  root: projectRoot,
1513
1980
  force: params.force,
1514
1981
  installPods: params.installPods,
1515
1982
  timeoutSeconds: params.timeoutSeconds,
1516
1983
  signal,
1517
- containerPath: target.workspace ?? target.project,
1984
+ containerPath,
1985
+ buildKey,
1518
1986
  onUpdate: (text) => onUpdate?.({ content: [{ type: "text", text }], details: {} }),
1519
1987
  });
1520
1988
  if (gate.podInstallFailed) {
@@ -1527,14 +1995,17 @@ export default function xcodebug(pi: ExtensionAPI): void {
1527
1995
  if (!gate.needsBuild) {
1528
1996
  const summary =
1529
1997
  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`;
1998
+ ? "nothing changed"
1999
+ : `${gate.report.changed.length} changed file(s), but they are unchanged`;
1532
2000
  return {
1533
- content: [{ type: "text", text: `build skipped: ${summary} (fingerprint ${gate.report.fingerprint}; pass force=true to rebuild)` }],
2001
+ content: [{ type: "text", text: `build skipped: ${summary} since this session's last successful build (fingerprint ${gate.report.fingerprint}; pass force=true to rebuild)` }],
1534
2002
  details: { report: gate.report, skipped: true },
1535
2003
  };
1536
2004
  }
1537
2005
  setRunPhase(`building ${target.scheme} for ${device.name}`);
2006
+ // Forgotten before the build, not after: one that fails can leave the
2007
+ // product half rewritten, which is no longer the build that was remembered.
2008
+ state.builds.delete(buildKey);
1538
2009
  const outcome = await buildForDevice(target, device, {
1539
2010
  logDir: logDir(ctx),
1540
2011
  cwd: projectRoot,
@@ -1544,13 +2015,14 @@ export default function xcodebug(pi: ExtensionAPI): void {
1544
2015
  signal,
1545
2016
  });
1546
2017
  clearRunPhase();
2018
+ let notRemembered: string | undefined;
1547
2019
  if (outcome.ok) {
1548
- state.lastBuiltFingerprint = (await detectChanges(projectRoot)).fingerprint;
2020
+ notRemembered = await rememberBuild(buildKey, gate.report.fingerprint, projectRoot, containerPath, outcome);
1549
2021
  await clearArchiveBeforeNewRun(ctx);
1550
2022
  }
1551
2023
  const prefix = gate.podInstall ? `${gate.podInstall}\n` : "";
1552
2024
  return {
1553
- content: [{ type: "text", text: `${prefix}${outcome.summary}\nlog: ${outcome.logFile}` }],
2025
+ content: [{ type: "text", text: `${prefix}${outcome.summary}${notRemembered ? `\nnote: ${notRemembered}` : ""}\nlog: ${outcome.logFile}` }],
1554
2026
  details: { ...outcome, report: gate.report },
1555
2027
  isError: !outcome.ok,
1556
2028
  };
@@ -1641,13 +2113,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1641
2113
  // Resolve the container up front: the Podfile that governs this run lives
1642
2114
  // beside it, so the pod gate must not search from an arbitrary cwd.
1643
2115
  const launchTarget = explicitApp && !wantsBuild ? undefined : await withContainer(projectRoot, config, params);
2116
+ const buildKey = launchTarget ? buildKeyOf(launchTarget, device) : undefined;
2117
+ const containerPath = launchTarget ? (launchTarget.workspace ?? launchTarget.project) : undefined;
1644
2118
  const gate = await prepareRun(ctx, {
1645
2119
  root: projectRoot,
1646
2120
  force: params.force,
1647
2121
  installPods: explicitApp && !wantsBuild ? false : params.installPods,
1648
2122
  timeoutSeconds: params.timeoutSeconds,
1649
2123
  signal,
1650
- containerPath: launchTarget ? (launchTarget.workspace ?? launchTarget.project) : undefined,
2124
+ containerPath,
2125
+ buildKey,
1651
2126
  onUpdate: (text) => onUpdate?.({ content: [{ type: "text", text }], details: {} }),
1652
2127
  });
1653
2128
  const notes = [...gate.notes];
@@ -1661,13 +2136,16 @@ export default function xcodebug(pi: ExtensionAPI): void {
1661
2136
  };
1662
2137
  }
1663
2138
 
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;
2139
+ // Rebuild when the tree changed, when this session has not built this
2140
+ // target yet, when the caller asked for a build, or when force is set.
2141
+ // `needsBuild` false means the gate found this target's build still good.
2142
+ const reused = buildKey === undefined || gate.needsBuild || wantsBuild ? undefined : state.builds.get(buildKey);
2143
+ const mustBuild = launchTarget !== undefined && buildKey !== undefined && reused === undefined;
1667
2144
  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, {
2145
+ setRunPhase(`building ${launchTarget.scheme} for ${device.name}`);
2146
+ // Forgotten before the build, for the reason `build` gives.
2147
+ state.builds.delete(buildKey);
2148
+ const build = await buildForDevice(launchTarget, device, {
1671
2149
  logDir: logDir(ctx),
1672
2150
  cwd: projectRoot,
1673
2151
  onProgress: (text) => setRunPhase(text),
@@ -1682,19 +2160,39 @@ export default function xcodebug(pi: ExtensionAPI): void {
1682
2160
  isError: true,
1683
2161
  };
1684
2162
  }
1685
- state.lastBuiltFingerprint = (await detectChanges(projectRoot)).fingerprint;
1686
- notes.push(await clearArchiveBeforeNewRun(ctx));
2163
+ const notRemembered = await rememberBuild(buildKey, gate.report.fingerprint, projectRoot, containerPath, build);
2164
+ const cleared = await clearArchiveBeforeNewRun(ctx);
2165
+ if (cleared) notes.push(cleared);
1687
2166
  appPath = build.appPath;
1688
2167
  bundleId = build.bundleId ?? bundleId;
1689
2168
  executable = build.executable;
1690
2169
  notes.push(build.summary);
2170
+ if (notRemembered) notes.push(`note: ${notRemembered}`);
1691
2171
  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})`);
2172
+ } else if (reused) {
2173
+ appPath = reused.appPath;
2174
+ bundleId = reused.bundleId ?? bundleId;
2175
+ executable = reused.executable;
2176
+ notes.push(`reusing this session's build (nothing changed since fingerprint ${gate.report.fingerprint}; force=true rebuilds)\napp: ${appPath}`);
1694
2177
  }
1695
2178
 
1696
2179
  if (!appPath) throw new Error("launch requires appPath, or a scheme to build.");
1697
2180
  executable ??= params.processName ?? (await readBundleExecutable(appPath));
2181
+
2182
+ // The instance this launch is about to replace, read before the install
2183
+ // because installing over a running app can end it already. The pid
2184
+ // recorded further down must not be this one, so when the table cannot be
2185
+ // read none is recorded.
2186
+ const before =
2187
+ executable && params.terminateExisting !== false
2188
+ ? await lookupProcess(device, executable, { attempts: 1, signal })
2189
+ : { queryFailed: false, pid: undefined };
2190
+ // Another session's capture, or the user's own running app: its state is
2191
+ // gone once this launch goes through, which is worth a line.
2192
+ if (before.pid !== undefined && ![...state.captures.values()].some((c) => c.appPid === before.pid)) {
2193
+ notes.push(`note: ${executable} was already running (pid ${before.pid}), not started by this session; this launch terminated it`);
2194
+ }
2195
+
1698
2196
  setRunPhase(`installing on ${device.name}`);
1699
2197
  const install = await installApp(device, appPath, { timeoutMs: 180_000, signal });
1700
2198
  if (!install.ok) {
@@ -1727,6 +2225,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1727
2225
  bundleId: resolvedBundleId,
1728
2226
  processName: executable,
1729
2227
  logDir: logDir(ctx),
2228
+ collectLaunchResult: true,
1730
2229
  command: "xcrun",
1731
2230
  args: consoleLaunchArgs(device, resolvedBundleId, {
1732
2231
  args: params.args ?? config.args,
@@ -1734,7 +2233,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1734
2233
  environment: { ...(config.environment ?? {}), ...(params.environment ?? {}) },
1735
2234
  }),
1736
2235
  });
1737
- await capture.start();
2236
+ await startCapture(capture, signal);
1738
2237
  state.captures.set(capture.id, capture);
1739
2238
  state.activeCaptureId = capture.id;
1740
2239
  watchExit(capture, device);
@@ -1766,11 +2265,21 @@ export default function xcodebug(pi: ExtensionAPI): void {
1766
2265
  // The previous run for this app was already retired before this capture
1767
2266
  // started (see above), so nothing is left to stop here. Other apps'
1768
2267
  // captures are untouched either way.
2268
+
2269
+ // Discover an operational PID while the console is live. Exit diagnosis
2270
+ // instead uses the identity from this launch's own command result.
2271
+ if (!before.queryFailed) await discoverAppPid(capture, device, before.pid, signal);
2272
+ if (signal?.aborted) {
2273
+ stopCapture(capture, false);
2274
+ await capture.waitForExit(3_000);
2275
+ signal.throwIfAborted();
2276
+ }
2277
+ // Finish console process discovery before opening another device log service.
1769
2278
  // Second channel: idevicesyslog reads the device's unified log directly
1770
2279
  // and survives a dropped --console bridge. It carries os_log only, so
1771
2280
  // NSLog/print lines (MySDK) stay exclusive to the console channel -
1772
2281
  // this is a safety net for the gap, not a replacement.
1773
- if (executable && params.dualChannel !== false) {
2282
+ if (executable && params.dualChannel !== false && !capture.stoppedByUser) {
1774
2283
  const syslogCapture = new Capture({
1775
2284
  mode: "syslog",
1776
2285
  deviceId: device.id,
@@ -1782,26 +2291,21 @@ export default function xcodebug(pi: ExtensionAPI): void {
1782
2291
  args: ["-u", device.udid ?? device.id, "-p", executable, "--no-colors"],
1783
2292
  });
1784
2293
  try {
1785
- await syslogCapture.start();
1786
- state.captures.set(syslogCapture.id, syslogCapture);
1787
- state.companions.set(capture.id, syslogCapture.id);
1788
- watchExit(syslogCapture, device);
1789
- notes.push(`syslog channel: ${syslogCapture.id}`);
2294
+ await startCapture(syslogCapture, signal);
2295
+ if (capture.stoppedByUser) {
2296
+ syslogCapture.stop(false);
2297
+ await syslogCapture.waitForExit(3_000);
2298
+ } else {
2299
+ state.captures.set(syslogCapture.id, syslogCapture);
2300
+ state.companions.set(capture.id, syslogCapture.id);
2301
+ watchExit(syslogCapture, device);
2302
+ notes.push(`syslog channel: ${syslogCapture.id}`);
2303
+ }
1790
2304
  } catch (error) {
1791
2305
  notes.push(`syslog channel unavailable: ${(error as Error).message}`);
1792
2306
  }
1793
2307
  }
1794
2308
 
1795
- // The app pid is not part of --console's output; discover it from the
1796
- // 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
- }
1803
- }
1804
-
1805
2309
  return {
1806
2310
  content: [{
1807
2311
  type: "text",
@@ -1836,7 +2340,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1836
2340
  command: "idevicesyslog",
1837
2341
  args,
1838
2342
  });
1839
- await capture.start();
2343
+ await startCapture(capture, signal);
1840
2344
  state.captures.set(capture.id, capture);
1841
2345
  state.activeCaptureId = capture.id;
1842
2346
  watchExit(capture, device);
@@ -1859,11 +2363,21 @@ export default function xcodebug(pi: ExtensionAPI): void {
1859
2363
  if (action === "logs") {
1860
2364
  const capture = requireCapture(params.captureId);
1861
2365
  const since = params.since ?? 0;
1862
- const formatted = formatLogLines(capture, since, params.limit ?? 200, params.grep);
2366
+ const formatted = await formatLogLines(capture, {
2367
+ since,
2368
+ limit: params.limit ?? 200,
2369
+ grep: toFilter(params.grep, params.regex),
2370
+ times: params.times,
2371
+ signal,
2372
+ });
1863
2373
  const companionId = state.companions.get(capture.id);
1864
2374
  if (!capture.running && companionId) {
1865
2375
  formatted.text += `\n\n[this channel has ended; system-level logs continue in ${companionId} - pass captureId=${companionId}]`;
1866
2376
  }
2377
+ // The lines that say so are in the log, but a filtered read leaves them out.
2378
+ if (capture.endReason) formatted.text += `\n\n[this capture ended on its own · ${capture.endReason}]`;
2379
+ if (capture.terminationReason) formatted.text += `\n[system termination: ${capture.terminationReason}]`;
2380
+ if (capture.crashReport) formatted.text += `\n[crash report: ${capture.crashReport}]`;
1867
2381
  return {
1868
2382
  content: [{ type: "text", text: formatted.text }],
1869
2383
  details: { captureId: capture.id, cursor: formatted.cursor, total: formatted.total, running: capture.running },
@@ -1872,15 +2386,21 @@ export default function xcodebug(pi: ExtensionAPI): void {
1872
2386
 
1873
2387
  if (action === "wait") {
1874
2388
  const capture = requireCapture(params.captureId);
1875
- const needle = params.match;
1876
- if (!needle) throw new Error("wait requires match (a substring to wait for).");
2389
+ const needle = toFilter(params.match, params.regex);
2390
+ if (!needle) throw new Error("wait requires match (a substring to wait for, or a pattern with regex=true).");
2391
+ const shown = typeof needle === "string" ? `"${needle}"` : String(needle);
1877
2392
  const timeoutMs = Math.min(Math.max(1, params.timeoutSeconds ?? 30), 600) * 1000;
1878
2393
  const since = params.since ?? 0;
1879
2394
 
1880
- const matches: LogLine[] = [];
2395
+ const matches: FoundLine[] = [];
1881
2396
  const seen = new Set<number>();
1882
2397
  let finished = false;
1883
2398
  let cancelled = false;
2399
+ let deadlineExpired = false;
2400
+ // The backlog is read from disk too, which takes a moment. A line that
2401
+ // arrives meanwhile must not settle the wait ahead of the earlier ones.
2402
+ let backlogRead = false;
2403
+ let note = "";
1884
2404
  let timer: ReturnType<typeof setTimeout> | undefined;
1885
2405
  let unsubscribeLine: () => void = () => {};
1886
2406
  let unsubscribeExit: () => void = () => {};
@@ -1892,21 +2412,22 @@ export default function xcodebug(pi: ExtensionAPI): void {
1892
2412
  if (matches.length === 0) {
1893
2413
  // Abort also settles through `finish`, so say what happened instead of
1894
2414
  // 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})`;
2415
+ if (cancelled) return `cancelled while waiting for ${shown} (cursor ${cursor})${note}`;
2416
+ if (timedOut) return `timed out after ${timeoutMs / 1000}s waiting for ${shown} (cursor ${cursor})${note}`;
2417
+ return `capture ended before ${shown} appeared (cursor ${cursor})${whyEnded(capture)}${note}`;
1899
2418
  }
1900
2419
  const body = matches
2420
+ .sort((a, b) => a.index - b.index)
1901
2421
  .slice(0, 200)
1902
- .map((line) => `${String(line.index).padStart(6, " ")} ${line.text}`)
2422
+ .map((line) => `${String(line.index).padStart(6, " ")} ${params.times ? clock(line.at) : ""}${line.text}`)
1903
2423
  .join("\n");
1904
- return `matched ${matches.length} line(s) · cursor ${cursor}\n${body}`;
2424
+ return `matched ${matches.length} line(s) · cursor ${cursor}\n${body}${note}`;
1905
2425
  };
1906
2426
 
1907
2427
  const finish = (timedOut: boolean): void => {
1908
2428
  if (finished) return;
1909
2429
  finished = true;
2430
+ deadlineExpired = timedOut;
1910
2431
  if (timer) clearTimeout(timer);
1911
2432
  unsubscribeLine();
1912
2433
  unsubscribeExit();
@@ -1916,14 +2437,14 @@ export default function xcodebug(pi: ExtensionAPI): void {
1916
2437
  resolveWait(settle(timedOut));
1917
2438
  };
1918
2439
 
1919
- const collect = (line: LogLine): void => {
2440
+ const collect = (line: FoundLine): void => {
1920
2441
  if (finished || line.index <= since || seen.has(line.index)) return;
1921
- if (!line.text.includes(needle)) return;
2442
+ if (!matchesFilter(line.text, needle)) return;
1922
2443
  seen.add(line.index);
1923
2444
  matches.push(line);
1924
2445
  };
1925
2446
 
1926
- const text = await new Promise<string>((resolve) => {
2447
+ const waiting = new Promise<string>((resolve) => {
1927
2448
  resolveWait = resolve;
1928
2449
  // Subscribe first, then scan the backlog: the scan covers
1929
2450
  // [since, cursor] and the listener covers everything after it, so no
@@ -1931,27 +2452,46 @@ export default function xcodebug(pi: ExtensionAPI): void {
1931
2452
  unsubscribeLine = capture.onLine((line) => {
1932
2453
  collect(line);
1933
2454
  // Let the rest of the same chunk land before settling.
1934
- if (matches.length > 0) setTimeout(() => finish(false), 50);
2455
+ if (backlogRead && matches.length > 0) setTimeout(() => finish(false), 50);
1935
2456
  });
1936
- unsubscribeExit = capture.onExit(() => setTimeout(() => finish(false), 0));
1937
- timer = setTimeout(() => finish(true), timeoutMs);
2457
+ unsubscribeExit = capture.onExit(() => setTimeout(() => backlogRead && finish(false), 0));
1938
2458
  onAbort = (): void => {
1939
2459
  cancelled = true;
1940
2460
  finish(true);
1941
2461
  };
1942
2462
  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
2463
  });
1951
2464
 
2465
+ try {
2466
+ const backlog = await capture.search({ since, limit: 500, grep: needle, signal });
2467
+ for (const line of backlog.lines) collect(line);
2468
+ note = evictedNote(backlog, capture.logFile);
2469
+ backlogRead = true;
2470
+ } catch (error) {
2471
+ if (signal?.aborted) onAbort?.();
2472
+ else {
2473
+ finish(false);
2474
+ throw error;
2475
+ }
2476
+ }
2477
+ // The deadline bounds the wait for a line still to come, so it starts
2478
+ // here: expiring while the lines already logged are being read back would
2479
+ // report a timeout for a line that is sitting on disk.
2480
+ if (!finished) timer = setTimeout(() => finish(true), timeoutMs);
2481
+ // A pattern already present in the backlog must return immediately,
2482
+ // not wait out the timeout.
2483
+ if (matches.length > 0 || !capture.running) finish(false);
2484
+ let text = await waiting;
2485
+ if (!cancelled && !deadlineExpired && matches.length === 0 && !capture.running) {
2486
+ await waitForCrashReport(capture, signal);
2487
+ if (signal?.aborted) cancelled = true;
2488
+ text = settle(cancelled);
2489
+ }
2490
+
1952
2491
  return {
1953
2492
  content: [{ type: "text", text }],
1954
- details: { captureId: capture.id, cursor: capture.status().cursor, matched: matches.length },
2493
+ details: { captureId: capture.id, cursor: capture.status().cursor, matched: matches.length,
2494
+ terminationReason: capture.terminationReason, crashReport: capture.crashReport },
1955
2495
  isError: matches.length === 0,
1956
2496
  };
1957
2497
  }
@@ -1968,7 +2508,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
1968
2508
  : [...state.companions.values()].includes(status.id)
1969
2509
  ? " · companion"
1970
2510
  : "";
1971
- return `- ${status.id} [${status.mode}] ${stateText}${role} · ${status.lineCount} lines · ${status.bundleId} · ${status.logFile}`;
2511
+ const relaunched = status.relaunches > 0 ? ` · app relaunched ${status.relaunches}×` : "";
2512
+ return `- ${status.id} [${status.mode}] ${stateText}${role}${relaunched}${endedNote(capture)} · ${status.lineCount} lines · ${status.bundleId} · ${status.logFile}`;
1972
2513
  });
1973
2514
  return { content: [{ type: "text", text: lines.join("\n") }], details: { captures: [...state.captures.values()].map((capture) => capture.status()) } };
1974
2515
  }
@@ -1987,7 +2528,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1987
2528
  // an error (requireCapture throws for that).
1988
2529
  const targets = params.captureId
1989
2530
  ? [requireCapture(params.captureId)]
1990
- : [...state.captures.values()].filter((c) => c.running);
2531
+ : [...state.captures.values()].filter((c) => !state.endedCaptures.has(c.id));
1991
2532
  if (targets.length === 0) {
1992
2533
  const known = [...state.captures.values()].map((c) => `${c.id} (${c.mode}, ended)`);
1993
2534
  return {
@@ -2020,14 +2561,17 @@ export default function xcodebug(pi: ExtensionAPI): void {
2020
2561
  const capture = state.activeCaptureId ? state.captures.get(state.activeCaptureId) : undefined;
2021
2562
  const bundleId = params.bundleId ?? capture?.bundleId ?? config.bundleId;
2022
2563
  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);
2564
+ const sameTarget = capture?.deviceId === device.id && capture.bundleId === bundleId &&
2565
+ (params.processName === undefined || params.processName === capture.processName);
2566
+ const executable = params.processName ?? (sameTarget ? capture.processName : undefined) ??
2567
+ (bundleId === config.bundleId ? config.scheme : undefined);
2568
+ const pid = (sameTarget ? capture.appPid : undefined) ??
2569
+ (executable ? (await lookupProcess(device, executable, { signal })).pid : undefined);
2570
+ signal?.throwIfAborted();
2027
2571
  if (!pid) {
2028
2572
  return { content: [{ type: "text", text: `no running process for ${bundleId} on ${device.name}` }], details: {} };
2029
2573
  }
2030
- const outcome = await terminateApp(device, pid, { timeoutMs: 30_000 });
2574
+ const outcome = await terminateApp(device, pid, { timeoutMs: 30_000, signal });
2031
2575
  return {
2032
2576
  content: [{ type: "text", text: outcome.message }],
2033
2577
  details: { ...outcome, pid },
@@ -2105,14 +2649,14 @@ export default function xcodebug(pi: ExtensionAPI): void {
2105
2649
  promptGuidelines: [
2106
2650
  "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
2651
  "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.",
2652
+ "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
2653
  "xcodebug action=changes reports whether a rebuild or pod install is pending without running either.",
2110
2654
  "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
2655
  "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
2656
  "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
2657
  "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
2658
  "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.",
2659
+ "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
2660
  ],
2117
2661
  executionMode: "sequential",
2118
2662
  parameters: Type.Object({
@@ -2146,6 +2690,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
2146
2690
  limit: Type.Optional(Type.Number({ description: "Max lines to return (default 200)" })),
2147
2691
  grep: Type.Optional(Type.String({ description: "Only return lines containing this text" })),
2148
2692
  match: Type.Optional(Type.String({ description: "wait: substring to wait for; also filters pushed lines" })),
2693
+ regex: Type.Optional(Type.Boolean({ description: "logs/wait: treat grep and match as regular expressions instead of substrings, e.g. match=\"sync (done|failed)\"." })),
2694
+ 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
2695
  timeoutSeconds: Type.Optional(Type.Number({ description: "wait/build timeout in seconds; await: max run time (default 1800)" })),
2150
2696
  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
2697
  push: Type.Optional(Type.Union([Type.Literal("off"), Type.Literal("context"), Type.Literal("wake")], {
@@ -2273,10 +2819,13 @@ export default function xcodebug(pi: ExtensionAPI): void {
2273
2819
  });
2274
2820
 
2275
2821
  pi.on("session_shutdown", async () => {
2822
+ shuttingDown = true;
2823
+ crashSearchAbort.abort();
2276
2824
  stopStatusTicker();
2277
2825
  state.uiCtx?.ui.setStatus("xcodebug", undefined);
2278
2826
  state.uiCtx?.ui.setWidget("xcodebug", undefined);
2279
- for (const capture of state.captures.values()) {
2827
+ const captures = [...new Set([...ownedCaptures, ...state.captures.values()])];
2828
+ for (const capture of captures) {
2280
2829
  stopPush(capture.id);
2281
2830
  stopWatchdog(capture.id);
2282
2831
  capture.stop(false);
@@ -2284,5 +2833,18 @@ export default function xcodebug(pi: ExtensionAPI): void {
2284
2833
  state.captures.clear();
2285
2834
  state.endedCaptures.clear();
2286
2835
  state.activeCaptureId = undefined;
2836
+ // Include pending starts and old result reads, not only the visible capture history.
2837
+ const settled = await Promise.all(captures.map((capture) => capture.shutdown(3_000)));
2838
+ ownedCaptures.clear();
2839
+ const warnings = retiredCleanupWarnings.splice(0);
2840
+ for (const [index, capture] of captures.entries()) {
2841
+ for (const error of capture.launchResultCleanupErrors ?? []) warnings.push(`${capture.id}: ${error}`);
2842
+ if (!settled[index]) warnings.push(`${capture.id}: ${capture.status().error}`);
2843
+ }
2844
+ if (warnings.length > 0) {
2845
+ const message = `xcodebug shutdown cleanup incomplete: ${warnings.join("; ")}`;
2846
+ state.uiCtx?.ui.notify(message, "warning");
2847
+ console.error(message);
2848
+ }
2287
2849
  });
2288
2850
  }