@slack/radar-mcp 1.23.0 → 1.24.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.
@@ -5,11 +5,27 @@ import path from "path";
5
5
  import { promisify } from "util";
6
6
  import { readDebugLogBuffer } from "./debug-log.js";
7
7
  import { filterLogLines, getCaptureFilePath, isCapturing, readRecentLogs, registerCleanup, rotateCaptureIfNeeded, startCapture, stopCapture, } from "./logcat-capture.js";
8
- import { RADAR_PORT, RADAR_VERSION, SLACK_DEBUG_PKG } from "./constants.js";
8
+ import { RADAR_PORT, RADAR_VERSION, slackDebugPackage, debugPackageFromPsName, debugPackageOverride, debugPackageOverrideError, SHIPPED_DEBUG_PACKAGES, setSlackDebugPackage, } from "./constants.js";
9
9
  import { getOrCreateRadarToken } from "./radar-token.js";
10
+ import { AmbiguousDebugPackageError, AndroidUserIdError, BareEnableError, DebugPackageOverrideError, NoDebugBuildRunningError, UnknownDebugBuildError, } from "./enable-diagnosis.js";
10
11
  import { LogSession } from "./log-session.js";
11
12
  const SOCKET_NAME = "slack-radar";
12
13
  const ENABLE_ACTION = "slack.debug.ENABLE_RADAR";
