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.
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createInterface } from "node:readline";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import { dirname, join } from "node:path";
7
+ import { spawn, spawnSync } from "node:child_process";
8
+
9
+ const TOOL_TIMEOUT_SECONDS = 4_200;
10
+ const STATUSLINE_MIN_CODEX_VERSION = [0, 171, 0];
11
+ const STATUSLINE_FEATURE = "features.tui_extensions_statusline";
12
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
13
+ const serverPath = join(packageRoot, "mcp", "server.ts");
14
+ const codex = process.env.CODEX_BIN ?? "codex";
15
+ const runtime = process.env.XCODEBUG_MCP_RUNTIME ?? "bun";
16
+
17
+ function run(command, args) {
18
+ const result = spawnSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
19
+ if (result.error) throw result.error;
20
+ return result;
21
+ }
22
+
23
+ function getRegistration() {
24
+ return run(codex, ["mcp", "get", "xcodebug"]);
25
+ }
26
+
27
+ function ensureServerRegistration() {
28
+ const existing = getRegistration();
29
+ if (existing.status === 0) return existing;
30
+
31
+ const runtimeCheck = run(runtime, ["--version"]);
32
+ if (runtimeCheck.status !== 0) {
33
+ throw new Error(`xcodebug is not registered and ${runtime} is unavailable; install Bun or set XCODEBUG_MCP_RUNTIME`);
34
+ }
35
+ const added = run(codex, ["mcp", "add", "xcodebug", "--", runtime, serverPath]);
36
+ if (added.status !== 0) {
37
+ throw new Error((added.stderr || added.stdout || "codex mcp add failed").trim());
38
+ }
39
+ const registered = getRegistration();
40
+ if (registered.status !== 0) {
41
+ throw new Error((registered.stderr || registered.stdout || "could not read the new xcodebug registration").trim());
42
+ }
43
+ return registered;
44
+ }
45
+
46
+ function projectOverrides() {
47
+ const configs = [];
48
+ for (let dir = process.cwd();; dir = dirname(dir)) {
49
+ const path = join(dir, ".codex", "config.toml");
50
+ try {
51
+ if (existsSync(path)) {
52
+ const text = readFileSync(path, "utf8");
53
+ if (/^\s*\[mcp_servers\.xcodebug\]\s*$/m.test(text) || (/^\s*\[mcp_servers\]\s*$/m.test(text) && /^\s*xcodebug\s*=/m.test(text))) configs.push(path);
54
+ }
55
+ } catch {
56
+ // A config that cannot be read is reported by Codex itself; setup must not edit it.
57
+ }
58
+ const parent = dirname(dir);
59
+ if (parent === dir) break;
60
+ }
61
+ return configs;
62
+ }
63
+
64
+ function reportWarnings(registration) {
65
+ for (const path of projectOverrides()) {
66
+ console.error(`Warning: project Codex config may override xcodebug: ${path}`);
67
+ }
68
+ if (registration.stdout && !registration.stdout.includes(serverPath)) {
69
+ console.error(`Warning: existing xcodebug registration points elsewhere; setup kept it: ${serverPath}`);
70
+ }
71
+ }
72
+
73
+ function hasTimeout(registration) {
74
+ return /^\s*tool_timeout_sec\s*:/m.test(registration.stdout);
75
+ }
76
+
77
+ function parseVersion(text) {
78
+ const match = text.match(/\b(\d+)\.(\d+)\.(\d+)\b/);
79
+ return match ? match.slice(1).map(Number) : undefined;
80
+ }
81
+
82
+ function codexVersion() {
83
+ const result = run(codex, ["--version"]);
84
+ if (result.status !== 0) return undefined;
85
+ return parseVersion(result.stdout);
86
+ }
87
+
88
+ function versionSupportsStatusline(version) {
89
+ return version[0] > STATUSLINE_MIN_CODEX_VERSION[0] ||
90
+ (version[0] === STATUSLINE_MIN_CODEX_VERSION[0] && (version[1] > STATUSLINE_MIN_CODEX_VERSION[1] ||
91
+ (version[1] === STATUSLINE_MIN_CODEX_VERSION[1] && version[2] >= STATUSLINE_MIN_CODEX_VERSION[2])));
92
+ }
93
+
94
+ function supportsStatusline() {
95
+ const version = codexVersion();
96
+ if (!version) {
97
+ console.error("Warning: could not determine Codex version; statusline feature was not enabled");
98
+ return false;
99
+ }
100
+ const supported = versionSupportsStatusline(version);
101
+ if (!supported) {
102
+ console.error(`Warning: Codex ${version.join(".")} is older than 0.171.0; statusline feature was not enabled`);
103
+ }
104
+ return supported;
105
+ }
106
+
107
+ function checkAppServerVersion() {
108
+ try {
109
+ const result = run(codex, ["app-server", "daemon", "version"]);
110
+ if (result.status !== 0) throw new Error((result.stderr || result.stdout || "daemon version query failed").trim());
111
+ const report = JSON.parse(result.stdout);
112
+ if (report?.status !== "running" || typeof report.appServerVersion !== "string") {
113
+ throw new Error("no running app-server version was reported");
114
+ }
115
+ const version = parseVersion(report.appServerVersion);
116
+ if (!version) throw new Error(`unrecognized app-server version: ${report.appServerVersion}`);
117
+ console.log(`Running Codex app-server version: ${report.appServerVersion}`);
118
+ if (!versionSupportsStatusline(version)) {
119
+ console.error(`Warning: running Codex app-server ${report.appServerVersion} is older than 0.171.0; saving the feature setting does not upgrade the server.`);
120
+ console.error("Finish active Codex tasks and captures before running:");
121
+ console.error(" codex app-server daemon update --from-cli --yes");
122
+ console.error(" codex app-server daemon restart");
123
+ }
124
+ } catch (error) {
125
+ console.error(`Warning: running Codex app-server version could not be verified: ${error instanceof Error ? error.message : String(error)}`);
126
+ console.error("If you use the shared daemon, start Codex and check with codex app-server daemon version.");
127
+ }
128
+ }
129
+
130
+ async function writeConfig(values) {
131
+ const app = startAppServer();
132
+ try {
133
+ await app.request("initialize", { clientInfo: { name: "xcodebug-setup-codex", version: "1" } });
134
+ app.child.stdin.write('{"jsonrpc":"2.0","method":"initialized"}\n');
135
+ const edits = [];
136
+ for (const keyPath of Object.keys(values)) {
137
+ edits.push({ keyPath, value: values[keyPath], mergeStrategy: "upsert" });
138
+ }
139
+ let providerSelected = false;
140
+ let filePath;
141
+ let expectedVersion;
142
+ if (values[STATUSLINE_FEATURE] === true) {
143
+ const response = await app.request("config/read", { includeLayers: true });
144
+ const userLayer = Array.isArray(response?.layers)
145
+ ? response.layers.find(layer => layer.name?.type === "user" && layer.name.profile === null && !layer.disabledReason)
146
+ : undefined;
147
+ if (!userLayer || typeof userLayer.name.file !== "string" || typeof userLayer.version !== "string" ||
148
+ !userLayer.config || typeof userLayer.config !== "object" || Array.isArray(userLayer.config)) {
149
+ throw new Error("Codex did not return user configuration metadata; statusline provider was not changed");
150
+ }
151
+ filePath = userLayer.name.file;
152
+ expectedVersion = userLayer.version;
153
+ const provider = userLayer.config.tui?.status_line_provider;
154
+ if (provider === undefined || provider === null || provider === "default") {
155
+ edits.push({ keyPath: "tui.status_line_provider", value: { server: "xcodebug", tool: "xcodebug_ui" }, mergeStrategy: "upsert" });
156
+ providerSelected = true;
157
+ } else if (provider.server !== "xcodebug" || provider.tool !== "xcodebug_ui") {
158
+ console.error("Warning: existing custom Codex statusline provider preserved; choose xcodebug_ui under /statusline or set tui.status_line_provider explicitly.");
159
+ }
160
+ }
161
+ // Codex 0.171.0 returns a non-reusable version after numeric writes; batch the edits.
162
+ const result = await app.request("config/batchWrite", { edits, filePath, expectedVersion });
163
+ if (result?.status !== "ok") throw new Error(`Codex rejected the config write: ${JSON.stringify(result)}`);
164
+ if (providerSelected) console.log("Configured Codex statusline provider: xcodebug / xcodebug_ui");
165
+ } finally {
166
+ await app.close();
167
+ }
168
+ }
169
+
170
+ async function configureCodex(registration) {
171
+ const values = {};
172
+ if (!hasTimeout(registration)) values["mcp_servers.xcodebug.tool_timeout_sec"] = TOOL_TIMEOUT_SECONDS;
173
+ if (supportsStatusline()) values[STATUSLINE_FEATURE] = true;
174
+ if (Object.keys(values).length > 0) await writeConfig(values);
175
+ if (hasTimeout(registration)) console.log("Existing Codex xcodebug tool timeout preserved");
176
+ else console.log(`Configured xcodebug MCP timeout: ${TOOL_TIMEOUT_SECONDS}s`);
177
+ if (values[STATUSLINE_FEATURE] === true) {
178
+ console.log("Enabled Codex xcodebug statusline feature in configuration");
179
+ checkAppServerVersion();
180
+ }
181
+ }
182
+
183
+ function startAppServer() {
184
+ const child = spawn(codex, ["app-server", "--stdio"], { stdio: ["pipe", "pipe", "pipe"] });
185
+ let stderr = "";
186
+ child.stderr.setEncoding("utf8");
187
+ child.stderr.on("data", chunk => { stderr += chunk; });
188
+ const pending = new Map();
189
+ let nextId = 0;
190
+ const input = createInterface({ input: child.stdout });
191
+ input.on("line", line => {
192
+ let message;
193
+ try { message = JSON.parse(line); } catch { return; }
194
+ const request = pending.get(message.id);
195
+ if (!request) return;
196
+ pending.delete(message.id);
197
+ clearTimeout(request.timer);
198
+ if (message.error) request.reject(new Error(JSON.stringify(message.error)));
199
+ else request.resolve(message.result);
200
+ });
201
+ const request = (method, params) => new Promise((resolve, reject) => {
202
+ const id = ++nextId;
203
+ const timer = setTimeout(() => {
204
+ pending.delete(id);
205
+ reject(new Error(`codex app-server timed out during ${method}`));
206
+ }, 15_000);
207
+ pending.set(id, { resolve, reject, timer });
208
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
209
+ });
210
+ const close = async () => {
211
+ for (const { timer } of pending.values()) clearTimeout(timer);
212
+ input.close();
213
+ child.stdin.end();
214
+ await new Promise(resolve => {
215
+ const timer = setTimeout(() => { child.kill(); resolve(); }, 3_000);
216
+ child.once("exit", () => { clearTimeout(timer); resolve(); });
217
+ });
218
+ };
219
+ return { child, request, close, get stderr() { return stderr; } };
220
+
221
+ }
222
+ try {
223
+ const registration = ensureServerRegistration();
224
+ reportWarnings(registration);
225
+ await configureCodex(registration);
226
+ } catch (error) {
227
+ console.error(`xcodebug setup-codex failed: ${error instanceof Error ? error.message : String(error)}`);
228
+ process.exitCode = 1;
229
+ }
package/capture.ts CHANGED
@@ -5,8 +5,8 @@
5
5
  */
