xcodebug 1.1.2 → 1.2.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.
Files changed (4) hide show
  1. package/README.md +100 -15
  2. package/capture.ts +166 -38
  3. package/index.ts +14 -10
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -27,8 +27,8 @@ it as a package or drop the directory in place.
27
27
  pi install npm:xcodebug
28
28
  pi install npm:xcodebug -l # project scope: .pi/settings.json
29
29
 
30
- # pin a version, or install from a checkout
31
- pi install npm:xcodebug@1.0.0
30
+ # explicitly select the latest release, or install from a checkout
31
+ pi install npm:xcodebug@latest
32
32
  pi install /path/to/xcodebug
33
33
  ```
34
34
 
@@ -67,7 +67,7 @@ extension rather than a parallel implementation.
67
67
  ### Set up (once per machine)
68
68
 
69
69
  ```bash
70
- npm i -g xcodebug # >= 1.1.0, the first release that ships mcp/
70
+ npm i -g xcodebug@latest # installs the latest published release
71
71
  codex mcp add xcodebug -- bun "$(npm root -g)/xcodebug/mcp/server.ts"
72
72
  claude mcp add xcodebug -- bun "$(npm root -g)/xcodebug/mcp/server.ts"
73
73
  ```
@@ -141,6 +141,40 @@ Logs land in `~/.xcodebug/logs/xcodebug/`, or under `XCODEBUG_AGENT_DIR` when se
141
141
  Every response also reports the exact path, so the model can read the file once a
142
142
  run is over.
143
143
 
144
+ ## Xcode's own MCP
145
+
146
+ Xcode 27.1 ships an MCP server of its own (`xcrun mcpbridge`) with 54 tools:
147
+ workspace and project editing, build/run/stop, tests, previews, the debugger,
148
+ build settings, String Catalogs, crash and performance reports, and device
149
+ interaction (tap, swipe, screenshot, UI hierarchy). One of those tools does the
150
+ same job as this extension, so pick deliberately rather than registering both by
151
+ habit:
152
+
153
+ ```bash
154
+ claude mcp add --transport stdio xcode -- xcrun mcpbridge
155
+ codex mcp add xcode -- xcrun mcpbridge
156
+ ```
157
+
158
+ Xcode asks for permission the first time an agent opens a project;
159
+ `xcrun mcp-server status` reports what has been granted.
160
+
161
+ `GetConsoleOutput` is the one that overlaps, and it is not a substitute:
162
+
163
+ | | Xcode `GetConsoleOutput` | xcodebug |
164
+ |---|---|---|
165
+ | source | the launch session `RunProject` created | any capture this extension started |
166
+ | positioning | `tailLimit` only - the last N lines | a cursor per capture; `since` resumes exactly |
167
+ | already-running app | only apps Xcode launched | `syslog` attaches without a relaunch |
168
+
169
+ So: **Xcode for anything that drives the IDE or the screen, xcodebug for the log
170
+ stream.** `GetConsoleOutput` answers "what did the last 500 lines say"; this
171
+ extension answers "what arrived since cursor 1694" - including from an app that
172
+ nobody launched from Xcode.
173
+
174
+ `RunProject` and `DeviceInteractionInstallAndRun` also build, install and launch.
175
+ They target whatever run destination Xcode has selected; `launch` takes a udid
176
+ directly.
177
+
144
178
  ## Requirements
145
179
 
146
180
  | Need | Why |
@@ -245,7 +279,7 @@ run. Set `installPods=false` to skip it deliberately.
245
279
  ## One-shot: `/xcodebug <what to verify>`
246
280
 
247
281
  ```text
248
- /xcodebug 验证天气添加城市
282
+ /xcodebug verify adding a city in Weather
249
283
  ```
250
284
 
251
285
  Detects the workspace from the current directory (walking up, so a nested cwd
@@ -312,7 +346,7 @@ what the app does while **a person** drives the phone: slow to reproduce and
312
346
  never quite identical twice.
313
347
 
314
348
  ```text