14
+ // Older builds must drop this action rather than open a tokenless session.
15
+ const TOKEN_FILE_ENABLE_ACTION = "slack.debug.ENABLE_RADAR_TOKEN_FILE";
16
+ const TOKEN_FILE = "files/slack-radar/enable-token";
17
+ // Older adb can leave stdin open, so cap the write before trying argv.
18
+ const TOKEN_FILE_WRITE_TIMEOUT_OVERRIDE_MS = Number(process.env.SLACK_RADAR_TOKEN_WRITE_TIMEOUT_MS);
19
+ const TOKEN_FILE_WRITE_TIMEOUT_MS = Number.isInteger(TOKEN_FILE_WRITE_TIMEOUT_OVERRIDE_MS) && TOKEN_FILE_WRITE_TIMEOUT_OVERRIDE_MS > 0
20
+ ? TOKEN_FILE_WRITE_TIMEOUT_OVERRIDE_MS : 10_000;
21
+ const TOKEN_FILE_CHECK_TIMEOUT_MS = 5000;
22
+ // The user id enters a shell command, so only decimal digits are safe.
23
+ const ANDROID_USER_ID = /^\d+$/;
24
+ function assertAndroidUserId(userId) {
25
+ if (!ANDROID_USER_ID.test(userId)) {
26
+ throw new AndroidUserIdError();
27
+ }
28
+ }
13
29
  /**
14
30
  * Default ceiling for the `ps` process probe. Patient by design: on the MCP enable path
15
31
  * several seconds of ping retries have already elapsed, so a slow adb is worth waiting out
@@ -79,6 +95,9 @@ export function resolveAdbPath() {
79
95
  catch {
80
96
  // `command -v adb` returns non-zero when not found; fall through
81
97
  }
98
+ // SLACK_RADAR_ADB_PATH_ONLY=1 (set by the test run and the smoke) skips every fallback past PATH, so a child with a bare PATH never finds a machine-wide adb.
99
+ if (process.env.SLACK_RADAR_ADB_PATH_ONLY === "1")
100
+ return null;
82
101
  // 2. Common install locations, in order of likelihood on macOS and Linux.
83
102
  const home = os.homedir();
84
103
  const candidates = [
@@ -215,34 +234,165 @@ export function parseAndroidLogcat(line, resolvePackage = () => undefined) {
215
234
  // rather than inherited, matching the stdio discipline execsync-stdio.test.mjs pins.
216
235
  const execFileAsync = promisify(execFile);
217
236
  // One wording for a missing adb on the forward path, shared by the sync and async rebuilds so
218
- // the two cannot drift.
219
- const ADB_NOT_FOUND_FORWARD_ERROR = "adb binary not found. Set ANDROID_HOME or install Android SDK platform-tools. Searched: PATH, $ANDROID_HOME/platform-tools/adb, ~/Library/Android/sdk/platform-tools/adb, ~/Android/Sdk/platform-tools/adb, /usr/local/bin/adb, /opt/homebrew/bin/adb.";
237
+ // the two cannot drift. Under SLACK_RADAR_ADB_PATH_ONLY=1 only PATH was searched, so the reason
238
+ // says that and names the way out, instead of listing fallbacks that never ran.
239
+ export function adbNotFoundError() {
240
+ if (process.env.SLACK_RADAR_ADB_PATH_ONLY === "1") {
241
+ return "adb binary not found on PATH. SLACK_RADAR_ADB_PATH_ONLY=1 skipped the SDK and /usr/local/bin, /opt/homebrew/bin fallbacks. Put the platform-tools adb on PATH, or unset SLACK_RADAR_ADB_PATH_ONLY.";
242
+ }
243
+ return "adb binary not found. Set ANDROID_HOME or install Android SDK platform-tools. Searched: PATH, $ANDROID_HOME/platform-tools/adb, ~/Library/Android/sdk/platform-tools/adb, ~/Android/Sdk/platform-tools/adb, /usr/local/bin/adb, /opt/homebrew/bin/adb.";
244
+ }
220
245
  // The device-side `ps` pipeline both debug-build probes run. See psDebugBuildProbe's doc
221
246
  // comment for why the `|| exit 9` and the trailing `|| true` are each load-bearing.
222
247
  const PS_DEBUG_BUILD_SCRIPT = 'out=$(ps -A -o USER,NAME) || exit 9; echo "$out" | grep Slack | grep debug || true';
223
248
  // The enable broadcast, in argv form so the sync and async activate paths send the exact
224
- // same command. The package target keeps other receivers from reading the token.
225
- function enableBroadcastArgs(userId, timeoutMinutes, token) {
226
- return [
249
+ // same command. The package target, which auto-detect takes only from the shipped debug ids,
250
+ // keeps other receivers from reading the token.
251
+ function enableBroadcastArgs(userId, timeoutMinutes, token, pkg = slackDebugPackage()) {
252
+ assertAndroidUserId(userId);
253
+ const base = [
227
254
  "shell",
228
255
  "am",
229
256
  "broadcast",
230
257
  "--user",
231
258
  userId,
232
259
  "-a",
233
- ENABLE_ACTION,
260
+ token === null ? TOKEN_FILE_ENABLE_ACTION : ENABLE_ACTION,
234
261
  "-p",
235
- SLACK_DEBUG_PKG,
262
+ pkg,
236
263
  "--ei",
237
264
  "timeout_minutes",
238
265
  String(timeoutMinutes),
239
266
  "--es",
240
267
  "mcp_version",
241
268
  RADAR_VERSION,
242
- "--es",
243
- "radar_token",
244
- token,
245
269
  ];
270
+ return token === null ? base : [...base, "--es", "radar_token", token];
271
+ }
272
+ // One remote string preserves quotes because adb shell re-joins argv without escaping.
273
+ // The package precedes --user because run-as reads it there.
274
+ export function tokenFileWriteArgs(userId, pkg = slackDebugPackage()) {
275
+ assertAndroidUserId(userId);
276
+ return ["shell", `run-as ${pkg} --user ${userId} sh -c 'umask 077; mkdir -p files/slack-radar && cat > ${TOKEN_FILE} && echo written'`];
277
+ }
278
+ // A leftover file can mean a dropped action or a failed app-side delete.
279
+ export function tokenFileCheckArgs(userId, pkg = slackDebugPackage()) {
280
+ assertAndroidUserId(userId);
281
+ return ["shell", `run-as ${pkg} --user ${userId} sh -c 'if [ -e ${TOKEN_FILE} ]; then rm -f ${TOKEN_FILE}; echo leftover; else echo consumed; fi'`];
282
+ }
283
+ // A run-as denial can exit zero, so only the final sentinel counts.
284
+ export function tokenFileWritten(stdout) {
285
+ return stdout.trim().split(/\r?\n/).pop()?.trim() === "written";
286
+ }
287
+ export function tokenFileLeftover(stdout) {
288
+ const lastLine = stdout.trim().split(/\r?\n/).pop()?.trim();
289
+ return lastLine === "leftover" ? true : lastLine === "consumed" ? false : null;
290
+ }
291
+ export function classifyPsDebugBuild(stdout) {
292
+ const lines = stdout.trim();
293
+ return lines ? { state: "running", lines } : { state: "stopped", lines: "" };
294
+ }
295
+ /**
296
+ * The rows the probe lines carry: the Android user and the debug package behind the process name.
297
+ * A `:process` suffix folds into its package, and a name that breaks the package rule gets a null
298
+ * pkg (never trusted into a shell string) but its row still counts for its user. Lines that are
299
+ * not an app process of a user, such as root's, are skipped.
300
+ */
301
+ export function parsePsRows(lines) {
302
+ const rows = [];
303
+ for (const line of lines.split("\n")) {
304
+ const match = line.trim().match(/^u(\d+)_\S*\s+(\S+)$/);
305
+ if (match)
306
+ rows.push({ user: match[1], pkg: debugPackageFromPsName(match[2]) });
307
+ }
308
+ return rows;
309
+ }
310
+ /** The distinct valid debug packages ps shows for one Android user. */
311
+ export function debugPackagesForUser(lines, userId) {
312
+ const found = new Set();
313
+ for (const row of parsePsRows(lines)) {
314
+ if (row.user === userId && row.pkg)
315
+ found.add(row.pkg);
316
+ }
317
+ return [...found];
318
+ }
319
+ // The override wins over the build this session armed; either one is only checked, never replaced.
320
+ function pinnedBuild(override, held) {
321
+ if (override !== null)
322
+ return { pkg: override, reason: "override" };
323
+ return held !== null ? { pkg: held, reason: "held" } : null;
324
+ }
325
+ /**
326
+ * Which package to arm for one user. `unknown` keeps the current package and never blocks,
327
+ * the same as the process gate always did. A pinned package (the override, else the build this
328
+ * session already armed) is only checked, never replaced.
329
+ */
330
+ export function pickDebugPackage(probe, userId, override, current, held = null) {
331
+ if (probe.state === "unknown")
332
+ return { kind: "use", pkg: current, detected: false };
333
+ const seen = debugPackagesForUser(probe.lines, userId);
334
+ const pinned = pinnedBuild(override, held);
335
+ if (pinned !== null) {
336
+ return seen.includes(pinned.pkg)
337
+ ? { kind: "use", pkg: pinned.pkg, detected: false }
338
+ : { kind: "stopped", ...pinned };
339
+ }
340
+ // Only the shipped ids are adopted. Another Slack debug process is on screen, so it is named
341
+ // rather than called stopped.
342
+ const packages = seen.filter((pkg) => SHIPPED_DEBUG_PACKAGES.includes(pkg));
343
+ if (packages.length === 0)
344
+ return seen.length === 0 ? { kind: "stopped" } : { kind: "unknown_flavour", packages: seen };
345
+ if (packages.length > 1) {
346
+ // Today's target stays armed when it is still among them; only a stranger needs the user's say.
347
+ return packages.includes(current) ? { kind: "use", pkg: current, detected: false } : { kind: "ambiguous", packages };
348
+ }
349
+ return { kind: "use", pkg: packages[0], detected: true };
350
+ }
351
+ function packageRunsAs(probe, userId, pkg) {
352
+ if (probe.state === "unknown")
353
+ return "unknown";
354
+ return debugPackagesForUser(probe.lines, userId).includes(pkg) ? "running" : "stopped";
355
+ }
356
+ function* probeDebugBuild() {
357
+ const ps = yield { args: ["shell", PS_DEBUG_BUILD_SCRIPT], timeoutMs: PS_PROBE_TIMEOUT_MS };
358
+ return "error" in ps ? { state: "unknown", lines: "" } : classifyPsDebugBuild(ps.stdout);
359
+ }
360
+ function* broadcast(args) {
361
+ const sent = yield { args, timeoutMs: ENABLE_BROADCAST_TIMEOUT_MS };
362
+ if ("error" in sent)
363
+ throw sent.error;
364
+ }
365
+ // One shared sequence keeps sync, async and profile arms from drifting.
366
+ function* enableSteps(userId, timeoutMinutes, token, probe, held) {
367
+ const overrideError = debugPackageOverrideError();
368
+ if (overrideError)
369
+ throw new DebugPackageOverrideError(overrideError);
370
+ if (probe === null)
371
+ probe = yield* probeDebugBuild();
372
+ const pick = pickDebugPackage(probe, userId, debugPackageOverride(), slackDebugPackage(), held);
373
+ if (pick.kind === "stopped")
374
+ return pick;
375
+ if (pick.kind === "ambiguous")
376
+ throw new AmbiguousDebugPackageError(userId, pick.packages);
377
+ if (pick.kind === "unknown_flavour")
378
+ throw new UnknownDebugBuildError(userId, pick.packages);
379
+ const pkg = pick.pkg;
380
+ const wrote = yield { args: tokenFileWriteArgs(userId, pkg), input: token, timeoutMs: TOKEN_FILE_WRITE_TIMEOUT_MS };
381
+ if ("error" in wrote || !tokenFileWritten(wrote.stdout)) {
382
+ yield { args: tokenFileCheckArgs(userId, pkg), timeoutMs: TOKEN_FILE_CHECK_TIMEOUT_MS };
383
+ yield* broadcast(enableBroadcastArgs(userId, timeoutMinutes, token, pkg));
384
+ return { kind: "sent", tokenViaArgv: "the token file write failed", pkg };
385
+ }
386
+ yield* broadcast(enableBroadcastArgs(userId, timeoutMinutes, null, pkg));
387
+ const check = yield { args: tokenFileCheckArgs(userId, pkg), timeoutMs: TOKEN_FILE_CHECK_TIMEOUT_MS };
388
+ if ("error" in check || tokenFileLeftover(check.stdout) !== true)
389
+ return { kind: "sent", tokenViaArgv: null, pkg };
390
+ // The app may have died since the gate, leaving no receiver for the argv enable.
391
+ if (packageRunsAs(yield* probeDebugBuild(), userId, pkg) === "stopped") {
392
+ return { kind: "stopped", ...pinnedBuild(debugPackageOverride(), held) };
393
+ }
394
+ yield* broadcast(enableBroadcastArgs(userId, timeoutMinutes, token, pkg));
395
+ return { kind: "sent", tokenViaArgv: "this build has no token file reader; update it", pkg };
246
396
  }
