xcodebug 0.0.0-stage → 1.0.0
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 +213 -0
- package/LICENSE +21 -0
- package/README.md +449 -2
- package/archive.ts +164 -0
- package/capture.ts +327 -0
- package/changes.ts +368 -0
- package/devices.ts +278 -0
- package/exec.ts +122 -0
- package/index.ts +2274 -0
- package/package.json +52 -4
- package/progress.ts +171 -0
- package/xcode.ts +220 -0
package/index.ts
ADDED
|
@@ -0,0 +1,2274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xcodebug — drive a physical iOS device build/launch and stream its Xcode
|
|
3
|
+
* console output into the current agent session.
|
|
4
|
+
*
|
|
5
|
+
* Console capture uses `xcrun devicectl device process launch --console` with
|
|
6
|
+
* OS_ACTIVITY_DT_MODE=YES, which bridges the app's stdout/stderr plus os_log —
|
|
7
|
+
* the same surface Xcode's debug console shows. No jailbreak, no debugger.
|
|
8
|
+
*/
|
|
9
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
10
|
+
import { basename, dirname, join } from "node:path";
|
|
11
|
+
// `import type` is erased at compile time, so this specifier never reaches the
|
|
12
|
+
// runtime: it only has to name a module the loader can resolve for typechecking.
|
|
13
|
+
// `@earendil-works/pi-coding-agent` is the official one the engine documents for
|
|
14
|
+
// extensions; `@code-yeongyu/senpi` and the `@mariozechner/*` names are aliases
|
|
15
|
+
// the loader maps to the same module, so a fork-only name would tie this file to
|
|
16
|
+
// one distribution of the engine.
|
|
17
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import { Type } from "typebox";
|
|
19
|
+
import { Capture, type LogLine } from "./capture";
|
|
20
|
+
import { describeDevices, findProcessPid, listDevices, lookupProcess, resolveDevice, type DeviceInfo } from "./devices";
|
|
21
|
+
import { lastLines, runCommand, timestamp } from "./exec";
|
|
22
|
+
import { buildForDevice, consoleLaunchArgs, installApp, terminateApp, type BuildTarget } from "./xcode";
|
|
23
|
+
import { checkPodLockSync, describeChanges, detectChanges, runPodInstall, type ChangeReport } from "./changes";
|
|
24
|
+
import { clearArchives } from "./archive";
|
|
25
|
+
|
|
26
|
+
const CAPTURE_PREFIX = "xcodebug";
|
|
27
|
+
const PUSH_INTERVAL_MS = 4_000;
|
|
28
|
+
const PUSH_MAX_LINES = 80;
|
|
29
|
+
/** How long a verification run may go quiet before we ask the user about it. */
|
|
30
|
+
const SILENCE_NOTICE_MS = 60_000;
|
|
31
|
+
/**
|
|
32
|
+
* How long the syslog channel may emit nothing before its bridge is presumed
|
|
33
|
+
* hung and restarted. The idevicesyslog process has been observed to stop
|
|
34
|
+
* mid-run while still alive; the app was healthy and the console channel kept
|
|
35
|
+
* producing lines, so only the syslog side needs this.
|
|
36
|
+
*/
|
|
37
|
+
const SYSLOG_SILENCE_MS = 30_000;
|
|
38
|
+
|
|
39
|
+
interface ProjectConfig {
|
|
40
|
+
workspace?: string;
|
|
41
|
+
project?: string;
|
|
42
|
+
scheme?: string;
|
|
43
|
+
configuration?: string;
|
|
44
|
+
bundleId?: string;
|
|
45
|
+
device?: string;
|
|
46
|
+
derivedDataPath?: string;
|
|
47
|
+
args?: string[];
|
|
48
|
+
environment?: Record<string, string>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
interface SessionState {
|
|
53
|
+
captures: Map<string, Capture>;
|
|
54
|
+
activeCaptureId?: string;
|
|
55
|
+
pushTimers: Map<string, ReturnType<typeof setInterval>>;
|
|
56
|
+
pushCursors: Map<string, number>;
|
|
57
|
+
/** Fingerprint of the working tree at the last successful build in this session. */
|
|
58
|
+
lastBuiltFingerprint?: string;
|
|
59
|
+
/** Key of the new-component-file set pod install has already handled. */
|
|
60
|
+
installedPodsFingerprint?: string;
|
|
61
|
+
/** console capture id -> parallel syslog capture id. */
|
|
62
|
+
companions: Map<string, string>;
|
|
63
|
+
/** capture id -> timestamp of the last line seen by the push loop. */
|
|
64
|
+
lastLineAt: Map<string, number>;
|
|
65
|
+
/** Captures already reminded about silence, so the notice fires once. */
|
|
66
|
+
silenceNotified: Set<string>;
|
|
67
|
+
/** Capture id -> last few log lines, for the status widget. */
|
|
68
|
+
recentLines: Map<string, string[]>;
|
|
69
|
+
/** The ctx of the latest tool/command call, used to refresh UI status. */
|
|
70
|
+
uiCtx?: ExtensionContext;
|
|
71
|
+
/** Drives the status repaint so counters move even when pushing is off. */
|
|
72
|
+
statusTimer?: ReturnType<typeof setInterval>;
|
|
73
|
+
/** capture id -> syslog silence watchdog. */
|
|
74
|
+
watchdogs: Map<string, ReturnType<typeof setInterval>>;
|
|
75
|
+
/**
|
|
76
|
+
* What a `restart` needs in order to relaunch the same app.
|
|
77
|
+
*
|
|
78
|
+
* `/xcodebug restart` is the mid-run answer to "I just changed the code": it
|
|
79
|
+
* rebuilds, relaunches and reattaches without the user retyping the phrase or
|
|
80
|
+
* the device. Holds one launch - the most recent in this session - which is
|
|
81
|
+
* what the edit/restart loop needs; launching a second app replaces it, so
|
|
82
|
+
* `restart` always targets the app launched last.
|
|
83
|
+
*/
|
|
84
|
+
lastLaunch?: {
|
|
85
|
+
bundleId: string;
|
|
86
|
+
processName?: string;
|
|
87
|
+
goal?: string;
|
|
88
|
+
args?: string[];
|
|
89
|
+
environment?: Record<string, string>;
|
|
90
|
+
device?: string;
|
|
91
|
+
scheme?: string;
|
|
92
|
+
workspace?: string;
|
|
93
|
+
project?: string;
|
|
94
|
+
configuration?: string;
|
|
95
|
+
derivedDataPath?: string;
|
|
96
|
+
push?: "off" | "context" | "wake";
|
|
97
|
+
match?: string;
|
|
98
|
+
dualChannel?: boolean;
|
|
99
|
+
/**
|
|
100
|
+
* The shell line this run was started with, if any.
|
|
101
|
+
*
|
|
102
|
+
* A `restart` after a code edit is usually the first half of an
|
|
103
|
+
* edit→restart→test loop; dropping the command would force the user to
|
|
104
|
+
* retype it every cycle.
|
|
105
|
+
*/
|
|
106
|
+
command?: string;
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* What the run is doing before any capture exists (pod install, building,
|
|
110
|
+
* installing). Rendered in the same footer/widget the captures later use, so
|
|
111
|
+
* the status line is continuous from build through verification instead of a
|
|
112
|
+
* stream of one-off messages.
|
|
113
|
+
*/
|
|
114
|
+
runPhase?: { label: string; startedAt: number };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Where this extension writes its logs.
|
|
119
|
+
*
|
|
120
|
+
* `ctx.agentDir` is declared on ExtensionContext but not every runtime populates
|
|
121
|
+
* it: omp 18.12.6 builds the tool context from `cwd`, `sessionManager`, `ui` and
|
|
122
|
+
* friends and leaves `agentDir` undefined. `join(undefined, ...)` then throws
|
|
123
|
+
* Bun's `The "paths[0]" property must be of type string, got undefined` out of
|
|
124
|
+
* every action that touches a log path - including `doctor`, which never
|
|
125
|
+
* resolves a scheme - and the raw message names no field the user could fix.
|
|
126
|
+
*
|
|
127
|
+
* The fallback must not hardcode a brand (`.pi`, `.omp`, `.omo`, `.senpi` are all
|
|
128
|
+
* this same engine): xcodebug is a generic pi extension. So derive it from what
|
|
129
|
+
* the host does tell us, in order:
|
|
130
|
+
* 1. `ctx.agentDir`, when the runtime supplies it;
|
|
131
|
+
* 2. the session directory's parent - every brand stores sessions at
|
|
132
|
+
* `<agentDir>/sessions/<encoded-cwd>`, so the layout is the invariant;
|
|
133
|
+
* 3. the `<PREFIX>_CODING_AGENT_DIR` override the host itself honours
|
|
134
|
+
* (senpi names it `${ENV_PREFIX}_CODING_AGENT_DIR`, prefix per brand).
|
|
135
|
+
* Failing all three, throw with the missing input named: logging to a guessed
|
|
136
|
+
* path would drop build and console logs somewhere nobody looks.
|
|
137
|
+
*/
|
|
138
|
+
function resolveAgentDir(ctx: ExtensionContext): string {
|
|
139
|
+
// `agentDir` is not part of the published ExtensionContext (pi 1.4.0 has only
|
|
140
|
+
// `cwd` and `sessionManager`); some hosts add it. `in` keeps this compiling
|
|
141
|
+
// against the published types while still honouring a host that supplies it.
|
|
142
|
+
if ("agentDir" in ctx) {
|
|
143
|
+
const direct = ctx.agentDir;
|
|
144
|
+
if (typeof direct === "string" && direct.length > 0) return direct;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
const sessionDir = ctx.sessionManager?.getSessionDir?.();
|
|
149
|
+
if (typeof sessionDir === "string" && sessionDir.length > 0) {
|
|
150
|
+
const parent = dirname(sessionDir);
|
|
151
|
+
// Default layout is `<agentDir>/sessions/<encoded-cwd>`, so the agent dir is
|
|
152
|
+
// the grandparent. A host run with an explicit session store (`--session-dir`
|
|
153
|
+
// or PI_CODING_AGENT_SESSION_DIR) points getSessionDir straight at that store
|
|
154
|
+
// with no per-cwd level, and the analogue of the agent dir is its parent.
|
|
155
|
+
// Without this branch such a host made every action that writes a log throw.
|
|
156
|
+
return basename(parent) === "sessions" ? dirname(parent) : parent;
|
|
157
|
+
}
|
|
158
|
+
} catch {
|
|
159
|
+
// No session manager in this context; try the environment override.
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
for (const [name, value] of Object.entries(process.env)) {
|
|
163
|
+
if (!name.endsWith("_CODING_AGENT_DIR")) continue;
|
|
164
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
throw new Error(
|
|
168
|
+
"xcodebug cannot locate the agent directory to write logs into: the runtime supplied no " +
|
|
169
|
+
"ctx.agentDir, no session directory and no *_CODING_AGENT_DIR override.",
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The project directory every file lookup is anchored to.
|
|
175
|
+
*
|
|
176
|
+
* The anchor is the tool context's `cwd`, which the published types declare and
|
|
177
|
+
* every host populates. `pi.cwd` is not in the published `ExtensionAPI` (pi 1.4.0
|
|
178
|
+
* omits it), so it is only consulted when a host happens to add it; the process
|
|
179
|
+
* cwd is the last resort. Reading the wrong one here is not cosmetic:
|
|
180
|
+
* `detectContainer(undefined)` walks nowhere, and build/launch then fail with
|
|
181
|
+
* "No scheme found. Container: (none)" even from inside the workspace.
|
|
182
|
+
*/
|
|
183
|
+
function resolveProjectRoot(pi: ExtensionAPI, ctx?: ExtensionContext): string {
|
|
184
|
+
// `ctx.cwd` is the published field; `pi.cwd` is an addition some hosts carry.
|
|
185
|
+
const fromCtx = ctx?.cwd;
|
|
186
|
+
if (typeof fromCtx === "string" && fromCtx.length > 0) return fromCtx;
|
|
187
|
+
if ("cwd" in pi) {
|
|
188
|
+
const fromPi = pi.cwd;
|
|
189
|
+
if (typeof fromPi === "string" && fromPi.length > 0) return fromPi;
|
|
190
|
+
}
|
|
191
|
+
return process.cwd();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function logDir(ctx: ExtensionContext): string {
|
|
195
|
+
return join(resolveAgentDir(ctx), "logs", "xcodebug");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Where pulled device archives live. Shared by the puller and the cleaner. */
|
|
199
|
+
function archiveWorkDir(ctx: ExtensionContext): string {
|
|
200
|
+
return join(logDir(ctx), "archive");
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Drop the previous run's archives now that a new build has landed.
|
|
205
|
+
*
|
|
206
|
+
* Every snapshot covers the device's last hour and they overlap almost fully,
|
|
207
|
+
* so old ones explain nothing about the run that is starting and only cost
|
|
208
|
+
* disk. A new build is the natural boundary: whatever happened before it
|
|
209
|
+
* belongs to a different binary.
|
|
210
|
+
*/
|
|
211
|
+
async function clearArchiveBeforeNewRun(ctx: ExtensionContext): Promise<string> {
|
|
212
|
+
const { removed, freedBytes } = await clearArchives(archiveWorkDir(ctx));
|
|
213
|
+
if (removed === 0) return "archive: nothing to clear";
|
|
214
|
+
const mb = (freedBytes / 1024 / 1024).toFixed(0);
|
|
215
|
+
return `archive: cleared ${removed} snapshot(s), freed ${mb} MB`;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function readBundleExecutable(appPath: string): Promise<string | undefined> {
|
|
219
|
+
const result = await runCommand(
|
|
220
|
+
"/usr/libexec/PlistBuddy",
|
|
221
|
+
["-c", "Print :CFBundleExecutable", join(appPath, "Info.plist")],
|
|
222
|
+
{ timeoutMs: 15_000 },
|
|
223
|
+
);
|
|
224
|
+
const value = result.code === 0 ? result.stdout.trim() : "";
|
|
225
|
+
return value.length > 0 ? value : undefined;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Read CFBundleIdentifier from a built .app, so launch works with only appPath. */
|
|
229
|
+
async function readBundleIdentifier(appPath: string): Promise<string | undefined> {
|
|
230
|
+
const result = await runCommand(
|
|
231
|
+
"/usr/libexec/PlistBuddy",
|
|
232
|
+
["-c", "Print :CFBundleIdentifier", join(appPath, "Info.plist")],
|
|
233
|
+
{ timeoutMs: 15_000 },
|
|
234
|
+
);
|
|
235
|
+
const value = result.code === 0 ? result.stdout.trim() : "";
|
|
236
|
+
return value.length > 0 ? value : undefined;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function readConfig(cwd: string): Promise<ProjectConfig> {
|
|
240
|
+
try {
|
|
241
|
+
return JSON.parse(await readFile(join(cwd, ".xcodebug.json"), "utf8")) as ProjectConfig;
|
|
242
|
+
} catch {
|
|
243
|
+
return {};
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Find the Xcode container that owns this directory.
|
|
249
|
+
*
|
|
250
|
+
* Walks up from cwd. Which container to use is decided by CocoaPods, not by
|
|
251
|
+
* what happens to be on disk:
|
|
252
|
+
* - a directory holding `Podfile` or `Podfile.lock` is a CocoaPods project,
|
|
253
|
+
* and its `.xcworkspace` is the container that links the Pods targets;
|
|
254
|
+
* - otherwise a plain `.xcodeproj` is used as-is.
|
|
255
|
+
*
|
|
256
|
+
* Scanning only cwd fails as soon as the user runs the command from a
|
|
257
|
+
* subdirectory, so the walk covers up to 8 levels.
|
|
258
|
+
*/
|
|
259
|
+
async function detectContainer(cwd: string): Promise<{
|
|
260
|
+
workspace?: string;
|
|
261
|
+
project?: string;
|
|
262
|
+
cocoaPods: boolean;
|
|
263
|
+
/** App containers found below cwd when more than one matched. */
|
|
264
|
+
ambiguous?: string[];
|
|
265
|
+
}> {
|
|
266
|
+
let dir = cwd;
|
|
267
|
+
for (let depth = 0; depth < 8; depth += 1) {
|
|
268
|
+
let entries: import("node:fs").Dirent[];
|
|
269
|
+
try {
|
|
270
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
271
|
+
} catch {
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
274
|
+
const names = new Set(entries.map((e) => e.name));
|
|
275
|
+
const isCocoaPods = names.has("Podfile") || names.has("Podfile.lock");
|
|
276
|
+
const workspace = entries.find((e) => e.isDirectory() && e.name.endsWith(".xcworkspace"));
|
|
277
|
+
const project = entries.find((e) => e.isDirectory() && e.name.endsWith(".xcodeproj"));
|
|
278
|
+
|
|
279
|
+
if (isCocoaPods) {
|
|
280
|
+
// CocoaPods project: the workspace is required. If it is missing, the
|
|
281
|
+
// user still needs `pod install`, but the project is the only container.
|
|
282
|
+
if (workspace) return { workspace: join(dir, workspace.name), cocoaPods: true };
|
|
283
|
+
if (project) return { project: join(dir, project.name), cocoaPods: true };
|
|
284
|
+
} else if (project) {
|
|
285
|
+
return { project: join(dir, project.name), cocoaPods: false };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const parent = dirname(dir);
|
|
289
|
+
if (parent === dir) break;
|
|
290
|
+
dir = parent;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Nothing above qualified. A monorepo can keep its app one level down (this
|
|
294
|
+
// repo has Example/ here and no container at the root at all).
|
|
295
|
+
const below = await findAppContainerBelow(cwd);
|
|
296
|
+
if (below.container) return below.container;
|
|
297
|
+
return { cocoaPods: false, ambiguous: below.ambiguous };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Look for the app container *below* cwd, used only when the upward walk found
|
|
302
|
+
* nothing.
|
|
303
|
+
*
|
|
304
|
+
* The signature is deliberately narrow: a directory counts only if it holds a
|
|
305
|
+
* `Podfile` and an `.xcworkspace` side by side. That is what an app project
|
|
306
|
+
* looks like, and it excludes the pod-only projects a monorepo is full of
|
|
307
|
+
* (`Projects/*` here - about a hundred of them - none of which has a Podfile),
|
|
308
|
+
* so they cannot be picked by accident.
|
|
309
|
+
*
|
|
310
|
+
* Ambiguity is reported rather than resolved: choosing which app to build is
|
|
311
|
+
* not a decision this function is entitled to make.
|
|
312
|
+
*/
|
|
313
|
+
async function findAppContainerBelow(cwd: string): Promise<{
|
|
314
|
+
container?: { workspace?: string; project?: string; cocoaPods: boolean };
|
|
315
|
+
ambiguous: string[];
|
|
316
|
+
}> {
|
|
317
|
+
const matches: Array<{ workspace: string; dir: string }> = [];
|
|
318
|
+
const SKIP = new Set(["Pods", "Carthage", "node_modules", ".git", "build", "DerivedData"]);
|
|
319
|
+
|
|
320
|
+
const scan = async (dir: string, depth: number): Promise<void> => {
|
|
321
|
+
if (depth > 2) return;
|
|
322
|
+
let entries: import("node:fs").Dirent[];
|
|
323
|
+
try {
|
|
324
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
325
|
+
} catch {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const names = new Set(entries.map((e) => e.name));
|
|
329
|
+
if (names.has("Podfile")) {
|
|
330
|
+
const workspace = entries.find((e) => e.isDirectory() && e.name.endsWith(".xcworkspace"));
|
|
331
|
+
if (workspace) {
|
|
332
|
+
matches.push({ workspace: join(dir, workspace.name), dir });
|
|
333
|
+
// A matched app is the answer for its subtree; do not look inside it.
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
for (const entry of entries) {
|
|
338
|
+
if (!entry.isDirectory()) continue;
|
|
339
|
+
if (entry.name.startsWith(".") || SKIP.has(entry.name)) continue;
|
|
340
|
+
if (entry.name.endsWith(".xcodeproj") || entry.name.endsWith(".xcworkspace")) continue;
|
|
341
|
+
await scan(join(dir, entry.name), depth + 1);
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
await scan(cwd, 0);
|
|
346
|
+
if (matches.length === 1) return { container: { workspace: matches[0].workspace, cocoaPods: true }, ambiguous: [] };
|
|
347
|
+
return { ambiguous: matches.map((m) => m.dir) };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
/**
|
|
352
|
+
* How a new capture mirrors lines into the session.
|
|
353
|
+
*
|
|
354
|
+
* A verification run is useless if its logs never arrive, so pushing is the
|
|
355
|
+
* default for both launch and syslog; only an explicit `push=off` opts out.
|
|
356
|
+
* Kept in one place so the tool path and the /xcodebug path cannot disagree.
|
|
357
|
+
*/
|
|
358
|
+
function defaultPushMode(params: { push?: "off" | "context" | "wake" }): "off" | "context" | "wake" {
|
|
359
|
+
return params.push ?? "context";
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Pick the scheme to build.
|
|
364
|
+
*
|
|
365
|
+
* This repo's convention is that the workspace and its app scheme share a name
|
|
366
|
+
* (`MyApp.xcworkspace` -> scheme `MyApp`), so the container's own
|
|
367
|
+
* name is the first guess. It is only a guess: a component demo's workspace
|
|
368
|
+
* name need not match a scheme, so `withContainer` verifies it against
|
|
369
|
+
* `xcodebuild -list` and falls back to reading the scheme files.
|
|
370
|
+
*/
|
|
371
|
+
function schemeFromContainer(container: string): string | undefined {
|
|
372
|
+
const name = container.split("/").pop()?.replace(/\.(xcworkspace|xcodeproj)$/, "");
|
|
373
|
+
return name && name.length > 0 ? name : undefined;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* The scheme that builds an installable `.app`, read from the scheme files.
|
|
378
|
+
*
|
|
379
|
+
* A workspace can list hundreds of pod schemes, and probing each with
|
|
380
|
+
* `-showBuildSettings` takes seconds apiece, so this reads the XML instead:
|
|
381
|
+
* an app scheme declares its product as `BuildableName = "X.app"`.
|
|
382
|
+
*
|
|
383
|
+
* A workspace usually holds no schemes of its own: the schemes live in the
|
|
384
|
+
* sibling `.xcodeproj` that the workspace wraps (in this repo,
|
|
385
|
+
* `MyApp.xcworkspace` has none while `MyApp.xcodeproj` has them), so
|
|
386
|
+
* both are scanned.
|
|
387
|
+
*/
|
|
388
|
+
async function appSchemeFromFiles(containerPath: string): Promise<{
|
|
389
|
+
scheme?: string;
|
|
390
|
+
/** Directories that were searched, so a failure can say where it looked. */
|
|
391
|
+
searched: string[];
|
|
392
|
+
}> {
|
|
393
|
+
const candidates: string[] = [];
|
|
394
|
+
const searched: string[] = [];
|
|
395
|
+
// A workspace wraps its .xcodeproj and usually keeps no schemes itself, so the
|
|
396
|
+
// sibling project (same directory, same base name) is scanned too.
|
|
397
|
+
const roots = [containerPath];
|
|
398
|
+
if (containerPath.endsWith(".xcworkspace")) {
|
|
399
|
+
const sibling = containerPath.replace(/\.xcworkspace$/, ".xcodeproj");
|
|
400
|
+
try {
|
|
401
|
+
await readdir(sibling);
|
|
402
|
+
roots.push(sibling);
|
|
403
|
+
} catch {
|
|
404
|
+
// No sibling project; the workspace's own schemes are all there is.
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const dirs: string[] = [];
|
|
408
|
+
for (const root of roots) {
|
|
409
|
+
dirs.push(join(root, "xcshareddata", "xcschemes"));
|
|
410
|
+
const users = join(root, "xcuserdata");
|
|
411
|
+
try {
|
|
412
|
+
for (const entry of await readdir(users, { withFileTypes: true })) {
|
|
413
|
+
if (entry.isDirectory() && entry.name.endsWith(".xcuserdatad")) {
|
|
414
|
+
dirs.push(join(users, entry.name, "xcschemes"));
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
} catch {
|
|
418
|
+
// No per-user schemes; the shared directory is still worth trying.
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
for (const dir of dirs) {
|
|
422
|
+
searched.push(dir);
|
|
423
|
+
try {
|
|
424
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
425
|
+
if (!entry.isFile() || !entry.name.endsWith(".xcscheme")) continue;
|
|
426
|
+
const file = join(dir, entry.name);
|
|
427
|
+
try {
|
|
428
|
+
const xml = await readFile(file, "utf8");
|
|
429
|
+
if (/BuildableName\s*=\s*"[^"]*\.app"/.test(xml)) {
|
|
430
|
+
candidates.push(entry.name.replace(/\.xcscheme$/, ""));
|
|
431
|
+
}
|
|
432
|
+
} catch {
|
|
433
|
+
// An unreadable scheme is simply not a candidate; the error surfaces
|
|
434
|
+
// through the "searched" list when nothing is found at all.
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
} catch {
|
|
438
|
+
// Directory absent or unreadable - recorded in `searched` either way.
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return { scheme: candidates[0], searched };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Ask xcodebuild for the schemes it knows.
|
|
446
|
+
*
|
|
447
|
+
* The three outcomes must stay distinct: "listed, and the guess is there",
|
|
448
|
+
* "listed, and it is not", and "could not list". Collapsing the last into an
|
|
449
|
+
* empty list made a failed `xcodebuild -list` silently accept a guessed scheme,
|
|
450
|
+
* which then failed later with an unrelated-looking build error.
|
|
451
|
+
*/
|
|
452
|
+
async function listSchemes(
|
|
453
|
+
container: { workspace?: string; project?: string },
|
|
454
|
+
cwd: string,
|
|
455
|
+
): Promise<{ ok: boolean; schemes: string[]; reason?: string }> {
|
|
456
|
+
const flag = container.workspace ? "-workspace" : "-project";
|
|
457
|
+
const path = container.workspace ?? container.project;
|
|
458
|
+
if (!path) return { ok: false, schemes: [], reason: "no container" };
|
|
459
|
+
const result = await runCommand("xcodebuild", [flag, path, "-list", "-json"], { cwd, timeoutMs: 120_000 });
|
|
460
|
+
if (result.code !== 0) {
|
|
461
|
+
return {
|
|
462
|
+
ok: false,
|
|
463
|
+
schemes: [],
|
|
464
|
+
reason: `xcodebuild -list exited ${result.code}: ${(result.stderr || result.stdout).trim().slice(0, 200)}`,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
try {
|
|
468
|
+
const parsed = JSON.parse(result.stdout) as {
|
|
469
|
+
workspace?: { schemes?: string[] };
|
|
470
|
+
project?: { schemes?: string[] };
|
|
471
|
+
};
|
|
472
|
+
return { ok: true, schemes: parsed.workspace?.schemes ?? parsed.project?.schemes ?? [] };
|
|
473
|
+
} catch {
|
|
474
|
+
return { ok: false, schemes: [], reason: "xcodebuild -list returned unparseable JSON" };
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function resolveBuildTarget(config: ProjectConfig, params: {
|
|
479
|
+
scheme?: string;
|
|
480
|
+
workspace?: string;
|
|
481
|
+
project?: string;
|
|
482
|
+
configuration?: string;
|
|
483
|
+
derivedDataPath?: string;
|
|
484
|
+
extraArgs?: string[];
|
|
485
|
+
}): BuildTarget {
|
|
486
|
+
const scheme = params.scheme ?? config.scheme;
|
|
487
|
+
if (!scheme) {
|
|
488
|
+
throw new Error(
|
|
489
|
+
'No scheme: pass scheme, or add "scheme" to .xcodebug.json in the project root. ' +
|
|
490
|
+
"List schemes with: xcodebuild -workspace <path>.xcworkspace -list",
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
return {
|
|
494
|
+
scheme,
|
|
495
|
+
workspace: params.workspace ?? config.workspace,
|
|
496
|
+
project: params.project ?? config.project,
|
|
497
|
+
configuration: params.configuration ?? config.configuration ?? "Debug",
|
|
498
|
+
derivedDataPath: params.derivedDataPath ?? config.derivedDataPath,
|
|
499
|
+
extraArgs: params.extraArgs,
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function formatLogLines(capture: Capture, since: number, limit: number, grep?: string): {
|
|
504
|
+
text: string;
|
|
505
|
+
cursor: number;
|
|
506
|
+
total: number;
|
|
507
|
+
} {
|
|
508
|
+
const read = capture.read({ since, limit, grep });
|
|
509
|
+
if (read.lines.length === 0) {
|
|
510
|
+
return { text: `(no new lines since ${since}; capture cursor is ${read.cursor})`, cursor: read.cursor, total: 0 };
|
|
511
|
+
}
|
|
512
|
+
const body = read.lines
|
|
513
|
+
.map((line) => {
|
|
514
|
+
// In console mode devicectl's own status lines arrive on stdout while the
|
|
515
|
+
// app's output arrives on stderr, so only stdout needs a label.
|
|
516
|
+
const tag = capture.mode === "console" && line.stream === "out" ? "[devicectl] " : "";
|
|
517
|
+
return `${String(line.index).padStart(6, " ")} ${tag}${line.text}`;
|
|
518
|
+
})
|
|
519
|
+
.join("\n");
|
|
520
|
+
const omitted = read.total - read.lines.length;
|
|
521
|
+
const header = `${read.lines.length} line(s)${omitted > 0 ? ` (${omitted} older omitted)` : ""} · cursor ${read.cursor}`;
|
|
522
|
+
return { text: `${header}\n${body}`, cursor: read.cursor, total: read.total };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Fill in the container when the caller and the config both omit it. */
|
|
526
|
+
async function withContainer(
|
|
527
|
+
cwd: string,
|
|
528
|
+
config: ProjectConfig,
|
|
529
|
+
params: { scheme?: string; workspace?: string; project?: string; configuration?: string; derivedDataPath?: string; extraArgs?: string[] },
|
|
530
|
+
): Promise<BuildTarget> {
|
|
531
|
+
const detected = await detectContainer(cwd);
|
|
532
|
+
const workspace = params.workspace ?? config.workspace ?? detected.workspace;
|
|
533
|
+
const project = params.project ?? config.project ?? detected.project;
|
|
534
|
+
const configuration = params.configuration ?? config.configuration ?? "Debug";
|
|
535
|
+
const container = workspace ?? project;
|
|
536
|
+
// An explicit scheme wins. Otherwise the container's own name is the first
|
|
537
|
+
// guess, checked against the container's real scheme list: a component demo's
|
|
538
|
+
// workspace name need not be a scheme, and an unknown scheme makes xcodebuild
|
|
539
|
+
// fail with a message that hides the real problem.
|
|
540
|
+
let scheme = params.scheme ?? config.scheme;
|
|
541
|
+
if (!scheme && container) {
|
|
542
|
+
const guess = schemeFromContainer(container);
|
|
543
|
+
if (guess) {
|
|
544
|
+
const listed = await listSchemes({ workspace, project }, cwd);
|
|
545
|
+
if (listed.ok && listed.schemes.includes(guess)) {
|
|
546
|
+
scheme = guess;
|
|
547
|
+
} else {
|
|
548
|
+
// Either the guess is absent from a list we could read, or the list
|
|
549
|
+
// could not be read at all - both need the file scan.
|
|
550
|
+
const scanned = await appSchemeFromFiles(container);
|
|
551
|
+
if (scanned.scheme) {
|
|
552
|
+
scheme = scanned.scheme;
|
|
553
|
+
} else if (!listed.ok) {
|
|
554
|
+
// The list could not be read, so the guess is unverified rather than
|
|
555
|
+
// wrong. Use it and let xcodebuild report; there is no better evidence
|
|
556
|
+
// to act on, and refusing here would block a build that may well work.
|
|
557
|
+
scheme = guess;
|
|
558
|
+
} else {
|
|
559
|
+
// The list was read and the guess is not in it, and no scheme file
|
|
560
|
+
// declares an .app product: the guess is known to be wrong. Carrying
|
|
561
|
+
// on would fail later with a message that hides this.
|
|
562
|
+
throw new Error(
|
|
563
|
+
`Scheme "${guess}" is not in xcodebuild -list and no scheme file declares a .app product. ` +
|
|
564
|
+
`Pass scheme=..., or add "scheme" to .xcodebug.json. ` +
|
|
565
|
+
`Container: ${container}. Searched: ${scanned.searched.join(", ") || "(no scheme directories)"}.`,
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (!scheme) {
|
|
572
|
+
throw new Error(
|
|
573
|
+
"No scheme found. Pass scheme=..., or add \"scheme\" to .xcodebug.json. " +
|
|
574
|
+
`Container: ${container ?? "(none)"}.` +
|
|
575
|
+
// More than one app project sits below cwd, so naming them beats
|
|
576
|
+
// leaving the user to guess why nothing was picked.
|
|
577
|
+
(detected.ambiguous && detected.ambiguous.length > 0
|
|
578
|
+
? ` Found several app projects below ${cwd}: ${detected.ambiguous.join(", ")}. ` +
|
|
579
|
+
`Run from one of them, or pass workspace=... .`
|
|
580
|
+
: ""),
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
return resolveBuildTarget(config, { ...params, scheme, workspace, project, configuration });
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Split a command line into tokens, honouring quotes.
|
|
588
|
+
*
|
|
589
|
+
* `command="npm run test:weather"` has to survive as ONE value: splitting
|
|
590
|
+
* on whitespace would turn the rest of the shell line into goal words and run
|
|
591
|
+
* `npm` with no arguments. Both quote styles are accepted, and a quote may sit
|
|
592
|
+
* anywhere in a token so `command="cd a b && npm test"` works too.
|
|
593
|
+
*/
|
|
594
|
+
function tokenizeArgs(raw: string): string[] {
|
|
595
|
+
const tokens: string[] = [];
|
|
596
|
+
let current = "";
|
|
597
|
+
let quote: string | undefined;
|
|
598
|
+
let started = false;
|
|
599
|
+
for (const char of raw) {
|
|
600
|
+
if (quote) {
|
|
601
|
+
if (char === quote) quote = undefined;
|
|
602
|
+
else current += char;
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
if (char === '"' || char === "'") {
|
|
606
|
+
quote = char;
|
|
607
|
+
started = true;
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
if (/\s/.test(char)) {
|
|
611
|
+
if (started) tokens.push(current);
|
|
612
|
+
current = "";
|
|
613
|
+
started = false;
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
current += char;
|
|
617
|
+
started = true;
|
|
618
|
+
}
|
|
619
|
+
if (started) tokens.push(current);
|
|
620
|
+
return tokens;
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Turn a command line into tool params.
|
|
624
|
+
*
|
|
625
|
+
* `/xcodebug 验证天气添加城市` -> launch, with the phrase as the log filter goal
|
|
626
|
+
* `/xcodebug logs grep=MySDK` -> logs
|
|
627
|
+
* `/xcodebug stop` -> stop
|
|
628
|
+
*
|
|
629
|
+
* Bare key=value tokens override anything derived from the free-text goal.
|
|
630
|
+
*/
|
|
631
|
+
function parseCommandArgs(raw: string): ToolParams {
|
|
632
|
+
// `command=` is a whole shell line, but the tokenizer splits on whitespace
|
|
633
|
+
// before the value is ever read: unquoted, `command=cd /repo && npm test`
|
|
634
|
+
// arrives as command="cd" and the rest of the line is silently demoted to
|
|
635
|
+
// goal words. `cd` with no arguments exits 0, so the run reports success
|
|
636
|
+
// having run no test at all - the one failure that looks exactly like a pass.
|
|
637
|
+
// Quoting is always available, so refuse the shape instead of guessing.
|
|
638
|
+
if (/(?:^|\s)(?:--)?command=/.test(raw) && !/(?:^|\s)(?:--)?command=["']/.test(raw)) {
|
|
639
|
+
throw new Error(
|
|
640
|
+
'command= must be quoted: command="cd /repo && npm run test". ' +
|
|
641
|
+
"Unquoted, only the first word reaches the shell line.",
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
const tokens = tokenizeArgs(raw);
|
|
645
|
+
const known = new Set([
|
|
646
|
+
"devices", "changes", "build", "install", "launch", "syslog",
|
|
647
|
+
"logs", "wait", "status", "stop", "terminate", "doctor", "restart", "await",
|
|
648
|
+
]);
|
|
649
|
+
|
|
650
|
+
const params: Record<string, unknown> = {};
|
|
651
|
+
const free: string[] = [];
|
|
652
|
+
const numberKeys = ["limit", "since", "timeoutSeconds"];
|
|
653
|
+
const boolKeys = ["force", "installPods", "dualChannel", "keepApp", "terminateExisting", "build"];
|
|
654
|
+
|
|
655
|
+
const assign = (key: string, value: string): void => {
|
|
656
|
+
if (numberKeys.includes(key)) {
|
|
657
|
+
const n = Number(value);
|
|
658
|
+
if (Number.isFinite(n)) params[key] = n;
|
|
659
|
+
} else if (boolKeys.includes(key)) {
|
|
660
|
+
params[key] = value !== "false";
|
|
661
|
+
} else {
|
|
662
|
+
params[key] = value;
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
for (let index = 0; index < tokens.length; index += 1) {
|
|
667
|
+
const token = tokens[index]!;
|
|
668
|
+
// `--key=value` and `--key value` are both ordinary ways to spell a param.
|
|
669
|
+
// A bare `--flag` is a switch: turning it into a goal word would silently
|
|
670
|
+
// describe the run as verifying "--force".
|
|
671
|
+
if (token.startsWith("--")) {
|
|
672
|
+
const body = token.slice(2);
|
|
673
|
+
const eqFlag = body.indexOf("=");
|
|
674
|
+
if (eqFlag > 0) {
|
|
675
|
+
assign(body.slice(0, eqFlag), body.slice(eqFlag + 1));
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
const next = tokens[index + 1];
|
|
679
|
+
if (!boolKeys.includes(body) && next !== undefined && !next.startsWith("-")) {
|
|
680
|
+
assign(body, next);
|
|
681
|
+
index += 1;
|
|
682
|
+
} else if (numberKeys.includes(body)) {
|
|
683
|
+
throw new Error(`--${body} needs a numeric value`);
|
|
684
|
+
} else {
|
|
685
|
+
params[body] = true;
|
|
686
|
+
}
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
const eq = token.indexOf("=");
|
|
690
|
+
if (eq > 0) {
|
|
691
|
+
assign(token.slice(0, eq), token.slice(eq + 1));
|
|
692
|
+
} else {
|
|
693
|
+
free.push(token);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const head = free[0];
|
|
698
|
+
if (head && known.has(head)) {
|
|
699
|
+
params.action = head;
|
|
700
|
+
free.shift();
|
|
701
|
+
} else {
|
|
702
|
+
// Bare `/xcodebug` and `/xcodebug 分析xxx` both mean "start the run": launch
|
|
703
|
+
// the app and keep listening with no deadline, so the user stays in control.
|
|
704
|
+
// `command=` is NOT an action - it is an extra phase appended to whatever
|
|
705
|
+
// the main action is (see `runCaseThenStop`), because a command run is only
|
|
706
|
+
// useful when the app is already being captured.
|
|
707
|
+
params.action = "launch";
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const goal = free.join(" ").trim();
|
|
711
|
+
if (goal) {
|
|
712
|
+
// The goal is a human phrase ("验证天气添加城市"); it is not a log filter.
|
|
713
|
+
params.goal = goal;
|
|
714
|
+
}
|
|
715
|
+
return params as unknown as ToolParams;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
type ToolParams = {
|
|
719
|
+
action: string;
|
|
720
|
+
/** Free-text description of what the user wants verified (command path only). */
|
|
721
|
+
goal?: string;
|
|
722
|
+
device?: string;
|
|
723
|
+
scheme?: string;
|
|
724
|
+
workspace?: string;
|
|
725
|
+
project?: string;
|
|
726
|
+
configuration?: string;
|
|
727
|
+
derivedDataPath?: string;
|
|
728
|
+
bundleId?: string;
|
|
729
|
+
appPath?: string;
|
|
730
|
+
processName?: string;
|
|
731
|
+
captureId?: string;
|
|
732
|
+
since?: number;
|
|
733
|
+
limit?: number;
|
|
734
|
+
grep?: string;
|
|
735
|
+
match?: string;
|
|
736
|
+
timeoutSeconds?: number;
|
|
737
|
+
push?: "off" | "context" | "wake";
|
|
738
|
+
force?: boolean;
|
|
739
|
+
installPods?: boolean;
|
|
740
|
+
changes?: boolean;
|
|
741
|
+
dualChannel?: boolean;
|
|
742
|
+
terminateExisting?: boolean;
|
|
743
|
+
keepApp?: boolean;
|
|
744
|
+
build?: boolean;
|
|
745
|
+
/** `await`/`command=`: a shell line run to completion after the app is up. */
|
|
746
|
+
command?: string;
|
|
747
|
+
args?: string[];
|
|
748
|
+
environment?: Record<string, string>;
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
export default function xcodebug(pi: ExtensionAPI): void {
|
|
752
|
+
const state: SessionState = {
|
|
753
|
+
captures: new Map(),
|
|
754
|
+
pushTimers: new Map(),
|
|
755
|
+
pushCursors: new Map(),
|
|
756
|
+
companions: new Map(),
|
|
757
|
+
lastLineAt: new Map(),
|
|
758
|
+
silenceNotified: new Set(),
|
|
759
|
+
recentLines: new Map(),
|
|
760
|
+
watchdogs: new Map(),
|
|
761
|
+
};
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Paint the live verification state: a footer line that is always visible and
|
|
765
|
+
* a widget above the editor with the most recent log lines. Both are cleared
|
|
766
|
+
* when no capture is running, so a finished task leaves no stale chrome.
|
|
767
|
+
*/
|
|
768
|
+
const refreshStatus = (): void => {
|
|
769
|
+
const ctx = state.uiCtx;
|
|
770
|
+
if (!ctx?.hasUI) return;
|
|
771
|
+
const running = [...state.captures.values()].filter((c) => c.running);
|
|
772
|
+
if (running.length === 0) {
|
|
773
|
+
const phase = state.runPhase;
|
|
774
|
+
if (!phase) {
|
|
775
|
+
ctx.ui.setStatus("xcodebug", undefined);
|
|
776
|
+
ctx.ui.setWidget("xcodebug", undefined);
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
const secs = Math.round((Date.now() - phase.startedAt) / 1000);
|
|
780
|
+
ctx.ui.setStatus("xcodebug", `🔨 xcodebug · ${phase.label} · ${secs}s`);
|
|
781
|
+
ctx.ui.setWidget("xcodebug", ["Xcodebug · running", ` ${phase.label}`, ` ${secs}s`], {
|
|
782
|
+
placement: "aboveEditor",
|
|
783
|
+
});
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// Prefer a channel that is actually pushing: a push=off capture shows no
|
|
788
|
+
// lines in the widget, so featuring it would misreport the run as silent.
|
|
789
|
+
const primary =
|
|
790
|
+
running.find((c) => state.companions.has(c.id)) ??
|
|
791
|
+
running.find((c) => c.pushMode !== undefined) ??
|
|
792
|
+
running[0];
|
|
793
|
+
const status = primary.status();
|
|
794
|
+
const lastAt = primary.lastLineAt;
|
|
795
|
+
const silentSec = Math.round((Date.now() - lastAt) / 1000);
|
|
796
|
+
const elapsed = Math.round((Date.now() - status.startedAt) / 1000);
|
|
797
|
+
const silence = silentSec >= 60 ? ` · quiet ${silentSec}s` : "";
|
|
798
|
+
ctx.ui.setStatus(
|
|
799
|
+
"xcodebug",
|
|
800
|
+
`📖 xcodebug · capturing · ${status.lineCount} lines · ${elapsed}s${silence} · /xcodebug stop to end`,
|
|
801
|
+
);
|
|
802
|
+
|
|
803
|
+
// Read the tail from the capture itself, not from `recentLines`: that map is
|
|
804
|
+
// only fed by the push loop, so a push=off run left the widget claiming
|
|
805
|
+
// "(waiting for the first line…)" while tens of thousands of lines had
|
|
806
|
+
// already been captured.
|
|
807
|
+
const recent =
|
|
808
|
+
state.recentLines.get(primary.id) ??
|
|
809
|
+
primary.read({ limit: 5 }).lines.map((line) => line.text);
|
|
810
|
+
// Report the pushed channels only: a syslog companion is a safety net, not a
|
|
811
|
+
// second stream into the session, and counting it would overstate coverage.
|
|
812
|
+
// A push=off run has no pushed channel at all - saying "0 streaming" next to
|
|
813
|
+
// a five-figure line count reads as "nothing is being captured", which is
|
|
814
|
+
// the opposite of what is happening, so name the mode instead.
|
|
815
|
+
const pushed = running.filter((c) => c.pushMode !== undefined).length;
|
|
816
|
+
const modeText = pushed > 0 ? `(${pushed} streaming)` : "(push off · pull with logs)";
|
|
817
|
+
const header = `Xcodebug · capturing ${modeText} · ${status.bundleId}`;
|
|
818
|
+
const summary = `${status.lineCount} lines · ${elapsed}s${silence}`;
|
|
819
|
+
const rows =
|
|
820
|
+
recent.length > 0
|
|
821
|
+
? recent.slice(-4).map((line) => ` ${line.slice(0, 110)}`)
|
|
822
|
+
: [" (waiting for the first line…)"];
|
|
823
|
+
ctx.ui.setWidget("xcodebug", [header, ` ${summary}`, ...rows], { placement: "aboveEditor" });
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Repaint on a slow timer so the elapsed/quiet counters keep moving even when
|
|
828
|
+
* pushing is off. Without it the widget freezes on the last pushed line and
|
|
829
|
+
* reads as a stalled run.
|
|
830
|
+
*/
|
|
831
|
+
const startStatusTicker = (): void => {
|
|
832
|
+
// Paint now, not on the first tick: the run must be visible the moment it
|
|
833
|
+
// starts, and a sub-second capture would otherwise never show at all.
|
|
834
|
+
refreshStatus();
|
|
835
|
+
if (state.statusTimer) return;
|
|
836
|
+
const timer = setInterval(() => {
|
|
837
|
+
const active =
|
|
838
|
+
state.runPhase !== undefined || [...state.captures.values()].some((c) => c.running);
|
|
839
|
+
if (!active) {
|
|
840
|
+
stopStatusTicker();
|
|
841
|
+
refreshStatus();
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
refreshStatus();
|
|
845
|
+
}, 1_000);
|
|
846
|
+
timer.unref?.();
|
|
847
|
+
state.statusTimer = timer;
|
|
848
|
+
};
|
|
849
|
+
|
|
850
|
+
const stopStatusTicker = (): void => {
|
|
851
|
+
if (state.statusTimer) clearInterval(state.statusTimer);
|
|
852
|
+
state.statusTimer = undefined;
|
|
853
|
+
};
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Show what the run is doing before it has a capture, in place.
|
|
857
|
+
*
|
|
858
|
+
* Build progress arrives several times a second; reporting each frame as its
|
|
859
|
+
* own message buried the conversation. One repainted line keeps it readable
|
|
860
|
+
* and matches where the capture status appears a moment later.
|
|
861
|
+
*/
|
|
862
|
+
const setRunPhase = (label: string): void => {
|
|
863
|
+
const startedAt = state.runPhase?.startedAt ?? Date.now();
|
|
864
|
+
state.runPhase = { label, startedAt };
|
|
865
|
+
startStatusTicker();
|
|
866
|
+
};
|
|
867
|
+
|
|
868
|
+
const clearRunPhase = (): void => {
|
|
869
|
+
state.runPhase = undefined;
|
|
870
|
+
refreshStatus();
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Release everything tied to a capture. Called from every path that ends one
|
|
875
|
+
* (explicit stop, app exit, shutdown) so per-capture bookkeeping cannot pile
|
|
876
|
+
* up across repeated launches in one session.
|
|
877
|
+
*/
|
|
878
|
+
const releaseCapture = (capture: Capture): void => {
|
|
879
|
+
stopPush(capture.id);
|
|
880
|
+
stopWatchdog(capture.id);
|
|
881
|
+
unlinkCompanion(capture);
|
|
882
|
+
state.recentLines.delete(capture.id);
|
|
883
|
+
state.lastLineAt.delete(capture.id);
|
|
884
|
+
state.silenceNotified.delete(capture.id);
|
|
885
|
+
state.pushCursors.delete(capture.id);
|
|
886
|
+
// The capture itself stays in `state.captures`: its log file is still on
|
|
887
|
+
// disk and `logs`/`status` must be able to read it after the app exits.
|
|
888
|
+
if (state.activeCaptureId === capture.id) state.activeCaptureId = undefined;
|
|
889
|
+
if (![...state.captures.values()].some((c) => c.running)) stopStatusTicker();
|
|
890
|
+
refreshStatus();
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
const stopPush = (captureId: string): void => {
|
|
894
|
+
const timer = state.pushTimers.get(captureId);
|
|
895
|
+
if (timer) clearInterval(timer);
|
|
896
|
+
state.pushTimers.delete(captureId);
|
|
897
|
+
};
|
|
898
|
+
|
|
899
|
+
/** Stop the syslog silence watchdog for a capture that is ending. */
|
|
900
|
+
const stopWatchdog = (captureId: string): void => {
|
|
901
|
+
const timer = state.watchdogs.get(captureId);
|
|
902
|
+
if (timer) clearInterval(timer);
|
|
903
|
+
state.watchdogs.delete(captureId);
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
/** Is this the syslog channel that shadows a console capture rather than a primary? */
|
|
907
|
+
const isCompanion = (capture: Capture): boolean =>
|
|
908
|
+
[...state.companions.values()].includes(capture.id);
|
|
909
|
+
|
|
910
|
+
/**
|
|
911
|
+
* Drop the companion link in both directions.
|
|
912
|
+
*
|
|
913
|
+
* Stopping the console capture must stop its syslog companion, and stopping
|
|
914
|
+
* the companion must clear the console's pointer to it; doing only one side
|
|
915
|
+
* leaves a mapping that resolves to a capture nobody is running.
|
|
916
|
+
*/
|
|
917
|
+
const unlinkCompanion = (capture: Capture): void => {
|
|
918
|
+
const companionId = state.companions.get(capture.id);
|
|
919
|
+
if (companionId) {
|
|
920
|
+
state.companions.delete(capture.id);
|
|
921
|
+
const companion = state.captures.get(companionId);
|
|
922
|
+
if (companion) {
|
|
923
|
+
stopPush(companion.id);
|
|
924
|
+
stopWatchdog(companion.id);
|
|
925
|
+
companion.stop(false);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
for (const [primaryId, id] of state.companions) {
|
|
929
|
+
if (id === capture.id) state.companions.delete(primaryId);
|
|
930
|
+
}
|
|
931
|
+
};
|
|
932
|
+
|
|
933
|
+
const stopCapture = (capture: Capture, terminateApp: boolean): void => {
|
|
934
|
+
stopPush(capture.id);
|
|
935
|
+
stopWatchdog(capture.id);
|
|
936
|
+
// The syslog channel is a companion of the console capture; stop it too so
|
|
937
|
+
// one "stop" does not leave a second bridge running.
|
|
938
|
+
unlinkCompanion(capture);
|
|
939
|
+
// The capture stays in `state.captures` so its log file remains readable,
|
|
940
|
+
// but the push bookkeeping is finished and must not linger.
|
|
941
|
+
state.recentLines.delete(capture.id);
|
|
942
|
+
state.lastLineAt.delete(capture.id);
|
|
943
|
+
state.silenceNotified.delete(capture.id);
|
|
944
|
+
state.pushCursors.delete(capture.id);
|
|
945
|
+
if (![...state.captures.values()].some((c) => c !== capture && c.running)) stopStatusTicker();
|
|
946
|
+
refreshStatus();
|
|
947
|
+
capture.stop(terminateApp);
|
|
948
|
+
if (state.activeCaptureId === capture.id) state.activeCaptureId = undefined;
|
|
949
|
+
};
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* Mirror new lines into the session. Both modes are bounded: a physical-device
|
|
954
|
+
* console is a firehose, so a push carries at most PUSH_MAX_LINES lines and
|
|
955
|
+
* reports how many were dropped instead of flooding the context.
|
|
956
|
+
*/
|
|
957
|
+
const startPush = (
|
|
958
|
+
capture: Capture,
|
|
959
|
+
mode: "context" | "wake",
|
|
960
|
+
match?: string,
|
|
961
|
+
options: { resume?: boolean } = {},
|
|
962
|
+
): void => {
|
|
963
|
+
// Remember how this capture is mirrored so a reconnected bridge can resume
|
|
964
|
+
// the same push instead of looking alive while the session goes deaf.
|
|
965
|
+
capture.pushMode = mode;
|
|
966
|
+
capture.pushMatch = match;
|
|
967
|
+
// A resume keeps the cursor: restarting from 0 would re-push the whole log.
|
|
968
|
+
if (!options.resume) state.pushCursors.set(capture.id, 0);
|
|
969
|
+
else state.pushCursors.set(capture.id, capture.status().cursor);
|
|
970
|
+
state.lastLineAt.set(capture.id, Date.now());
|
|
971
|
+
state.silenceNotified.delete(capture.id);
|
|
972
|
+
const timer = setInterval(() => {
|
|
973
|
+
const since = state.pushCursors.get(capture.id) ?? 0;
|
|
974
|
+
const read = capture.read({ since, limit: PUSH_MAX_LINES, grep: match });
|
|
975
|
+
if (read.lines.length === 0) {
|
|
976
|
+
// A verification run is driven by the user tapping the phone; silence
|
|
977
|
+
// means either the task is done or they walked away. Ask once, never
|
|
978
|
+
// stop the capture on our own.
|
|
979
|
+
const lastAt = state.lastLineAt.get(capture.id) ?? Date.now();
|
|
980
|
+
const silentMs = Date.now() - lastAt;
|
|
981
|
+
if (
|
|
982
|
+
silentMs >= SILENCE_NOTICE_MS &&
|
|
983
|
+
!state.silenceNotified.has(capture.id) &&
|
|
984
|
+
capture.running
|
|
985
|
+
) {
|
|
986
|
+
state.silenceNotified.add(capture.id);
|
|
987
|
+
try {
|
|
988
|
+
pi.sendMessage(
|
|
989
|
+
{
|
|
990
|
+
customType: CAPTURE_PREFIX,
|
|
991
|
+
content:
|
|
992
|
+
`[xcodebug] ${capture.bundleId} · no new log lines for ${Math.round(silentMs / 1000)}s. ` +
|
|
993
|
+
`Still capturing (cursor ${capture.status().cursor}). If nothing was tried on the phone yet, say what to do next - the run keeps listening.`,
|
|
994
|
+
display: true,
|
|
995
|
+
details: { captureId: capture.id, silence: true },
|
|
996
|
+
},
|
|
997
|
+
{ deliverAs: "nextTurn" },
|
|
998
|
+
);
|
|
999
|
+
} catch {
|
|
1000
|
+
// Session teardown.
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
refreshStatus();
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
state.lastLineAt.set(capture.id, Date.now());
|
|
1007
|
+
state.silenceNotified.delete(capture.id);
|
|
1008
|
+
const recent = state.recentLines.get(capture.id) ?? [];
|
|
1009
|
+
recent.push(...read.lines.map((line) => line.text));
|
|
1010
|
+
state.recentLines.set(capture.id, recent.slice(-5));
|
|
1011
|
+
refreshStatus();
|
|
1012
|
+
state.pushCursors.set(capture.id, read.cursor);
|
|
1013
|
+
const omitted = read.total - read.lines.length;
|
|
1014
|
+
const body = read.lines.map((line) => line.text).join("\n");
|
|
1015
|
+
const header = [
|
|
1016
|
+
`[xcodebug ${capture.mode}] ${capture.deviceLabel} · ${capture.bundleId} · ${read.lines.length} new line(s)${omitted > 0 ? ` (+${omitted} older dropped)` : ""}`,
|
|
1017
|
+
`cursor ${read.cursor}`,
|
|
1018
|
+
].join(" · ");
|
|
1019
|
+
try {
|
|
1020
|
+
pi.sendMessage(
|
|
1021
|
+
{
|
|
1022
|
+
customType: CAPTURE_PREFIX,
|
|
1023
|
+
content: `${header}\n${body}`,
|
|
1024
|
+
// The model needs every line to analyse the run; the reader does not
|
|
1025
|
+
// need the firehose on screen. display:false keeps the content in
|
|
1026
|
+
// context and out of the transcript.
|
|
1027
|
+
display: false,
|
|
1028
|
+
details: { captureId: capture.id, cursor: read.cursor },
|
|
1029
|
+
},
|
|
1030
|
+
mode === "wake"
|
|
1031
|
+
? { deliverAs: "steer", triggerTurn: true }
|
|
1032
|
+
: { deliverAs: "nextTurn" },
|
|
1033
|
+
);
|
|
1034
|
+
} catch {
|
|
1035
|
+
// The session may be shutting down; the file log still has everything.
|
|
1036
|
+
}
|
|
1037
|
+
}, PUSH_INTERVAL_MS);
|
|
1038
|
+
timer.unref?.();
|
|
1039
|
+
state.pushTimers.set(capture.id, timer);
|
|
1040
|
+
};
|
|
1041
|
+
|
|
1042
|
+
/**
|
|
1043
|
+
* Sleep in short slices so `stop` interrupts a pending reconnect instead of
|
|
1044
|
+
* leaving the loop to wake up and probe the device once more after the user
|
|
1045
|
+
* has already ended the run.
|
|
1046
|
+
*/
|
|
1047
|
+
const sleepUnlessStopped = async (capture: Capture, ms: number): Promise<void> => {
|
|
1048
|
+
const deadline = Date.now() + ms;
|
|
1049
|
+
while (!capture.stoppedByUser && Date.now() < deadline) {
|
|
1050
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(250, deadline - Date.now())));
|
|
1051
|
+
}
|
|
1052
|
+
};
|
|
1053
|
+
/**
|
|
1054
|
+
* Keep a capture alive for as long as the run lasts.
|
|
1055
|
+
*
|
|
1056
|
+
* `devicectl --console` is the only channel that carries the app's own
|
|
1057
|
+
* stdout/stderr (idevicesyslog sees system logs only). Its process can drop
|
|
1058
|
+
* while the app keeps running - a transient CoreDevice error, or the bridge
|
|
1059
|
+
* being torn down. Losing it silently would end log capture mid-verification,
|
|
1060
|
+
* so reconnect with backoff until the user stops the capture or the app dies.
|
|
1061
|
+
*
|
|
1062
|
+
* This function also installs the syslog silence watchdog, which only kills a
|
|
1063
|
+
* stalled bridge: reattachment is owned solely by the exit hook below.
|
|
1064
|
+
*/
|
|
1065
|
+
const watchExit = (capture: Capture, device: DeviceInfo, onReconnect?: (n: number) => void): void => {
|
|
1066
|
+
let attempts = 0;
|
|
1067
|
+
let reconnecting = false;
|
|
1068
|
+
|
|
1069
|
+
/**
|
|
1070
|
+
* Reattach a dropped bridge, retrying until the user stops or (console only)
|
|
1071
|
+
* the app exits.
|
|
1072
|
+
*
|
|
1073
|
+
* Both channels use this. `idevicesyslog` can also stop emitting while its
|
|
1074
|
+
* process stays alive, so `exit` is not the only entry point - the silence
|
|
1075
|
+
* watchdog calls this too. `reconnecting` keeps the two from racing.
|
|
1076
|
+
*/
|
|
1077
|
+
const reconnect = async (): Promise<void> => {
|
|
1078
|
+
if (reconnecting) return;
|
|
1079
|
+
reconnecting = true;
|
|
1080
|
+
try {
|
|
1081
|
+
const label = capture.mode === "console" ? "console" : "syslog";
|
|
1082
|
+
while (!capture.stoppedByUser) {
|
|
1083
|
+
attempts += 1;
|
|
1084
|
+
const delay = Math.min(1000 * 2 ** (Math.min(attempts, 5) - 1), 15_000);
|
|
1085
|
+
await sleepUnlessStopped(capture, delay);
|
|
1086
|
+
if (capture.stoppedByUser) return;
|
|
1087
|
+
|
|
1088
|
+
// Only the console channel is bound to the app's lifetime, so only it
|
|
1089
|
+
// consults the process table. A syslog bridge outlives the app and its
|
|
1090
|
+
// drops say nothing about whether the app is still running.
|
|
1091
|
+
if (capture.mode === "console" && capture.processName) {
|
|
1092
|
+
const lookup = await lookupProcess(device, capture.processName, {
|
|
1093
|
+
attempts: 1,
|
|
1094
|
+
signal: capture.signal,
|
|
1095
|
+
});
|
|
1096
|
+
if (!lookup.queryFailed && lookup.pid === undefined) {
|
|
1097
|
+
capture.pushLine("err", "[xcodebug] app process is gone; stopping capture");
|
|
1098
|
+
releaseCapture(capture);
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
if (lookup.queryFailed) {
|
|
1102
|
+
capture.pushLine("err", "[xcodebug] could not read the process table; still retrying");
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
capture.pushLine("err", `[xcodebug] reconnecting ${label} bridge (attempt ${attempts})`);
|
|
1107
|
+
capture.resetForReconnect();
|
|
1108
|
+
try {
|
|
1109
|
+
await capture.start();
|
|
1110
|
+
attempts = 0;
|
|
1111
|
+
onReconnect?.(1);
|
|
1112
|
+
// Resume pushing for whichever channel this is. The active-id check
|
|
1113
|
+
// cannot gate this: a syslog companion is never the active capture.
|
|
1114
|
+
if (capture.pushMode && state.pushTimers.get(capture.id) === undefined) {
|
|
1115
|
+
startPush(capture, capture.pushMode, capture.pushMatch, { resume: true });
|
|
1116
|
+
}
|
|
1117
|
+
capture.pushLine("err", `[xcodebug] ${label} bridge reattached`);
|
|
1118
|
+
return;
|
|
1119
|
+
} catch (error) {
|
|
1120
|
+
capture.pushLine("err", `[xcodebug] reconnect failed: ${(error as Error).message}`);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
} finally {
|
|
1124
|
+
reconnecting = false;
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
|
|
1128
|
+
capture.onExit((code, signal) => {
|
|
1129
|
+
stopPush(capture.id);
|
|
1130
|
+
const reason = signal ? `signal ${signal}` : `exit ${code ?? "?"}`;
|
|
1131
|
+
capture.pushLine("err", `[xcodebug] bridge ended (${reason})`);
|
|
1132
|
+
|
|
1133
|
+
// A user stop is the only reason not to reconnect. Both channels are
|
|
1134
|
+
// reconnected: the syslog bridge can drop while the app is perfectly
|
|
1135
|
+
// healthy, and losing it silently would leave the console channel with no
|
|
1136
|
+
// backup - exactly the gap dual-channel exists to cover.
|
|
1137
|
+
if (capture.stoppedByUser) {
|
|
1138
|
+
if (state.activeCaptureId === capture.id) state.activeCaptureId = undefined;
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
// Always hand off. If a reconnect loop is already running it returns at
|
|
1142
|
+
// once and keeps retrying on its own; if none is running, this starts it.
|
|
1143
|
+
// An earlier version skipped this while the watchdog was restarting, which
|
|
1144
|
+
// could leave the bridge dead with no loop alive to revive it.
|
|
1145
|
+
void reconnect();
|
|
1146
|
+
});
|
|
1147
|
+
|
|
1148
|
+
// `idevicesyslog` can go silent while its process stays alive - no exit, no
|
|
1149
|
+
// error, just nothing more. The exit hook above never fires in that case, so
|
|
1150
|
+
// a stalled bridge is only detectable by watching the line flow.
|
|
1151
|
+
//
|
|
1152
|
+
// Silence by itself is ambiguous: an app that is simply idle looks exactly
|
|
1153
|
+
// like a hung bridge, and restarting on that signal alone churned a healthy
|
|
1154
|
+
// bridge every 30s. The console channel is the tie-breaker - it carries the
|
|
1155
|
+
// app's stdout/stderr *and* os_log, so while it is still receiving lines the
|
|
1156
|
+
// app is emitting and syslog's silence is real. When both are quiet, nothing
|
|
1157
|
+
// is happening and there is nothing to repair.
|
|
1158
|
+
//
|
|
1159
|
+
// A standalone `action=syslog` has no console channel to compare against, so
|
|
1160
|
+
// it gets no watchdog: guessing there caused false restarts, and a user who
|
|
1161
|
+
// asked for that channel can restart it themselves.
|
|
1162
|
+
const primaryId = [...state.companions].find(([, id]) => id === capture.id)?.[0];
|
|
1163
|
+
if (primaryId) {
|
|
1164
|
+
const timer = setInterval(() => {
|
|
1165
|
+
if (capture.stoppedByUser || reconnecting) return;
|
|
1166
|
+
const primary = state.captures.get(primaryId);
|
|
1167
|
+
const appEmitting =
|
|
1168
|
+
primary?.running === true && Date.now() - primary.lastLineAt < SYSLOG_SILENCE_MS;
|
|
1169
|
+
if (!appEmitting) return;
|
|
1170
|
+
if (Date.now() - capture.lastLineAt < SYSLOG_SILENCE_MS) return;
|
|
1171
|
+
capture.pushLine("err", `[xcodebug] syslog silent for ${Math.round(SYSLOG_SILENCE_MS / 1000)}s while the app is still logging; restarting the bridge`);
|
|
1172
|
+
// Kill without `stop()`: that would record a user intent this watchdog
|
|
1173
|
+
// does not have, and clearing it afterwards could undo a real stop.
|
|
1174
|
+
// Reattaching is left to the exit hook, which is the single path that
|
|
1175
|
+
// owns reconnection - calling it here too is what used to race.
|
|
1176
|
+
capture.lastLineAt = Date.now();
|
|
1177
|
+
capture.restartBridge();
|
|
1178
|
+
}, 5_000);
|
|
1179
|
+
timer.unref?.();
|
|
1180
|
+
state.watchdogs.set(capture.id, timer);
|
|
1181
|
+
}
|
|
1182
|
+
};
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
/**
|
|
1186
|
+
* Retire the previous cycle's capture for one app.
|
|
1187
|
+
*
|
|
1188
|
+
* A verification loop is conclude -> edit -> relaunch, so a new capture must
|
|
1189
|
+
* end the old one for that app: otherwise the stale bridge keeps pushing
|
|
1190
|
+
* lines into the session (interleaved with the new run) and shows up as a
|
|
1191
|
+
* second live capture in `status`.
|
|
1192
|
+
*
|
|
1193
|
+
* Scoped by app rather than global: several apps are debugged in one session,
|
|
1194
|
+
* and relaunching one must not silence the others. `processName` is the app's
|
|
1195
|
+
* executable, which is what both channels record; a capture with no
|
|
1196
|
+
* processName cannot be matched and is left alone rather than guessed at.
|
|
1197
|
+
*/
|
|
1198
|
+
const stopRunningCaptures = async (processName: string | undefined, exceptId?: string): Promise<void> => {
|
|
1199
|
+
if (!processName) return;
|
|
1200
|
+
const running = [...state.captures.values()].filter(
|
|
1201
|
+
(c) => c.running && c.processName === processName && c.id !== exceptId,
|
|
1202
|
+
);
|
|
1203
|
+
for (const capture of running) {
|
|
1204
|
+
stopCapture(capture, false);
|
|
1205
|
+
}
|
|
1206
|
+
for (const capture of running) {
|
|
1207
|
+
await capture.waitForExit(3_000);
|
|
1208
|
+
}
|
|
1209
|
+
};
|
|
1210
|
+
|
|
1211
|
+
const requireCapture = (captureId?: string): Capture => {
|
|
1212
|
+
// A capture that exited (app quit or crashed) clears activeCaptureId but stays
|
|
1213
|
+
// in the map so its log file is still reachable. With one candidate left, an
|
|
1214
|
+
// explicit id is unnecessary — without this, `stop`/`logs` report a puzzling
|
|
1215
|
+
// `Unknown capture ""` even though the capture is right there.
|
|
1216
|
+
//
|
|
1217
|
+
// A launch also records two captures (console + its syslog companion) and the
|
|
1218
|
+
// command phase clears activeCaptureId when it stops the pair, so the plain
|
|
1219
|
+
// `stop` a user types next hits the same empty-id case with four entries in
|
|
1220
|
+
// the map. Falling back to the one running primary keeps that working: the
|
|
1221
|
+
// companion is excluded because stopping it alone would leave the console
|
|
1222
|
+
// bridge streaming, which is the opposite of what `stop` means.
|
|
1223
|
+
const running = [...state.captures.values()].filter((c) => c.running);
|
|
1224
|
+
const runningPrimaries = running.filter((c) => !isCompanion(c));
|
|
1225
|
+
const fallback =
|
|
1226
|
+
!captureId && !state.activeCaptureId
|
|
1227
|
+
? (state.captures.size === 1
|
|
1228
|
+
? state.captures.values().next().value
|
|
1229
|
+
: runningPrimaries.length === 1
|
|
1230
|
+
? runningPrimaries[0]
|
|
1231
|
+
: undefined)
|
|
1232
|
+
: undefined;
|
|
1233
|
+
const id = captureId ?? state.activeCaptureId ?? fallback?.id;
|
|
1234
|
+
const capture = id ? state.captures.get(id) : undefined;
|
|
1235
|
+
if (!capture) {
|
|
1236
|
+
const known = [...state.captures.values()].map(
|
|
1237
|
+
(item) => `${item.id} (${item.mode}${item.running ? ", running" : ", ended"})`,
|
|
1238
|
+
);
|
|
1239
|
+
// Naming the ids matters here: several captures means the caller must pick
|
|
1240
|
+
// one, and an empty selector in the message reads like a bug in the tool.
|
|
1241
|
+
throw new Error(
|
|
1242
|
+
known.length > 0
|
|
1243
|
+
? `${captureId ? `Unknown capture "${captureId}"` : "Several captures exist and none is active"} ` +
|
|
1244
|
+
`- pass captureId. Known: ${known.join(", ")}`
|
|
1245
|
+
: "No active capture. Run xcodebug with action=launch (or action=syslog) first.",
|
|
1246
|
+
);
|
|
1247
|
+
}
|
|
1248
|
+
return capture;
|
|
1249
|
+
};
|
|
1250
|
+
|
|
1251
|
+
const resolveDeviceParam = async (selector: string | undefined, root: string): Promise<DeviceInfo> => {
|
|
1252
|
+
const config = await readConfig(root);
|
|
1253
|
+
const { device } = await resolveDevice(selector ?? config.device);
|
|
1254
|
+
return device;
|
|
1255
|
+
};
|
|
1256
|
+
|
|
1257
|
+
/**
|
|
1258
|
+
* Decide what must happen before a device run.
|
|
1259
|
+
*
|
|
1260
|
+
* - New file inside a pod: `pod install` first (once per change set), because
|
|
1261
|
+
* the generated Pods project will not compile a file it never saw.
|
|
1262
|
+
* - Any build-relevant change: rebuild and relaunch.
|
|
1263
|
+
* - `force`: rebuild regardless of the fingerprint.
|
|
1264
|
+
*/
|
|
1265
|
+
const prepareRun = async (ctx: ExtensionContext, options: {
|
|
1266
|
+
/** Project root the change detection is anchored to. */
|
|
1267
|
+
root: string;
|
|
1268
|
+
force?: boolean;
|
|
1269
|
+
installPods?: boolean;
|
|
1270
|
+
timeoutSeconds?: number;
|
|
1271
|
+
signal?: AbortSignal;
|
|
1272
|
+
onUpdate?: (text: string) => void;
|
|
1273
|
+
/** The .xcworkspace/.xcodeproj this run targets; anchors the Podfile lookup. */
|
|
1274
|
+
containerPath?: string;
|
|
1275
|
+
}): Promise<{ report: ChangeReport; needsBuild: boolean; podInstall?: string; podInstallFailed: boolean; notes: string[] }> => {
|
|
1276
|
+
let report = await detectChanges(options.root);
|
|
1277
|
+
const notes: string[] = [];
|
|
1278
|
+
let podInstallNote: string | undefined;
|
|
1279
|
+
let podInstallFailed = false;
|
|
1280
|
+
|
|
1281
|
+
// Key on the set of new component files, not the whole-tree fingerprint:
|
|
1282
|
+
// an untracked pod file keeps showing up in git status, so a whole-tree key
|
|
1283
|
+
// would re-run pod install after every unrelated edit.
|
|
1284
|
+
const podKeyOf = (r: ChangeReport): string =>
|
|
1285
|
+
r.newComponentFiles
|
|
1286
|
+
.map((file) => `${file.path}:${file.pods.join(",")}`)
|
|
1287
|
+
.sort()
|
|
1288
|
+
.join("|");
|
|
1289
|
+
const podKey = podKeyOf(report);
|
|
1290
|
+
const newFilesNeedInstall =
|
|
1291
|
+
options.installPods !== false &&
|
|
1292
|
+
report.podsNeedingInstall.length > 0 &&
|
|
1293
|
+
state.installedPodsFingerprint !== podKey;
|
|
1294
|
+
|
|
1295
|
+
// A lock/manifest mismatch breaks every target's "Check Pods Manifest.lock"
|
|
1296
|
+
// phase with an error the user cannot act on from a build log, so it forces
|
|
1297
|
+
// pod install regardless of which files changed.
|
|
1298
|
+
const lockCheck =
|
|
1299
|
+
options.installPods === false || !options.containerPath
|
|
1300
|
+
? undefined
|
|
1301
|
+
: await checkPodLockSync(options.containerPath);
|
|
1302
|
+
const lockNeedsInstall = lockCheck !== undefined && !lockCheck.synced;
|
|
1303
|
+
|
|
1304
|
+
if (newFilesNeedInstall || lockNeedsInstall) {
|
|
1305
|
+
// pod install only runs in the directory that owns this container's
|
|
1306
|
+
// Podfile. Searching elsewhere risks reinstalling another project's pods.
|
|
1307
|
+
const podfileDir = lockCheck?.podfileDir;
|
|
1308
|
+
if (!podfileDir) {
|
|
1309
|
+
notes.push(
|
|
1310
|
+
`pod install skipped: no Podfile beside ${options.containerPath ?? "the container"} ` +
|
|
1311
|
+
`(${newFilesNeedInstall ? `new files in ${report.podsNeedingInstall.join(", ")}` : "Podfile.lock out of sync"})`,
|
|
1312
|
+
);
|
|
1313
|
+
} else {
|
|
1314
|
+
const why = lockNeedsInstall
|
|
1315
|
+
? (lockCheck?.reason ?? "Podfile.lock out of sync")
|
|
1316
|
+
: `${report.podsNeedingInstall.join(", ")} changed`;
|
|
1317
|
+
options.onUpdate?.(`pod install (${why})…`);
|
|
1318
|
+
const outcome = await runPodInstall(podfileDir, {
|
|
1319
|
+
timeoutMs: (options.timeoutSeconds ?? 900) * 1000,
|
|
1320
|
+
signal: options.signal,
|
|
1321
|
+
logFile: join(logDir(ctx), `pod-install-${timestamp()}.log`),
|
|
1322
|
+
});
|
|
1323
|
+
podInstallNote = `${outcome.message}\nlog: ${outcome.logFile}`;
|
|
1324
|
+
if (!outcome.ok) {
|
|
1325
|
+
return { report, needsBuild: false, podInstall: podInstallNote, podInstallFailed: true, notes };
|
|
1326
|
+
}
|
|
1327
|
+
// pod install rewrites Podfile.lock and the Pods project, so re-read the
|
|
1328
|
+
// tree: storing the pre-install fingerprint would make the next launch
|
|
1329
|
+
// think the pods are still stale and install them again.
|
|
1330
|
+
report = await detectChanges(options.root);
|
|
1331
|
+
// Record the key derived from the post-install tree, not the one that
|
|
1332
|
+
// triggered this install: pod install can change the new-file set, and a
|
|
1333
|
+
// stale key would make the next run skip an install it still needs.
|
|
1334
|
+
state.installedPodsFingerprint = podKeyOf(report);
|
|
1335
|
+
|
|
1336
|
+
// The install is only meaningful if the lock actually converged. Re-check
|
|
1337
|
+
// rather than trusting the pre-install verdict.
|
|
1338
|
+
if (options.containerPath) {
|
|
1339
|
+
const after = await checkPodLockSync(options.containerPath);
|
|
1340
|
+
if (after && !after.synced) {
|
|
1341
|
+
podInstallNote += `\nwarning: Podfile.lock is still out of sync after pod install (${after.reason})`;
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
const needsBuild =
|
|
1348
|
+
options.force === true ||
|
|
1349
|
+
report.unavailable ||
|
|
1350
|
+
state.lastBuiltFingerprint === undefined ||
|
|
1351
|
+
state.lastBuiltFingerprint !== report.fingerprint;
|
|
1352
|
+
|
|
1353
|
+
return { report, needsBuild, podInstall: podInstallNote, podInstallFailed, notes };
|
|
1354
|
+
};
|
|
1355
|
+
|
|
1356
|
+
/**
|
|
1357
|
+
* Run a shell command to completion, then stop the capture it was watching
|
|
1358
|
+
* and report what the run produced.
|
|
1359
|
+
*
|
|
1360
|
+
* This is the whole `await` action, and also the second phase of
|
|
1361
|
+
* `/xcodebug 分析xxx command="<shell line>"`: the phrase describes the goal,
|
|
1362
|
+
* the command is the automated driver for it, and the capture is stopped only
|
|
1363
|
+
* when the driver exits - never on a timer or a silence heuristic, both of
|
|
1364
|
+
* which used to end runs the user had not finished.
|
|
1365
|
+
*/
|
|
1366
|
+
const runCaseThenStop = async (
|
|
1367
|
+
params: ToolParams,
|
|
1368
|
+
signal: AbortSignal | undefined,
|
|
1369
|
+
root: string,
|
|
1370
|
+
): Promise<{ text: string; details: Record<string, unknown>; isError: boolean }> => {
|
|
1371
|
+
const timeoutMs = Math.min(Math.max(1, params.timeoutSeconds ?? 1_800), 7_200) * 1000;
|
|
1372
|
+
const startedAt = Date.now();
|
|
1373
|
+
// The capture is optional on purpose: a case run with nothing being
|
|
1374
|
+
// captured still reports its exit code instead of failing.
|
|
1375
|
+
const target = params.captureId
|
|
1376
|
+
? state.captures.get(params.captureId)
|
|
1377
|
+
: state.activeCaptureId
|
|
1378
|
+
? state.captures.get(state.activeCaptureId)
|
|
1379
|
+
: undefined;
|
|
1380
|
+
|
|
1381
|
+
let bin: string;
|
|
1382
|
+
let argv: string[];
|
|
1383
|
+
let cwd: string | undefined;
|
|
1384
|
+
let label: string;
|
|
1385
|
+
if (!params.command) {
|
|
1386
|
+
throw new Error('await needs command="<shell line>".');
|
|
1387
|
+
}
|
|
1388
|
+
// A shell line, not an argv: the user pastes what they would type, which
|
|
1389
|
+
// includes the `cd` into whatever repo owns the test runner.
|
|
1390
|
+
bin = "/bin/sh";
|
|
1391
|
+
argv = ["-lc", params.command];
|
|
1392
|
+
cwd = root;
|
|
1393
|
+
label = params.command;
|
|
1394
|
+
|
|
1395
|
+
const since = target?.status().cursor ?? 0;
|
|
1396
|
+
const linesAtStart = target?.status().lineCount ?? 0;
|
|
1397
|
+
const result = await runCommand(bin, argv, {
|
|
1398
|
+
cwd,
|
|
1399
|
+
timeoutMs,
|
|
1400
|
+
signal,
|
|
1401
|
+
// Keep the tail only: a full test log can run to megabytes, and the
|
|
1402
|
+
// console capture already holds the app side of the story.
|
|
1403
|
+
maxBytes: 400_000,
|
|
1404
|
+
});
|
|
1405
|
+
const elapsedS = Math.round((Date.now() - startedAt) / 1000);
|
|
1406
|
+
|
|
1407
|
+
// Stopping is scoped to the targeted capture: a second app under debug
|
|
1408
|
+
// keeps streaming. The app itself is left running (keepApp semantics), so
|
|
1409
|
+
// the screen stays where the case left it.
|
|
1410
|
+
let captureNote = "no capture was running; nothing to stop";
|
|
1411
|
+
if (target) {
|
|
1412
|
+
stopCapture(target, false);
|
|
1413
|
+
await target.waitForExit(5_000);
|
|
1414
|
+
const status = target.status();
|
|
1415
|
+
const added = Math.max(0, status.lineCount - linesAtStart);
|
|
1416
|
+
captureNote = `stopped ${status.id} · ${added} new line(s) · ${status.logFile}`;
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
const verdict = result.timedOut
|
|
1420
|
+
? `timed out after ${timeoutMs / 1000}s (process killed)`
|
|
1421
|
+
: `exit ${result.code}`;
|
|
1422
|
+
const tail = lastLines(`${result.stdout}\n${result.stderr}`, 40);
|
|
1423
|
+
const text = [
|
|
1424
|
+
`awaited ${label} · ${verdict} · ${elapsedS}s`,
|
|
1425
|
+
captureNote,
|
|
1426
|
+
target ? `next: xcodebug action=logs captureId=${target.id} since=${since} - analyse the app side of this run` : "",
|
|
1427
|
+
tail ? `--- last output ---\n${tail}` : "",
|
|
1428
|
+
].filter(Boolean).join("\n");
|
|
1429
|
+
|
|
1430
|
+
return {
|
|
1431
|
+
text,
|
|
1432
|
+
details: {
|
|
1433
|
+
command: params.command,
|
|
1434
|
+
exitCode: result.code,
|
|
1435
|
+
timedOut: result.timedOut,
|
|
1436
|
+
elapsedSeconds: elapsedS,
|
|
1437
|
+
captureId: target?.id,
|
|
1438
|
+
cursor: since,
|
|
1439
|
+
},
|
|
1440
|
+
// A non-zero exit is a failed case, and the caller must see it as such
|
|
1441
|
+
// rather than as a successful "run finished".
|
|
1442
|
+
isError: result.timedOut || result.code !== 0,
|
|
1443
|
+
};
|
|
1444
|
+
};
|
|
1445
|
+
|
|
1446
|
+
/**
|
|
1447
|
+
* The single implementation behind both the tool and the /xcodebug command.
|
|
1448
|
+
*
|
|
1449
|
+
* Everything (build, install, launch, capture) lives here so the two surfaces
|
|
1450
|
+
* cannot drift apart.
|
|
1451
|
+
*/
|
|
1452
|
+
const runAction = async (
|
|
1453
|
+
params: ToolParams,
|
|
1454
|
+
ctx: ExtensionContext,
|
|
1455
|
+
signal: AbortSignal | undefined,
|
|
1456
|
+
onUpdate: ((update: { content: Array<{ type: "text"; text: string }>; details: unknown }) => void) | undefined,
|
|
1457
|
+
): Promise<{ content: Array<{ type: "text"; text: string }>; details: unknown; isError?: boolean }> => {
|
|
1458
|
+
state.uiCtx = ctx;
|
|
1459
|
+
// Resolved once per action: `pi.cwd` is undefined under pi 1.4.0, and every
|
|
1460
|
+
// lookup below (config, change detection, container discovery, the command's
|
|
1461
|
+
// working directory) must agree on one root or they disagree about the project.
|
|
1462
|
+
const projectRoot = resolveProjectRoot(pi, ctx);
|
|
1463
|
+
const config = await readConfig(projectRoot);
|
|
1464
|
+
const action = params.action;
|
|
1465
|
+
|
|
1466
|
+
if (action === "doctor") {
|
|
1467
|
+
const checks = await Promise.all([
|
|
1468
|
+
runCommand("xcodebuild", ["-version"], { timeoutMs: 30_000 }),
|
|
1469
|
+
runCommand("xcrun", ["devicectl", "--version"], { timeoutMs: 30_000 }),
|
|
1470
|
+
runCommand("idevicesyslog", ["--version"], { timeoutMs: 20_000 }),
|
|
1471
|
+
]);
|
|
1472
|
+
const lines = [
|
|
1473
|
+
`xcodebuild: ${checks[0].code === 0 ? checks[0].stdout.split("\n")[0] : "missing"}`,
|
|
1474
|
+
`devicectl: ${checks[1].code === 0 ? (checks[1].stdout || checks[1].stderr).trim().split("\n")[0] : "missing"}`,
|
|
1475
|
+
`idevicesyslog: ${checks[2].code === 0 ? (checks[2].stdout || checks[2].stderr).trim().split("\n")[0] : "missing (optional, syslog action only)"}`,
|
|
1476
|
+
`config: ${Object.keys(config).length > 0 ? join(projectRoot, ".xcodebug.json") : "(none)"}`,
|
|
1477
|
+
`log dir: ${logDir(ctx)}`,
|
|
1478
|
+
];
|
|
1479
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: {} };
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
if (action === "changes") {
|
|
1483
|
+
const report = await detectChanges(projectRoot);
|
|
1484
|
+
const lines = [
|
|
1485
|
+
describeChanges(report),
|
|
1486
|
+
`fingerprint: ${report.fingerprint}`,
|
|
1487
|
+
`last build in this session: ${state.lastBuiltFingerprint ?? "(none)"}`,
|
|
1488
|
+
`rebuild needed: ${report.needsBuild || state.lastBuiltFingerprint !== report.fingerprint ? "yes" : "no"}`,
|
|
1489
|
+
`pod install needed: ${report.podsNeedingInstall.length > 0 ? report.podsNeedingInstall.join(", ") : "no"}`,
|
|
1490
|
+
];
|
|
1491
|
+
return {
|
|
1492
|
+
content: [{ type: "text", text: lines.join("\n") }],
|
|
1493
|
+
details: { report, lastBuiltFingerprint: state.lastBuiltFingerprint },
|
|
1494
|
+
};
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
if (action === "devices") {
|
|
1498
|
+
const devices = await listDevices();
|
|
1499
|
+
return { content: [{ type: "text", text: describeDevices(devices) }], details: { devices } };
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
if (action === "build") {
|
|
1503
|
+
// Painting from the first line means the run is visible while the scheme
|
|
1504
|
+
// is still being resolved, which itself takes a few seconds.
|
|
1505
|
+
setRunPhase("resolving the project…");
|
|
1506
|
+
const device = await resolveDeviceParam(params.device, projectRoot);
|
|
1507
|
+
const target = await withContainer(projectRoot, config, params);
|
|
1508
|
+
const gate = await prepareRun(ctx, {
|
|
1509
|
+
root: projectRoot,
|
|
1510
|
+
force: params.force,
|
|
1511
|
+
installPods: params.installPods,
|
|
1512
|
+
timeoutSeconds: params.timeoutSeconds,
|
|
1513
|
+
signal,
|
|
1514
|
+
containerPath: target.workspace ?? target.project,
|
|
1515
|
+
onUpdate: (text) => onUpdate?.({ content: [{ type: "text", text }], details: {} }),
|
|
1516
|
+
});
|
|
1517
|
+
if (gate.podInstallFailed) {
|
|
1518
|
+
return {
|
|
1519
|
+
content: [{ type: "text", text: `${gate.podInstall}\n\n${describeChanges(gate.report)}` }],
|
|
1520
|
+
details: { report: gate.report },
|
|
1521
|
+
isError: true,
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
if (!gate.needsBuild) {
|
|
1525
|
+
const summary =
|
|
1526
|
+
gate.report.changed.length === 0
|
|
1527
|
+
? "no build-relevant changes"
|
|
1528
|
+
: `${gate.report.changed.length} changed file(s), but they are unchanged since the last successful build`;
|
|
1529
|
+
return {
|
|
1530
|
+
content: [{ type: "text", text: `build skipped: ${summary} (fingerprint ${gate.report.fingerprint}; pass force=true to rebuild)` }],
|
|
1531
|
+
details: { report: gate.report, skipped: true },
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
setRunPhase(`building ${target.scheme} for ${device.name}`);
|
|
1535
|
+
const outcome = await buildForDevice(target, device, {
|
|
1536
|
+
logDir: logDir(ctx),
|
|
1537
|
+
cwd: projectRoot,
|
|
1538
|
+
// Several frames a second: repaint one line instead of emitting messages.
|
|
1539
|
+
onProgress: (text) => setRunPhase(text),
|
|
1540
|
+
timeoutMs: (params.timeoutSeconds ?? 900) * 1000,
|
|
1541
|
+
signal,
|
|
1542
|
+
});
|
|
1543
|
+
clearRunPhase();
|
|
1544
|
+
if (outcome.ok) {
|
|
1545
|
+
state.lastBuiltFingerprint = (await detectChanges(projectRoot)).fingerprint;
|
|
1546
|
+
await clearArchiveBeforeNewRun(ctx);
|
|
1547
|
+
}
|
|
1548
|
+
const prefix = gate.podInstall ? `${gate.podInstall}\n` : "";
|
|
1549
|
+
return {
|
|
1550
|
+
content: [{ type: "text", text: `${prefix}${outcome.summary}\nlog: ${outcome.logFile}` }],
|
|
1551
|
+
details: { ...outcome, report: gate.report },
|
|
1552
|
+
isError: !outcome.ok,
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
if (action === "install") {
|
|
1557
|
+
const device = await resolveDeviceParam(params.device, projectRoot);
|
|
1558
|
+
const appPath = params.appPath;
|
|
1559
|
+
if (!appPath) throw new Error("install requires appPath (or use action=build first).");
|
|
1560
|
+
const outcome = await installApp(device, appPath, { timeoutMs: (params.timeoutSeconds ?? 180) * 1000, signal });
|
|
1561
|
+
return {
|
|
1562
|
+
content: [{ type: "text", text: `${outcome.message}\napp: ${appPath}\ndevice: ${device.name}` }],
|
|
1563
|
+
details: outcome,
|
|
1564
|
+
isError: !outcome.ok,
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
if (action === "restart") {
|
|
1569
|
+
// `/xcodebug restart` answers the mid-run question "I just changed the
|
|
1570
|
+
// code, now what?": rebuild, relaunch and reattach without retyping the
|
|
1571
|
+
// phrase, the device or the scheme. It replays the last launch's params,
|
|
1572
|
+
// so a restart after an edit is one word instead of the original command.
|
|
1573
|
+
const last = state.lastLaunch;
|
|
1574
|
+
if (!last) {
|
|
1575
|
+
throw new Error(
|
|
1576
|
+
"restart needs a previous launch in this session. Start one with `/xcodebug <goal>`, then `restart` after editing.",
|
|
1577
|
+
);
|
|
1578
|
+
}
|
|
1579
|
+
// The rebuild must happen even though nothing else changed about the
|
|
1580
|
+
// invocation: the point of restart is the edited code, and the pod/build
|
|
1581
|
+
// gate would otherwise reuse the stale build.
|
|
1582
|
+
const replay: ToolParams = {
|
|
1583
|
+
action: "launch",
|
|
1584
|
+
// Explicit args win over the remembered ones: `restart device=X` has to
|
|
1585
|
+
// target X, not silently relaunch on the previous device.
|
|
1586
|
+
goal: params.goal ?? last.goal,
|
|
1587
|
+
bundleId: params.bundleId ?? last.bundleId,
|
|
1588
|
+
processName: params.processName ?? last.processName,
|
|
1589
|
+
args: params.args ?? last.args,
|
|
1590
|
+
environment: params.environment ?? last.environment,
|
|
1591
|
+
device: params.device ?? last.device,
|
|
1592
|
+
scheme: params.scheme ?? last.scheme,
|
|
1593
|
+
workspace: params.workspace ?? last.workspace,
|
|
1594
|
+
project: params.project ?? last.project,
|
|
1595
|
+
configuration: params.configuration ?? last.configuration,
|
|
1596
|
+
derivedDataPath: params.derivedDataPath ?? last.derivedDataPath,
|
|
1597
|
+
push: params.push ?? last.push,
|
|
1598
|
+
match: params.match ?? last.match,
|
|
1599
|
+
dualChannel: params.dualChannel ?? last.dualChannel,
|
|
1600
|
+
terminateExisting: params.terminateExisting ?? true,
|
|
1601
|
+
// These two are per-invocation, not properties of the app, so they pass
|
|
1602
|
+
// straight through instead of being remembered. `appPath` deliberately
|
|
1603
|
+
// is not forwarded: `force` above always rebuilds, which overwrites it.
|
|
1604
|
+
installPods: params.installPods,
|
|
1605
|
+
timeoutSeconds: params.timeoutSeconds,
|
|
1606
|
+
// The command rides along so restart keeps an edit→restart→test loop intact.
|
|
1607
|
+
command: params.command ?? last.command,
|
|
1608
|
+
build: true,
|
|
1609
|
+
force: true,
|
|
1610
|
+
};
|
|
1611
|
+
const result = await runAction(replay, ctx, signal, onUpdate);
|
|
1612
|
+
return {
|
|
1613
|
+
content: [{
|
|
1614
|
+
type: "text",
|
|
1615
|
+
// Report the merged values, not `last`: an explicit override means the
|
|
1616
|
+
// app being relaunched is not the one remembered.
|
|
1617
|
+
text: `restarting ${replay.bundleId}${replay.processName ? ` (${replay.processName})` : ""}\n${result.content[0]?.text ?? ""}`,
|
|
1618
|
+
}],
|
|
1619
|
+
details: { restart: true, previous: last, launch: result.details },
|
|
1620
|
+
isError: result.isError,
|
|
1621
|
+
};
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
if (action === "launch") {
|
|
1625
|
+
setRunPhase("resolving the project…");
|
|
1626
|
+
const device = await resolveDeviceParam(params.device, projectRoot);
|
|
1627
|
+
let appPath = params.appPath;
|
|
1628
|
+
let bundleId = params.bundleId ?? config.bundleId;
|
|
1629
|
+
let executable: string | undefined;
|
|
1630
|
+
|
|
1631
|
+
// Every run re-checks the working tree: new files in a pod need
|
|
1632
|
+
// `pod install`, and any build-relevant change needs a fresh build.
|
|
1633
|
+
// An explicit appPath means "use this app as-is". Only build when the
|
|
1634
|
+
// caller also asked for it; otherwise a missing scheme must not block.
|
|
1635
|
+
const explicitApp = params.appPath !== undefined;
|
|
1636
|
+
const wantsBuild = params.build === true || params.force === true;
|
|
1637
|
+
// Resolve the container up front: the Podfile that governs this run lives
|
|
1638
|
+
// beside it, so the pod gate must not search from an arbitrary cwd.
|
|
1639
|
+
const launchTarget = explicitApp && !wantsBuild ? undefined : await withContainer(projectRoot, config, params);
|
|
1640
|
+
const gate = await prepareRun(ctx, {
|
|
1641
|
+
root: projectRoot,
|
|
1642
|
+
force: params.force,
|
|
1643
|
+
installPods: explicitApp && !wantsBuild ? false : params.installPods,
|
|
1644
|
+
timeoutSeconds: params.timeoutSeconds,
|
|
1645
|
+
signal,
|
|
1646
|
+
containerPath: launchTarget ? (launchTarget.workspace ?? launchTarget.project) : undefined,
|
|
1647
|
+
onUpdate: (text) => onUpdate?.({ content: [{ type: "text", text }], details: {} }),
|
|
1648
|
+
});
|
|
1649
|
+
const notes = [...gate.notes];
|
|
1650
|
+
if (gate.podInstall) notes.push(gate.podInstall);
|
|
1651
|
+
|
|
1652
|
+
if (gate.podInstallFailed) {
|
|
1653
|
+
return {
|
|
1654
|
+
content: [{ type: "text", text: `${gate.podInstall}\n\n${describeChanges(gate.report)}` }],
|
|
1655
|
+
details: { report: gate.report },
|
|
1656
|
+
isError: true,
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
// Rebuild when the tree changed, when no build happened yet in this
|
|
1661
|
+
// session, when the caller asked for a build, or when force is set.
|
|
1662
|
+
const mustBuild = explicitApp && !wantsBuild ? false : gate.needsBuild || wantsBuild || !appPath;
|
|
1663
|
+
if (mustBuild) {
|
|
1664
|
+
const target = launchTarget ?? (await withContainer(projectRoot, config, params));
|
|
1665
|
+
setRunPhase(`building ${target.scheme} for ${device.name}`);
|
|
1666
|
+
const build = await buildForDevice(target, device, {
|
|
1667
|
+
logDir: logDir(ctx),
|
|
1668
|
+
cwd: projectRoot,
|
|
1669
|
+
onProgress: (text) => setRunPhase(text),
|
|
1670
|
+
timeoutMs: (params.timeoutSeconds ?? 900) * 1000,
|
|
1671
|
+
signal,
|
|
1672
|
+
});
|
|
1673
|
+
clearRunPhase();
|
|
1674
|
+
if (!build.ok) {
|
|
1675
|
+
return {
|
|
1676
|
+
content: [{ type: "text", text: `${notes.join("\n")}\n${build.summary}\nlog: ${build.logFile}` }],
|
|
1677
|
+
details: build,
|
|
1678
|
+
isError: true,
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
state.lastBuiltFingerprint = (await detectChanges(projectRoot)).fingerprint;
|
|
1682
|
+
notes.push(await clearArchiveBeforeNewRun(ctx));
|
|
1683
|
+
appPath = build.appPath;
|
|
1684
|
+
bundleId = build.bundleId ?? bundleId;
|
|
1685
|
+
executable = build.executable;
|
|
1686
|
+
notes.push(build.summary);
|
|
1687
|
+
if (!appPath) throw new Error(`Build succeeded but the product path is unknown.\nlog: ${build.logFile}`);
|
|
1688
|
+
} else {
|
|
1689
|
+
notes.push(`reusing this session's build (no changes since fingerprint ${gate.report.fingerprint})`);
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
if (!appPath) throw new Error("launch requires appPath, or a scheme to build.");
|
|
1693
|
+
executable ??= params.processName ?? (await readBundleExecutable(appPath));
|
|
1694
|
+
const install = await installApp(device, appPath, { timeoutMs: 180_000, signal });
|
|
1695
|
+
if (!install.ok) {
|
|
1696
|
+
return { content: [{ type: "text", text: install.message }], details: install, isError: true };
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
const resolvedBundleId = bundleId ?? params.bundleId ?? (await readBundleIdentifier(appPath));
|
|
1700
|
+
if (!resolvedBundleId) throw new Error("launch requires bundleId (or an appPath whose Info.plist carries one).");
|
|
1701
|
+
|
|
1702
|
+
// Retire the previous run for this app BEFORE the new bridge starts.
|
|
1703
|
+
//
|
|
1704
|
+
// This used to run after `capture.start()`, to keep the session from being
|
|
1705
|
+
// left with no capture at all if starting the new one threw. That trade is
|
|
1706
|
+
// wrong in the common case: `devicectl --console` takes a second or two to
|
|
1707
|
+
// attach, and during that window the old capture is still pushing its
|
|
1708
|
+
// app's lines into the conversation - so a relaunch interleaves two runs
|
|
1709
|
+
// and the reader cannot tell which one a line belongs to. A failed start
|
|
1710
|
+
// reports its own error, which is a clearer outcome than mixed logs.
|
|
1711
|
+
await stopRunningCaptures(executable, undefined);
|
|
1712
|
+
|
|
1713
|
+
// One launch only: devicectl --console starts the app, attaches its
|
|
1714
|
+
// stdout/stderr (plus os_log via OS_ACTIVITY_DT_MODE) and keeps running
|
|
1715
|
+
// until the app exits. A second plain launch would create a second,
|
|
1716
|
+
// short-lived instance and leave a stale pid behind.
|
|
1717
|
+
const capture = new Capture({
|
|
1718
|
+
mode: "console",
|
|
1719
|
+
deviceId: device.id,
|
|
1720
|
+
deviceLabel: device.name,
|
|
1721
|
+
bundleId: resolvedBundleId,
|
|
1722
|
+
processName: executable,
|
|
1723
|
+
logDir: logDir(ctx),
|
|
1724
|
+
command: "xcrun",
|
|
1725
|
+
args: consoleLaunchArgs(device, resolvedBundleId, {
|
|
1726
|
+
args: params.args ?? config.args,
|
|
1727
|
+
terminateExisting: params.terminateExisting !== false,
|
|
1728
|
+
environment: { ...(config.environment ?? {}), ...(params.environment ?? {}) },
|
|
1729
|
+
}),
|
|
1730
|
+
});
|
|
1731
|
+
await capture.start();
|
|
1732
|
+
state.captures.set(capture.id, capture);
|
|
1733
|
+
state.activeCaptureId = capture.id;
|
|
1734
|
+
watchExit(capture, device);
|
|
1735
|
+
const pushMode = defaultPushMode(params);
|
|
1736
|
+
if (pushMode !== "off") startPush(capture, pushMode, params.match);
|
|
1737
|
+
// Start the ticker after pushing is configured: the header counts pushed
|
|
1738
|
+
// channels, so painting before pushMode is set would show "0 streaming".
|
|
1739
|
+
startStatusTicker();
|
|
1740
|
+
// Remember enough to relaunch this same app when `/xcodebug restart` asks
|
|
1741
|
+
// for it after a code change. The device and the phrase are the parts a
|
|
1742
|
+
// user should not have to repeat.
|
|
1743
|
+
state.lastLaunch = {
|
|
1744
|
+
bundleId: resolvedBundleId,
|
|
1745
|
+
processName: executable,
|
|
1746
|
+
goal: params.goal,
|
|
1747
|
+
args: params.args ?? config.args,
|
|
1748
|
+
environment: { ...(config.environment ?? {}), ...(params.environment ?? {}) },
|
|
1749
|
+
device: params.device ?? config.device,
|
|
1750
|
+
scheme: params.scheme ?? config.scheme,
|
|
1751
|
+
workspace: params.workspace ?? config.workspace,
|
|
1752
|
+
project: params.project ?? config.project,
|
|
1753
|
+
configuration: params.configuration ?? config.configuration,
|
|
1754
|
+
derivedDataPath: params.derivedDataPath ?? config.derivedDataPath,
|
|
1755
|
+
push: params.push,
|
|
1756
|
+
match: params.match,
|
|
1757
|
+
dualChannel: params.dualChannel,
|
|
1758
|
+
command: params.command,
|
|
1759
|
+
};
|
|
1760
|
+
// The previous run for this app was already retired before this capture
|
|
1761
|
+
// started (see above), so nothing is left to stop here. Other apps'
|
|
1762
|
+
// captures are untouched either way.
|
|
1763
|
+
// Second channel: idevicesyslog reads the device's unified log directly
|
|
1764
|
+
// and survives a dropped --console bridge. It carries os_log only, so
|
|
1765
|
+
// NSLog/print lines (MySDK) stay exclusive to the console channel -
|
|
1766
|
+
// this is a safety net for the gap, not a replacement.
|
|
1767
|
+
if (executable && params.dualChannel !== false) {
|
|
1768
|
+
const syslogCapture = new Capture({
|
|
1769
|
+
mode: "syslog",
|
|
1770
|
+
deviceId: device.id,
|
|
1771
|
+
deviceLabel: device.name,
|
|
1772
|
+
bundleId: resolvedBundleId,
|
|
1773
|
+
processName: executable,
|
|
1774
|
+
logDir: logDir(ctx),
|
|
1775
|
+
command: "idevicesyslog",
|
|
1776
|
+
args: ["-u", device.udid ?? device.id, "-p", executable, "--no-colors"],
|
|
1777
|
+
});
|
|
1778
|
+
try {
|
|
1779
|
+
await syslogCapture.start();
|
|
1780
|
+
state.captures.set(syslogCapture.id, syslogCapture);
|
|
1781
|
+
state.companions.set(capture.id, syslogCapture.id);
|
|
1782
|
+
watchExit(syslogCapture, device);
|
|
1783
|
+
notes.push(`syslog channel: ${syslogCapture.id}`);
|
|
1784
|
+
} catch (error) {
|
|
1785
|
+
notes.push(`syslog channel unavailable: ${(error as Error).message}`);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
// The app pid is not part of --console's output; discover it from the
|
|
1790
|
+
// process table so terminate can target the app rather than the bridge.
|
|
1791
|
+
if (executable) {
|
|
1792
|
+
const deadline = Date.now() + 20_000;
|
|
1793
|
+
while (Date.now() < deadline && capture.appPid === undefined && capture.running) {
|
|
1794
|
+
capture.appPid = await findProcessPid(device, executable, { attempts: 1 });
|
|
1795
|
+
if (capture.appPid === undefined) await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
return {
|
|
1800
|
+
content: [{
|
|
1801
|
+
type: "text",
|
|
1802
|
+
text: [
|
|
1803
|
+
...notes,
|
|
1804
|
+
`launched ${resolvedBundleId} on ${device.name}${capture.appPid ? ` (pid ${capture.appPid})` : ""}`,
|
|
1805
|
+
`capture: ${capture.id} · push=${pushMode}`,
|
|
1806
|
+
`log: ${capture.logFile}`,
|
|
1807
|
+
"next: xcodebug action=logs (cursor is tracked per capture), or action=wait match=\"...\"",
|
|
1808
|
+
].join("\n"),
|
|
1809
|
+
}],
|
|
1810
|
+
details: { capture: capture.status(), report: gate.report, built: mustBuild },
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
if (action === "syslog") {
|
|
1815
|
+
const device = await resolveDeviceParam(params.device, projectRoot);
|
|
1816
|
+
const processName = params.processName ?? config.scheme;
|
|
1817
|
+
if (!processName) throw new Error("syslog requires processName (the app's executable/process name).");
|
|
1818
|
+
// Same ordering as `launch`: retire the previous bridge for this app before
|
|
1819
|
+
// the new one attaches, so the two never push the same app's lines at once.
|
|
1820
|
+
await stopRunningCaptures(processName, undefined);
|
|
1821
|
+
const args = ["-u", device.udid ?? device.id, "-p", processName, "--no-colors"];
|
|
1822
|
+
if (params.match) args.push("-m", params.match);
|
|
1823
|
+
const capture = new Capture({
|
|
1824
|
+
mode: "syslog",
|
|
1825
|
+
deviceId: device.id,
|
|
1826
|
+
deviceLabel: device.name,
|
|
1827
|
+
bundleId: params.bundleId ?? config.bundleId ?? processName,
|
|
1828
|
+
processName,
|
|
1829
|
+
logDir: logDir(ctx),
|
|
1830
|
+
command: "idevicesyslog",
|
|
1831
|
+
args,
|
|
1832
|
+
});
|
|
1833
|
+
await capture.start();
|
|
1834
|
+
state.captures.set(capture.id, capture);
|
|
1835
|
+
state.activeCaptureId = capture.id;
|
|
1836
|
+
watchExit(capture, device);
|
|
1837
|
+
const pushMode = defaultPushMode(params);
|
|
1838
|
+
if (pushMode !== "off") startPush(capture, pushMode, params.match);
|
|
1839
|
+
startStatusTicker();
|
|
1840
|
+
return {
|
|
1841
|
+
content: [{
|
|
1842
|
+
type: "text",
|
|
1843
|
+
text: [
|
|
1844
|
+
`syslog capture started for ${processName} on ${device.name} (app keeps running)`,
|
|
1845
|
+
`capture: ${capture.id} · push=${pushMode}`,
|
|
1846
|
+
`log: ${capture.logFile}`,
|
|
1847
|
+
].join("\n"),
|
|
1848
|
+
}],
|
|
1849
|
+
details: { capture: capture.status() },
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
if (action === "logs") {
|
|
1854
|
+
const capture = requireCapture(params.captureId);
|
|
1855
|
+
const since = params.since ?? 0;
|
|
1856
|
+
const formatted = formatLogLines(capture, since, params.limit ?? 200, params.grep);
|
|
1857
|
+
const companionId = state.companions.get(capture.id);
|
|
1858
|
+
if (!capture.running && companionId) {
|
|
1859
|
+
formatted.text += `\n\n[this channel has ended; system-level logs continue in ${companionId} - pass captureId=${companionId}]`;
|
|
1860
|
+
}
|
|
1861
|
+
return {
|
|
1862
|
+
content: [{ type: "text", text: formatted.text }],
|
|
1863
|
+
details: { captureId: capture.id, cursor: formatted.cursor, total: formatted.total, running: capture.running },
|
|
1864
|
+
};
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
if (action === "wait") {
|
|
1868
|
+
const capture = requireCapture(params.captureId);
|
|
1869
|
+
const needle = params.match;
|
|
1870
|
+
if (!needle) throw new Error("wait requires match (a substring to wait for).");
|
|
1871
|
+
const timeoutMs = Math.min(Math.max(1, params.timeoutSeconds ?? 30), 600) * 1000;
|
|
1872
|
+
const since = params.since ?? 0;
|
|
1873
|
+
|
|
1874
|
+
const matches: LogLine[] = [];
|
|
1875
|
+
const seen = new Set<number>();
|
|
1876
|
+
let finished = false;
|
|
1877
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1878
|
+
let unsubscribeLine: () => void = () => {};
|
|
1879
|
+
let unsubscribeExit: () => void = () => {};
|
|
1880
|
+
let onAbort: (() => void) | undefined;
|
|
1881
|
+
let resolveWait: (text: string) => void = () => {};
|
|
1882
|
+
|
|
1883
|
+
const settle = (timedOut: boolean): string => {
|
|
1884
|
+
const cursor = capture.status().cursor;
|
|
1885
|
+
if (matches.length === 0) {
|
|
1886
|
+
return timedOut
|
|
1887
|
+
? `timed out after ${timeoutMs / 1000}s waiting for "${needle}" (cursor ${cursor})`
|
|
1888
|
+
: `capture ended before "${needle}" appeared (cursor ${cursor})`;
|
|
1889
|
+
}
|
|
1890
|
+
const body = matches
|
|
1891
|
+
.slice(0, 200)
|
|
1892
|
+
.map((line) => `${String(line.index).padStart(6, " ")} ${line.text}`)
|
|
1893
|
+
.join("\n");
|
|
1894
|
+
return `matched ${matches.length} line(s) · cursor ${cursor}\n${body}`;
|
|
1895
|
+
};
|
|
1896
|
+
|
|
1897
|
+
const finish = (timedOut: boolean): void => {
|
|
1898
|
+
if (finished) return;
|
|
1899
|
+
finished = true;
|
|
1900
|
+
if (timer) clearTimeout(timer);
|
|
1901
|
+
unsubscribeLine();
|
|
1902
|
+
unsubscribeExit();
|
|
1903
|
+
// `once` only detaches when abort actually fires; a normal match or a
|
|
1904
|
+
// timeout would leave the listener on the caller's signal for good.
|
|
1905
|
+
if (onAbort) signal?.removeEventListener("abort", onAbort);
|
|
1906
|
+
resolveWait(settle(timedOut));
|
|
1907
|
+
};
|
|
1908
|
+
|
|
1909
|
+
const collect = (line: LogLine): void => {
|
|
1910
|
+
if (finished || line.index <= since || seen.has(line.index)) return;
|
|
1911
|
+
if (!line.text.includes(needle)) return;
|
|
1912
|
+
seen.add(line.index);
|
|
1913
|
+
matches.push(line);
|
|
1914
|
+
};
|
|
1915
|
+
|
|
1916
|
+
const text = await new Promise<string>((resolve) => {
|
|
1917
|
+
resolveWait = resolve;
|
|
1918
|
+
// Subscribe first, then scan the backlog: the scan covers
|
|
1919
|
+
// [since, cursor] and the listener covers everything after it, so no
|
|
1920
|
+
// line can fall through the gap.
|
|
1921
|
+
unsubscribeLine = capture.onLine((line) => {
|
|
1922
|
+
collect(line);
|
|
1923
|
+
// Let the rest of the same chunk land before settling.
|
|
1924
|
+
if (matches.length > 0) setTimeout(() => finish(false), 50);
|
|
1925
|
+
});
|
|
1926
|
+
unsubscribeExit = capture.onExit(() => setTimeout(() => finish(false), 0));
|
|
1927
|
+
timer = setTimeout(() => finish(true), timeoutMs);
|
|
1928
|
+
onAbort = (): void => finish(true);
|
|
1929
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1930
|
+
|
|
1931
|
+
for (const line of capture.read({ since, limit: 500, grep: needle }).lines) collect(line);
|
|
1932
|
+
|
|
1933
|
+
// A pattern already present in the backlog must return immediately,
|
|
1934
|
+
// not wait out the timeout.
|
|
1935
|
+
if (matches.length > 0) finish(false);
|
|
1936
|
+
else if (!capture.running) finish(false);
|
|
1937
|
+
});
|
|
1938
|
+
|
|
1939
|
+
return {
|
|
1940
|
+
content: [{ type: "text", text }],
|
|
1941
|
+
details: { captureId: capture.id, cursor: capture.status().cursor, matched: matches.length },
|
|
1942
|
+
isError: matches.length === 0,
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
if (action === "status") {
|
|
1947
|
+
if (state.captures.size === 0) {
|
|
1948
|
+
return { content: [{ type: "text", text: "no captures in this session" }], details: {} };
|
|
1949
|
+
}
|
|
1950
|
+
const lines = [...state.captures.values()].map((capture) => {
|
|
1951
|
+
const status = capture.status();
|
|
1952
|
+
const stateText = status.running ? "running" : `exited${status.exitCode !== undefined ? ` code=${status.exitCode}` : ""}`;
|
|
1953
|
+
const role = state.companions.get(status.id)
|
|
1954
|
+
? " · primary"
|
|
1955
|
+
: [...state.companions.values()].includes(status.id)
|
|
1956
|
+
? " · companion"
|
|
1957
|
+
: "";
|
|
1958
|
+
return `- ${status.id} [${status.mode}] ${stateText}${role} · ${status.lineCount} lines · ${status.bundleId} · ${status.logFile}`;
|
|
1959
|
+
});
|
|
1960
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { captures: [...state.captures.values()].map((capture) => capture.status()) } };
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
if (action === "stop") {
|
|
1964
|
+
const keepApp = params.keepApp !== false;
|
|
1965
|
+
// A bare `stop` means "stop what is running", not "guess one capture":
|
|
1966
|
+
// a launch records a console capture plus its syslog companion, and an
|
|
1967
|
+
// earlier run may still be live for another app. Stopping a single
|
|
1968
|
+
// arbitrary one would leave bridges streaming after the user asked for
|
|
1969
|
+
// silence, so the no-selector form closes every running capture.
|
|
1970
|
+
// `stop` is the last step of a run, often after the app was terminated or
|
|
1971
|
+
// exited on its own - in which case the captures already ended and there is
|
|
1972
|
+
// nothing left to close. That is the state the caller asked for, so it
|
|
1973
|
+
// reports success; only an explicitly named capture that never existed is
|
|
1974
|
+
// an error (requireCapture throws for that).
|
|
1975
|
+
const targets = params.captureId
|
|
1976
|
+
? [requireCapture(params.captureId)]
|
|
1977
|
+
: [...state.captures.values()].filter((c) => c.running);
|
|
1978
|
+
if (targets.length === 0) {
|
|
1979
|
+
const known = [...state.captures.values()].map((c) => `${c.id} (${c.mode}, ended)`);
|
|
1980
|
+
return {
|
|
1981
|
+
content: [{
|
|
1982
|
+
type: "text",
|
|
1983
|
+
text: known.length > 0
|
|
1984
|
+
? `nothing to stop - every capture has already ended: ${known.join(", ")}`
|
|
1985
|
+
: "nothing to stop - no capture has been started in this session",
|
|
1986
|
+
}],
|
|
1987
|
+
details: { captures: [...state.captures.values()].map((capture) => capture.status()) },
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
for (const capture of targets) stopCapture(capture, !keepApp);
|
|
1991
|
+
for (const capture of targets) await capture.waitForExit(5_000);
|
|
1992
|
+
const lines = targets.map((capture) => {
|
|
1993
|
+
const status = capture.status();
|
|
1994
|
+
return `${status.id} (${status.mode}) ${status.running ? "still shutting down" : "exited"} · ${status.lineCount} lines · ${status.logFile}`;
|
|
1995
|
+
});
|
|
1996
|
+
return {
|
|
1997
|
+
content: [{
|
|
1998
|
+
type: "text",
|
|
1999
|
+
text: `stopped ${targets.length} capture(s)\n${lines.join("\n")}`,
|
|
2000
|
+
}],
|
|
2001
|
+
details: { captures: targets.map((capture) => capture.status()) },
|
|
2002
|
+
};
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
if (action === "terminate") {
|
|
2006
|
+
const device = await resolveDeviceParam(params.device, projectRoot);
|
|
2007
|
+
const capture = state.activeCaptureId ? state.captures.get(state.activeCaptureId) : undefined;
|
|
2008
|
+
const bundleId = params.bundleId ?? capture?.bundleId ?? config.bundleId;
|
|
2009
|
+
if (!bundleId) throw new Error("terminate requires bundleId or an active capture.");
|
|
2010
|
+
const executable = params.processName ?? capture?.processName ?? config.scheme;
|
|
2011
|
+
// Prefer the app pid recorded at launch; the process table can lag a fresh launch.
|
|
2012
|
+
const knownPid = capture?.appPid;
|
|
2013
|
+
const pid = knownPid ?? (executable ? await findProcessPid(device, executable) : undefined);
|
|
2014
|
+
if (!pid) {
|
|
2015
|
+
return { content: [{ type: "text", text: `no running process for ${bundleId} on ${device.name}` }], details: {} };
|
|
2016
|
+
}
|
|
2017
|
+
const outcome = await terminateApp(device, pid, { timeoutMs: 30_000 });
|
|
2018
|
+
return {
|
|
2019
|
+
content: [{ type: "text", text: outcome.message }],
|
|
2020
|
+
details: { ...outcome, pid },
|
|
2021
|
+
isError: !outcome.ok,
|
|
2022
|
+
};
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
if (action === "await") {
|
|
2026
|
+
const outcome = await runCaseThenStop(params, signal, projectRoot);
|
|
2027
|
+
return {
|
|
2028
|
+
content: [{ type: "text", text: outcome.text }],
|
|
2029
|
+
details: outcome.details,
|
|
2030
|
+
isError: outcome.isError,
|
|
2031
|
+
};
|
|
2032
|
+
}
|
|
2033
|
+
throw new Error(`Unknown action: ${String(params.action)}`);
|
|
2034
|
+
};
|
|
2035
|
+
|
|
2036
|
+
/**
|
|
2037
|
+
* Run the main action, then the command it names.
|
|
2038
|
+
*
|
|
2039
|
+
* `command=` is a second phase, not an action: the app must be built,
|
|
2040
|
+
* installed, launched and capturing before the command runs, or the log would
|
|
2041
|
+
* have nothing about this run in it. Shared by the tool and the slash command
|
|
2042
|
+
* so the two surfaces cannot drift.
|
|
2043
|
+
*
|
|
2044
|
+
* Returns `ranCommand` so the caller can decide how the result reaches the
|
|
2045
|
+
* session: a finished command run is worth steering on, a bare launch is not.
|
|
2046
|
+
*/
|
|
2047
|
+
const runActionThenCommand = async (
|
|
2048
|
+
params: ToolParams,
|
|
2049
|
+
ctx: ExtensionContext,
|
|
2050
|
+
signal: AbortSignal | undefined,
|
|
2051
|
+
onUpdate: ((update: { content: Array<{ type: "text"; text: string }>; details: unknown }) => void) | undefined,
|
|
2052
|
+
): Promise<{
|
|
2053
|
+
content: Array<{ type: "text"; text: string }>;
|
|
2054
|
+
details: unknown;
|
|
2055
|
+
isError?: boolean;
|
|
2056
|
+
ranCommand: boolean;
|
|
2057
|
+
}> => {
|
|
2058
|
+
// `restart` names no command of its own: it replays the remembered launch,
|
|
2059
|
+
// and that launch may have carried the shell line. Resolving it here is what
|
|
2060
|
+
// makes the edit → restart → test loop work; reading only `params.command`
|
|
2061
|
+
// would rebuild and relaunch while silently skipping the test.
|
|
2062
|
+
const command =
|
|
2063
|
+
params.command ?? (params.action === "restart" ? state.lastLaunch?.command : undefined);
|
|
2064
|
+
const primary = await runAction(params, ctx, signal, onUpdate);
|
|
2065
|
+
if (primary.isError === true || !command || params.action === "await") {
|
|
2066
|
+
return { ...primary, ranCommand: false };
|
|
2067
|
+
}
|
|
2068
|
+
setRunPhase(`command: ${command}`);
|
|
2069
|
+
const outcome = await runCaseThenStop({ ...params, command }, signal, resolveProjectRoot(pi, ctx));
|
|
2070
|
+
const head = primary.content[0]?.text ?? "";
|
|
2071
|
+
return {
|
|
2072
|
+
content: [{ type: "text", text: `${head}\n\n${outcome.text}` }],
|
|
2073
|
+
details: { primary: primary.details, command: outcome.details },
|
|
2074
|
+
isError: outcome.isError,
|
|
2075
|
+
ranCommand: true,
|
|
2076
|
+
};
|
|
2077
|
+
};
|
|
2078
|
+
|
|
2079
|
+
pi.registerTool({
|
|
2080
|
+
name: "xcodebug",
|
|
2081
|
+
label: "Xcode Device Debug",
|
|
2082
|
+
description:
|
|
2083
|
+
"Build/install/launch an iOS app on a physical device and stream its Xcode-console output into this session. " +
|
|
2084
|
+
"Actions: devices, changes, build, install, launch, syslog, logs, wait, status, stop, terminate, doctor, restart, await. " +
|
|
2085
|
+
"build and launch first check the working tree: any source change rebuilds, and a new file inside a pod runs " +
|
|
2086
|
+
"pod install first. An unchanged tree reuses this session's build (force=true overrides). " +
|
|
2087
|
+
"launch restarts the app and captures stdout/stderr + os_log (no jailbreak, no LLDB). " +
|
|
2088
|
+
"syslog attaches to an already-running app without restarting it. " +
|
|
2089
|
+
"restart rebuilds, reinstalls and relaunches the last app in this session, for a mid-run code edit; a command= that launch carried runs again afterwards, so restart alone closes the edit→restart→test loop. " +
|
|
2090
|
+
"await runs a shell command (command=\"...\") to completion, then stops the capture it was watching and reports the exit code, so an automated run and its app-side log arrive together. Passing command= to launch runs it after the app is already up, which is the one-command linkage run.",
|
|
2091
|
+
promptSnippet: "Build/launch an iOS app on a real device and read its console logs",
|
|
2092
|
+
promptGuidelines: [
|
|
2093
|
+
"Use xcodebug instead of raw xcodebuild/devicectl when debugging on a physical iOS device; it keeps a cursor so xcodebug action=logs returns only new output.",
|
|
2094
|
+
"xcodebug action=launch restarts the app; use action=syslog when the app must keep running.",
|
|
2095
|
+
"Use xcodebug action=wait to block on an expected log line when verifying a feature end to end.",
|
|
2096
|
+
"xcodebug action=changes reports whether a rebuild or pod install is pending without running either.",
|
|
2097
|
+
"After editing code mid-run, use xcodebug action=restart instead of a full launch: it replays the last launch's app, device, scheme, goal and command, and forces the rebuild.",
|
|
2098
|
+
"For an automated run, pass command=\"cd /repo && npm run test:xxx\" to launch: it builds, installs, launches, runs the command to completion, then stops the capture and returns the exit code plus the app-side cursor. Never poll the log for silence to decide a run is done.",
|
|
2099
|
+
"The command's runner must not restart the app itself (disable any auto-launch option in the test config), or the launch that xcodebug is capturing dies and the log stops at the restart.",
|
|
2100
|
+
"Verification is a loop: run, read the log, stop, edit the code, run again. Once the log has answered the question, call action=stop and report the conclusion - keeping the capture alive only floods the session.",
|
|
2101
|
+
"The one case where you must NOT stop: the user has not touched the app yet, so the log is silent because nothing happened. Wait, tell them what to do on the phone, and keep capturing.",
|
|
2102
|
+
"A capture also ends on its own when the app process exits; do not reconnect a run whose app the user deliberately closed.",
|
|
2103
|
+
],
|
|
2104
|
+
executionMode: "sequential",
|
|
2105
|
+
parameters: Type.Object({
|
|
2106
|
+
action: Type.Union([
|
|
2107
|
+
Type.Literal("devices"),
|
|
2108
|
+
Type.Literal("build"),
|
|
2109
|
+
Type.Literal("install"),
|
|
2110
|
+
Type.Literal("launch"),
|
|
2111
|
+
Type.Literal("syslog"),
|
|
2112
|
+
Type.Literal("logs"),
|
|
2113
|
+
Type.Literal("wait"),
|
|
2114
|
+
Type.Literal("status"),
|
|
2115
|
+
Type.Literal("stop"),
|
|
2116
|
+
Type.Literal("terminate"),
|
|
2117
|
+
Type.Literal("doctor"),
|
|
2118
|
+
Type.Literal("changes"),
|
|
2119
|
+
Type.Literal("restart"),
|
|
2120
|
+
Type.Literal("await"),
|
|
2121
|
+
]),
|
|
2122
|
+
device: Type.Optional(Type.String({ description: "Device name, UDID, ECID or CoreDevice uuid. Defaults to .xcodebug.json device, else the only connected physical device." })),
|
|
2123
|
+
scheme: Type.Optional(Type.String()),
|
|
2124
|
+
workspace: Type.Optional(Type.String()),
|
|
2125
|
+
project: Type.Optional(Type.String()),
|
|
2126
|
+
configuration: Type.Optional(Type.String({ description: "Defaults to Debug" })),
|
|
2127
|
+
derivedDataPath: Type.Optional(Type.String()),
|
|
2128
|
+
bundleId: Type.Optional(Type.String({ description: "App bundle id; defaults to the built product's CFBundleIdentifier" })),
|
|
2129
|
+
appPath: Type.Optional(Type.String({ description: "Install this .app instead of building" })),
|
|
2130
|
+
processName: Type.Optional(Type.String({ description: "Executable/process name for syslog filtering" })),
|
|
2131
|
+
captureId: Type.Optional(Type.String()),
|
|
2132
|
+
since: Type.Optional(Type.Number({ description: "Return lines with index > since; omit for all buffered lines" })),
|
|
2133
|
+
limit: Type.Optional(Type.Number({ description: "Max lines to return (default 200)" })),
|
|
2134
|
+
grep: Type.Optional(Type.String({ description: "Only return lines containing this text" })),
|
|
2135
|
+
match: Type.Optional(Type.String({ description: "wait: substring to wait for; also filters pushed lines" })),
|
|
2136
|
+
timeoutSeconds: Type.Optional(Type.Number({ description: "wait/build timeout in seconds; await: max run time (default 1800)" })),
|
|
2137
|
+
command: Type.Optional(Type.String({ description: "await/launch/restart: shell command line to run to completion after the app is up, e.g. \"cd /repo && npm run test:xxx\". Only /bin/sh -lc runs it, so the cd into the repo that owns the runner is part of the line. Quoted in the slash command (command=\"...\"); restart re-runs the last launch's command unless this overrides it." })),
|
|
2138
|
+
push: Type.Optional(Type.Union([Type.Literal("off"), Type.Literal("context"), Type.Literal("wake")], {
|
|
2139
|
+
description: "How new lines reach the session. Defaults to context. off: pull only (opt out). context: append new lines for the next turn. wake: trigger a turn when new lines arrive.",
|
|
2140
|
+
})),
|
|
2141
|
+
force: Type.Optional(Type.Boolean({ description: "Rebuild even when the working tree has not changed since the last build in this session." })),
|
|
2142
|
+
installPods: Type.Optional(Type.Boolean({ description: "Run pod install when new files belong to a pod (default true)." })),
|
|
2143
|
+
dualChannel: Type.Optional(Type.Boolean({ description: "launch: also capture idevicesyslog in parallel so a dropped console bridge leaves no gap (default true)." })),
|
|
2144
|
+
changes: Type.Optional(Type.Boolean({ description: "Only report local changes and what they require (no build)." })),
|
|
2145
|
+
terminateExisting: Type.Optional(Type.Boolean({ description: "launch: kill an existing instance first (default true)" })),
|
|
2146
|
+
keepApp: Type.Optional(Type.Boolean({ description: "stop: leave the app running (default true)" })),
|
|
2147
|
+
build: Type.Optional(Type.Boolean({ description: "launch: build and install before launching" })),
|
|
2148
|
+
args: Type.Optional(Type.Array(Type.String(), { description: "Launch arguments passed to the app" })),
|
|
2149
|
+
environment: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Extra launch environment variables" })),
|
|
2150
|
+
}),
|
|
2151
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
2152
|
+
// Whatever the action returns (including an early error), the transient
|
|
2153
|
+
// phase must not outlive it or the footer keeps advertising stale work.
|
|
2154
|
+
try {
|
|
2155
|
+
const result = await runActionThenCommand(params, ctx, signal, onUpdate);
|
|
2156
|
+
return { content: result.content, details: result.details, isError: result.isError };
|
|
2157
|
+
} finally {
|
|
2158
|
+
clearRunPhase();
|
|
2159
|
+
}
|
|
2160
|
+
},
|
|
2161
|
+
});
|
|
2162
|
+
|
|
2163
|
+
/**
|
|
2164
|
+
* `/xcodebug <what you want to verify>` - the one-shot path.
|
|
2165
|
+
*
|
|
2166
|
+
* Builds the project in the current directory, installs it on the connected
|
|
2167
|
+
* device, launches it, and streams the console into this session. A leading
|
|
2168
|
+
* action word is honoured when present (/xcodebug logs, /xcodebug stop);
|
|
2169
|
+
* anything else is treated as the goal of a launch.
|
|
2170
|
+
*/
|
|
2171
|
+
// `argumentHint` is a host addition (the published RegisteredCommand has only
|
|
2172
|
+
// name/description/handler). Spreading a typed object passes it through to hosts
|
|
2173
|
+
// that read it and is ignored by those that do not, which keeps this compiling
|
|
2174
|
+
// against the published types without dropping the hint where it is supported.
|
|
2175
|
+
const commandExtras: { argumentHint?: string } = {
|
|
2176
|
+
argumentHint:
|
|
2177
|
+
'[what to verify] | [what to verify] command="cd /repo && npm run test:xxx" | <action> [key=value ...]',
|
|
2178
|
+
};
|
|
2179
|
+
|
|
2180
|
+
pi.registerCommand("xcodebug", {
|
|
2181
|
+
description: "Build, install and launch the current project on a device, then stream its console; command=\"<shell line>\" runs a test command to completion and stops the capture",
|
|
2182
|
+
...commandExtras,
|
|
2183
|
+
handler: async (args, ctx) => {
|
|
2184
|
+
const parsed = parseCommandArgs(args);
|
|
2185
|
+
ctx.ui.notify(`xcodebug: ${parsed.action}${parsed.match ? ` (${parsed.match})` : ""}…`, "info");
|
|
2186
|
+
|
|
2187
|
+
// A command handler has no caller to surface a throw to, so a failed
|
|
2188
|
+
// action - `/xcodebug stop` with nothing running, say - must be caught and
|
|
2189
|
+
// reported like any other failure instead of escaping as a raw error.
|
|
2190
|
+
let text: string;
|
|
2191
|
+
let isError = false;
|
|
2192
|
+
let ranCommand = false;
|
|
2193
|
+
try {
|
|
2194
|
+
const result = await runActionThenCommand(
|
|
2195
|
+
parsed,
|
|
2196
|
+
ctx,
|
|
2197
|
+
undefined,
|
|
2198
|
+
// Progress frames repaint the status line instead of each becoming a
|
|
2199
|
+
// message: a build emits one every two seconds, which used to bury the
|
|
2200
|
+
// conversation under identical bars.
|
|
2201
|
+
(update) => {
|
|
2202
|
+
const frame = update.content[0]?.text;
|
|
2203
|
+
if (frame) setRunPhase(frame);
|
|
2204
|
+
},
|
|
2205
|
+
);
|
|
2206
|
+
text = result.content[0]?.text ?? (result.isError ? "xcodebug failed" : "xcodebug done");
|
|
2207
|
+
isError = result.isError === true;
|
|
2208
|
+
ranCommand = result.ranCommand;
|
|
2209
|
+
} catch (error) {
|
|
2210
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2211
|
+
text = `xcodebug ${parsed.action} failed: ${reason}`;
|
|
2212
|
+
isError = true;
|
|
2213
|
+
} finally {
|
|
2214
|
+
clearRunPhase();
|
|
2215
|
+
}
|
|
2216
|
+
// The phrase the user typed is what the run is for; without it the model
|
|
2217
|
+
// sees build output and logs but not the thing being verified. Only
|
|
2218
|
+
// `restart` needs a fallback: it is the one action that types no phrase,
|
|
2219
|
+
// because it reuses the run it is restarting. A `stop` or `status` must
|
|
2220
|
+
// not inherit that goal, or its output would claim a purpose it lacked.
|
|
2221
|
+
const goal =
|
|
2222
|
+
parsed.goal ?? (parsed.action === "restart" ? state.lastLaunch?.goal : undefined);
|
|
2223
|
+
const withGoal = goal ? `goal: ${goal}\n${text}` : text;
|
|
2224
|
+
ctx.ui.notify(text, isError ? "error" : "info");
|
|
2225
|
+
// The command surface is how a verification run starts, so its outcome -
|
|
2226
|
+
// including a failed build or install - has to reach the session itself.
|
|
2227
|
+
// A toast is invisible to the model and would leave it blind to failures.
|
|
2228
|
+
try {
|
|
2229
|
+
pi.sendMessage(
|
|
2230
|
+
{
|
|
2231
|
+
customType: CAPTURE_PREFIX,
|
|
2232
|
+
content: withGoal,
|
|
2233
|
+
display: true,
|
|
2234
|
+
details: { action: parsed.action, goal, isError, command: parsed.command },
|
|
2235
|
+
},
|
|
2236
|
+
// A finished command run always steers: its whole point is that the
|
|
2237
|
+
// run is over and the log is ready to analyse, so waiting for the next
|
|
2238
|
+
// user turn would strand the result. A bare launch stays `nextTurn` -
|
|
2239
|
+
// the user still has to drive the phone and there is nothing to analyse.
|
|
2240
|
+
isError || ranCommand
|
|
2241
|
+
? { deliverAs: "steer", triggerTurn: true }
|
|
2242
|
+
: { deliverAs: "nextTurn" },
|
|
2243
|
+
);
|
|
2244
|
+
} catch {
|
|
2245
|
+
// Session teardown; the toast already reported it.
|
|
2246
|
+
}
|
|
2247
|
+
},
|
|
2248
|
+
});
|
|
2249
|
+
|
|
2250
|
+
// The todo widget survives turns because it repaints on agent_end; do the same
|
|
2251
|
+
// so a verification run stays visible while the user drives the phone.
|
|
2252
|
+
pi.on("agent_end", async (_event, ctx) => {
|
|
2253
|
+
state.uiCtx ??= ctx;
|
|
2254
|
+
refreshStatus();
|
|
2255
|
+
});
|
|
2256
|
+
|
|
2257
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
2258
|
+
state.uiCtx = ctx;
|
|
2259
|
+
refreshStatus();
|
|
2260
|
+
});
|
|
2261
|
+
|
|
2262
|
+
pi.on("session_shutdown", async () => {
|
|
2263
|
+
stopStatusTicker();
|
|
2264
|
+
state.uiCtx?.ui.setStatus("xcodebug", undefined);
|
|
2265
|
+
state.uiCtx?.ui.setWidget("xcodebug", undefined);
|
|
2266
|
+
for (const capture of state.captures.values()) {
|
|
2267
|
+
stopPush(capture.id);
|
|
2268
|
+
stopWatchdog(capture.id);
|
|
2269
|
+
capture.stop(false);
|
|
2270
|
+
}
|
|
2271
|
+
state.captures.clear();
|
|
2272
|
+
state.activeCaptureId = undefined;
|
|
2273
|
+
});
|
|
2274
|
+
}
|