315
- /xcodebug 分析天气添加城市 command="cd /repo && npm run test:weather"
349
+ /xcodebug analyze adding a city in Weather command="cd /repo && npm run test:weather"
316
350
  ```
317
351
 
318
352
  | Without `command=` | With `command=` |
@@ -335,7 +369,7 @@ That single line does the whole linkage run:
335
369
  2. run the shell line to completion (blocking);
336
370
  3. stop the capture it was watching;
337
371
  4. report the exit code, the app-side cursor, and the log path - with the
338
- phrase `分析天气添加城市` attached as the goal the analysis must answer.
372
+ phrase `analyze adding a city in Weather` attached as the goal the analysis must answer.
339
373
 
340
374
  `command=` is a **second phase appended to the main action**, never an action of
341
375
  its own. That ordering is the point: a command is only meaningful when the app is
@@ -356,7 +390,7 @@ xcodebug action=await command="cd /repo && npm run test:weather"
356
390
  /xcodebug await command="cd /repo && npm run test:weather" timeoutSeconds=900
357
391
  ```
358
392
 
359
- A bare `/xcodebug` (or `/xcodebug 分析xxx`) has **no deadline**: it launches,
393
+ A bare `/xcodebug` (or `/xcodebug analyze <scenario>`) has **no deadline**: it launches,
360
394
  streams, and waits for you. Nothing stops it except `stop`, a new launch of the
361
395
  same app, or the app exiting.
362
396
 
@@ -509,6 +543,46 @@ xcodebug action=await command="cd /repo && npm run test:weather"
509
543
  /xcodebug await command="cd /repo && npm run test:weather"