247
397
  /**
248
398
  * Parse the output of `ps -A -o USER,NAME` to extract the Android user ID
@@ -252,21 +402,27 @@ function enableBroadcastArgs(userId, timeoutMinutes, token) {
252
402
  * "10", which is often a work profile, but the id alone cannot prove that).
253
403
  */
254
404
  export function parseUserFromPsOutput(psOutput) {
405
+ return pickUserFromPs(psOutput).userId;
406
+ }
407
+ /**
408
+ * Same pick as parseUserFromPsOutput, plus whether a line of a target package decided it.
409
+ * With targets, only their lines count; when none match the user still comes from all lines
410
+ * (so errors can name a real user) and `matched` is false.
411
+ */
412
+ export function pickUserFromPs(psOutput, targetPackages) {
255
413
  if (!psOutput || !psOutput.trim())
256
- return "0";
257
- const lines = psOutput.trim().split("\n");
258
- // Collect all user IDs from matching lines
259
- const userIds = [];
260
- for (const line of lines) {
261
- const match = line.match(/u(\d+)_/);
262
- if (match)
263
- userIds.push(match[1]);
264
- }
265
- if (userIds.length === 0)
266
- return "0";
414
+ return { userId: "0", matched: false };
415
+ const rows = parsePsRows(psOutput);
416
+ const all = rows.map((row) => row.user);
417
+ const inTarget = targetPackages
418
+ ? rows.filter((row) => row.pkg && targetPackages.includes(row.pkg)).map((row) => row.user)
419
+ : [];
420
+ const ids = targetPackages && inTarget.length > 0 ? inTarget : all;
421
+ if (ids.length === 0)
422
+ return { userId: "0", matched: false };
267
423
  // Prefer a secondary user (non-zero user ID) when multiple profiles are running
268
- const secondaryUser = userIds.find((id) => id !== "0");
269
- return secondaryUser ?? userIds[0];
424
+ const userId = ids.find((id) => id !== "0") ?? ids[0];
425
+ return { userId, matched: !targetPackages || inTarget.length > 0 };
270
426
  }
