xcodebug 1.2.2 → 1.2.4

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
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { readdir, readFile } from "node:fs/promises";
10
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
@@ -18,7 +19,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
18
19
  import { Type } from "typebox";
19
20
  import { Capture, matchesFilter, type FoundLine } from "./capture.ts";
20
21
  import { describeDevices, findProcessPid, listDevices, lookupProcess, pullCrashReport, resolveDevice, type DeviceInfo } from "./devices.ts";
21
- import { lastLines, runCommand, timestamp } from "./exec.ts";
22
+ import { asRecord, lastLines, runCommand, timestamp } from "./exec.ts";
22
23
  import { buildForDevice, consoleLaunchArgs, installApp, terminateApp, type BuildOutcome, type BuildTarget } from "./xcode.ts";
23
24
  import { checkPodLockSync, describeChanges, detectChanges, directorySignature, runPodInstall, type ChangeReport } from "./changes.ts";
24
25
  import { clearArchives, pruneLogs } from "./archive.ts";
@@ -604,7 +605,8 @@ function lastWords(capture: Capture): string | undefined {
604
605
  */
605
606
  function endedNote(capture: Capture): string {
606
607
  const reason = capture.endReason ? ` · ${capture.endReason}` : "";
607
- return `${reason}${capture.crashReport ? ` · crash report: ${capture.crashReport}` : ""}`;
608
+ const termination = capture.terminationReason ? ` · system termination: ${capture.terminationReason}` : "";
609
+ return `${reason}${termination}${capture.crashReport ? ` · crash report: ${capture.crashReport}` : ""}`;
608
610
  }
609
611
 
610
612
  /**
@@ -896,6 +898,35 @@ export default function xcodebug(pi: ExtensionAPI): void {
896
898
  watchdogs: new Map(),
897
899
  };
898
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
+
899
930
  /**
900
931
  * Paint the live verification state: a footer line that is always visible and
901
932
  * a widget above the editor with the most recent log lines. Both are cleared
@@ -1186,66 +1217,152 @@ export default function xcodebug(pi: ExtensionAPI): void {
1186
1217
  await new Promise((resolve) => setTimeout(resolve, Math.min(250, deadline - Date.now())));
1187
1218
  }
1188
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
+
1189
1223
  /**
1190
1224
  * Record the pid of the instance a console bridge has just launched.
1191
1225
  *
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.
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.
1196
1229
  */
1197
1230
  const discoverAppPid = async (capture: Capture, device: DeviceInfo, replaced: number | undefined, signal = capture.signal): Promise<void> => {
1198
- if (!capture.processName) return;
1231
+ if (!capture.processName || capture.processExited) return;
1199
1232
  const launch = capture.relaunches;
1233
+ const result = capture.launchResult;
1200
1234
  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;
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));
1206
1248
  }
1207
- await new Promise((resolve) => setTimeout(resolve, 500));
1249
+ } finally {
1250
+ if (signal !== capture.signal) signal.removeEventListener("abort", onAbort);
1208
1251
  }
1209
1252
  };
1210
1253
 
1211
- /** Captures a crash report is being looked for, so two bridge drops close together search once. */
1212
- const crashSearches = new Set<string>();
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();
1213
1262
 
1214
1263
  /**
1215
1264
  * Look for the crash report of an app whose console bridge went down.
1216
1265
  *
1217
1266
  * 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
1267
+ * few times. A missing report is not proof of a crash. The search runs apart
1268
+ * from the capture:
1220
1269
  * `stop` a moment later must not call it off, since that is exactly how a run
1221
1270
  * that ends in a crash is wrapped up.
1222
1271
  */
1223
- const fetchCrashReport = async (capture: Capture, device: DeviceInfo): Promise<void> => {
1272
+ const fetchCrashReport = async (capture: Capture, device: DeviceInfo, pid: number): Promise<void> => {
1224
1273
  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;
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;
1245
1317
  }
1318
+ } catch {
1319
+ // Missing or malformed launch output cannot establish instance ownership.
1246
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]);
1247
1364
  } finally {
1248
- crashSearches.delete(capture.id);
1365
+ signal.removeEventListener("abort", onAbort);
1249
1366
  }
1250
1367
  };
1251
1368
 
@@ -1258,7 +1375,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1258
1375
  const last = lastWords(capture);
1259
1376
  capture.endReason = last ? `${reason}; last line before the bridge ended: "${last}"` : reason;
1260
1377
  capture.pushLine("err", `[xcodebug] ${capture.endReason}; stopping capture`);
1261
- releaseCapture(capture);
1378
+ stopCapture(capture, false);
1262
1379
  };
1263
1380
 