510
544
  ```
511
545
 
546
+ ### Reading logs from a cursor
547
+
548
+ Every `logs` read returns a cursor: the latest absolute line index in that
549
+ capture. Pass it as `since` to exclude lines at or before that index. Reads
550
+ return the newest matching lines up to `limit`; if the response says older
551
+ lines were omitted, advancing to its cursor skips those lines too.
552
+
553
+ ```text
554
+ xcodebug action=logs since=0 limit=2
555
+ 2 line(s) (1692 older omitted) · cursor 1694
556
+
557
+ xcodebug action=logs since=1694
558
+ (no new lines since 1694; capture cursor is 1694)
559
+
560
+ xcodebug action=logs since=1694 limit=3
561
+ 3 line(s) (6135 older omitted) · cursor 7832
562
+ ```
563
+
564
+ Each capture retains at most 20k lines and 4 MiB of text in memory (counted as
565
+ UTF-16 bytes, excluding object overhead). A line larger than that text budget
566
+ is written to disk and delivered to live subscribers but not retained for
567
+ `logs`. The session keeps the most recent 10 ended captures; active captures
568
+ and captures reconnecting after a bridge failure are not evicted. Older capture
569
+ IDs leave `logs`/`status`, while their retained disk segments remain available.
570
+
571
+ ### `syslog`: attach without relaunching
572
+
573
+ `launch` restarts the app because `devicectl --console` has to start it. When the
574
+ app is already running and the state you want to observe would not survive a
575
+ restart, attach instead:
576
+
577
+ ```text
578
+ xcodebug action=syslog processName=MyApp
579
+ ```
580
+
581
+ This runs `idevicesyslog -p <ProcessName>` and leaves the app running. It needs
582
+ `idevicesyslog` from libimobiledevice (`action=doctor` reports whether it is
583
+ present), and it reads the device log for that process - `print` output still
584
+ only comes from the console bridge, per the table at the top.
585
+
512
586
  ### Pushing logs into the conversation
513
587
 
514
588
  `push` controls whether new lines are mirrored into the session:
@@ -523,14 +597,25 @@ useful, e.g. `xcodebug action=launch match=MySDK push=wake`.
523
597
 
524
598
  ### Files
525
599
 
526
- Every capture also writes a full log to
527
- `<agentDir>/logs/xcodebug/<mode>-<bundleId>-<YYYY-MM-DD_HH-mm-ss-SSS>.log`, so
528
- nothing is lost when the in-memory ring buffer (20k lines) rolls over.
529
-
530
- The app's bundle id is part of the name because several apps are debugged in
531
- one session; the timestamp carries milliseconds so a relaunch of the same app
532
- cannot reuse the previous run's file (files are opened in append mode, so a
533
- collision would interleave two runs with no way to tell them apart).
600
+ Every capture writes timestamped logs under
601
+ `<agentDir>/logs/xcodebug/<mode>-<bundleId>-<YYYY-MM-DD_HH-mm-ss-SSS>.log`.
602
+ It rotates through that base path plus `.1` and `.2`, replacing the oldest
603
+ segment after three segments. Each segment targets 50 MiB and keeps complete
604
+ lines (a single larger line may exceed that size). Logging continues after
605
+ rotation; it no longer stops at the first 50 MiB. Capture status details list
606
+ successfully opened paths in chronological order as `logFiles`; `logFile` stays
607
+ the stable base path. Reconnecting appends to the current segment.
608
+
609
+ Disk writes apply backpressure to both capture pipes, so a slow disk pauses
610
+ ingestion instead of accumulating an unlimited write queue. After the bridge
611
+ exits, capture shutdown allows up to two seconds for the pipes and pending file
612
+ writes to drain. If they remain blocked, it destroys the streams, reports a
613
+ drain-timeout error in capture status, and completes shutdown; pending logs may
614
+ be truncated.
615
+
616
+ The bundle id separates apps, and the timestamp includes milliseconds to
617
+ separate runs. Segment limits apply per capture: old runs are not automatically
618
+ deleted from disk when their capture IDs leave the in-memory history.
534
619
 
535
620
  A successful build clears `<agentDir>/logs/xcodebug/archive/` first, so snapshots
536
621
  from a previous binary cannot be mistaken for the run that is starting.
package/capture.ts CHANGED
@@ -7,11 +7,15 @@ import { spawn, type ChildProcess } from "node:child_process";
7
7
  import { createWriteStream, type WriteStream } from "node:fs";
8
8
  import { mkdir } from "node:fs/promises";
9
9
  import { dirname } from "node:path";
10
+ import { finished } from "node:stream/promises";
10
11
  import { timestamp } from "./exec.ts";
11
12
 
12
13
  const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
13
14
  const MAX_BUFFER_LINES = 20_000;
15
+ const MAX_BUFFER_BYTES = 4 * 1024 * 1024;
14
16
  const MAX_FILE_BYTES = 50 * 1024 * 1024;
17
+ const MAX_LOG_FILES = 3;
18
+ const MAX_DRAIN_MS = 2_000;
15
19
 
16
20
  export type CaptureMode = "console" | "syslog";
17
21
 
@@ -57,6 +61,8 @@ export interface CaptureStatus {
57
61
  droppedLines: number;
58
62
  cursor: number;
59
63
  logFile: string;
64
+ /** Retained segments in chronological order; logFile is their stable base path. */
65
+ logFiles: string[];
60
66
  commandLine: string;
61
67
  error?: string;
62
68
  }
@@ -104,7 +110,10 @@ export class Capture {
104
110
  readonly abort = new AbortController();
105
111
  private child: ChildProcess | undefined;
106
112
  private file: WriteStream | undefined;
107
- private readonly lines: LogLine[] = [];
113
+ private readonly lines: Array<LogLine | undefined> = new Array(MAX_BUFFER_LINES);
114
+ private head = 0;
115
+ private lineCount = 0;
116
+ private bufferBytes = 0;
108
117
  private droppedLines = 0;
109
118
  private cursor = 0;
110
119
  private buffered: { out: string; err: string } = { out: "", err: "" };
@@ -112,6 +121,11 @@ export class Capture {
112
121
  private exitSignal: string | undefined;
113
122
  private error: string | undefined;
114
123
  private fileBytes = 0;
124
+ private fileNumber = 0;
125
+ private fileOrder = 0;
126
+ private readonly logFiles = new Map<string, number>();
127
+ private readonly files = new Set<WriteStream>();
128
+ private readonly blockedFiles = new Set<WriteStream>();
115
129
  private readonly exitListeners = new Set<(code: number | undefined, signal: string | undefined) => void>();
116
130
  private readonly lineListeners = new Set<(line: LogLine) => void>();
117
131
 
@@ -130,8 +144,9 @@ export class Capture {
130
144
  init.logFile ?? `${init.logDir}/${init.mode}-${init.bundleId}-${timestamp()}.log`;
131
145
  }
132
146
 
147
+ /** Remain live until the pipes and file writes drain, or their deadline expires. */
133
148
  get running(): boolean {
134
- return this.child !== undefined && this.child.exitCode === null && this.exitSignal === undefined;
149
+ return this.child !== undefined;
135
150
  }
136
151
 
137
152
  /** Clear the terminal state so start() can attach a fresh bridge. */
@@ -162,29 +177,112 @@ export class Capture {
162
177
 
163
178
  async start(): Promise<void> {
164
179
  await mkdir(dirname(this.logFile), { recursive: true });
165
- this.file = createWriteStream(this.logFile, { flags: "a" });
166
- this.file.on("error", () => {
167
- this.file = undefined;
168
- });
180
+ this.openFile(true);
169
181
 
170
182
  const child = spawn(this.command, this.launchArgs, { stdio: ["ignore", "pipe", "pipe"] });
171
183
  this.child = child;
184
+ let finishing = false;
185
+ let drainTimer: NodeJS.Timeout | undefined;
186
+ const drainAbort = new AbortController();
187
+ const complete = (code: number | undefined, signal: string | undefined): void => {
188
+ if (this.child !== child) return;
189
+ clearTimeout(drainTimer);
190
+ this.exitCode = code;
191
+ this.exitSignal = signal;
192
+ this.child = undefined;
193
+ for (const listener of this.exitListeners) {
194
+ try {
195
+ listener(code, signal);
196
+ } catch {
197
+ // A listener must never break capture teardown.
198
+ }
199
+ }
200
+ };
201
+ const beginDrain = (code: number | undefined, signal: string | undefined): void => {
202
+ if (this.child !== child || drainTimer) return;
203
+ drainTimer = setTimeout(() => {
204
+ this.error = `log drain timed out after ${MAX_DRAIN_MS}ms; pending logs may be truncated`;
205
+ finishing = true;
206
+ this.file = undefined;
207
+ for (const file of this.files) file.destroy();
208
+ this.files.clear();
209
+ this.blockedFiles.clear();
210
+ child.stdout?.destroy();
211
+ child.stderr?.destroy();
212
+ this.flush("out");
213
+ this.flush("err");
214
+ drainAbort.abort();
215
+ complete(code, signal);
216
+ }, MAX_DRAIN_MS);
217
+ };
218
+ const finish = (code: number | undefined, signal: string | undefined): void => {
219
+ if (this.child !== child || finishing) return;
220
+ finishing = true;
221
+ beginDrain(code, signal);
222
+ const writes = [...this.files].map((file) => {
223
+ const done = finished(file, { cleanup: true, signal: drainAbort.signal }).catch(() => {});
224
+ if (!file.writableEnded) file.end();
225
+ return done;
226
+ });
227
+ this.file = undefined;
228
+ void Promise.all(writes).then(() => complete(code, signal));
229
+ };
172
230
  child.stdout?.setEncoding("utf8");
173
231
  child.stderr?.setEncoding("utf8");
174
- child.stdout?.on("data", (chunk: string) => this.consume("out", chunk));
175
- child.stderr?.on("data", (chunk: string) => this.consume("err", chunk));
232
+ child.stdout?.on("data", (chunk: string) => {
233
+ if (this.child === child) this.consume("out", chunk);
234
+ });
235
+ child.stderr?.on("data", (chunk: string) => {
236
+ if (this.child === child) this.consume("err", chunk);
237
+ });
176
238
  child.on("error", (error: Error) => {
239
+ if (this.child !== child) return;
177
240
  this.error = error.message;
178
241
  this.pushLine("err", `[xcodebug] failed to start: ${error.message}`);
179
- this.finish(undefined, undefined);
242
+ finish(undefined, undefined);
180
243
  });
181
- child.on("exit", (code: number | null, signal: NodeJS.Signals | null) => {
244
+ // `close` can itself wait forever while a backed-up writer pauses the pipes.
245
+ child.on("exit", (code, signal) => beginDrain(code ?? undefined, signal ?? undefined));
246
+ child.on("close", (code: number | null, signal: NodeJS.Signals | null) => {
247
+ if (this.child !== child) return;
182
248
  this.flush("out");
183
249
  this.flush("err");
184
- this.finish(code ?? undefined, signal ?? undefined);
250
+ finish(code ?? undefined, signal ?? undefined);
251
+ });
252
+ }
253
+
254
+ private openFile(append: boolean): void {
255
+ const path = this.fileNumber === 0 ? this.logFile : `${this.logFile}.${this.fileNumber}`;
256
+ const file = createWriteStream(path, { flags: append ? "a" : "w" });
257
+ this.file = file;
258
+ this.files.add(file);
259
+ const order = ++this.fileOrder;
260
+ file.once("open", () => {
261
+ if (!this.files.has(file) || file.destroyed) return;
262
+ if (order > (this.logFiles.get(path) ?? -1)) this.logFiles.set(path, order);
263
+ });
264
+ file.on("error", (error: Error) => {
265
+ if (!this.files.has(file)) return;
266
+ this.error = `log write failed: ${error.message}`;
267
+ if (this.file === file) this.file = undefined;
268
+ });
269
+ file.on("drain", () => {
270
+ this.blockedFiles.delete(file);
271
+ this.resume();
272
+ });
273
+ file.on("close", () => {
274
+ this.files.delete(file);
275
+ this.blockedFiles.delete(file);
276
+ this.resume();
185
277
  });
186
278
  }
187
279
 
280
+ private resume(): void {
281
+ if (this.blockedFiles.size > 0) return;
282
+ this.child?.stdout?.resume();
283
+ this.child?.stderr?.resume();
284
+ }
285
+
188
286
  private consume(stream: "out" | "err", chunk: string): void {
189
287
  const pending = this.buffered[stream] + chunk;
190
288
  const parts = pending.split("\n");
@@ -205,9 +303,22 @@ export class Capture {
205
303
  const line: LogLine = { index: ++this.cursor, at: Date.now(), stream, text };
206
304
  // Every line proves the bridge is alive, whether or not it is being pushed.
207
305
  this.lastLineAt = line.at;
208
- this.lines.push(line);
209
- if (this.lines.length > MAX_BUFFER_LINES) {
210
- this.lines.shift();
306
+ // UTF-16 size is a conservative text bound even on engines storing Latin-1.
307
+ const bytes = text.length * 2;
308
+ if (bytes <= MAX_BUFFER_BYTES) {
309
+ while (this.lineCount === MAX_BUFFER_LINES || this.bufferBytes + bytes > MAX_BUFFER_BYTES) {
310
+ const oldest = this.lines[this.head]!;
311
+ this.bufferBytes -= oldest.text.length * 2;
312
+ this.lines[this.head] = undefined;
313
+ this.head = (this.head + 1) % MAX_BUFFER_LINES;
314
+ this.lineCount -= 1;
315
+ this.droppedLines += 1;
316
+ }
317
+ this.lines[(this.head + this.lineCount) % MAX_BUFFER_LINES] = line;
318
+ this.lineCount += 1;
319
+ this.bufferBytes += bytes;
320
+ } else {
321
+ // Still deliver and write an oversized line, without retaining it in memory.
211
322
  this.droppedLines += 1;
212
323
  }
213
324
  for (const listener of this.lineListeners) {
@@ -217,25 +328,21 @@ export class Capture {
217
328
  // A listener must never break capture.
218
329
  }
219
330
  }
220
- if (this.file && this.fileBytes < MAX_FILE_BYTES) {
331
+ if (this.file) {
221
332
  const encoded = `${new Date(line.at).toISOString()} ${line.text}\n`;
222
- this.fileBytes += Buffer.byteLength(encoded);
223
- this.file.write(encoded);
224
- }
225
- }
226
-
227
- private finish(code: number | undefined, signal: string | undefined): void {
228
- if (this.exitCode !== undefined || this.exitSignal !== undefined) return;
229
- this.exitCode = code;
230
- this.exitSignal = signal;
231
- this.child = undefined;
232
- this.file?.end();
233
- this.file = undefined;
234
- for (const listener of this.exitListeners) {
235
- try {
236
- listener(code, signal);
237
- } catch {
238
- // A listener must never break capture teardown.
333
+ const size = Buffer.byteLength(encoded);
334
+ if (this.fileBytes > 0 && this.fileBytes + size > MAX_FILE_BYTES) {
335
+ this.file.end();
336
+ this.fileNumber = (this.fileNumber + 1) % MAX_LOG_FILES;
337
+ this.fileBytes = 0;
338
+ this.openFile(false);
339
+ }
340
+ this.fileBytes += size;
341
+ const file = this.file;
342
+ if (!file.write(encoded)) {
343
+ this.blockedFiles.add(file);
344
+ this.child?.stdout?.pause();
345
+ this.child?.stderr?.pause();
239
346
  }
240
347
  }
241
348
  }
@@ -293,14 +400,34 @@ export class Capture {
293
400
  total: number;
294
401
  } {
295
402
  const since = Math.max(0, options.since ?? 0);
296
- const limit = Math.min(Math.max(1, options.limit ?? 200), 5_000);
403
+ const limit = Math.trunc(Math.min(Math.max(1, options.limit ?? 200), 5_000));
297
404
  const grep = options.grep?.trim();
298
405
  const streams = options.streams;
299
- let matched = this.lines.filter((line) => line.index > since);
300
- if (streams && streams.length > 0) matched = matched.filter((line) => streams.includes(line.stream));
301
- if (grep) matched = matched.filter((line) => line.text.includes(grep));
302
- const cursor = this.cursor;
303
- return { lines: matched.slice(-limit), cursor, total: matched.length };
406
+ // Locate the first eligible index without scanning or copying the buffer.
407
+ let first = 0;
408
+ let end = this.lineCount;
409
+ while (first < end) {
410
+ const middle = Math.floor((first + end) / 2);
411
+ if (this.lines[(this.head + middle) % MAX_BUFFER_LINES]!.index <= since) first = middle + 1;
412
+ else end = middle;
413
+ }
414
+ const lines: LogLine[] = [];
415
+ if (!grep && (!streams || streams.length === 0)) {
416
+ for (let i = Math.max(first, this.lineCount - limit); i < this.lineCount; i++) {
417
+ lines.push(this.lines[(this.head + i) % MAX_BUFFER_LINES]!);
418
+ }
419
+ return { lines, cursor: this.cursor, total: this.lineCount - first };
420
+ }
421
+ let total = 0;
422
+ for (let i = this.lineCount - 1; i >= first; i--) {
423
+ const line = this.lines[(this.head + i) % MAX_BUFFER_LINES]!;
424
+ if (streams && streams.length > 0 && !streams.includes(line.stream)) continue;
425
+ if (grep && !line.text.includes(grep)) continue;
426
+ total += 1;
427
+ if (lines.length < limit) lines.push(line);
428
+ }
429
+ lines.reverse();
430
+ return { lines, cursor: this.cursor, total };
304
431
  }
305
432
 
306
433
  status(): CaptureStatus {
@@ -320,6 +447,7 @@ export class Capture {
320
447
  droppedLines: this.droppedLines,
321
448
  cursor: this.cursor,
322
449
  logFile: this.logFile,
450
+ logFiles: [...this.logFiles].sort((a, b) => a[1] - b[1]).map(([path]) => path),
323
451
  commandLine: [this.command, ...this.launchArgs].join(" "),
324
452
  error: this.error,
325
453
  };
package/index.ts CHANGED
@@ -26,6 +26,7 @@ import { clearArchives } from "./archive.ts";
26
26
  const CAPTURE_PREFIX = "xcodebug";
27
27
  const PUSH_INTERVAL_MS = 4_000;
28
28
  const PUSH_MAX_LINES = 80;
29
+ const MAX_ENDED_CAPTURES = 10;
29
30
  /** How long a verification run may go quiet before we ask the user about it. */
30
31
  const SILENCE_NOTICE_MS = 60_000;
31
32
  /**
@@ -51,6 +52,8 @@ interface ProjectConfig {
51
52
 
52
53
  interface SessionState {
53
54
  captures: Map<string, Capture>;
55
+ /** Permanently ended captures, ordered by completion time for bounded history. */
56
+ endedCaptures: Set<string>;
54
57
  activeCaptureId?: string;
55
58
  pushTimers: Map<string, ReturnType<typeof setInterval>>;
56
59
  pushCursors: Map<string, number>;
@@ -751,6 +754,7 @@ type ToolParams = {
751
754
  export default function xcodebug(pi: ExtensionAPI): void {
752
755
  const state: SessionState = {
753
756
  captures: new Map(),
757
+ endedCaptures: new Set(),
754
758
  pushTimers: new Map(),
755
759
  pushCursors: new Map(),
756
760
  companions: new Map(),
@@ -870,11 +874,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
870
874
  refreshStatus();
871
875
  };
872
876
 
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
- */
877
+ /** Release live bookkeeping and retain only the most recent ended captures. */
878
878
  const releaseCapture = (capture: Capture): void => {
879
879
  stopPush(capture.id);
880
880
  stopWatchdog(capture.id);
@@ -883,8 +883,12 @@ export default function xcodebug(pi: ExtensionAPI): void {
883
883
  state.lastLineAt.delete(capture.id);
884
884
  state.silenceNotified.delete(capture.id);
885
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.
886
+ state.endedCaptures.add(capture.id);
887
+ while (state.endedCaptures.size > MAX_ENDED_CAPTURES) {
888
+ const oldest = state.endedCaptures.values().next().value!;
889
+ state.endedCaptures.delete(oldest);
890
+ state.captures.delete(oldest);
891
+ }
888
892
  if (state.activeCaptureId === capture.id) state.activeCaptureId = undefined;
889
893
  if (![...state.captures.values()].some((c) => c.running)) stopStatusTicker();
890
894
  refreshStatus();
@@ -936,8 +940,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
936
940
  // The syslog channel is a companion of the console capture; stop it too so
937
941
  // one "stop" does not leave a second bridge running.
938
942
  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.
943
+ // Recent ended captures remain readable, but their live bookkeeping must stop.
941
944
  state.recentLines.delete(capture.id);
942
945
  state.lastLineAt.delete(capture.id);
943
946
  state.silenceNotified.delete(capture.id);
@@ -1135,7 +1138,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
1135
1138
  // healthy, and losing it silently would leave the console channel with no
1136
1139
  // backup - exactly the gap dual-channel exists to cover.
1137
1140
  if (capture.stoppedByUser) {
1138
- if (state.activeCaptureId === capture.id) state.activeCaptureId = undefined;
1141
+ releaseCapture(capture);
1139
1142
  return;
1140
1143
  }
1141
1144
  // Always hand off. If a reconnect loop is already running it returns at
@@ -2278,6 +2281,7 @@ export default function xcodebug(pi: ExtensionAPI): void {
2278
2281
  capture.stop(false);
2279
2282
  }
2280
2283
  state.captures.clear();
2284
+ state.endedCaptures.clear();
2281
2285
  state.activeCaptureId = undefined;
2282
2286
  });
2283
2287
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xcodebug",
3
- "version": "1.1.2",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "Build, install and launch an iOS app on a physical device and read its console inside the agent session (pi / omp extension)",
6
6
  "keywords": [