@rezkam/browser-tools 0.2.1 → 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.
@@ -0,0 +1,270 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Record filtered active-tab network traffic as a standard HAR 1.2 file.
4
+ *
5
+ * Usage:
6
+ * scripts/record-har.mjs start --output ./checkout_api_network.har [filters]
7
+ * scripts/record-har.mjs status [--json]
8
+ * scripts/record-har.mjs stop
9
+ */
10
+
11
+ import { closeSync, existsSync, openSync, realpathSync } from 'node:fs';
12
+ import { spawn } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+ import {
15
+ OWNER_TOKEN_ENV,
16
+ hasFlag,
17
+ ownerTokenHash,
18
+ parseOwnerToken,
19
+ parsePort,
20
+ requiredOptionValue,
21
+ } from './browser-control.mjs';
22
+ import { privateOutputPath, withPageCdpSession } from './cdp-common.mjs';
23
+ import {
24
+ CDP_CAPTURE_STOP_TIMEOUT_MS,
25
+ assertCdpRecordingOwner,
26
+ cdpRecordingLogFile,
27
+ cdpRecordingReport,
28
+ cdpRecordingStopFile,
29
+ claimCdpRecording,
30
+ readCdpRecordingState,
31
+ removeCdpRecordingState,
32
+ requestCdpRecordingStop,
33
+ updateCdpRecordingState,
34
+ waitForCdpRecordingState,
35
+ } from './cdp-recording-state.mjs';
36
+ import {
37
+ DEFAULT_HAR_DRAIN_TIMEOUT_MS,
38
+ parseHarCaptureOptions,
39
+ runHarCapture,
40
+ writeHar,
41
+ } from './har-capture.mjs';
42
+
43
+ const SCRIPT_FILE = fileURLToPath(import.meta.url);
44
+ const CAPTURE_KIND = 'har';
45
+
46
+ function usage() {
47
+ console.error(`Usage: browser-tools record-har <command> [options]
48
+
49
+ Commands:
50
+ start --output <meaningful.har> Start filtered active-tab HAR capture
51
+ status [--json] Report HAR capture status
52
+ stop Drain in-flight requests and write the HAR
53
+
54
+ Selection:
55
+ --preset <api|page|all> Resource preset (default: all)
56
+ --resource-type <types> Include CDP types, repeatable or comma-separated
57
+ --exclude-resource-type <types>
58
+ --url-pattern <glob> Include URL glob, repeatable
59
+ --exclude-url-pattern <glob>
60
+ --method <methods> Include HTTP methods
61
+ --exclude-method <methods>
62
+ --status <code|range> Include response status, for example 200-299
63
+ --exclude-status <code|range>
64
+ --mime-type <glob> Include response MIME type
65
+ --exclude-mime-type <glob>
66
+ --min-size <bytes>
67
+ --max-size <bytes>
68
+
69
+ Content and lifecycle:
70
+ --capture <components> headers,bodies,timing (default: all)
71
+ --max-body-bytes <n> Per-body capture limit (default: 1048576)
72
+ --idle-ms <n> Required quiet period on stop (default: 500)
73
+ --drain-timeout-ms <n> Maximum in-flight drain wait (default: 5000)
74
+ --max-duration <seconds> Safety limit (default: 300)
75
+ --redact Redact auth, cookies, and secret-looking body fields
76
+ --overwrite Replace existing output
77
+ --port <n> Managed browser port (default: 9222)
78
+ --owner-token <token> Prefer ${OWNER_TOKEN_ENV} instead
79
+
80
+ Outputs are private (0600). The Browser Tools owner token is never stored in the HAR.`);
81
+ }
82
+
83
+ function encodeOptions(options) {
84
+ return Buffer.from(JSON.stringify(options), 'utf-8').toString('base64url');
85
+ }
86
+
87
+ function decodeOptions(value) {
88
+ if (!value) throw new Error('Missing internal HAR worker options');
89
+ return JSON.parse(Buffer.from(value, 'base64url').toString('utf-8'));
90
+ }
91
+
92
+ async function startCapture(args) {
93
+ const port = parsePort(args);
94
+ const ownerToken = parseOwnerToken(args);
95
+ if (!ownerToken) {
96
+ throw new Error(`Missing browser owner token. Export ${OWNER_TOKEN_ENV} with the token printed by browser-tools start`);
97
+ }
98
+ const overwrite = hasFlag(args, '--overwrite');
99
+ const output = privateOutputPath(requiredOptionValue(args, '--output', null), 'har', { overwrite });
100
+ const options = parseHarCaptureOptions(args);
101
+ claimCdpRecording(CAPTURE_KIND, port);
102
+
103
+ const logFile = cdpRecordingLogFile(CAPTURE_KIND, port);
104
+ let logFd = null;
105
+ try {
106
+ logFd = openSync(logFile, 'a', 0o600);
107
+ const child = spawn(process.execPath, [
108
+ SCRIPT_FILE,
109
+ 'worker',
110
+ '--port', String(port),
111
+ '--output', output,
112
+ '--worker-options', encodeOptions(options),
113
+ ], {
114
+ detached: true,
115
+ stdio: ['ignore', logFd, logFd],
116
+ env: { ...process.env, [OWNER_TOKEN_ENV]: ownerToken },
117
+ });
118
+ child.unref();
119
+ } catch (error) {
120
+ removeCdpRecordingState(CAPTURE_KIND, port);
121
+ throw error;
122
+ } finally {
123
+ if (logFd !== null) closeSync(logFd);
124
+ }
125
+
126
+ const state = await waitForCdpRecordingState(
127
+ CAPTURE_KIND,
128
+ port,
129
+ (candidate) => candidate.status === 'recording' || candidate.status === 'failed',
130
+ );
131
+ if (!state) throw new Error(`HAR recorder did not start within 30 seconds. See ${logFile}`);
132
+ if (state.status === 'failed') throw new Error(`HAR recorder failed: ${state.error || 'unknown failure'}. See ${logFile}`);
133
+ console.log(`✓ HAR capture active on :${port}: ${output}`);
134
+ }
135
+
136
+ function showStatus(args) {
137
+ const port = parsePort(args);
138
+ const report = cdpRecordingReport(CAPTURE_KIND, port);
139
+ if (hasFlag(args, '--json')) {
140
+ console.log(JSON.stringify(report, null, 2));
141
+ } else if (report.recording) {
142
+ console.log(`✓ HAR capture ${report.phase} on :${port}: ${report.output}`);
143
+ } else if (report.status) {
144
+ console.log(`HAR capture ${report.status} on :${port}: ${report.output}`);
145
+ } else {
146
+ console.log(`No HAR capture found for port ${port}`);
147
+ }
148
+ }
149
+
150
+ async function stopCapture(args) {
151
+ const port = parsePort(args);
152
+ const ownerToken = parseOwnerToken(args);
153
+ const initialState = readCdpRecordingState(CAPTURE_KIND, port);
154
+ if (!initialState) throw new Error(`No HAR capture found on port ${port}`);
155
+ assertCdpRecordingOwner(initialState, ownerToken);
156
+ if (initialState.status === 'completed') {
157
+ console.log(initialState.output);
158
+ removeCdpRecordingState(CAPTURE_KIND, port);
159
+ return;
160
+ }
161
+ if (initialState.status === 'failed') {
162
+ throw new Error(`HAR recorder failed: ${initialState.error || 'unknown failure'}. See ${cdpRecordingLogFile(CAPTURE_KIND, port)}`);
163
+ }
164
+
165
+ requestCdpRecordingStop(CAPTURE_KIND, port, ownerToken);
166
+ console.error('⟳ Draining in-flight requests and finalizing HAR...');
167
+ const timeoutMs = CDP_CAPTURE_STOP_TIMEOUT_MS
168
+ + (initialState.options?.drainTimeoutMs || DEFAULT_HAR_DRAIN_TIMEOUT_MS);
169
+ const state = await waitForCdpRecordingState(
170
+ CAPTURE_KIND,
171
+ port,
172
+ (candidate) => ['completed', 'failed'].includes(candidate.status),
173
+ { timeoutMs },
174
+ );
175
+ if (!state || !['completed', 'failed'].includes(state.status)) {
176
+ throw new Error(`HAR recorder did not stop within ${Math.ceil(timeoutMs / 1000)} seconds`);
177
+ }
178
+ if (state.status === 'failed') {
179
+ throw new Error(`HAR recorder failed: ${state.error || 'unknown failure'}. See ${cdpRecordingLogFile(CAPTURE_KIND, port)}`);
180
+ }
181
+ console.log(state.output);
182
+ removeCdpRecordingState(CAPTURE_KIND, port);
183
+ }
184
+
185
+ async function runWorker(args) {
186
+ const port = parsePort(args);
187
+ const ownerToken = parseOwnerToken(args);
188
+ const output = requiredOptionValue(args, '--output', null);
189
+ const options = decodeOptions(requiredOptionValue(args, '--worker-options', null));
190
+ const startedAt = new Date().toISOString();
191
+ let state = {
192
+ managedBy: 'browser-tools-cdp-recorder',
193
+ kind: CAPTURE_KIND,
194
+ pid: process.pid,
195
+ port,
196
+ output,
197
+ ownerTokenHash: ownerTokenHash(ownerToken),
198
+ status: 'starting',
199
+ phase: 'starting',
200
+ startedAt,
201
+ options,
202
+ };
203
+ const update = (changes) => {
204
+ state = { ...state, ...changes };
205
+ updateCdpRecordingState(CAPTURE_KIND, port, state);
206
+ };
207
+ update({});
208
+
209
+ try {
210
+ const result = await withPageCdpSession(port, ownerToken, async ({ page, session }) => runHarCapture({
211
+ session,
212
+ page,
213
+ options,
214
+ shouldStop: () => existsSync(cdpRecordingStopFile(CAPTURE_KIND, port)),
215
+ onPhase: (phase, reason = null) => update({
216
+ status: phase === 'recording' ? 'recording' : state.status,
217
+ phase,
218
+ reason: reason ?? state.reason,
219
+ readyAt: phase === 'recording' ? new Date().toISOString() : state.readyAt,
220
+ }),
221
+ }));
222
+ writeHar(output, result.har);
223
+ update({
224
+ status: 'completed',
225
+ phase: 'completed',
226
+ reason: result.reason,
227
+ eventCount: result.eventCount,
228
+ completedAt: new Date().toISOString(),
229
+ });
230
+ } catch (error) {
231
+ update({
232
+ status: 'failed',
233
+ phase: 'failed',
234
+ error: error.message,
235
+ completedAt: new Date().toISOString(),
236
+ });
237
+ throw error;
238
+ }
239
+ }
240
+
241
+ export async function main(args = process.argv.slice(2)) {
242
+ const [command] = args;
243
+ if (!command || command === '--help' || command === '-h') {
244
+ usage();
245
+ return command ? 0 : 1;
246
+ }
247
+ if (command === 'start') await startCapture(args.slice(1));
248
+ else if (command === 'status') showStatus(args.slice(1));
249
+ else if (command === 'stop') await stopCapture(args.slice(1));
250
+ else if (command === 'worker') await runWorker(args.slice(1));
251
+ else {
252
+ usage();
253
+ throw new Error(`Unknown record-har command: ${command}`);
254
+ }
255
+ return 0;
256
+ }
257
+
258
+ function isDirectExecution() {
259
+ if (!process.argv[1]) return false;
260
+ return realpathSync(process.argv[1]) === realpathSync(SCRIPT_FILE);
261
+ }
262
+
263
+ if (isDirectExecution()) {
264
+ try {
265
+ process.exitCode = await main();
266
+ } catch (error) {
267
+ console.error(`✗ ${error.message}`);
268
+ process.exitCode = 1;
269
+ }
270
+ }
@@ -0,0 +1,203 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Probe a GIF and render sampled frames as a contact sheet for visual review.
4
+ *
5
+ * Usage:
6
+ * scripts/review-gif.mjs ./login_process.gif
7
+ * scripts/review-gif.mjs ./login_process.gif --fps 2 --width 480 --columns 4 --rows 4
8
+ * scripts/review-gif.mjs ./login_process.gif --out-dir ./.gif-review --json
9
+ */
10
+
11
+ import { spawnSync } from 'node:child_process';
12
+ import {
13
+ chmodSync,
14
+ closeSync,
15
+ existsSync,
16
+ mkdirSync,
17
+ realpathSync,
18
+ statSync,
19
+ } from 'node:fs';
20
+ import { basename, dirname, extname, join, parse, resolve } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { hasFlag, optionValue, requiredOptionValue } from './browser-control.mjs';
23
+ import { openPrivateFile, writePrivateJson } from './cdp-common.mjs';
24
+ import { parseBoundedNumber } from './gif-recorder.mjs';
25
+
26
+ export const DEFAULT_REVIEW_FPS = 2;
27
+ export const DEFAULT_REVIEW_WIDTH = 480;
28
+ export const DEFAULT_REVIEW_COLUMNS = 4;
29
+ export const DEFAULT_REVIEW_ROWS = 4;
30
+
31
+ const SCRIPT_FILE = fileURLToPath(import.meta.url);
32
+
33
+ function usage() {
34
+ console.error(`Usage: browser-tools review-gif <meaningful.gif> [options]
35
+
36
+ Options:
37
+ --out-dir <path> Review output directory (default: <GIF directory>/.gif-review)
38
+ --fps <0.1-30> Maximum frame sampling rate (default: ${DEFAULT_REVIEW_FPS})
39
+ --width <64-1920> Width of each sampled frame (default: ${DEFAULT_REVIEW_WIDTH})
40
+ --columns <1-10> Contact sheet columns (default: ${DEFAULT_REVIEW_COLUMNS})
41
+ --rows <1-10> Contact sheet rows (default: ${DEFAULT_REVIEW_ROWS})
42
+ --json Print the review report as JSON
43
+
44
+ The sampling rate is reduced automatically when needed so the sheet covers the full GIF.`);
45
+ }
46
+
47
+ function run(command, args) {
48
+ const result = spawnSync(command, args, { encoding: 'utf-8' });
49
+ if (result.error?.code === 'ENOENT') {
50
+ throw new Error(`${command} is required for GIF review. Install it with: brew install ffmpeg`);
51
+ }
52
+ if (result.error) throw new Error(`Could not run ${command}: ${result.error.message}`);
53
+ if (result.status !== 0) {
54
+ throw new Error(`${command} failed with exit status ${result.status}: ${(result.stderr || result.stdout).trim()}`);
55
+ }
56
+ return result.stdout;
57
+ }
58
+
59
+ function gifInputPath(value) {
60
+ if (!value || value.startsWith('--')) throw new Error('Missing GIF path');
61
+ const path = resolve(value);
62
+ if (extname(path).toLowerCase() !== '.gif') throw new Error(`GIF input must end in .gif: ${value}`);
63
+ if (!existsSync(path) || !statSync(path).isFile()) throw new Error(`GIF input not found: ${path}`);
64
+ return path;
65
+ }
66
+
67
+ function safeStem(path) {
68
+ return parse(basename(path)).name.replace(/[^a-zA-Z0-9._-]/g, '-');
69
+ }
70
+
71
+ function gifProbe(path) {
72
+ const raw = run('ffprobe', [
73
+ '-v', 'error',
74
+ '-count_frames',
75
+ '-select_streams', 'v:0',
76
+ '-show_entries', 'stream=codec_name,width,height,nb_read_frames,duration,r_frame_rate:format=duration',
77
+ '-of', 'json',
78
+ path,
79
+ ]);
80
+ const probe = JSON.parse(raw);
81
+ const stream = probe.streams?.[0];
82
+ if (!stream || stream.codec_name !== 'gif') throw new Error(`Input is not a readable GIF: ${path}`);
83
+
84
+ const frameCount = Number(stream.nb_read_frames);
85
+ const durationSeconds = Number(stream.duration ?? probe.format?.duration);
86
+ if (!Number.isFinite(frameCount) || frameCount < 1) throw new Error(`Could not determine GIF frame count: ${path}`);
87
+ if (!Number.isFinite(durationSeconds) || durationSeconds <= 0) throw new Error(`Could not determine GIF duration: ${path}`);
88
+
89
+ return {
90
+ frameCount,
91
+ durationSeconds,
92
+ frameRate: stream.r_frame_rate,
93
+ width: Number(stream.width),
94
+ height: Number(stream.height),
95
+ };
96
+ }
97
+
98
+ export function contactSheetSampleFps({ requestedFps, durationSeconds, columns, rows }) {
99
+ const cells = columns * rows;
100
+ return Number(Math.min(requestedFps, cells / durationSeconds).toFixed(6));
101
+ }
102
+
103
+ export function reviewGif(input, {
104
+ outDir = join(dirname(input), '.gif-review'),
105
+ fps = DEFAULT_REVIEW_FPS,
106
+ width = DEFAULT_REVIEW_WIDTH,
107
+ columns = DEFAULT_REVIEW_COLUMNS,
108
+ rows = DEFAULT_REVIEW_ROWS,
109
+ } = {}) {
110
+ const probe = gifProbe(input);
111
+ const sampleFps = contactSheetSampleFps({
112
+ requestedFps: fps,
113
+ durationSeconds: probe.durationSeconds,
114
+ columns,
115
+ rows,
116
+ });
117
+ const outputDir = resolve(outDir);
118
+ const stem = safeStem(input);
119
+ const contactSheet = join(outputDir, `${stem}-contact-sheet.png`);
120
+ const metadata = join(outputDir, `${stem}-review.json`);
121
+ mkdirSync(outputDir, { recursive: true, mode: 0o700 });
122
+ chmodSync(outputDir, 0o700);
123
+ closeSync(openPrivateFile(contactSheet, 'w'));
124
+
125
+ run('ffmpeg', [
126
+ '-v', 'error',
127
+ '-i', input,
128
+ '-vf', `fps=${sampleFps},scale=${width}:-1:flags=lanczos,tile=${columns}x${rows}`,
129
+ '-frames:v', '1',
130
+ '-y',
131
+ contactSheet,
132
+ ]);
133
+ chmodSync(contactSheet, 0o600);
134
+
135
+ const report = {
136
+ input,
137
+ frame_count: probe.frameCount,
138
+ duration_seconds: probe.durationSeconds,
139
+ frame_rate: probe.frameRate,
140
+ dimensions: { width: probe.width, height: probe.height },
141
+ review: {
142
+ sample_fps: sampleFps,
143
+ frame_width: width,
144
+ columns,
145
+ rows,
146
+ contact_sheet: contactSheet,
147
+ metadata,
148
+ },
149
+ };
150
+ writePrivateJson(metadata, report);
151
+ return report;
152
+ }
153
+
154
+ export function parseReviewOptions(args) {
155
+ const value = (name) => optionValue(args, name, null);
156
+ return {
157
+ outDir: requiredOptionValue(args, '--out-dir', null),
158
+ fps: parseBoundedNumber(value('--fps'), '--fps', { fallback: DEFAULT_REVIEW_FPS, min: 0.1, max: 30 }),
159
+ width: parseBoundedNumber(value('--width'), '--width', { fallback: DEFAULT_REVIEW_WIDTH, min: 64, max: 1920, integer: true }),
160
+ columns: parseBoundedNumber(value('--columns'), '--columns', { fallback: DEFAULT_REVIEW_COLUMNS, min: 1, max: 10, integer: true }),
161
+ rows: parseBoundedNumber(value('--rows'), '--rows', { fallback: DEFAULT_REVIEW_ROWS, min: 1, max: 10, integer: true }),
162
+ };
163
+ }
164
+
165
+ export async function main(args = process.argv.slice(2)) {
166
+ if (!args.length || args[0] === '--help' || args[0] === '-h') {
167
+ usage();
168
+ return args.length ? 0 : 1;
169
+ }
170
+
171
+ const input = gifInputPath(args[0]);
172
+ const options = parseReviewOptions(args.slice(1));
173
+ const report = reviewGif(input, {
174
+ ...options,
175
+ outDir: options.outDir || join(dirname(input), '.gif-review'),
176
+ });
177
+
178
+ if (hasFlag(args, '--json')) {
179
+ console.log(JSON.stringify(report, null, 2));
180
+ } else {
181
+ console.log(`GIF: ${report.input}`);
182
+ console.log(`Frames: ${report.frame_count}`);
183
+ console.log(`Duration: ${report.duration_seconds}s`);
184
+ console.log(`Frame rate: ${report.frame_rate}`);
185
+ console.log(`Contact sheet: ${report.review.contact_sheet}`);
186
+ console.log(`Review metadata: ${report.review.metadata}`);
187
+ }
188
+ return 0;
189
+ }
190
+
191
+ function isDirectExecution() {
192
+ if (!process.argv[1]) return false;
193
+ return realpathSync(process.argv[1]) === realpathSync(SCRIPT_FILE);
194
+ }
195
+
196
+ if (isDirectExecution()) {
197
+ try {
198
+ process.exitCode = await main();
199
+ } catch (error) {
200
+ console.error(`✗ ${error.message}`);
201
+ process.exitCode = 1;
202
+ }
203
+ }
package/scripts/start.mjs CHANGED
@@ -13,7 +13,7 @@
13
13
  * BROWSER_TOOLS_OWNER_TOKEN="<owner token>" scripts/start.mjs