1264
1381
  /**
@@ -1295,6 +1412,15 @@ export default function xcodebug(pi: ExtensionAPI): void {
1295
1412
  const delay = Math.min(1000 * 2 ** (Math.min(attempts, 5) - 1), 15_000);
1296
1413
  await sleepUnlessStopped(capture, delay);
1297
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
+ }
1298
1424
 
1299
1425
  // Only the console channel is bound to the app's lifetime, so only it
1300
1426
  // consults the process table. A syslog bridge outlives the app and its
@@ -1335,7 +1461,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1335
1461
  capture.pushLine("err", `[xcodebug] reconnecting ${label} bridge (attempt ${attempts})`);
1336
1462
  capture.resetForReconnect();
1337
1463
  try {
1338
- await capture.start();
1464
+ await startCapture(capture);
1339
1465
  if (capture.stoppedByUser) return;
1340
1466
  attempts = 0;
1341
1467
  onReconnect?.(1);
@@ -1369,6 +1495,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
1369
1495
  }
1370
1496
  };
1371
1497
 
1498
+ capture.onProcessExit(() => startCrashReportSearch(capture, device));
1499
+
1372
1500
  capture.onExit((code, signal) => {
1373
1501
  stopPush(capture.id);
1374
1502
  const reason = signal ? `signal ${signal}` : `exit ${code ?? "?"}`;
@@ -1382,10 +1510,6 @@ export default function xcodebug(pi: ExtensionAPI): void {
1382
1510
  releaseCapture(capture);
1383
1511
  return;
1384
1512
  }
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);
1389
1513
  // Always hand off. If a reconnect loop is already running it returns at
1390
1514
  // once and keeps retrying on its own; if none is running, this starts it.
1391
1515
  // An earlier version skipped this while the watchdog was restarting, which
@@ -1704,13 +1828,17 @@ export default function xcodebug(pi: ExtensionAPI): void {
1704
1828
  // say so: "the case ran" and "the app died under the case" must not read
1705
1829
  // alike. Stopping still matters then - it calls off a pending reattach,
1706
1830
  // which would relaunch the app now that the case is over.
1707
- const how = target.running
1831
+ const wasRunning = target.running && !target.processExited;
1832
+ const wasUserStopped = target.stoppedByUser && !target.endReason;
1833
+ stopCapture(target, false);
1834
+ // Report collection is independent; stop a queued reattach before awaiting it.
1835
+ if (!wasRunning && !wasUserStopped) await waitForCrashReport(target, signal);
1836
+ await target.waitForExit(5_000);
1837
+ const how = wasRunning
1708
1838
  ? `stopped ${target.id}`
1709
- : target.stoppedByUser
1839
+ : wasUserStopped
1710
1840
  ? `${target.id} was already stopped`
1711
1841
  : `warning: ${target.id} was no longer capturing when the command finished${whyEnded(target)}`;
1712
- stopCapture(target, false);
1713
- await target.waitForExit(5_000);
1714
1842
  const status = target.status();
1715
1843
  const added = Math.max(0, status.lineCount - linesAtStart);
1716
1844
  captureNote = `${how} · ${added} new line(s) · ${status.logFile}`;
@@ -1740,6 +1868,8 @@ export default function xcodebug(pi: ExtensionAPI): void {
1740
1868
  elapsedSeconds: elapsedS,
1741
1869
  captureId: target?.id,
1742
1870
  cursor: since,
1871
+ terminationReason: target?.terminationReason,
1872
+ crashReport: target?.crashReport,
1743
1873
  },
1744
1874
  // A non-zero exit is a failed case, and the caller must see it as such
1745
1875
  // rather than as a successful "run finished".
@@ -2095,6 +2225,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
2095
2225
  bundleId: resolvedBundleId,
2096
2226
  processName: executable,
2097
2227
  logDir: logDir(ctx),
2228
+ collectLaunchResult: true,
2098
2229
  command: "xcrun",
2099
2230
  args: consoleLaunchArgs(device, resolvedBundleId, {
2100
2231
  args: params.args ?? config.args,
@@ -2102,7 +2233,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
2102
2233
  environment: { ...(config.environment ?? {}), ...(params.environment ?? {}) },
2103
2234
  }),
2104
2235
  });
2105
- await capture.start(signal);
2236
+ await startCapture(capture, signal);
2106
2237
  state.captures.set(capture.id, capture);
2107
2238
  state.activeCaptureId = capture.id;
2108
2239
  watchExit(capture, device);
@@ -2134,11 +2265,21 @@ export default function xcodebug(pi: ExtensionAPI): void {
2134
2265
  // The previous run for this app was already retired before this capture
2135
2266
  // started (see above), so nothing is left to stop here. Other apps'
2136
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.
2137
2278
  // Second channel: idevicesyslog reads the device's unified log directly
2138
2279
  // and survives a dropped --console bridge. It carries os_log only, so
2139
2280
  // NSLog/print lines (MySDK) stay exclusive to the console channel -
2140
2281
  // this is a safety net for the gap, not a replacement.
2141
- if (executable && params.dualChannel !== false) {
2282
+ if (executable && params.dualChannel !== false && !capture.stoppedByUser) {
2142
2283
  const syslogCapture = new Capture({
2143
2284
  mode: "syslog",
2144
2285
  deviceId: device.id,
@@ -2150,25 +2291,21 @@ export default function xcodebug(pi: ExtensionAPI): void {
2150
2291
  args: ["-u", device.udid ?? device.id, "-p", executable, "--no-colors"],
2151
2292
  });
2152
2293
  try {
2153
- await syslogCapture.start(signal);
2154
- state.captures.set(syslogCapture.id, syslogCapture);
2155
- state.companions.set(capture.id, syslogCapture.id);
2156
- watchExit(syslogCapture, device);
2157
- 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
+ }
2158
2304
  } catch (error) {
2159
2305
  notes.push(`syslog channel unavailable: ${(error as Error).message}`);
2160
2306
  }
2161
2307
  }
2162
2308
 
2163
- // The app pid is not part of --console's output; discover it from the
2164
- // process table so terminate can target the app rather than the bridge.
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();
2170
- }
2171
-
2172
2309
  return {
2173
2310
  content: [{
2174
2311
  type: "text",
@@ -2203,7 +2340,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
2203
2340
  command: "idevicesyslog",
2204
2341
  args,
2205
2342
  });
2206
- await capture.start(signal);
2343
+ await startCapture(capture, signal);
2207
2344
  state.captures.set(capture.id, capture);
2208
2345
  state.activeCaptureId = capture.id;
2209
2346
  watchExit(capture, device);
@@ -2239,6 +2376,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
2239
2376
  }
2240
2377
  // The lines that say so are in the log, but a filtered read leaves them out.
2241
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}]`;
2242
2380
  if (capture.crashReport) formatted.text += `\n[crash report: ${capture.crashReport}]`;
2243
2381
  return {
2244
2382
  content: [{ type: "text", text: formatted.text }],
@@ -2258,6 +2396,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
2258
2396
  const seen = new Set<number>();
2259
2397
  let finished = false;
2260
2398
  let cancelled = false;
2399
+ let deadlineExpired = false;
2261
2400
  // The backlog is read from disk too, which takes a moment. A line that
2262
2401
  // arrives meanwhile must not settle the wait ahead of the earlier ones.
2263
2402
  let backlogRead = false;
@@ -2288,6 +2427,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
2288
2427
  const finish = (timedOut: boolean): void => {
2289
2428
  if (finished) return;
2290
2429
  finished = true;
2430
+ deadlineExpired = timedOut;
2291
2431
  if (timer) clearTimeout(timer);
2292
2432
  unsubscribeLine();
2293
2433
  unsubscribeExit();
@@ -2341,11 +2481,17 @@ export default function xcodebug(pi: ExtensionAPI): void {
2341
2481
  // A pattern already present in the backlog must return immediately,
2342
2482
  // not wait out the timeout.
2343
2483
  if (matches.length > 0 || !capture.running) finish(false);
2344
- const text = await waiting;
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
+ }
2345
2490
 
2346
2491
  return {
2347
2492
  content: [{ type: "text", text }],
2348
- 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 },
2349
2495
  isError: matches.length === 0,
2350
2496
  };
2351
2497
  }
@@ -2673,10 +2819,12 @@ export default function xcodebug(pi: ExtensionAPI): void {
2673
2819
  });
2674
2820
 
2675
2821
  pi.on("session_shutdown", async () => {
2822
+ shuttingDown = true;
2823
+ crashSearchAbort.abort();
2676
2824
  stopStatusTicker();
2677
2825
  state.uiCtx?.ui.setStatus("xcodebug", undefined);
2678
2826
  state.uiCtx?.ui.setWidget("xcodebug", undefined);
2679
- const captures = [...state.captures.values()];
2827
+ const captures = [...new Set([...ownedCaptures, ...state.captures.values()])];
2680
2828
  for (const capture of captures) {
2681
2829
  stopPush(capture.id);
2682
2830
  stopWatchdog(capture.id);
@@ -2685,8 +2833,18 @@ export default function xcodebug(pi: ExtensionAPI): void {
2685
2833
  state.captures.clear();
2686
2834
  state.endedCaptures.clear();
2687
2835
  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)));
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
+ }
2691
2849
  });
2692
2850
  }
package/mcp/server.ts CHANGED
@@ -14,9 +14,9 @@
14
14
  *
15
15
  * codex mcp add xcodebug -- bun /path/to/xcodebug/mcp/server.ts
16
16
  *
17
- * The protocol is hand-written JSON-RPC over stdio because only three methods are
18
- * needed (initialize, tools/list, tools/call); the official SDK would add ~97
19
- * transitive packages to every install, including the pi users who never run MCP.
17
+ * The protocol is hand-written JSON-RPC over stdio because the adapter only needs
18
+ * the MCP handshake, tool calls, and the status-line resource methods; the official
19
+ * SDK would add ~97 transitive packages to every install, including pi users.
20
20
  */