6
6
  import { spawn, type ChildProcess } from "node:child_process";
7
7
  import { appendFileSync, createReadStream, createWriteStream, statSync, type WriteStream } from "node:fs";
8
- import { mkdir } from "node:fs/promises";
9
- import { dirname } from "node:path";
8
+ import { lstat, mkdir, mkdtemp, readFile, readdir, rmdir, unlink, writeFile } from "node:fs/promises";
9
+ import { dirname, join } from "node:path";
10
10
  import { finished } from "node:stream/promises";
11
11
  import { timestamp } from "./exec.ts";
12
12
 
@@ -40,6 +40,8 @@ export interface CaptureInit {
40
40
  logDir: string;
41
41
  command: string;
42
42
  args: string[];
43
+ /** Collect the native console launch's raw command result, outside the log stream. */
44
+ collectLaunchResult?: boolean;
43
45
  /** Reuse an existing log file (used when auto-reconnecting a dropped bridge). */
44
46
  logFile?: string;
45
47
  /** How new lines are mirrored into the session; the reconnect path restarts it. */
@@ -71,6 +73,7 @@ export interface CaptureStatus {
71
73
  relaunches: number;
72
74
  endReason?: string;
73
75
  crashReport?: string;
76
+ terminationReason?: string;
74
77
  }
75
78
 
76
79
  function clean(text: string): string {
@@ -94,6 +97,32 @@ function sizeOnDisk(path: string): number {
94
97
  }
95
98
  }
96
99
 
100
+ async function removeLaunchResultDirectory(path: string): Promise<void> {
101
+ const directory = await lstat(path);
102
+ if (!directory.isDirectory()) throw new Error("owned result path is not a real directory");
103
+ const entries = (await readdir(path)).sort();
104
+ if (entries.some(name => name !== "owner.json" && name !== "launch.json")) {
105
+ throw new Error("owned result directory contains an unexpected entry");
106
+ }
107
+ const files = [];
108
+ for (const name of entries) {
109
+ const filePath = join(path, name);
110
+ const file = await lstat(filePath);
111
+ if (!file.isFile()) throw new Error("owned result payload is not a real file");
112
+ files.push({ path: filePath, stat: file });
113
+ }
114
+ for (const file of files) {
115
+ const currentDirectory = await lstat(path);
116
+ const currentFile = await lstat(file.path);
117
+ if (!currentDirectory.isDirectory() || currentDirectory.dev !== directory.dev || currentDirectory.ino !== directory.ino ||
118
+ !currentFile.isFile() || currentFile.dev !== file.stat.dev || currentFile.ino !== file.stat.ino) {
119
+ throw new Error("owned result path changed during cleanup");
120
+ }
121
+ await unlink(file.path);
122
+ }
123
+ await rmdir(path);
124
+ }
125
+
97
126
  export class Capture {
98
127
  readonly id: string;
99
128
  readonly mode: CaptureMode;
@@ -101,13 +130,22 @@ export class Capture {
101
130
  readonly deviceLabel: string;
102
131
  readonly bundleId: string;
103
132
  readonly processName?: string;
104
- /** App pid on the device; filled in once discovery succeeds, never the bridge pid. */
133
+ /** Operational live PID; exit diagnosis replaces it with the owned launch result's PID. */
105
134
  appPid?: number;
106
135
  readonly startedAt = Date.now();
107
136
  readonly logFile: string;
108
137
 
109
138
  readonly command: string;
110
139
  readonly launchArgs: string[];
140
+ /** One owned native command result per bridge start; absent for generic captures. */
141
+ launchResult?: Promise<string | undefined>;
142
+ private readonly collectLaunchResult: boolean;
143
+ private spawnedArgs: string[];
144
+ private shuttingDown = false;
145
+ private readonly startups = new Set<Promise<void>>();
146
+ private readonly resultJobs = new Set<{ done: Promise<void>; cancel: () => void }>();
147
+ /** Failed result removals survive reattachment and history eviction until session shutdown reports them. */
148
+ launchResultCleanupErrors?: string[];
111
149
  /** Set when the user explicitly stops this capture, so auto-reconnect stays off. */
112
150
  stoppedByUser = false;
113
151
  /**
@@ -135,6 +173,9 @@ export class Capture {
135
173
  endReason?: string;
136
174
  /** The crash report pulled from the device after the app died, if it left one. */
137
175
  crashReport?: string;
176
+ terminationReason?: string;
177
+ /** Bridge exit time before any stop, retained through drain and report collection. */
178
+ naturalExitAt?: number;
138
179
  /**
139
180
  * Aborted when this capture is stopped, so an in-flight device probe returns
140
181
  * at once instead of running out its own timeout first.
@@ -173,6 +214,7 @@ export class Capture {
173
214
  private readonly files = new Set<WriteStream>();
174
215
  private readonly blockedFiles = new Set<WriteStream>();
175
216
  private readonly exitListeners = new Set<(code: number | undefined, signal: string | undefined) => void>();
217
+ private readonly processExitListeners = new Set<(code: number | undefined, signal: string | undefined) => void>();
176
218
  private readonly lineListeners = new Set<(line: LogLine) => void>();
177
219
 
178
220
  constructor(init: CaptureInit) {
@@ -186,6 +228,8 @@ export class Capture {
186
228
  this.pushMode = init.pushMode;
187
229
  this.command = init.command;
188
230
  this.launchArgs = init.args;
231
+ this.collectLaunchResult = init.mode === "console" && init.collectLaunchResult === true;
232
+ this.spawnedArgs = this.launchArgs;
189
233
  this.logFile =
190
234
  init.logFile ?? `${init.logDir}/${init.mode}-${init.bundleId}-${timestamp()}.log`;
191
235
  }
@@ -195,17 +239,37 @@ export class Capture {
195
239
  return this.child !== undefined;
196
240
  }
197
241
 
242
+ get starting(): boolean {
243
+ return this.startups.size > 0;
244
+ }
245
+
246
+ get processExited(): boolean {
247
+ return this.child
248
+ ? this.child.exitCode !== null || this.child.signalCode !== null
249
+ : this.exitCode !== undefined || this.exitSignal !== undefined;
250
+ }
251
+
198
252
  /** Clear the terminal state so start() can attach a fresh bridge. */
199
253
  resetForReconnect(): void {
200
254
  this.exitCode = undefined;
201
255
  this.exitSignal = undefined;
202
256
  this.error = undefined;
257
+ this.endReason = undefined;
258
+ this.crashReport = undefined;
259
+ this.terminationReason = undefined;
260
+ this.naturalExitAt = undefined;
203
261
  this.buffered = { out: "", err: "" };
204
262
  // A fresh bridge starts its silence clock now, or the watchdog would see the
205
263
  // gap it just repaired and immediately restart the new bridge too.
206
264
  this.lastLineAt = Date.now();
207
265
  }
208
266
 
267
+ /** Observe process exit before the pipes and writers finish draining. */
268
+ onProcessExit(listener: (code: number | undefined, signal: string | undefined) => void): () => void {
269
+ this.processExitListeners.add(listener);
270
+ return () => this.processExitListeners.delete(listener);
271
+ }
272
+
209
273
  get pid(): number | undefined {
210
274
  return this.child?.pid;
211
275
  }
@@ -221,14 +285,98 @@ export class Capture {
221
285
  return () => this.lineListeners.delete(listener);
222
286
  }
223
287
 
224
- async start(signal?: AbortSignal): Promise<void> {
225
- await mkdir(dirname(this.logFile), { recursive: true });
226
- signal?.throwIfAborted();
227
- if (this.stoppedByUser) return;
228
- this.openFile(true);
288
+ start(signal?: AbortSignal): Promise<void> {
289
+ if (this.shuttingDown) return Promise.resolve();
290
+ let resolveStartup!: () => void;
291
+ const startup = new Promise<void>(resolve => { resolveStartup = resolve; });
292
+ this.startups.add(startup);
293
+ const operation = this.startRun(signal);
294
+ const complete = (): void => {
295
+ this.startups.delete(startup);
296
+ resolveStartup();
297
+ };
298
+ void operation.then(complete, complete);
299
+ return operation;
300
+ }
229
301
 
230
- const child = spawn(this.command, this.launchArgs, { stdio: ["ignore", "pipe", "pipe"] });
231
- this.child = child;
302
+ private async startRun(signal?: AbortSignal): Promise<void> {
303
+ let resultDir: string | undefined;
304
+ let resolveResult: ((raw: string | undefined) => void) | undefined;
305
+ let resolveCleanup: (() => void) | undefined;
306
+ let resultJob: { done: Promise<void>; cancel: () => void } | undefined;
307
+ let collecting = false;
308
+ const resultAbort = this.collectLaunchResult ? new AbortController() : undefined;
309
+ if (resultAbort) {
310
+ // Node 20's Promise API requires an executor; it has no withResolvers().
311
+ this.launchResult = new Promise((resolve) => { resolveResult = resolve; });
312
+ resultJob = {
313
+ done: new Promise(resolve => { resolveCleanup = resolve; }),
314
+ cancel: () => resultAbort.abort(),
315
+ };
316
+ this.resultJobs.add(resultJob);
317
+ }
318
+ const result = this.launchResult;
319
+ // Exit diagnosis outlives stop/reconnect; only session shutdown cancels its read.
320
+ const collectResult = async (): Promise<void> => {
321
+ if (!resolveResult || !resultAbort || collecting) return;
322
+ collecting = true;
323
+ let raw: string | undefined;
324
+ let onAbort: (() => void) | undefined;
325
+ try {
326
+ if (resultDir && !resultAbort.signal.aborted) {
327
+ raw = await Promise.race([
328
+ readFile(join(resultDir, "launch.json"), { encoding: "utf8", signal: resultAbort.signal }).catch(() => undefined),
329
+ new Promise<undefined>(resolve => {
330
+ onAbort = () => resolve(undefined);
331
+ resultAbort.signal.addEventListener("abort", onAbort, { once: true });
332
+ if (resultAbort.signal.aborted) onAbort();
333
+ }),
334
+ ]);
335
+ }
336
+ } catch {
337
+ // A killed console or failed spawn may never produce a command result.
338
+ } finally {
339
+ if (onAbort) resultAbort.signal.removeEventListener("abort", onAbort);
340
+ if (resultDir) await removeLaunchResultDirectory(resultDir).catch(error => {
341
+ const detail = `launch result cleanup failed: ${resultDir}: ${error instanceof Error ? error.message : String(error)}`;
342
+ (this.launchResultCleanupErrors ??= []).push(detail);
343
+ if (this.launchResult !== result) return;
344
+ this.error = this.error ? `${this.error}; ${detail}` : detail;
345
+ });
346
+ resolveResult(resultAbort.signal.aborted ? undefined : raw);
347
+ if (resultJob) this.resultJobs.delete(resultJob);
348
+ resolveCleanup?.();
349
+ }
350
+ };
351
+ let child: ChildProcess;
352
+ try {
353
+ await mkdir(dirname(this.logFile), { recursive: true });
354
+ signal?.throwIfAborted();
355
+ if (this.stoppedByUser || this.shuttingDown) { await collectResult(); return; }
356
+ let args = this.launchArgs;
357
+ if (this.collectLaunchResult) {
358
+ resultDir = await mkdtemp(join(dirname(this.logFile), ".xcodebug-launch-"));
359
+ signal?.throwIfAborted();
360
+ if (this.stoppedByUser || this.shuttingDown) { await collectResult(); return; }
361
+ await writeFile(join(resultDir, "owner.json"), JSON.stringify({
362
+ kind: "xcodebug.launch-result", version: 1, pid: process.pid, createdAt: Date.now(),
363
+ }), { mode: 0o600, flag: "wx" });
364
+ signal?.throwIfAborted();
365
+ if (this.stoppedByUser || this.shuttingDown) { await collectResult(); return; }
366
+ const consoleIndex = args.indexOf("--console");
367
+ const separatorIndex = args.indexOf("--");
368
+ const index = consoleIndex >= 0 ? consoleIndex : separatorIndex >= 0 ? separatorIndex : args.length;
369
+ args = args.slice();
370
+ args.splice(index, 0, "--json-output", join(resultDir, "launch.json"));
371
+ }
372
+ this.openFile(true);
373
+ this.spawnedArgs = args;
374
+ child = spawn(this.command, args, { stdio: ["ignore", "pipe", "pipe"] });
375
+ this.child = child;
376
+ } catch (error) {
377
+ await collectResult();
378
+ throw error;
379
+ }
232
380
  let finishing = false;
233
381
  let drainTimer: NodeJS.Timeout | undefined;
234
382
  const drainAbort = new AbortController();
@@ -284,13 +432,24 @@ export class Capture {
284
432
  if (this.child === child) this.consume("err", chunk);
285
433
  });
286
434
  child.on("error", (error: Error) => {
435
+ void collectResult();
287
436
  if (this.child !== child) return;
288
437
  this.error = error.message;
289
438
  this.pushLine("err", `[xcodebug] failed to start: ${error.message}`);
290
439
  finish(undefined, undefined);
291
440
  });
292
441
  // `close` can itself wait forever while a backed-up writer pauses the pipes.
293
- child.on("exit", (code, signal) => beginDrain(code ?? undefined, signal ?? undefined));
442
+ child.on("exit", (code, signal) => {
443
+ void collectResult();
444
+ if (this.child !== child) return;
445
+ if (!this.stoppedByUser) this.naturalExitAt = Date.now();
446
+ beginDrain(code ?? undefined, signal ?? undefined);
447
+ for (const listener of this.processExitListeners) {
448
+ try { listener(code ?? undefined, signal ?? undefined); } catch {
449
+ // A listener must never break capture teardown.
450
+ }
451
+ }
452
+ });
294
453
  child.on("close", (code: number | null, signal: NodeJS.Signals | null) => {
295
454
  if (this.child !== child) return;
296
455
  this.flush("out");
@@ -432,6 +591,39 @@ export class Capture {
432
591
  }
433
592
  }
434
593
 
594
+ /** Join every retained per-start result task, including old reconnect results. */
595
+ async waitForLaunchResults(): Promise<void> {
596
+ await Promise.all([...this.resultJobs].map(job => job.done));
597
+ }
598
+
599
+ /** Session exit cancels diagnostics as well as the bridge, unlike ordinary stop. */
600
+ shutdown(timeoutMs = 3_000): Promise<boolean> {
601
+ this.shuttingDown = true;
602
+ this.stop(false);
603
+ for (const job of this.resultJobs) job.cancel();
604
+ return new Promise(resolve => {
605
+ let settled = false;
606
+ let unsubscribe = (): void => {};
607
+ const done = (cleaned: boolean): void => {
608
+ if (settled) return;
609
+ settled = true;
610
+ clearTimeout(timer);
611
+ unsubscribe();
612
+ if (!cleaned) {
613
+ const detail = `capture shutdown timed out after ${timeoutMs}ms; resource cleanup remains pending`;
614
+ this.error = this.error ? `${this.error}; ${detail}` : detail;
615
+ }
616
+ resolve(cleaned);
617
+ };
618
+ const timer = setTimeout(() => done(false), Math.max(0, timeoutMs));
619
+ timer.unref();
620
+ const drained = this.running
621
+ ? new Promise<void>(resolve => { unsubscribe = this.onExit(() => resolve()); })
622
+ : Promise.resolve();
623
+ void Promise.all([Promise.all([...this.startups]), this.waitForLaunchResults(), drained]).then(() => done(true));
624
+ });
625
+ }
626
+
435
627
  /**
436
628
  * Kill the bridge for a restart, without touching `stoppedByUser`.
437
629
  *
@@ -641,11 +833,12 @@ export class Capture {
641
833
  cursor: this.cursor,
642
834
  logFile: this.logFile,
643
835
  logFiles: [...this.logFiles].sort((a, b) => a[1] - b[1]).map(([path]) => path),
644
- commandLine: [this.command, ...this.launchArgs].join(" "),
836
+ commandLine: [this.command, ...this.spawnedArgs].join(" "),
645
837
  error: this.error,
646
838
  relaunches: this.relaunches,
647
839
  endReason: this.endReason,
648
840
  crashReport: this.crashReport,
841
+ terminationReason: this.terminationReason,
649
842
  };
650
843
  }
651
844
  }
package/devices.ts CHANGED
@@ -296,15 +296,15 @@ async function findProcessPidOnce(
296
296
  export async function pullCrashReport(
297
297
  device: DeviceInfo,
298
298
  executableName: string,
299
- options: { since: number; directory: string; pid?: number },
300
- ): Promise<string | undefined> {
299
+ options: { since: number; directory: string; pid?: number; signal?: AbortSignal },
300
+ ): Promise<{ path: string; terminationReason?: string } | undefined> {
301
301
  const listed = await runCommand(
302
302
  "xcrun",
303
303
  [
304
304
  "devicectl", "device", "info", "files", "--device", device.id,
305
305
  "--domain-type", "systemCrashLogs", "--search", executableName, "--json-output", "-",
306
306
  ],
307
- { timeoutMs: 45_000 },
307
+ { timeoutMs: 45_000, signal: options.signal },
308
308
  );
309
309
  if (listed.code !== 0) return undefined;
310
310
  let files: unknown;
@@ -322,6 +322,7 @@ export async function pullCrashReport(
322
322
  if (name?.startsWith(`${executableName}-`) && name.endsWith(".ips") && basename(name) === name && at >= options.since) candidates.push({ name, at });
323
323
  }
324
324
  for (const { name } of candidates.sort((a, b) => b.at - a.at)) {
325
+ options.signal?.throwIfAborted();
325
326
  const directory = await mkdtemp(join(options.directory, "crash-")).catch(() => undefined);
326
327
  if (!directory) return undefined;
327
328
  const destination = join(directory, `crash-${name}`);
@@ -332,15 +333,35 @@ export async function pullCrashReport(
332
333
  "devicectl", "device", "copy", "from", "--device", device.id,
333
334
  "--domain-type", "systemCrashLogs", "--source", name, "--destination", destination,
334
335
  ],
335
- { timeoutMs: 60_000 },
336
+ { timeoutMs: 60_000, signal: options.signal },
336
337
  );
337
338
  if (copied.code !== 0) continue;
338
339
  const report = await readFile(destination, "utf8").catch(() => undefined);
339
340
  if (report === undefined) continue;
340
- const reported = /"pid"\s*:\s*(\d+)/.exec(report)?.[1];
341
- if (options.pid !== undefined && Number(reported) !== options.pid) continue;
341
+ let parsed: Record<string, unknown>;
342
+ try {
343
+ // An Apple .ips has a one-line metadata object before the report JSON.
344
+ const header = /^[^\n]*\}\s*\n(?=\s*\{)/.exec(report);
345
+ parsed = asRecord(JSON.parse(header ? report.slice(header[0].length) : report));
346
+ } catch {
347
+ continue;
348
+ }
349
+ if (options.pid !== undefined && parsed.pid !== options.pid) continue;
342
350
  const retained = join(options.directory, `${basename(directory)}-${name}`);
343
- if (await rename(destination, retained).then(() => true, () => false)) return retained;
351
+ if (await rename(destination, retained).then(() => true, () => false)) {
352
+ const termination = asRecord(parsed.termination);
353
+ let reason = asString(termination.namespace);
354
+ let code = asString(termination.code);
355
+ if (typeof termination.code === "number" && Number.isSafeInteger(termination.code) && termination.code >= 0) {
356
+ code = `0x${termination.code.toString(16).toUpperCase()}`;
357
+ }
358
+ if (code) reason = reason ? `${reason} ${code}` : code;
359
+ const explanation = (Array.isArray(termination.reasons)
360
+ ? termination.reasons.filter((value): value is string => typeof value === "string").join(" ")
361
+ : undefined) || asString(termination.indicator);
362
+ if (explanation) reason = reason ? `${reason}: ${explanation}` : explanation;
363
+ return { path: retained, terminationReason: reason };
364
+ }
344
365
  } finally {
345
366
  await rm(directory, { recursive: true, force: true }).catch(() => {});
346
367
  }