14
14
  */
15
15
 
16
- import { hasFlag, requiredOptionValue, parseOwnerId, parseOwnerToken, parsePort, startChrome } from './browser-control.mjs';
16
+ import { CLI_OWNER_ID, hasFlag, requiredOptionValue, parseOwnerId, parseOwnerToken, parsePort, startChrome } from './browser-control.mjs';
17
17
 
18
18
  const args = process.argv.slice(2);
19
19
  const profileName = requiredOptionValue(args, '--profile', null);
@@ -24,7 +24,7 @@ const includeGoogle = hasFlag(args, '--include-google');
24
24
  const explicitPort = args.includes('--port');
25
25
  const port = parsePort(args);
26
26
  const ownerToken = parseOwnerToken(args);
27
- const ownerId = parseOwnerId(args);
27
+ const ownerId = parseOwnerId(args) || CLI_OWNER_ID;
28
28
 
29
29
  try {
30
30
  const result = await startChrome({ port, profileName, taskName, forceProfileSync, autoAllocatePort: !explicitPort, ownerToken, ownerId, headless, includeGoogle });
package/scripts/stop.mjs CHANGED
@@ -8,11 +8,24 @@
8
8
  * scripts/stop.mjs --port 9223
9
9
  * scripts/stop.mjs --clean
10
10
  * scripts/stop.mjs --dry-run
11
- * scripts/stop.mjs --prune (remove all cached clones not in use)
11
+ * scripts/stop.mjs --prune (reap orphans, then remove all cached clones not in use)
12
+ * scripts/stop.mjs --reap (kill managed browsers no lifecycle file tracks)
13
+ * scripts/stop.mjs --reap --dry-run (list them without killing anything)
14
+ * scripts/stop.mjs --status (show how many managed browsers are running)
12
15
  * scripts/stop.mjs --owner-token "$BROWSER_TOOLS_OWNER_TOKEN"
13
16
  */
14
17
 
15
- import { hasFlag, parseOwnerToken, parsePort, pruneChromeClones, stopChrome } from './browser-control.mjs';
18
+ import {
19
+ hasFlag,
20
+ managedBrowserCapacity,
21
+ managedBrowserStartupWarnings,
22
+ parseOwnerToken,
23
+ parsePort,
24
+ pruneChromeClones,
25
+ reapExitCode,
26
+ reapOrphanedChromes,
27
+ stopChrome,
28
+ } from './browser-control.mjs';
16
29
 
17
30
  const args = process.argv.slice(2);
18
31
  const port = parsePort(args);
@@ -20,8 +33,48 @@ const clean = hasFlag(args, '--clean');
20
33
  const dryRun = hasFlag(args, '--dry-run');
21
34
  const ownerToken = parseOwnerToken(args);
22
35
 
36
+ function reportReaped(reaped, wasDryRun) {
37
+ if (!reaped.length) {
38
+ console.log('No untracked managed browsers found.');
39
+ return;
40
+ }
41
+ for (const entry of reaped) {
42
+ const verb = wasDryRun ? 'Would reap' : entry.status === 'failed' ? '✗ Failed to reap' : '✓ Reaped';
43
+ console.log(`${verb} :${entry.port} (PID ${entry.pid})`);
44
+ }
45
+ }
46
+
47
+ if (hasFlag(args, '--status')) {
48
+ const capacity = managedBrowserCapacity();
49
+ console.log(`${capacity.count} of ${capacity.max} managed Chrome browsers running, ${capacity.remaining} slot(s) free`);
50
+ for (const entry of capacity.processes) {
51
+ const hours = Number.isFinite(entry.ageMs) ? (entry.ageMs / 3600000).toFixed(1) : '?';
52
+ console.log(` :${entry.port} PID ${entry.pid} up ${hours}h`);
53
+ }
54
+ for (const warning of managedBrowserStartupWarnings({ processes: capacity.processes, max: capacity.max })) {
55
+ console.log(`⚠ ${warning}`);
56
+ }
57
+ process.exit(0);
58
+ }
59
+
60
+ if (hasFlag(args, '--reap')) {
61
+ const result = reapOrphanedChromes({ dryRun });
62
+ reportReaped(result.reaped, dryRun);
63
+ // A caller reaping to free a slot must be able to tell that a browser survived.
64
+ process.exit(reapExitCode(result.reaped));
65
+ }
66
+
23
67
  if (hasFlag(args, '--prune')) {
24
- const prune = pruneChromeClones({ dryRun });
68
+ // Reap first: a clone dir held open by an untracked browser is otherwise unreclaimable, which is
69
+ // how 2.4 GB of clones survived every prune during the leak.
70
+ const reaped = reapOrphanedChromes({ dryRun });
71
+ reportReaped(reaped.reaped, dryRun);
72
+ // A real prune reclaims the clones of the browsers just reaped. Tell the dry run to assume the
73
+ // same, otherwise the preview reports those clones as in use and understates what will be removed.
74
+ const freedPorts = reaped.reaped
75
+ .filter((entry) => entry.status === 'would-reap' || entry.status === 'reaped' || entry.status === 'killed' || entry.status === 'already-gone')
76
+ .map((entry) => entry.port);
77
+ const prune = pruneChromeClones({ dryRun, assumeStoppedPorts: dryRun ? freedPorts : [] });
25
78
  if (!prune.removed.length && !prune.kept.length) {
26
79
  console.log('No cached Chrome clones found.');
27
80
  }
@@ -32,7 +85,7 @@ if (hasFlag(args, '--prune')) {
32
85
  const count = entry.paths.length;
33
86
  console.log(`${dryRun ? '• Would remove' : '✓ Removed'} clone for :${entry.port} (${count} item${count === 1 ? '' : 's'})`);
34
87
  }
35
- process.exit(0);
88
+ process.exit(reapExitCode(reaped.reaped));
36
89
  }
37
90
 
38
91
  const result = stopChrome({ port, clean, dryRun, ownerToken });
@@ -45,7 +98,8 @@ if (result.status === 'missing') {
45
98
  if (result.status === 'would-stop') {
46
99
  console.log(`✓ Dry run: would stop managed Chrome (PID ${result.pid}) on :${port}`);
47
100
  } else if (result.status === 'stopped') {
48
- console.log(`✓ Stopped managed Chrome (PID ${result.pid}) on :${port}`);
101
+ const reclaimed = result.reclaimedUnowned ? ' (reclaimed: nothing owned it)' : '';
102
+ console.log(`✓ Stopped managed Chrome (PID ${result.pid}) on :${port}${reclaimed}`);
49
103
  } else if (result.status === 'killed') {
50
104
  console.log(`✓ Killed managed Chrome (PID ${result.pid}) on :${port} after SIGTERM did not exit`);
51
105
  } else if (result.status === 'already-gone') {
@@ -54,6 +108,7 @@ if (result.status === 'would-stop') {
54
108
  const target = result.pid ? `PID ${result.pid}` : `port ${port}`;
55
109
  console.error(`✗ Refusing to stop ${target}: ${result.reason}`);
56
110
  console.error(' Safety rule: stop.mjs only kills Chrome processes launched by start.mjs.');
111
+ if (result.hint) console.error(` ${result.hint}`);
57
112
  process.exit(1);
58
113
  } else if (result.status === 'not-owned') {
59
114
  const owner = result.ownerId ? ` owned by ${result.ownerId}` : '';