21
21
  import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
22
22
  import { homedir } from "node:os";
@@ -150,11 +150,15 @@ try {
150
150
  } catch {
151
151
  // No directory to sweep: publishUi() could not create it and said so.
152
152
  }
153
+ const statusResource = { uri: "ui://xcodebug/statusline", name: "xcodebug live status", mimeType: "application/json" };
154
+ const normalizeStatusText = (value: string | undefined): string | undefined =>
155
+ value?.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
153
156
  const uiTool = {
154
157
  name: "xcodebug_ui",
155
158
  description: "Read the current display snapshot for the xcodebug Claude Code mod. For capture details or log analysis use xcodebug with action=status or action=logs.",
156
159
  inputSchema: { type: "object", properties: {}, additionalProperties: false },
157
160
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
161
+ _meta: { "openai/ui": { entrypoints: [{ type: "statusline", resourceUri: statusResource.uri }] } },
158
162
  };
159
163
 
160
164
  function sendNotification(method: string, params: unknown): void {
@@ -243,7 +247,7 @@ async function handle(message: Record<string, unknown>, controller?: AbortContro
243
247
  const requested = (message.params as { protocolVersion?: string } | undefined)?.protocolVersion;
244
248
  reply(id, {
245
249
  protocolVersion: requested ?? PROTOCOL_VERSION,
246
- capabilities: { tools: {} },
250
+ capabilities: { tools: {}, resources: {} },
247
251
  serverInfo: { name: "xcodebug", version: pkg.version },
248
252
  });
249
253
  return;
@@ -256,6 +260,14 @@ async function handle(message: Record<string, unknown>, controller?: AbortContro
256
260
  reply(id, { tools: [{ name: "xcodebug", description: tool.description, inputSchema }, uiTool] });
257
261
  return;
258
262
  }
263
+ if (method === "resources/list") {
264
+ reply(id, { resources: [statusResource] });
265
+ return;
266
+ }
267
+ if (method === "resources/templates/list") {
268
+ reply(id, { resourceTemplates: [] });
269
+ return;
270
+ }
259
271
  if (method === "tools/call") {
260
272
  const params = (message.params ?? {}) as {
261
273
  name?: string;
@@ -337,6 +349,28 @@ input.on("line", (line) => {
337
349
  }
338
350
  // UI reads must remain responsive during a build/install/wait and must never
339
351
  // replace state.uiCtx with the context of a polling call.
352
+ if (message.method === "resources/read") {
353
+ if (message.id === undefined) return;
354
+ const uri = (message.params as { uri?: string } | undefined)?.uri;
355
+ if (uri !== statusResource.uri) {
356
+ replyError(message.id, -32002, "Resource not found");
357
+ return;
358
+ }
359
+ const { status, rows } = uiSnapshot;
360
+ const capturing = rows[0]?.startsWith("Xcodebug · capturing ");
361
+ const label = capturing ? status?.replace(/ · \/xcodebug stop to end$/, "") : status;
362
+ // Keep every text leaf valid UTF-8; Codex rejects UI trees containing lone surrogates.
363
+ const normalized = normalizeStatusText(label);
364
+ const preview = normalized && normalized.length > 1024
365
+ ? normalizeStatusText(`${normalized.slice(0, 1024)}…`)
366
+ : normalized;
367
+ const latest = capturing ? normalizeStatusText(rows.at(-1)?.trim()) : undefined;
368
+ const tree = preview && latest && latest !== "(waiting for the first line…)"
369
+ ? { type: "row", props: { gap: 2, wrap: "wrap" }, children: [preview, latest] }
370
+ : preview ?? null;
371
+ reply(message.id, { contents: [{ uri, mimeType: statusResource.mimeType, text: JSON.stringify(tree) }] });
372
+ return;
373
+ }
340
374
  if (message.method === "tools/call" &&
341
375
  (message.params as { name?: string } | undefined)?.name === uiTool.name) {
342
376
  if (message.id !== undefined) {