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/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";
@@ -54,7 +54,7 @@ interface RegisteredTool {
54
54
  /** Only the members index.ts calls on the host API. */
55
55
  interface StubPi {
56
56
  cwd: string;
57
- on(): void;
57
+ on(event: string, handler: () => Promise<void>): void;
58
58
  registerCommand(): void;
59
59
  sendMessage(): void;
60
60
  registerTool(tool: RegisteredTool): void;
@@ -70,9 +70,13 @@ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url),
70
70
  };
71
71
 
72
72
  let registered: RegisteredTool | undefined;
73
+ /** The extension's own teardown: it stops every capture the session started. */
74
+ let endSession: (() => Promise<void>) | undefined;
73
75
  const stubPi: StubPi = {
74
76
  cwd: process.cwd(),
75
- on() {},
77
+ on(event, handler) {
78
+ if (event === "session_shutdown") endSession = handler;
79
+ },
76
80
  registerCommand() {},
77
81
  // Nothing consumes pushed lines here: MCP has no channel that injects messages
78
82
  // into the conversation, so push is refused below instead of silently dropped.
@@ -131,8 +135,8 @@ process.on("exit", () => {
131
135
  });
132
136
  // Claude Code ends a stdio server with SIGINT. Left to the default, a signal
133
137
  // ends the process without the handler above; the exit codes are the shell's.
134
- process.on("SIGINT", () => process.exit(130));
135
- process.on("SIGTERM", () => process.exit(143));
138
+ process.on("SIGINT", () => void shutdown(130));
139
+ process.on("SIGTERM", () => void shutdown(143));
136
140
  // A server that was killed outright never ran it either. Its file is named after
137
141
  // a process that no longer exists, which is how the next server to start finds it.
138
142
  try {
@@ -146,11 +150,15 @@ try {
146
150
  } catch {
147
151
  // No directory to sweep: publishUi() could not create it and said so.
148
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");
149
156
  const uiTool = {
150
157
  name: "xcodebug_ui",
151
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.",
152
159
  inputSchema: { type: "object", properties: {}, additionalProperties: false },
153
160
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
161
+ _meta: { "openai/ui": { entrypoints: [{ type: "statusline", resourceUri: statusResource.uri }] } },
154
162
  };
155
163
 
156
164
  function sendNotification(method: string, params: unknown): void {
@@ -229,7 +237,7 @@ async function callTool(
229
237
  }
230
238
  }
231
239
 
232
- async function handle(message: Record<string, unknown>): Promise<void> {
240
+ async function handle(message: Record<string, unknown>, controller?: AbortController): Promise<void> {
233
241
  const id = message.id;
234
242
  const method = message.method;
235
243
  // Notifications carry no id and must never be answered.
@@ -239,7 +247,7 @@ async function handle(message: Record<string, unknown>): Promise<void> {
239
247
  const requested = (message.params as { protocolVersion?: string } | undefined)?.protocolVersion;
240
248
  reply(id, {
241
249
  protocolVersion: requested ?? PROTOCOL_VERSION,
242
- capabilities: { tools: {} },
250
+ capabilities: { tools: {}, resources: {} },
243
251
  serverInfo: { name: "xcodebug", version: pkg.version },
244
252
  });
245
253
  return;
@@ -252,6 +260,14 @@ async function handle(message: Record<string, unknown>): Promise<void> {
252
260
  reply(id, { tools: [{ name: "xcodebug", description: tool.description, inputSchema }, uiTool] });
253
261
  return;
254
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
+ }
255
271
  if (method === "tools/call") {
256
272
  const params = (message.params ?? {}) as {
257
273
  name?: string;
@@ -262,16 +278,14 @@ async function handle(message: Record<string, unknown>): Promise<void> {
262
278
  replyError(id, -32602, `Unknown tool "${params.name ?? ""}"`);
263
279
  return;
264
280
  }
265
- // Registered before the call starts so a cancellation that arrives while it
266
- // runs finds the controller; `finally` keeps the map from growing.
267
- const controller = new AbortController();
268
- inflight.set(id, controller);
269
281
  try {
270
- reply(id, await callTool(params.arguments ?? {}, controller.signal, params._meta?.progressToken));
282
+ if (controller!.signal.aborted) {
283
+ reply(id, { content: [{ type: "text", text: "Request cancelled" }], isError: true });
284
+ return;
285
+ }
286
+ reply(id, await callTool(params.arguments ?? {}, controller!.signal, params._meta?.progressToken));
271
287
  } catch (error) {
272
288
  reply(id, { content: [{ type: "text", text: (error as Error).message }], isError: true });
273
- } finally {
274
- inflight.delete(id);
275
289
  }
276
290
  return;
277
291
  }
@@ -281,9 +295,49 @@ async function handle(message: Record<string, unknown>): Promise<void> {
281
295
  // Requests are serialized: a capture's state is a plain map, and two overlapping
282
296
  // calls (launch + stop) would interleave mutations on it.
283
297
  let queue: Promise<void> = Promise.resolve();
284
- /** Calls running right now, so a cancellation can reach the one it names. */
298
+ /** Admitted calls, including queued calls, so cancellation cannot miss one. */
285
299
  const inflight = new Map<unknown, AbortController>();
286
- createInterface({ input: process.stdin }).on("line", (line) => {
300
+
301
+ /**
302
+ * Stop what the client's calls started, then exit.
303
+ *
304
+ * A capture's bridge and a running build are child processes that nothing else
305
+ * stops. A bridge that is still alive keeps this process alive after stdin has
306
+ * closed, and one that outlives it stays for good if the app is quiet.
307
+ */
308
+ let exiting = false;
309
+ async function shutdown(code: number): Promise<void> {
310
+ if (exiting) return;
311
+ exiting = true;
312
+ for (const controller of inflight.values()) controller.abort();
313
+ try {
314
+ // Aborting is not settlement: an operation may still be rolling back a
315
+ // partially started capture. Teardown must run after that rollback, never
316
+ // concurrently with it, and queued work must not start after this barrier.
317
+ await queue;
318
+ await endSession?.();
319
+ if (!process.stdout.destroyed) {
320
+ const { promise, resolve } = Promise.withResolvers<void>();
321
+ process.stdout.write("", () => resolve());
322
+ await promise;
323
+ }
324
+ } finally {
325
+ process.exit(code);
326
+ }
327
+ }
328
+
329
+ // EOF on stdin is only a half-close: scripts commonly finish sending requests
330
+ // and keep stdout open to collect replies. A full disconnect is observable only
331
+ // when stdout closes or a write fails; stdio cannot detect a silent reader gone.
332
+ process.stdout.on("error", () => { void shutdown(0); });
333
+ process.stdout.on("close", () => { void shutdown(0); });
334
+
335
+ const input = createInterface({ input: process.stdin });
336
+ input.on("close", () => {
337
+ void queue.then(() => shutdown(0));
338
+ });
339
+ input.on("line", (line) => {
340
+ if (exiting) return;
287
341
  const text = line.trim();
288
342
  if (text.length === 0) return;
289
343
  let message: Record<string, unknown>;
@@ -295,6 +349,28 @@ createInterface({ input: process.stdin }).on("line", (line) => {
295
349
  }
296
350
  // UI reads must remain responsive during a build/install/wait and must never
297
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
+ }
298
374
  if (message.method === "tools/call" &&
299
375
  (message.params as { name?: string } | undefined)?.name === uiTool.name) {
300
376
  if (message.id !== undefined) {
@@ -312,7 +388,16 @@ createInterface({ input: process.stdin }).on("line", (line) => {
312
388
  inflight.get(requestId)?.abort();
313
389
  return;
314
390
  }
315
- queue = queue.then(() => handle(message)).catch((error: unknown) => {
391
+ const controller = message.method === "tools/call" && message.id !== undefined
392
+ ? new AbortController() : undefined;
393
+ if (controller) inflight.set(message.id, controller);
394
+ queue = queue.then(async () => {
395
+ try {
396
+ if (!exiting) await handle(message, controller);
397
+ } finally {
398
+ if (controller && inflight.get(message.id) === controller) inflight.delete(message.id);
399
+ }
400
+ }).catch((error: unknown) => {
316
401
  console.error("xcodebug-mcp:", error);
317
402
  });
318
403
  });
@@ -1,15 +1,27 @@
1
1
  ---
2
2
  name: xcodebug
3
- description: "Builds, launches, and captures console logs from physical iOS devices through the xcodebug MCP server. Use when the user invokes xcodebug, requests its doctor/devices/status/logs/wait/stop/restart actions, or wants to verify an iOS app on a real device using its console."
3
+ description: "Builds, launches, and captures console logs from physical iOS devices using the registered native xcodebug tool or an explicitly configured xcodebug MCP connection. Use when the user invokes xcodebug, requests its doctor/devices/status/logs/wait/stop/restart actions, or wants to verify an iOS app on a real device using its console."
4
4
  ---
5
5
 
6
6
  # xcodebug
7
7
 
8
- Use the **existing xcodebug MCP connection**. Its tool is named `xcodebug`
9
- (Claude Code: `mcp__xcodebug__xcodebug`; Codex may display `xcodebug.xcodebug`).
10
- Do not run an `xcodebug` shell command or start another MCP server: captures and
11
- restart settings belong to the connected server process. If the tool is absent,
12
- report that the xcodebug MCP connection must be configured first.
8
+ Select the execution tool by exposed capability, not by client name:
9
+
10
+ - If the session exposes the registered native extension tool `xcodebug`,
11
+ execute the action through that tool. A native transport exposed as
12
+ `xd://xcodebug` is the same backend: read its live schema, then write the action
13
+ JSON to that URI. Reading a schema or this skill does not execute an action.
14
+ - If the user explicitly requests the native extension but it is not exposed,
15
+ report that it must be loaded. Do not substitute MCP or a shell command.
16
+ - Otherwise, use only an existing configured xcodebug MCP tool, commonly named
17
+ `mcp__xcodebug__xcodebug` or `xcodebug.xcodebug`. If it is absent, report the
18
+ missing connection; do not start another server.
19
+ - Captures and restart settings belong to the selected tool's process. Do not
20
+ switch backends or substitute another operation.
21
+
22
+ Native command dispatch is enforced by the host's registered command handler,
23
+ not by these instructions. A shared skill may still be discovered through a
24
+ user-level skills directory; these instructions do not disable that discovery.
13
25
 
14
26
  ## Dispatch the request
15
27
 
@@ -17,10 +29,10 @@ Read the request following `/xcodebug` in Claude Code or `$xcodebug` in Codex.
17
29
  Both explicit invocation and a matching natural-language request can use this skill.
18
30
 
19
31
  - With no arguments, call `{"action":"launch"}` once to build as needed, install,
20
- launch and start capturing with the server's defaults. Keep the capture running;
32
+ launch and start capturing with the selected tool's defaults. Keep the capture running;
21
33
  report a launch error without substituting a status query or another action.
22
34
  - For `status`, call `{"action":"status"}` to inspect captures without launching.
23
- - For an explicit action, call the MCP tool with that action and the supplied
35
+ - For an explicit action, call the selected tool with that action and the supplied
24
36
  parameters immediately. Do not replace execution with instructions for the user.
25
37
  - Accept `action [key=value ...]`, `action=... [key=value ...]`, or a JSON parameter
26
38
  object. Actions: `doctor`, `devices`, `changes`, `build`, `install`, `launch`,
@@ -28,10 +40,11 @@ Both explicit invocation and a matching natural-language request can use this sk
28
40
  - Use the live tool schema for parameter names and types. Preserve quoted strings,
29
41
  numeric `since`/`limit`/`timeoutSeconds`, booleans, JSON `args` arrays and
30
42
  `environment` objects. Keep a supplied `command` shell line intact.
31
- - Omit unspecified parameters so the server can apply its project configuration.
32
- MCP supports pull reads: omit `push` or use `push="off"`; `context` and `wake`
33
- are unsupported. Explain an unsupported explicit value instead of changing it silently.
34
- - For an explicit action, make exactly one xcodebug MCP call, report its result,
43
+ - Omit unspecified parameters so the selected tool can apply its project configuration.
44
+ - Only on MCP, use pull reads: omit `push` or use `push="off"`; `context` and
45
+ `wake` are unsupported. Explain an unsupported explicit value instead of changing it silently.
46
+ Native tools retain their live schema's push modes.
47
+ - For an explicit action, make exactly one selected-tool call, report its result,
35
48
  and stop, including on error. Do not add diagnostic `status` calls or retry
36
49
  with another action unless the user asks. `logs` never authorizes launching
37
50
  an app, and `launch` does not imply an immediate `stop`.
@@ -42,7 +55,7 @@ Both explicit invocation and a matching natural-language request can use this sk
42
55
 
43
56
  ## Examples
44
57
 
45
- | Request after the skill name | MCP arguments |
58
+ | Request after the skill name | Selected tool arguments |
46
59
  |---|---|
47
60
  | *(no arguments)* | `{"action":"launch"}` |
48
61
  | `status` | `{"action":"status"}` |
@@ -64,15 +77,29 @@ Both explicit invocation and a matching natural-language request can use this sk
64
77
  `logs` returns the newest matching lines up to `limit` and advances to the
65
78
  latest capture cursor, so omitted or evicted lines will not reappear merely
66
79
  by advancing `since`. Report omissions instead of claiming a lossless stream.
67
- - Use bounded `wait` for an expected line. An empty read or quiet log is not proof
80
+ - A filtered read (`logs grep=...`, `wait`) also searches the log files for lines
81
+ memory has dropped, and a `note:` line in the reply says what it covered. If
82
+ the note says some lines were not searched, say so instead of "not logged".
83
+ - Use bounded `wait` for an expected line. With `regex=true`, `match` and `grep`
84
+ are regular expressions, so one `wait` covers both outcomes of a step:
85
+ `match="sync (done|failed)"`. An empty read or quiet log is not proof
68
86
  that a test finished. While waiting for the user to operate the phone, tell them
69
87
  the required action and keep the capture running.
70
88
  - For an automated scenario, pass the user's `command` to `launch`, or use `await`
71
89
  with the current capture. The command must not relaunch the app itself, since
72
90
  that would break the console bridge. Use the returned exit code and logs as evidence.
91
+ - A capture that ended on its own says why in `status`, under `logs`, and in the
92
+ reply of the `wait` or `command` it interrupted: the app exited, or was
93
+ restarted outside the capture. Interrupted actions wait for the existing
94
+ crash-report search and include its system termination cause and report path
95
+ when available; missing evidence is reported explicitly, not guessed. Caller
96
+ cancellation still applies. A reply can also warn that a console reattach
97
+ relaunched the app.
98
+ Report these with the result; the log then does not describe one
99
+ uninterrupted run.
73
100
  - When a verification goal is answered, stop the capture started for that goal.
74
101
  Include its `captureId` so other captures are not stopped. An explicit `stop`
75
- without an ID intentionally stops all running captures in this server.
102
+ without an ID intentionally stops all running captures in the selected tool.
76
103
  - Report the operation's result, relevant log evidence, capture ID/cursor or log
77
104
  path when returned, and whether capture remains active. Do not invent device
78
105
  activity, successful builds, or test outcomes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xcodebug",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
4
4
  "type": "module",
5
5
  "description": "Build, install and launch an iOS app on a physical device and read its console inside the agent session (pi / omp extension)",
6
6
  "keywords": [
@@ -25,10 +25,13 @@
25
25
  "bugs": {
26
26
  "url": "https://github.com/sublimter/xcodebug/issues"
27
27
  },
28
+ "bin": {
29
+ "xcodebug-setup-codex": "./bin/xcodebug-setup-codex.mjs"
30
+ },
28
31
  "files": [
29
32
  "*.ts",
33
+ "bin/",
30
34
  "mcp/",
31
- "skills/",
32
35
  "claude/",
33
36
  "README.md",
34
37
  "GUIDE.md",
@@ -37,6 +40,9 @@
37
40
  "engines": {
38
41
  "node": ">=20"
39
42
  },
43
+ "scripts": {
44
+ "test": "node --test tests/*.test.mjs"
45
+ },
40
46
  "omp": {
41
47
  "extensions": [
42
48
  "./index.ts"
@@ -45,7 +51,8 @@
45
51
  "pi": {
46
52
  "extensions": [
47
53
  "./index.ts"
48
- ]
54
+ ],
55
+ "skills": []
49
56
  },
50
57
  "peerDependencies": {
51
58
  "@earendil-works/pi-coding-agent": "*",
package/xcode.ts CHANGED
@@ -35,6 +35,71 @@ function destination(device: DeviceInfo): string {
35
35
  return `platform=iOS,id=${id}`;
36
36
  }
37
37
 
38
+ const MAX_DIAGNOSTICS = 12;
39
+ const MAX_DIAGNOSTIC_CHARS = 320;
40
+ /** Indented lines kept under a linker's symbol list: the symbols and what references them. */
41
+ const MAX_SYMBOL_LINES = 6;
42
+ /**
43
+ * `path:line:column: error: …` from a compiler, `xcodebuild: error: …`, or a
44
+ * bare `error: …`. Never indented: the indented ones are the compiler's own
45
+ * rendering of the source line under a diagnostic already taken.
46
+ */
47
+ const ERROR_LINE = /^(?:\S.*: )?(?:fatal )?error: /;
48
+ /** The linker's own failures, which carry no `error:`. Its warnings are left out. */
49
+ const LINKER_LINE = /^ld: (?!warning: )/;
50
+ /** Linker symbol-list headings, followed by indented references or conflicting objects. */
51
+ const SYMBOLS_LINE = /^(?:(?:Undefined|duplicate) symbols? for architecture|duplicate symbol .+ in:)/;
52
+
53
+ /**
54
+ * Collects the lines of a build's output that say what failed, as they pass.
55
+ *
56
+ * xcodebuild prints an error in the middle of its output, under the
57
+ * multi-kilobyte command that produced it and above everything the build still
58
+ * goes on to do, so the end of a failed build is build commands. Collecting
59
+ * while the output streams also keeps an error the size cap later drops.
60
+ */
61
+ export class BuildDiagnostics {
62
+ private readonly seen = new Set<string>();
63
+ private readonly kept: string[] = [];
64
+ private total = 0;
65
+ private remainder = "";
66
+ /** Indented lines still to keep under the symbol list just opened. */
67
+ private symbolLines = 0;
68
+
69
+ update(chunk: string): void {
70
+ const parts = (this.remainder + chunk).split("\n");
71
+ this.remainder = parts.pop() ?? "";
72
+ for (const part of parts) this.take(part.trimEnd());
73
+ }
74
+
75
+ private take(line: string): void {
76
+ if (this.symbolLines > 0 && /^\s+\S/.test(line)) {
77
+ this.symbolLines -= 1;
78
+ this.kept.push(line.slice(0, MAX_DIAGNOSTIC_CHARS));
79
+ return;
80
+ }
81
+ this.symbolLines = 0;
82
+ const symbols = SYMBOLS_LINE.test(line);
83
+ if (!symbols && !LINKER_LINE.test(line) && !ERROR_LINE.test(line)) return;
84
+ // The compiler reports a diagnostic once per pass over the file. A symbol
85
+ // list opens with the same words every time and is told apart by what follows.
86
+ if (!symbols) {
87
+ if (this.seen.has(line)) return;
88
+ this.seen.add(line);
89
+ }
90
+ this.total += 1;
91
+ if (this.total > MAX_DIAGNOSTICS) return;
92
+ this.kept.push(line.slice(0, MAX_DIAGNOSTIC_CHARS));
93
+ if (symbols) this.symbolLines = MAX_SYMBOL_LINES;
94
+ }
95
+
96
+ /** The diagnostics kept, and how many more there were. */
97
+ result(): { lines: string[]; omitted: number } {
98
+ this.update("\n");
99
+ return { lines: this.kept, omitted: Math.max(0, this.total - MAX_DIAGNOSTICS) };
100
+ }
101
+ }
102
+
38
103
  function targetFlags(target: BuildTarget): string[] {
39
104
  const flags: string[] = [];
40
105
  if (target.workspace) flags.push("-workspace", target.workspace);
@@ -74,6 +139,8 @@ export async function buildForDevice(
74
139
 
75
140
  const args = [...targetFlags(target), "-destination", destination(device), "build"];
76
141
  const tracker = new BuildProgressTracker();
142
+ // One per stream: each is split into lines on its own.
143
+ const diagnostics = { stdout: new BuildDiagnostics(), stderr: new BuildDiagnostics() };
77
144
  let lastEmit = 0;
78
145
  let lastStage = "";
79
146
  // xcodebuild can go quiet for minutes (signing, copying a large bundle). A
@@ -90,7 +157,8 @@ export async function buildForDevice(
90
157
  timeoutMs: options.timeoutMs,
91
158
  maxBytes: 12_000_000,
92
159
  signal: options.signal,
93
- onChunk: (_stream, chunk) => {
160
+ onChunk: (stream, chunk) => {
161
+ diagnostics[stream].update(chunk);
94
162
  const progress = tracker.update(chunk);
95
163
  // Throttle: a build emits tens of thousands of lines.
96
164
  const now = Date.now();
@@ -117,11 +185,23 @@ export async function buildForDevice(
117
185
  const final = tracker.finish("failed");
118
186
  options.onProgress?.(formatProgress(final));
119
187
  const reason = result.timedOut ? "build timed out" : `build failed (exit ${result.code})`;
188
+ const found = [diagnostics.stdout.result(), diagnostics.stderr.result()];
189
+ const errors = found.flatMap((each) => each.lines);
190
+ const omitted = found.reduce((sum, each) => sum + each.omitted, 0);
191
+ // xcodebuild closes stderr with its own account: the verdict and the
192
+ // commands that failed.
193
+ const verdictAt = result.stderr.lastIndexOf("** BUILD ");
194
+ const verdict = verdictAt < 0 ? [] : result.stderr.slice(verdictAt).split("\n").filter((line) => line.trim()).slice(0, 12);
195
+ const detail =
196
+ errors.length > 0
197
+ ? [...errors, omitted > 0 ? `(+${omitted} more error(s) in the log)` : "", ...verdict].filter(Boolean).join("\n")
198
+ : // Nothing called itself an error, so the end of the output is all there is.
199
+ lastLines(`${result.stderr}\n${result.stdout}`, 25);
120
200
  return {
121
201
  ok: false,
122
202
  logFile,
123
203
  durationMs,
124
- summary: `${reason}\n${lastLines(`${result.stderr}\n${result.stdout}`, 25)}`,
204
+ summary: `${reason}\n${detail}`,
125
205
  };
126
206
  }
127
207
  options.onProgress?.(formatProgress(tracker.finish("done")));
@@ -210,12 +290,12 @@ export function consoleLaunchArgs(
210
290
  export async function terminateApp(
211
291
  device: DeviceInfo,
212
292
  pid: number,
213
- options: { timeoutMs: number },
293
+ options: { timeoutMs: number; signal?: AbortSignal },
214
294
  ): Promise<{ ok: boolean; message: string }> {
215
295
  const result = await runCommand(
216
296
  "xcrun",
217
297
  ["devicectl", "device", "process", "terminate", "--device", device.id, "--pid", String(pid)],
218
- { timeoutMs: options.timeoutMs, maxBytes: 200_000 },
298
+ { timeoutMs: options.timeoutMs, maxBytes: 200_000, signal: options.signal },
219
299
  );
220
300
  if (result.code === 0) return { ok: true, message: `terminated pid ${pid}` };
221
301
  return {