xcodebug 1.2.0 → 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/GUIDE.md +65 -16
- package/README.md +364 -47
- package/archive.ts +29 -0
- package/capture.ts +212 -16
- package/changes.ts +113 -15
- package/claude/.claude-plugin/plugin.json +6 -0
- package/claude/hooks/hooks.json +3 -0
- package/claude/hooks/register.js +113 -0
- package/claude/tests/live.test.ts +321 -0
- package/devices.ts +74 -3
- package/index.ts +518 -113
- package/mcp/server.ts +141 -17
- package/package.json +6 -1
- package/skills/xcodebug/SKILL.md +89 -0
- package/xcode.ts +84 -4
package/mcp/server.ts
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* needed (initialize, tools/list, tools/call); the official SDK would add ~97
|
|
19
19
|
* transitive packages to every install, including the pi users who never run MCP.
|
|
20
20
|
*/
|
|
21
|
-
import { readFileSync } from "node:fs";
|
|
21
|
+
import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
22
22
|
import { homedir } from "node:os";
|
|
23
23
|
import { join } from "node:path";
|
|
24
24
|
import { createInterface } from "node:readline";
|
|
@@ -29,7 +29,7 @@ interface ExtensionContextLike {
|
|
|
29
29
|
agentDir: string;
|
|
30
30
|
/** The status ticker in index.ts only runs when this is set. */
|
|
31
31
|
hasUI?: boolean;
|
|
32
|
-
ui: { notify(): void; setStatus(key: string, text?: string): void; setWidget(): void };
|
|
32
|
+
ui: { notify(): void; setStatus(key: string, text?: string): void; setWidget(key: string, rows?: string[]): void };
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
interface ToolResult {
|
|
@@ -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.
|
|
@@ -96,6 +100,63 @@ if (!registered) {
|
|
|
96
100
|
}
|
|
97
101
|
const tool = registered;
|
|
98
102
|
|
|
103
|
+
// The native Claude mod reads this without joining the mutating action queue.
|
|
104
|
+
// Keep the last repaint alive after tools/call ends; only progress is request-scoped.
|
|
105
|
+
const uiSnapshot: { status?: string; rows: string[] } = { rows: [] };
|
|
106
|
+
|
|
107
|
+
// Every xcodebug_ui call runs the client's tool hooks, so a mod that polled it
|
|
108
|
+
// once a second ran them once a second for as long as a capture lived. The same
|
|
109
|
+
// snapshot goes to a file the mod reads between calls. One file per process:
|
|
110
|
+
// several sessions each run their own server.
|
|
111
|
+
const UI_DIR = join(AGENT_DIR, "ui");
|
|
112
|
+
let uiFile: string | undefined = join(UI_DIR, `${process.pid}.json`);
|
|
113
|
+
// Advances on every repaint, which happens once a second while anything is
|
|
114
|
+
// shown; a reader that sees it stand still knows this process stopped painting.
|
|
115
|
+
let uiSeq = 0;
|
|
116
|
+
|
|
117
|
+
function publishUi(): void {
|
|
118
|
+
if (!uiFile) return;
|
|
119
|
+
uiSeq += 1;
|
|
120
|
+
try {
|
|
121
|
+
mkdirSync(UI_DIR, { recursive: true });
|
|
122
|
+
// Renamed into place so a reader never sees half a snapshot.
|
|
123
|
+
writeFileSync(`${uiFile}.tmp`, JSON.stringify({ ...uiSnapshot, seq: uiSeq }));
|
|
124
|
+
renameSync(`${uiFile}.tmp`, uiFile);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
// A repaint must not take the action down with it. Without the file the
|
|
127
|
+
// mod is told nothing about it and keeps calling xcodebug_ui.
|
|
128
|
+
console.error("xcodebug-mcp: live display file unavailable:", (error as Error).message);
|
|
129
|
+
uiFile = undefined;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
publishUi();
|
|
133
|
+
process.on("exit", () => {
|
|
134
|
+
if (uiFile) rmSync(uiFile, { force: true });
|
|
135
|
+
});
|
|
136
|
+
// Claude Code ends a stdio server with SIGINT. Left to the default, a signal
|
|
137
|
+
// ends the process without the handler above; the exit codes are the shell's.
|
|
138
|
+
process.on("SIGINT", () => void shutdown(130));
|
|
139
|
+
process.on("SIGTERM", () => void shutdown(143));
|
|
140
|
+
// A server that was killed outright never ran it either. Its file is named after
|
|
141
|
+
// a process that no longer exists, which is how the next server to start finds it.
|
|
142
|
+
try {
|
|
143
|
+
for (const name of readdirSync(UI_DIR)) {
|
|
144
|
+
try {
|
|
145
|
+
process.kill(Number.parseInt(name, 10), 0);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if ((error as NodeJS.ErrnoException).code === "ESRCH") rmSync(join(UI_DIR, name), { force: true });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} catch {
|
|
151
|
+
// No directory to sweep: publishUi() could not create it and said so.
|
|
152
|
+
}
|
|
153
|
+
const uiTool = {
|
|
154
|
+
name: "xcodebug_ui",
|
|
155
|
+
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
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
157
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
158
|
+
};
|
|
159
|
+
|
|
99
160
|
function sendNotification(method: string, params: unknown): void {
|
|
100
161
|
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
|
|
101
162
|
}
|
|
@@ -121,9 +182,14 @@ function makeCtx(progressToken: unknown): { ctx: ExtensionContextLike; close():
|
|
|
121
182
|
ui: {
|
|
122
183
|
notify() {},
|
|
123
184
|
setStatus(_key, text) {
|
|
185
|
+
uiSnapshot.status = text;
|
|
186
|
+
publishUi();
|
|
124
187
|
report(text);
|
|
125
188
|
},
|
|
126
|
-
setWidget() {
|
|
189
|
+
setWidget(_key, rows) {
|
|
190
|
+
uiSnapshot.rows = rows ?? [];
|
|
191
|
+
publishUi();
|
|
192
|
+
},
|
|
127
193
|
},
|
|
128
194
|
},
|
|
129
195
|
// The status ticker keeps running while a capture is alive, which outlives
|
|
@@ -167,7 +233,7 @@ async function callTool(
|
|
|
167
233
|
}
|
|
168
234
|
}
|
|
169
235
|
|
|
170
|
-
async function handle(message: Record<string, unknown
|
|
236
|
+
async function handle(message: Record<string, unknown>, controller?: AbortController): Promise<void> {
|
|
171
237
|
const id = message.id;
|
|
172
238
|
const method = message.method;
|
|
173
239
|
// Notifications carry no id and must never be answered.
|
|
@@ -187,7 +253,7 @@ async function handle(message: Record<string, unknown>): Promise<void> {
|
|
|
187
253
|
return;
|
|
188
254
|
}
|
|
189
255
|
if (method === "tools/list") {
|
|
190
|
-
reply(id, { tools: [{ name: "xcodebug", description: tool.description, inputSchema }] });
|
|
256
|
+
reply(id, { tools: [{ name: "xcodebug", description: tool.description, inputSchema }, uiTool] });
|
|
191
257
|
return;
|
|
192
258
|
}
|
|
193
259
|
if (method === "tools/call") {
|
|
@@ -200,16 +266,14 @@ async function handle(message: Record<string, unknown>): Promise<void> {
|
|
|
200
266
|
replyError(id, -32602, `Unknown tool "${params.name ?? ""}"`);
|
|
201
267
|
return;
|
|
202
268
|
}
|
|
203
|
-
// Registered before the call starts so a cancellation that arrives while it
|
|
204
|
-
// runs finds the controller; `finally` keeps the map from growing.
|
|
205
|
-
const controller = new AbortController();
|
|
206
|
-
inflight.set(id, controller);
|
|
207
269
|
try {
|
|
208
|
-
|
|
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));
|
|
209
275
|
} catch (error) {
|
|
210
276
|
reply(id, { content: [{ type: "text", text: (error as Error).message }], isError: true });
|
|
211
|
-
} finally {
|
|
212
|
-
inflight.delete(id);
|
|
213
277
|
}
|
|
214
278
|
return;
|
|
215
279
|
}
|
|
@@ -219,9 +283,49 @@ async function handle(message: Record<string, unknown>): Promise<void> {
|
|
|
219
283
|
// Requests are serialized: a capture's state is a plain map, and two overlapping
|
|
220
284
|
// calls (launch + stop) would interleave mutations on it.
|
|
221
285
|
let queue: Promise<void> = Promise.resolve();
|
|
222
|
-
/**
|
|
286
|
+
/** Admitted calls, including queued calls, so cancellation cannot miss one. */
|
|
223
287
|
const inflight = new Map<unknown, AbortController>();
|
|
224
|
-
|
|
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;
|
|
225
329
|
const text = line.trim();
|
|
226
330
|
if (text.length === 0) return;
|
|
227
331
|
let message: Record<string, unknown>;
|
|
@@ -231,6 +335,17 @@ createInterface({ input: process.stdin }).on("line", (line) => {
|
|
|
231
335
|
replyError(null, -32700, "Parse error");
|
|
232
336
|
return;
|
|
233
337
|
}
|
|
338
|
+
// UI reads must remain responsive during a build/install/wait and must never
|
|
339
|
+
// replace state.uiCtx with the context of a polling call.
|
|
340
|
+
if (message.method === "tools/call" &&
|
|
341
|
+
(message.params as { name?: string } | undefined)?.name === uiTool.name) {
|
|
342
|
+
if (message.id !== undefined) {
|
|
343
|
+
reply(message.id, {
|
|
344
|
+
content: [{ type: "text", text: JSON.stringify({ ...uiSnapshot, seq: uiSeq, file: uiFile }) }],
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
234
349
|
// Handled here rather than in handle(): the queue serializes calls, so a
|
|
235
350
|
// cancellation queued behind the very call it targets could never arrive in
|
|
236
351
|
// time. It is a notification, so nothing is sent back.
|
|
@@ -239,7 +354,16 @@ createInterface({ input: process.stdin }).on("line", (line) => {
|
|
|
239
354
|
inflight.get(requestId)?.abort();
|
|
240
355
|
return;
|
|
241
356
|
}
|
|
242
|
-
|
|
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) => {
|
|
243
367
|
console.error("xcodebug-mcp:", error);
|
|
244
368
|
});
|
|
245
369
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "xcodebug",
|
|
3
|
-
"version": "1.2.
|
|
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": [
|
|
@@ -28,6 +28,8 @@
|
|
|
28
28
|
"files": [
|
|
29
29
|
"*.ts",
|
|
30
30
|
"mcp/",
|
|
31
|
+
"skills/",
|
|
32
|
+
"claude/",
|
|
31
33
|
"README.md",
|
|
32
34
|
"GUIDE.md",
|
|
33
35
|
"LICENSE"
|
|
@@ -35,6 +37,9 @@
|
|
|
35
37
|
"engines": {
|
|
36
38
|
"node": ">=20"
|
|
37
39
|
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"test": "node --test tests/*.test.mjs"
|
|
42
|
+
},
|
|
38
43
|
"omp": {
|
|
39
44
|
"extensions": [
|
|
40
45
|
"./index.ts"
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
---
|
|
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."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# xcodebug
|
|
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.
|
|
13
|
+
|
|
14
|
+
## Dispatch the request
|
|
15
|
+
|
|
16
|
+
Read the request following `/xcodebug` in Claude Code or `$xcodebug` in Codex.
|
|
17
|
+
Both explicit invocation and a matching natural-language request can use this skill.
|
|
18
|
+
|
|
19
|
+
- 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;
|
|
21
|
+
report a launch error without substituting a status query or another action.
|
|
22
|
+
- 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
|
|
24
|
+
parameters immediately. Do not replace execution with instructions for the user.
|
|
25
|
+
- Accept `action [key=value ...]`, `action=... [key=value ...]`, or a JSON parameter
|
|
26
|
+
object. Actions: `doctor`, `devices`, `changes`, `build`, `install`, `launch`,
|
|
27
|
+
`syslog`, `logs`, `wait`, `status`, `stop`, `terminate`, `restart`, `await`.
|
|
28
|
+
- Use the live tool schema for parameter names and types. Preserve quoted strings,
|
|
29
|
+
numeric `since`/`limit`/`timeoutSeconds`, booleans, JSON `args` arrays and
|
|
30
|
+
`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,
|
|
35
|
+
and stop, including on error. Do not add diagnostic `status` calls or retry
|
|
36
|
+
with another action unless the user asks. `logs` never authorizes launching
|
|
37
|
+
an app, and `launch` does not imply an immediate `stop`.
|
|
38
|
+
- For a natural-language verification goal, use `launch` with known project/device
|
|
39
|
+
parameters, then collect evidence for that goal. The goal describes what to
|
|
40
|
+
verify; do not use the entire sentence as a literal log filter. If the app must
|
|
41
|
+
keep running, use `syslog` with its known process name instead of `launch`.
|
|
42
|
+
|
|
43
|
+
## Examples
|
|
44
|
+
|
|
45
|
+
| Request after the skill name | MCP arguments |
|
|
46
|
+
|---|---|
|
|
47
|
+
| *(no arguments)* | `{"action":"launch"}` |
|
|
48
|
+
| `status` | `{"action":"status"}` |
|
|
49
|
+
| `doctor` | `{"action":"doctor"}` |
|
|
50
|
+
| `launch scheme=MyApp device="My iPhone"` | `{"action":"launch","scheme":"MyApp","device":"My iPhone"}` |
|
|
51
|
+
| `logs captureId=console-123 since=42 limit=100 grep="Weather Sync"` | `{"action":"logs","captureId":"console-123","since":42,"limit":100,"grep":"Weather Sync"}` |
|
|
52
|
+
| `wait match="sync complete" timeoutSeconds=30` | `{"action":"wait","match":"sync complete","timeoutSeconds":30}` |
|
|
53
|
+
| `stop captureId=console-123 keepApp=true` | `{"action":"stop","captureId":"console-123","keepApp":true}` |
|
|
54
|
+
| `restart` | `{"action":"restart"}` |
|
|
55
|
+
|
|
56
|
+
## Follow a capture
|
|
57
|
+
|
|
58
|
+
- `launch` restarts the app and captures stdout/stderr plus os_log. `syslog`
|
|
59
|
+
attaches without restarting. `stop` leaves the app running by default;
|
|
60
|
+
`terminate` explicitly terminates it. `restart` reuses this server's last launch
|
|
61
|
+
and forces a rebuild; a saved `command` runs again.
|
|
62
|
+
- Track `captureId` and the returned cursor **per capture**. Pass that cursor as
|
|
63
|
+
`since` on the next incremental read; never reuse another capture's cursor.
|
|
64
|
+
`logs` returns the newest matching lines up to `limit` and advances to the
|
|
65
|
+
latest capture cursor, so omitted or evicted lines will not reappear merely
|
|
66
|
+
by advancing `since`. Report omissions instead of claiming a lossless stream.
|
|
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
|
|
73
|
+
that a test finished. While waiting for the user to operate the phone, tell them
|
|
74
|
+
the required action and keep the capture running.
|
|
75
|
+
- For an automated scenario, pass the user's `command` to `launch`, or use `await`
|
|
76
|
+
with the current capture. The command must not relaunch the app itself, since
|
|
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.
|
|
84
|
+
- When a verification goal is answered, stop the capture started for that goal.
|
|
85
|
+
Include its `captureId` so other captures are not stopped. An explicit `stop`
|
|
86
|
+
without an ID intentionally stops all running captures in this server.
|
|
87
|
+
- Report the operation's result, relevant log evidence, capture ID/cursor or log
|
|
88
|
+
path when returned, and whether capture remains active. Do not invent device
|
|
89
|
+
activity, successful builds, or test outcomes.
|
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: (
|
|
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${
|
|
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 {
|