xcodebug 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mcp/server.ts CHANGED
@@ -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 {
@@ -229,7 +233,7 @@ async function callTool(
229
233
  }
230
234
  }
231
235
 
232
- async function handle(message: Record<string, unknown>): Promise<void> {
236
+ async function handle(message: Record<string, unknown>, controller?: AbortController): Promise<void> {
233
237
  const id = message.id;
234
238
  const method = message.method;
235
239
  // Notifications carry no id and must never be answered.
@@ -262,16 +266,14 @@ async function handle(message: Record<string, unknown>): Promise<void> {
262
266
  replyError(id, -32602, `Unknown tool "${params.name ?? ""}"`);
263
267
  return;
264
268
  }
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
269
  try {
270
- reply(id, await callTool(params.arguments ?? {}, controller.signal, params._meta?.progressToken));
270
+ if (controller!.signal.aborted) {
271
+ reply(id, { content: [{ type: "text", text: "Request cancelled" }], isError: true });
272
+ return;
273
+ }
274
+ reply(id, await callTool(params.arguments ?? {}, controller!.signal, params._meta?.progressToken));
271
275
  } catch (error) {
272
276
  reply(id, { content: [{ type: "text", text: (error as Error).message }], isError: true });
273
- } finally {
274
- inflight.delete(id);
275
277
  }
276
278
  return;
277
279
  }
@@ -281,9 +283,49 @@ async function handle(message: Record<string, unknown>): Promise<void> {
281
283
  // Requests are serialized: a capture's state is a plain map, and two overlapping
282
284
  // calls (launch + stop) would interleave mutations on it.
283
285
  let queue: Promise<void> = Promise.resolve();
284
- /** Calls running right now, so a cancellation can reach the one it names. */
286
+ /** Admitted calls, including queued calls, so cancellation cannot miss one. */
285
287
  const inflight = new Map<unknown, AbortController>();
286
- createInterface({ input: process.stdin }).on("line", (line) => {
288
+
289
+ /**
290
+ * Stop what the client's calls started, then exit.
291
+ *
292
+ * A capture's bridge and a running build are child processes that nothing else
293
+ * stops. A bridge that is still alive keeps this process alive after stdin has
294
+ * closed, and one that outlives it stays for good if the app is quiet.
295
+ */
296
+ let exiting = false;
297
+ async function shutdown(code: number): Promise<void> {
298
+ if (exiting) return;
299
+ exiting = true;
300
+ for (const controller of inflight.values()) controller.abort();
301
+ try {
302
+ // Aborting is not settlement: an operation may still be rolling back a
303
+ // partially started capture. Teardown must run after that rollback, never
304
+ // concurrently with it, and queued work must not start after this barrier.
305
+ await queue;
306
+ await endSession?.();
307
+ if (!process.stdout.destroyed) {
308
+ const { promise, resolve } = Promise.withResolvers<void>();
309
+ process.stdout.write("", () => resolve());
310
+ await promise;
311
+ }
312
+ } finally {
313
+ process.exit(code);
314
+ }
315
+ }
316
+
317
+ // EOF on stdin is only a half-close: scripts commonly finish sending requests
318
+ // and keep stdout open to collect replies. A full disconnect is observable only
319
+ // when stdout closes or a write fails; stdio cannot detect a silent reader gone.
320
+ process.stdout.on("error", () => { void shutdown(0); });
321
+ process.stdout.on("close", () => { void shutdown(0); });
322
+
323
+ const input = createInterface({ input: process.stdin });
324
+ input.on("close", () => {
325
+ void queue.then(() => shutdown(0));
326
+ });
327
+ input.on("line", (line) => {
328
+ if (exiting) return;
287
329
  const text = line.trim();
288
330
  if (text.length === 0) return;
289
331
  let message: Record<string, unknown>;
@@ -312,7 +354,16 @@ createInterface({ input: process.stdin }).on("line", (line) => {
312
354
  inflight.get(requestId)?.abort();
313
355
  return;
314
356
  }
315
- queue = queue.then(() => handle(message)).catch((error: unknown) => {
357
+ const controller = message.method === "tools/call" && message.id !== undefined
358
+ ? new AbortController() : undefined;
359
+ if (controller) inflight.set(message.id, controller);
360
+ queue = queue.then(async () => {
361
+ try {
362
+ if (!exiting) await handle(message, controller);
363
+ } finally {
364
+ if (controller && inflight.get(message.id) === controller) inflight.delete(message.id);
365
+ }
366
+ }).catch((error: unknown) => {
316
367
  console.error("xcodebug-mcp:", error);
317
368
  });
318
369
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xcodebug",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
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": [
@@ -37,6 +37,9 @@
37
37
  "engines": {
38
38
  "node": ">=20"
39
39
  },
40
+ "scripts": {
41
+ "test": "node --test tests/*.test.mjs"
42
+ },
40
43
  "omp": {
41
44
  "extensions": [
42
45
  "./index.ts"
@@ -64,12 +64,23 @@ Both explicit invocation and a matching natural-language request can use this sk
64
64
  `logs` returns the newest matching lines up to `limit` and advances to the
65
65
  latest capture cursor, so omitted or evicted lines will not reappear merely
66
66
  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
67
+ - A filtered read (`logs grep=...`, `wait`) also searches the log files for lines
68
+ memory has dropped, and a `note:` line in the reply says what it covered. If
69
+ the note says some lines were not searched, say so instead of "not logged".
70
+ - Use bounded `wait` for an expected line. With `regex=true`, `match` and `grep`
71
+ are regular expressions, so one `wait` covers both outcomes of a step:
72
+ `match="sync (done|failed)"`. An empty read or quiet log is not proof
68
73
  that a test finished. While waiting for the user to operate the phone, tell them
69
74
  the required action and keep the capture running.
70
75
  - For an automated scenario, pass the user's `command` to `launch`, or use `await`
71
76
  with the current capture. The command must not relaunch the app itself, since
72
77
  that would break the console bridge. Use the returned exit code and logs as evidence.
78
+ - A capture that ended on its own says why in `status`, under `logs`, and in the
79
+ reply of the `wait` or `command` it interrupted: the app exited, or was
80
+ restarted outside the capture. It gives a crash report path when the device
81
+ wrote one. A reply can also warn that a console reattach relaunched the app.
82
+ Report these with the result; the log then does not describe one
83
+ uninterrupted run.
73
84
  - When a verification goal is answered, stop the capture started for that goal.
74
85
  Include its `captureId` so other captures are not stopped. An explicit `stop`
75
86
  without an ID intentionally stops all running captures in this server.
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 {