271
427
  /**
272
428
  * Parse `adb devices -l` output into a list of attached devices. Skips the
@@ -309,14 +465,37 @@ export function parseAdbDevicesOutput(raw) {
309
465
  function spawnAndroidLogcat() {
310
466
  const adb = resolveAdbPath();
311
467
  if (!adb)
312
- throw new Error(ADB_NOT_FOUND_FORWARD_ERROR);
468
+ throw new Error(adbNotFoundError());
313
469
  return spawn(adb, ["logcat", "-v", "threadtime", "-T", "1"], {
314
470
  stdio: ["ignore", "pipe", "ignore"],
315
471
  });
316
472
  }
317
473
  export class AndroidTransport {
318
474
  platform = "android";
319
- logPackage = SLACK_DEBUG_PKG;
475
+ get logPackage() { return slackDebugPackage(); }
476
+ // Only a shipped id is adopted, the same lookalike rule as ps auto-detect, and a pinned
477
+ // override always wins. The ping already names the owner, so no broadcast or ps is needed.
478
+ // The same ping names the user the build is bound to, so ps does not guess it again.
479
+ adoptRadarOwner(ping) {
480
+ const pkg = typeof ping.package === "string" ? ping.package : null;
481
+ // An older build names no package; it counts as ours, so hold the current one.
482
+ if (pkg === null)
483
+ this.commitBuild(slackDebugPackage());
484
+ else if (debugPackageOverride() === null && SHIPPED_DEBUG_PACKAGES.includes(pkg)) {
485
+ this.commitBuild(pkg);
486
+ }
487
+ if (pkg !== null && pkg !== slackDebugPackage())
488
+ return;
489
+ const user = ping.android_user_id;
490
+ const whole = typeof user === "number" ? Number.isInteger(user) && user >= 0 : typeof user === "string" && /^\d+$/.test(user);
491
+ if (whole)
492
+ this.detectedUserId = String(user);
493
+ }
494
+ // An older build sends no package, so a missing field is accepted rather than refused.
495
+ foreignRadarOwner(ping) {
496
+ const pkg = ping.package;
497
+ return typeof pkg === "string" && pkg !== slackDebugPackage() ? pkg : null;
498
+ }
320
499
  supportsHostLogs = true;
321
500
  logSession;
322
501
  // The Android debug build serves Radar's HTTP API through the adb-forwarded local socket.
@@ -329,11 +508,25 @@ export class AndroidTransport {
329
508
  supportsDeviceDashboard = true;
330
509
  portForwarded = false;
331
510
  detectedUserId = null;
511
+ // The last ps showed a debug-process user even though it was not cached, so errors can name it.
512
+ psSawUser = false;
513
+ // The build this session armed. Re-arms target it and never re-detect; only a fresh decision
514
+ // (enable, a profile switch) releases it. resetState leaves it, since a re-arm runs after one.
515
+ armedBuild = null;
516
+ // The armed package and the hold move together, and only once an arm was sent, so a failed
517
+ // arm leaves both on the build that was already running.
518
+ commitBuild(pkg) {
519
+ this.armedBuild = pkg;
520
+ setSlackDebugPackage(pkg);
521
+ }
332
522
  currentTimeoutMinutes = 5;
333
523
  radarEnabled = false;
334
524
  lastForwardError = null;
335
525
  lastActivateError = null;
336
526
  lastActivateTokenFileError = null;
527
+ // Any error whose message already says what to do; the surfaces show it plain.
528
+ lastActivateBareError = null;
529
+ lastTokenViaArgv = null;
337
530
  // The device pinned by selectDevice, surfaced via getSelectedDevice for the enable
338
531
  // body and web /health. Not cleared by resetState: the env pin is sticky by design.
339
532
  selectedDevice = null;
@@ -358,7 +551,7 @@ export class AndroidTransport {
358
551
  // never trust the cache (see reassertForward's doc comment on shared-transport.ts).
359
552
  rebuildForward() {
360
553
  if (!ADB) {
361
- this.lastForwardError = ADB_NOT_FOUND_FORWARD_ERROR;
554
+ this.lastForwardError = adbNotFoundError();
362
555
  return false;
363
556
  }
364
557
  // Drop any existing mapping first. Re-issuing `adb forward` over a stale mapping
@@ -454,7 +647,7 @@ export class AndroidTransport {
454
647
  // existing mapping (failure is harmless), then add ours and record the outcome.
455
648
  async rebuildForwardAsync() {
456
649
  if (!ADB) {
457
- this.lastForwardError = ADB_NOT_FOUND_FORWARD_ERROR;
650
+ this.lastForwardError = adbNotFoundError();
458
651
  return false;
459
652
  }
460
653
  try {
@@ -491,25 +684,14 @@ export class AndroidTransport {
491
684
  if (token === null)
492
685
  return;
493
686
  try {
494
- const userId = this.detectDebugBuildUser();
495
- // Same taller ceiling as the async twin: the broadcast waits for ordered delivery and a
496
- // cold debug build can hold completion past 5 seconds.
497
- execFileSync(ADB, enableBroadcastArgs(userId, timeout, token), {
498
- timeout: ENABLE_BROADCAST_TIMEOUT_MS,
499
- stdio: ["ignore", "ignore", "pipe"],
500
- });
501
- this.recordActivateSuccess(timeout);
687
+ const { userId, probe } = this.detectDebugBuildUserProbe();
688
+ this.applyArmOutcome(this.runEnableSteps(ADB, enableSteps(userId, timeout, token, probe, this.armedBuild)), userId, timeout);
502
689
  }
503
690
  catch (e) {
504
691
  this.recordActivateFailure(e);
505
692
  }
506
693
  }
507
- /**
508
- * activate, off the event loop. Same skip guard, the same broadcast argv, and the same
509
- * state recording as the sync twin, but the `ps` user detection and the broadcast run
510
- * through execFileAsync so a caller serving HTTP (the dashboard's boot-arm chain) keeps
511
- * answering while adb runs.
512
- */
694
+ /** Keep adb off the event loop so HTTP requests still get answers during an arm. */
513
695
  async activateAsync(timeoutMinutes) {
514
696
  if (!ADB) {
515
697
  this.lastActivateError = "adb binary not found";
@@ -522,12 +704,8 @@ export class AndroidTransport {
522
704
  if (token === null)
523
705
  return;
524
706
  try {
525
- const userId = await this.detectDebugBuildUserAsync();
526
- // The broadcast waits for ordered delivery, and a cold debug build has been observed to
527
- // hold completion past 5 seconds; a killed broadcast reads as a failed arm, so this one
528
- // call gets a taller ceiling than the quick adb queries.
529
- await execFileAsync(ADB, enableBroadcastArgs(userId, timeout, token), { timeout: ENABLE_BROADCAST_TIMEOUT_MS });
530
- this.recordActivateSuccess(timeout);
707
+ const { userId, probe } = await this.detectDebugBuildUserProbeAsync();
708
+ this.applyArmOutcome(await this.runEnableStepsAsync(ADB, enableSteps(userId, timeout, token, probe, this.armedBuild)), userId, timeout);
531
709
  }
532
710
  catch (e) {
533
711
  this.recordActivateFailure(e);
@@ -556,9 +734,63 @@ export class AndroidTransport {
556
734
  return "unknown";
557
735
  }
558
736
  }
559
- // A broadcast landed: record the session state and start streaming logcat to a
560
- // session-scoped file so reads are not subject to the device ring buffer rotating
561
- // under load. Shared by activate and activateAsync so the two cannot drift.
737
+ runEnableSteps(adb, steps) {
738
+ let next = steps.next();
739
+ while (!next.done) {
740
+ const step = next.value;
741
+ let result;
742
+ try {
743
+ result = { stdout: execFileSync(adb, step.args, {
744
+ timeout: step.timeoutMs,
745
+ encoding: "utf-8",
746
+ input: step.input,
747
+ stdio: [step.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
748
+ }) };
749
+ }
750
+ catch (error) {
751
+ result = { error: error };
752
+ }
753
+ next = steps.next(result);
754
+ }
755
+ return next.value;
756
+ }
757
+ async runEnableStepsAsync(adb, steps) {
758
+ let next = steps.next();
759
+ while (!next.done) {
760
+ const step = next.value;
761
+ let result;
762
+ try {
763
+ const pending = execFileAsync(adb, step.args, { timeout: step.timeoutMs, encoding: "utf-8" });
764
+ if (step.input !== undefined) {
765
+ // A run-as denial can close stdin early, so ignore EPIPE rather than crash.
766
+ pending.child.stdin?.on("error", () => { });
767
+ pending.child.stdin?.end(step.input);
768
+ }
769
+ result = { stdout: (await pending).stdout };
770
+ }
771
+ catch (error) {
772
+ result = { error: error };
773
+ }
774
+ next = steps.next(result);
775
+ }
776
+ return next.value;
777
+ }
778
+ // A user ps never saw is only the fallback 0, so the stopped error leaves it out.
779
+ applyArmOutcome(outcome, userId, timeout) {
780
+ if (outcome.kind === "stopped") {
781
+ this.recordActivateFailure(new NoDebugBuildRunningError(this.detectedUserId === null && !this.psSawUser ? null : userId, outcome.pkg, outcome.reason));
782
+ return;
783
+ }
784
+ this.lastTokenViaArgv = outcome.tokenViaArgv;
785
+ this.commitBuild(outcome.pkg);
786
+ this.recordActivateSuccess(timeout);
787
+ }
788
+ clearArmOutcome() {
789
+ this.lastActivateTokenFileError = null;
790
+ this.lastActivateBareError = null;
791
+ this.lastTokenViaArgv = null;
792
+ }
793
+ // Keep logs in a session file so reads survive device buffer rotation.
562
794
  recordActivateSuccess(timeout) {
563
795
  this.currentTimeoutMinutes = timeout;
564
796
  this.radarEnabled = true;
@@ -566,16 +798,14 @@ export class AndroidTransport {
566
798
  this.lastActivateTokenFileError = null;
567
799
  this.ensureLogCapture();
568
800
  }
569
- // Broadcast failed, device may not be connected. Recorded so the enable path can report
570
- // it instead of claiming success with a failing ping. radarEnabled drops too: a prior
571
- // success no longer proves the device side is armed, and leaving it true would make every
572
- // later activate() early-return and never re-send the broadcast.
801
+ // A failed enable must not leave a prior success cached.
573
802
  recordActivateFailure(e) {
574
803
  this.radarEnabled = false;
575
- this.lastActivateError = describeBroadcastFailure(e);
804
+ this.lastActivateBareError = e instanceof BareEnableError ? e : null;
805
+ this.lastActivateError = e instanceof BareEnableError ? e.message : describeBroadcastFailure(e);
576
806
  }
577
807
  readArmToken() {
578
- this.lastActivateTokenFileError = null;
808
+ this.clearArmOutcome();
579
809
  try {
580
810
  return getOrCreateRadarToken();
581
811
  }
@@ -595,13 +825,24 @@ export class AndroidTransport {
595
825
  getLastActivateTokenFileError() {
596
826
  return this.lastActivateTokenFileError;
597
827
  }
828
+ getLastActivateBareError() {
829
+ return this.lastActivateBareError;
830
+ }
831
+ getLastTokenViaArgv() {
832
+ return this.lastTokenViaArgv;
833
+ }
834
+ /** Forget the held build so the next arm detects one afresh. */
835
+ releaseDebugBuild() {
836
+ this.armedBuild = null;
837
+ }
598
838
  resetState() {
599
839
  this.portForwarded = false;
600
840
  this.detectedUserId = null;
841
+ this.psSawUser = false;
601
842
  this.radarEnabled = false;
602
843
  this.lastForwardError = null;
603
844
  this.lastActivateError = null;
604
- this.lastActivateTokenFileError = null;
845
+ this.clearArmOutcome();
605
846
  // Capture has its own idle timer; not stopped on activation reset (see logcat-capture.ts).
606
847
  }
607
848
  dropForward() {
@@ -664,7 +905,7 @@ export class AndroidTransport {
664
905
  getAppState() {
665
906
  if (!ADB)
666
907
  throw new Error("adb not found on PATH or common SDK locations");
667
- return execSync(`${ADB} shell "dumpsys activity activities | grep -A 5 'com.Slack.internal'"`, { timeout: 10000, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
908
+ return execSync(`${ADB} shell "dumpsys activity activities | grep -A 5 '${slackDebugPackage()}'"`, { timeout: 10000, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
668
909
  }
669
910
  getRecentLogs(tag, limit, grep) {
670
911
  if (!ADB)
@@ -725,20 +966,19 @@ export class AndroidTransport {
725
966
  }
726
967
  const seen = new Set();
727
968
  const profiles = [];
728
- for (const line of probe.lines.split("\n")) {
729
- const match = line.match(/u(\d+)_/);
730
- if (match && !seen.has(match[1])) {
731
- seen.add(match[1]);
732
- const id = match[1];
733
- profiles.push({
734
- userId: id,
735
- label: id === "0" ? "Personal (user 0)" : `Secondary (user ${id}, e.g. a work profile)`,
736
- });
737
- }
969
+ for (const { user: id } of parsePsRows(probe.lines)) {
970
+ if (seen.has(id))
971
+ continue;
972
+ seen.add(id);
973
+ profiles.push({
974
+ userId: id,
975
+ label: id === "0" ? "Personal (user 0)" : `Secondary (user ${id}, e.g. a work profile)`,
976
+ });
738
977
  }
739
978
  return profiles.length > 0 ? profiles : [{ userId: "0", label: "Personal (user 0)" }];
740
979
  }
741
980
  activateForUser(userId, timeoutMinutes) {
981
+ assertAndroidUserId(userId);
742
982
  if (!ADB)
743
983
  throw new Error("adb not found on PATH or common SDK locations");
744
984
  const timeout = timeoutMinutes || this.currentTimeoutMinutes;
@@ -746,19 +986,21 @@ export class AndroidTransport {
746
986
  // scoped to a profile we could not detect, and appending this profile's
747
987
  // run to it would mix profiles in one file. Rotating is the safe default.
748
988
  const profileChanged = this.detectedUserId !== userId;
749
- this.lastActivateTokenFileError = null;
989
+ this.clearArmOutcome();
750
990
  const token = getOrCreateRadarToken();
751
- // The same argv and the same tall ceiling as activate's twins: the broadcast waits for
752
- // ordered delivery and a cold debug build can hold completion past 5 seconds.
991
+ let outcome;
753
992
  try {
754
- execFileSync(ADB, enableBroadcastArgs(userId, timeout, token), {
755
- timeout: ENABLE_BROADCAST_TIMEOUT_MS,
756
- stdio: ["ignore", "ignore", "pipe"],
757
- });
993
+ outcome = this.runEnableSteps(ADB, enableSteps(userId, timeout, token, null, null));
758
994
  }
759
995
  catch (error) {
996
+ if (error instanceof BareEnableError)
997
+ throw error;
760
998
  throw new Error(describeBroadcastFailure(error));
761
999
  }
1000
+ if (outcome.kind === "stopped")
1001
+ throw new NoDebugBuildRunningError(userId, outcome.pkg, outcome.reason);
1002
+ this.lastTokenViaArgv = outcome.tokenViaArgv;
1003
+ this.commitBuild(outcome.pkg);
762
1004
  this.detectedUserId = userId;
763
1005
  this.currentTimeoutMinutes = timeout;
764
1006
  this.radarEnabled = true;
@@ -979,10 +1221,8 @@ export class AndroidTransport {
979
1221
  timeout: timeoutMs,
980
1222
  encoding: "utf-8",
981
1223
  stdio: ["ignore", "pipe", "pipe"],
982
- }).trim();
983
- return ps.length > 0
984
- ? { state: "running", lines: ps }
985
- : { state: "stopped", lines: "" };
1224
+ });
1225
+ return classifyPsDebugBuild(ps);
986
1226
  }
987
1227
  catch {
988
1228
  return { state: "unknown", lines: "" };
@@ -997,44 +1237,45 @@ export class AndroidTransport {
997
1237
  timeout: timeoutMs,
998
1238
  encoding: "utf-8",
999
1239
  });
1000
- const ps = stdout.trim();
1001
- return ps.length > 0
1002
- ? { state: "running", lines: ps }
1003
- : { state: "stopped", lines: "" };
1240
+ return classifyPsDebugBuild(stdout);
1004
1241
  }
1005
1242
  catch {
1006
1243
  return { state: "unknown", lines: "" };
1007
1244
  }
1008
1245
  }
1009
- /** Raw `ps` lines for running debug-build Slack processes, or null if there are none. */
1010
- psDebugBuildLine() {
1011
- const probe = this.psDebugBuildProbe();
1012
- return probe.state === "running" ? probe.lines : null;
1013
- }
1014
1246
  detectDebugBuildUser() {
1247
+ return this.detectDebugBuildUserProbe().userId;
1248
+ }
1249
+ detectDebugBuildUserProbe() {
1015
1250
  if (this.detectedUserId !== null)
1016
- return this.detectedUserId;
1017
- return this.cacheUserFromPs(this.psDebugBuildLine());
1251
+ return { userId: this.detectedUserId, probe: null };
1252
+ const probe = this.psDebugBuildProbe();
1253
+ return { userId: this.cacheUserFromPs(probe.state === "running" ? probe.lines : null), probe };
1018
1254
  }
1019
- // detectDebugBuildUser, off the event loop. Same cache, same fallback rules.
1020
- async detectDebugBuildUserAsync() {
1255
+ async detectDebugBuildUserProbeAsync() {
1021
1256
  if (this.detectedUserId !== null)
1022
- return this.detectedUserId;
1257
+ return { userId: this.detectedUserId, probe: null };
1023
1258
  const probe = await this.psDebugBuildProbeAsync();
1024
- return this.cacheUserFromPs(probe.state === "running" ? probe.lines : null);
1259
+ return { userId: this.cacheUserFromPs(probe.state === "running" ? probe.lines : null), probe };
1025
1260
  }
1026
- // Cache only when a debug-build process was actually seen. Caching the "0"
1027
- // fallback would pin every later enable to user 0 for the process lifetime,
1028
- // so a work-profile build (user 10) launched after a failed detect would
1029
- // never receive the enable broadcast.
1261
+ // Cache only when a process of the build radar will arm was seen. Caching the "0" fallback, or
1262
+ // the user of a lookalike, would pin every later enable to that user for the process lifetime,
1263
+ // so a build launched afterwards (say in a work profile) would never receive the broadcast.
1030
1264
  cacheUserFromPs(ps) {
1031
1265
  if (!ps)
1032
1266
  return "0";
1033
- const match = ps.match(/u(\d+)_/);
1034
- if (!match)
1267
+ this.psSawUser = parsePsRows(ps).length > 0;
1268
+ if (!this.psSawUser)
1035
1269
  return "0";
1036
- this.detectedUserId = parseUserFromPsOutput(ps);
1037
- return this.detectedUserId;
1270
+ // The build this session is on decides the user first, so a second shipped build started in
1271
+ // another profile cannot move a re-arm. Nothing pinned and no match falls back to the shipped ids.
1272
+ const pinned = debugPackageOverride() ?? this.armedBuild;
1273
+ let pick = pickUserFromPs(ps, [pinned ?? slackDebugPackage()]);
1274
+ if (!pick.matched && pinned === null)
1275
+ pick = pickUserFromPs(ps, SHIPPED_DEBUG_PACKAGES);
1276
+ if (pick.matched)
1277
+ this.detectedUserId = pick.userId;
1278
+ return pick.userId;
1038
1279
  }
1039
1280
  /**
1040
1281
  * State of the debug-build Slack process, checked fresh via `ps` (independent of