@slack/radar-mcp 1.20.0 → 1.22.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 (91) hide show
  1. package/README.md +75 -17
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +56 -20
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +138 -36
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/network-detail.d.ts +5 -0
  10. package/dist/mcp/network-detail.js +86 -0
  11. package/dist/mcp/radar-export-get.d.ts +30 -0
  12. package/dist/mcp/radar-export-get.js +49 -0
  13. package/dist/mcp/radar-response.d.ts +11 -1
  14. package/dist/mcp/radar-response.js +23 -3
  15. package/dist/mcp/session-backfill.d.ts +9 -3
  16. package/dist/mcp/session-backfill.js +76 -17
  17. package/dist/mcp/session-detail.js +54 -2
  18. package/dist/mcp/session-enable.d.ts +1 -0
  19. package/dist/mcp/session-enable.js +146 -15
  20. package/dist/mcp/session-query.js +53 -11
  21. package/dist/mcp/snapshot.js +42 -26
  22. package/dist/mcp/sources-gate.js +5 -0
  23. package/dist/mcp/stale-dashboard.d.ts +23 -0
  24. package/dist/mcp/stale-dashboard.js +122 -0
  25. package/dist/mcp/switchboard-spool.d.ts +12 -0
  26. package/dist/mcp/switchboard-spool.js +107 -0
  27. package/dist/mcp/switchboard-tools.d.ts +18 -0
  28. package/dist/mcp/switchboard-tools.js +178 -0
  29. package/dist/mcp/tools.d.ts +4 -1
  30. package/dist/mcp/tools.js +114 -23
  31. package/dist/mcp/web-child-env.d.ts +4 -1
  32. package/dist/mcp/web-child-env.js +4 -1
  33. package/dist/shared/android.d.ts +43 -0
  34. package/dist/shared/android.js +227 -19
  35. package/dist/shared/constants.d.ts +19 -4
  36. package/dist/shared/constants.js +19 -4
  37. package/dist/shared/event-spool.js +3 -2
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/form-body.d.ts +18 -0
  41. package/dist/shared/form-body.js +251 -0
  42. package/dist/shared/ios-logs.d.ts +10 -0
  43. package/dist/shared/ios-logs.js +91 -0
  44. package/dist/shared/ios.d.ts +25 -2
  45. package/dist/shared/ios.js +157 -3
  46. package/dist/{web → shared}/log-session.d.ts +45 -31
  47. package/dist/shared/log-session.js +300 -0
  48. package/dist/shared/radar-request-raw.d.ts +7 -0
  49. package/dist/shared/radar-request-raw.js +89 -0
  50. package/dist/shared/radar-token.d.ts +25 -0
  51. package/dist/shared/radar-token.js +164 -0
  52. package/dist/shared/stream.d.ts +4 -1
  53. package/dist/shared/stream.js +107 -15
  54. package/dist/shared/switchboard-host-store.d.ts +21 -0
  55. package/dist/shared/switchboard-host-store.js +166 -0
  56. package/dist/shared/switchboard-note.d.ts +15 -0
  57. package/dist/shared/switchboard-note.js +92 -0
  58. package/dist/shared/switchboard-report-file.d.ts +5 -0
  59. package/dist/shared/switchboard-report-file.js +26 -0
  60. package/dist/shared/switchboard-report.d.ts +20 -0
  61. package/dist/shared/switchboard-report.js +406 -0
  62. package/dist/shared/switchboard.d.ts +118 -0
  63. package/dist/shared/switchboard.js +487 -0
  64. package/dist/shared/transport.d.ts +43 -3
  65. package/dist/shared/version.d.ts +2 -0
  66. package/dist/shared/version.js +18 -0
  67. package/dist/shared/wire.d.ts +46 -1
  68. package/dist/web/install-app.d.ts +57 -8
  69. package/dist/web/install-app.js +270 -60
  70. package/dist/web/macapp/RadarApp.swift +340 -22
  71. package/dist/web/public/index.html +216 -12
  72. package/dist/web/public/next/app.js +43 -22
  73. package/dist/web/public/next/db.js +4 -1
  74. package/dist/web/public/next/feed.js +604 -59
  75. package/dist/web/public/next/filters.js +158 -40
  76. package/dist/web/public/next/flags.js +3 -0
  77. package/dist/web/public/next/form-body.js +252 -0
  78. package/dist/web/public/next/inspector.js +171 -14
  79. package/dist/web/public/next/prefs.js +5 -2
  80. package/dist/web/public/next/registry.js +35 -3
  81. package/dist/web/public/next/store.js +947 -69
  82. package/dist/web/public/next/switchboard-note.js +93 -0
  83. package/dist/web/public/next/toast.js +9 -5
  84. package/dist/web/public/next/voice-model.js +712 -0
  85. package/dist/web/public/next/voice.js +552 -0
  86. package/dist/web/server.d.ts +20 -9
  87. package/dist/web/server.js +834 -174
  88. package/dist/web/spec.d.ts +11 -6
  89. package/dist/web/spec.js +62 -6
  90. package/package.json +4 -4
  91. package/dist/web/log-session.js +0 -166
@@ -0,0 +1,251 @@
1
+ // Decode an application/x-www-form-urlencoded request body into its fields. A record that carries
2
+ // `request_content_type` (the request's Content-Type, read off the OkHttp body by the device
3
+ // interceptor) is a form or not by that field alone. A record without it predates the field, so a
4
+ // form body is recognised by shape: `key=value&key=value` with nothing that would make it JSON or
5
+ // prose. Slack API POSTs routinely tuck JSON inside a field (blocks, types, client_context), so
6
+ // every decoded value that looks like JSON is parsed too. Pure, never throws.
7
+ //
8
+ // The browser build cannot import from src/shared, so scripts/mirror-shared.mjs copies this file
9
+ // to src/web/public/next/form-body.ts at build time (gitignored). This is the one to edit.
10
+ // Every pair is `name=value` with no whitespace; a trailing empty value (`draft_id=`) is fine.
11
+ const FORM_SHAPE = /^[^=&\s]+=[^&\s]*(&[^=&\s]+=[^&\s]*)*$/;
12
+ // A lone pair needs a field-like key: a base64 blob such as `QUJDRA==` otherwise passes the
13
+ // shape as key `QUJDRA` with value `=`. Real field names start with a letter or underscore and
14
+ // stay short; the padding pattern catches the blobs that happen to start with a letter too.
15
+ const KEY_START = /^[A-Za-z_]/;
16
+ const MAX_LONE_KEY = 64;
17
+ const BASE64_BLOB = /^[A-Za-z0-9+/]+=*$/;
18
+ // A lower-case snake_case key is a field name, never base64 padding (`token=`, `_x=1`).
19
+ const PLAIN_FIELD_NAME = /^[a-z_][a-z0-9_]*$/;
20
+ // Bracket nesting past this is not a payload the tool needs to read, and the dashboard's JSON
21
+ // highlighter recurses one frame per level, so a hostile depth stays a string, marked as left
22
+ // unparsed so the reader knows it was a choice. Real bodies sit far under it: the fixture's `blocks` nest 6
23
+ // deep, and rich_text lists carry their indent as a field rather than by nesting.
24
+ const MAX_JSON_DEPTH = 32;
25
+ const DEPTH_UNPARSED = `JSON nested past ${MAX_JSON_DEPTH} levels; left unparsed`;
26
+ // The declared media type, with or without parameters. Anchored on the type itself so a
27
+ // multipart boundary or a suffix that happens to contain the words does not read as a form.
28
+ const FORM_MEDIA_TYPE = /^\s*application\/x-www-form-urlencoded\s*(;|$)/i;
29
+ // application/json, the +json structured-syntax family (application/vnd.api+json) and the
30
+ // unregistered but seen text/json, with or without parameters.
31
+ const JSON_MEDIA_TYPE = /^\s*(application|text)\/([\w.+-]*\+)?json\s*(;|$)/i;
32
+ // The first two characters of a JSON object or array with something (or nothing) inside. A
33
+ // value like `[WIP] fix` or `{fire}` opens with a bracket too, but not like a JSON token.
34
+ const JSON_OPENER = /^(\{"|\{\}|\[\{|\["|\[\[|\[-?\d|\[(true|false|null)|\[\])/;
35
+ // Split off a tail the device cap left without an `=`: the body was cut inside a field name or
36
+ // right after an `&`. Only applies when a complete pair precedes it, so a bare word stays intact.
37
+ function splitCutTail(body) {
38
+ const amp = body.lastIndexOf("&");
39
+ if (amp > 0 && /^[^=&\s]*$/.test(body.slice(amp + 1))) {
40
+ return { body: body.slice(0, amp), truncated: true };
41
+ }
42
+ return { body, truncated: false };
43
+ }
44
+ // The record's own answer when it has one: `request_content_type` settles the form question
45
+ // without the shape rules. undefined means the record carries no verdict (a build that predates
46
+ // the field), so the caller falls back to shape.
47
+ export function formContentType(contentType) {
48
+ if (typeof contentType !== "string" || contentType.trim() === "")
49
+ return undefined;
50
+ return FORM_MEDIA_TYPE.test(contentType);
51
+ }
52
+ // The record's own answer to "is this JSON?", by the same rule: undefined without a verdict.
53
+ function jsonContentType(contentType) {
54
+ if (typeof contentType !== "string" || contentType.trim() === "")
55
+ return undefined;
56
+ return JSON_MEDIA_TYPE.test(contentType);
57
+ }
58
+ // Is this request body a form? The declared Content-Type wins when the record has one; the shape
59
+ // rules stand in when it does not. One shape rule holds either way: a body that opens like a JSON
60
+ // token (`{"`, `[{`, `[1`; not `[WIP]` or `{fire}`) is not a form, whatever the header says,
61
+ // because URLSearchParams would swallow the whole text as a single key and hide a cut. Both the
62
+ // decode and the caller that skips it for an oversized body go through here, so the two paths
63
+ // cannot disagree about what is a form.
64
+ export function isFormBody(text, contentType) {
65
+ if (typeof text !== "string")
66
+ return false;
67
+ const declared = formContentType(contentType);
68
+ if (declared === undefined)
69
+ return looksLikeFormBody(text);
70
+ const trimmed = text.trim();
71
+ return declared && trimmed.length > 0 && !opensLikeJsonToken(trimmed);
72
+ }
73
+ // The whole-body opener: JSON_OPENER after collapsing whitespace behind the bracket, so a
74
+ // pretty-printed body qualifies and bracketed prose does not.
75
+ function opensLikeJsonToken(trimmed) {
76
+ return JSON_OPENER.test(trimmed.replace(/^([[{])\s+/, "$1"));
77
+ }
78
+ // The whole shape verdict without the decode: the pair pattern plus the lone-pair rules, for a
79
+ // record with no Content-Type of its own.
80
+ export function looksLikeFormBody(text) {
81
+ if (typeof text !== "string")
82
+ return false;
83
+ // Surrounding whitespace (a captured trailing newline) is not part of the body shape.
84
+ const trimmed = text.trim();
85
+ if (trimmed.length === 0 || trimmed[0] === "{" || trimmed[0] === "[")
86
+ return false;
87
+ const { body } = splitCutTail(trimmed);
88
+ if (!FORM_SHAPE.test(body))
89
+ return false;
90
+ if (!body.includes("&")) {
91
+ const key = body.slice(0, body.indexOf("="));
92
+ if (key.length > MAX_LONE_KEY || !KEY_START.test(key))
93
+ return false;
94
+ if (!PLAIN_FIELD_NAME.test(key) && BASE64_BLOB.test(body))
95
+ return false;
96
+ }
97
+ return true;
98
+ }
99
+ export function decodeFormBody(text, contentType) {
100
+ if (!isFormBody(text, contentType))
101
+ return null;
102
+ const { body, truncated } = splitCutTail(text.trim());
103
+ let params;
104
+ try {
105
+ params = new URLSearchParams(body);
106
+ }
107
+ catch {
108
+ return null;
109
+ }
110
+ const fields = [];
111
+ params.forEach((value, key) => {
112
+ const field = { key, value };
113
+ if (opensLikeJson(value) && scanJson(value).depth > MAX_JSON_DEPTH) {
114
+ field.unparsedReason = DEPTH_UNPARSED;
115
+ }
116
+ else {
117
+ const json = parseJsonValue(value);
118
+ if (json !== undefined)
119
+ field.json = json;
120
+ }
121
+ fields.push(field);
122
+ });
123
+ return fields.length ? { fields, truncated } : null;
124
+ }
125
+ function opensLikeJson(value) {
126
+ const c = value[0];
127
+ return c === "{" || c === "[";
128
+ }
129
+ function parseJsonValue(value) {
130
+ if (!opensLikeJson(value))
131
+ return undefined;
132
+ if (scanJson(value).depth > MAX_JSON_DEPTH)
133
+ return undefined;
134
+ try {
135
+ return JSON.parse(value);
136
+ }
137
+ catch {
138
+ return undefined;
139
+ }
140
+ }
141
+ // One linear pass over a JSON-looking value: the deepest `{` / `[` nesting, skipping bracket
142
+ // characters inside strings, and whether the text is still open when it ends (a bracket never
143
+ // closed, or a string never terminated). Open at the end is what a cut looks like; a value that
144
+ // merely ends in a letter (`[1] fix typo`) is balanced and is not.
145
+ function scanJson(value) {
146
+ let depth = 0;
147
+ let deepest = 0;
148
+ let inString = false;
149
+ for (let i = 0; i < value.length; i++) {
150
+ const ch = value[i];
151
+ if (inString) {
152
+ if (ch === "\\")
153
+ i++;
154
+ else if (ch === '"')
155
+ inString = false;
156
+ }
157
+ else if (ch === '"') {
158
+ inString = true;
159
+ }
160
+ else if (ch === "{" || ch === "[") {
161
+ depth++;
162
+ if (depth > deepest)
163
+ deepest = depth;
164
+ }
165
+ else if (ch === "}" || ch === "]") {
166
+ depth--;
167
+ }
168
+ }
169
+ return { depth: deepest, open: depth > 0 || inString };
170
+ }
171
+ // The device caps a captured body, so a long form body can end mid-field. Either the tail was
172
+ // cut inside a field name (dropped at decode time), or the last value opens like a JSON token,
173
+ // did not parse, and is still open where the text ends: it was clipped inside its JSON.
174
+ export function formBodyLooksTruncated(body) {
175
+ if (body.truncated)
176
+ return true;
177
+ const last = body.fields[body.fields.length - 1];
178
+ if (!last || last.json !== undefined)
179
+ return false;
180
+ return valueLooksCut(last.value);
181
+ }
182
+ // The same verdict from the raw text, reading only the last pair, for a body too large to decode.
183
+ export function formTextLooksTruncated(text) {
184
+ if (typeof text !== "string")
185
+ return false;
186
+ const { body, truncated } = splitCutTail(text.trim());
187
+ if (truncated)
188
+ return true;
189
+ const last = body.slice(body.lastIndexOf("&") + 1);
190
+ if (!last.includes("="))
191
+ return false;
192
+ // Read the value off the parsed pair rather than by raw key: a `+` or percent escape in the
193
+ // name would make a raw-key lookup miss.
194
+ const value = [...new URLSearchParams(last).values()][0] ?? "";
195
+ return valueLooksCut(value);
196
+ }
197
+ // Bracket balance decides, not the last character: `[1] fix typo` closes its bracket and is a
198
+ // plain value; `[{"a":1}` closes the inner brace and is still a cut.
199
+ function valueLooksCut(value) {
200
+ return JSON_OPENER.test(value) && scanJson(value).open && parseJsonValue(value) === undefined;
201
+ }
202
+ // The same cut verdict for a whole JSON request body (not a form): it opens like a JSON token,
203
+ // does not parse, and the text ends inside an open bracket or string. `{"a":1}trailing` fails to
204
+ // parse but is balanced, so it is malformed rather than cut and stays unflagged; `[draft` opens
205
+ // with a bracket but not like JSON, so a plain-text body is not flagged either. Whitespace after
206
+ // the opening bracket is collapsed first so a pretty-printed body still qualifies. A record that
207
+ // declares a type that is neither JSON nor form (text/plain, multipart) is text whatever it opens
208
+ // with, so it is never flagged. A declared form body is read by shape here like a record with no
209
+ // declared type: the only form-typed body that can be a cut is one that opens like a JSON token,
210
+ // which isFormBody already refused as a mislabel.
211
+ export function jsonTextLooksCut(text, contentType) {
212
+ if (typeof text !== "string")
213
+ return false;
214
+ if (jsonContentType(contentType) === false && formContentType(contentType) !== true)
215
+ return false;
216
+ const s = text.trim();
217
+ if (!opensLikeJsonToken(s) || !scanJson(s).open)
218
+ return false;
219
+ try {
220
+ JSON.parse(s);
221
+ return false;
222
+ }
223
+ catch {
224
+ return true;
225
+ }
226
+ }
227
+ // Collapse the field list into a plain object: the parsed JSON where a value parsed, else the
228
+ // decoded string. A key that repeats becomes an array in wire order.
229
+ export function formBodyToObject(body) {
230
+ // Built without a prototype so a field named toString, constructor or __proto__ is just a key.
231
+ const out = Object.create(null);
232
+ // Keys seen more than once. Needed because a first value can itself be a JSON array
233
+ // (`attachments=[]`), which must not be mistaken for an accumulator on a repeat.
234
+ const repeated = new Set();
235
+ for (const f of body.fields) {
236
+ const v = f.json !== undefined ? f.json : f.value;
237
+ if (!Object.hasOwn(out, f.key)) {
238
+ out[f.key] = v;
239
+ }
240
+ else if (repeated.has(f.key)) {
241
+ out[f.key].push(v);
242
+ }
243
+ else {
244
+ out[f.key] = [out[f.key], v];
245
+ repeated.add(f.key);
246
+ }
247
+ }
248
+ // Hand back an ordinary object; fromEntries defines own properties, so a `__proto__` key
249
+ // stays a key instead of swapping the prototype the way assignment would.
250
+ return Object.fromEntries(Object.entries(out));
251
+ }
@@ -0,0 +1,10 @@
1
+ /** iOS Simulator unified-log adapter for Radar. */
2
+ import { type ChildProcess } from "node:child_process";
3
+ import type { LogFrame } from "./log-session.js";
4
+ export declare const SLACK_IOS_PACKAGE = "com.tinyspeck.chatlyio";
5
+ export declare function iosLogLevel(value: unknown): string;
6
+ /** Parse one `log stream --style ndjson` record into Radar's normalized shape. */
7
+ export declare function parseIosUnifiedLog(line: string): LogFrame | null;
8
+ /** A readable line for get_recent_logs and snapshot-style output. */
9
+ export declare function formatIosLogFrame(frame: LogFrame): string;
10
+ export declare function spawnIosUnifiedLogStream(simulatorUdid: string): ChildProcess;
@@ -0,0 +1,91 @@
1
+ /** iOS Simulator unified-log adapter for Radar. */
2
+ import { spawn } from "node:child_process";
3
+ import path from "node:path";
4
+ const SLACK_IOS_PROCESS = "Slack";
5
+ export const SLACK_IOS_PACKAGE = "com.tinyspeck.chatlyio";
6
+ function numberField(value) {
7
+ const parsed = typeof value === "number" ? value : Number(value);
8
+ return Number.isFinite(parsed) ? parsed : 0;
9
+ }
10
+ function iosTimestamp(value) {
11
+ if (typeof value !== "string")
12
+ return null;
13
+ const match = value.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})\.(\d{3})\d*([+-]\d{2})(\d{2})$/);
14
+ if (!match)
15
+ return null;
16
+ const parsed = Date.parse(`${match[1]}T${match[2]}.${match[3]}${match[4]}:${match[5]}`);
17
+ return Number.isFinite(parsed) ? parsed : null;
18
+ }
19
+ export function iosLogLevel(value) {
20
+ switch (String(value ?? "").toLowerCase()) {
21
+ case "debug": return "DEBUG";
22
+ case "info": return "INFO";
23
+ case "error": return "ERROR";
24
+ case "fault": return "FATAL";
25
+ case "default": return "INFO";
26
+ default: return String(value ?? "INFO").toUpperCase() || "INFO";
27
+ }
28
+ }
29
+ /** Parse one `log stream --style ndjson` record into Radar's normalized shape. */
30
+ export function parseIosUnifiedLog(line) {
31
+ let record;
32
+ try {
33
+ record = JSON.parse(line);
34
+ }
35
+ catch {
36
+ // simctl/log can print host-account warnings before the NDJSON stream.
37
+ return null;
38
+ }
39
+ if (!record || record.eventType !== "logEvent" || typeof record.eventMessage !== "string")
40
+ return null;
41
+ const timestamp = iosTimestamp(record.timestamp);
42
+ if (timestamp === null)
43
+ return null;
44
+ const logTimestamp = record.timestamp;
45
+ const subsystem = typeof record.subsystem === "string" && record.subsystem
46
+ ? record.subsystem
47
+ : undefined;
48
+ const category = typeof record.category === "string" && record.category
49
+ ? record.category
50
+ : undefined;
51
+ const processImagePath = typeof record.processImagePath === "string"
52
+ ? record.processImagePath
53
+ : "";
54
+ const processName = typeof record.process === "string" && record.process
55
+ ? record.process
56
+ : processImagePath ? path.basename(processImagePath) : SLACK_IOS_PROCESS;
57
+ return {
58
+ id: 0,
59
+ timestamp,
60
+ package: SLACK_IOS_PACKAGE,
61
+ log_ts: logTimestamp,
62
+ pid: numberField(record.processID),
63
+ tid: numberField(record.threadID),
64
+ level: iosLogLevel(record.messageType),
65
+ tag: category ?? subsystem ?? processName,
66
+ message: record.eventMessage,
67
+ ...(subsystem ? { subsystem } : {}),
68
+ ...(processName ? { process: processName } : {}),
69
+ };
70
+ }
71
+ /** A readable line for get_recent_logs and snapshot-style output. */
72
+ export function formatIosLogFrame(frame) {
73
+ const match = frame.log_ts.match(/\b(\d{2}:\d{2}:\d{2})\.(\d{3})/);
74
+ const time = match
75
+ ? `${match[1]}.${match[2]}`
76
+ : new Date(frame.timestamp).toISOString().slice(11, 23);
77
+ return `${time} ${frame.level} ${frame.tag}: ${frame.message}`;
78
+ }
79
+ export function spawnIosUnifiedLogStream(simulatorUdid) {
80
+ return spawn("xcrun", [
81
+ "simctl", "spawn", simulatorUdid,
82
+ "log", "stream",
83
+ "--style", "ndjson",
84
+ "--level", "debug",
85
+ "--type", "log",
86
+ "--predicate", `subsystem BEGINSWITH "com.tinyspeck"`,
87
+ ],
88
+ // `log stream` is long-lived and nobody consumes diagnostics here. Leaving
89
+ // stderr piped would eventually backpressure and stall stdout on noisy runs.
90
+ { stdio: ["ignore", "pipe", "ignore"] });
91
+ }
@@ -1,10 +1,13 @@
1
- import type { DeviceInfo, DevicePick, DeviceTransport } from "./transport.js";
1
+ import { type ChildProcess } from "child_process";
2
+ import { LogSession } from "./log-session.js";
3
+ import type { LogResult, DeviceInfo, DevicePick, DeviceTransport } from "./transport.js";
2
4
  export type IosScreenshotCapturer = (simulatorUdid: string, outputPath: string) => void;
3
5
  export type IosScreenRecorder = (simulatorUdid: string, outputPath: string, durationSeconds: number) => void;
4
6
  export interface IosSimulatorTransportDependencies {
5
7
  readBootedSimulators?: () => string;
6
8
  captureScreenshot?: IosScreenshotCapturer;
7
9
  recordScreen?: IosScreenRecorder;
10
+ spawnLogStream?: (simulatorUdid: string) => ChildProcess;
8
11
  }
9
12
  /** Convert a CoreSimulator runtime identifier into the label users see in Xcode. */
10
13
  export declare function simulatorRuntimeLabel(identifier: string): string;
@@ -31,14 +34,23 @@ export declare function recordIosSimulatorScreen(simulatorUdid: string, outputPa
31
34
  /** Host-side transport for iOS Simulators. */
32
35
  export declare class IosSimulatorTransport implements DeviceTransport {
33
36
  readonly platform = "ios";
34
- readonly supportsRadarHttpTools = false;
37
+ readonly logPackage = "com.tinyspeck.chatlyio";
38
+ readonly supportsHostLogs = true;
39
+ readonly supportsRadarHttpTools = true;
40
+ readonly radarListenerHint = "Open the Slack app on the Simulator with Radar enabled, then retry.";
41
+ readonly supportsDeviceDashboard = true;
42
+ readonly logSession: LogSession;
35
43
  private forwarded;
44
+ private logIdSequence;
36
45
  private timeoutMinutes;
37
46
  private selectedDevice;
47
+ private logSimulatorUdid;
38
48
  private lastForwardError;
49
+ private lastActivateError;
39
50
  private readonly readBootedSimulators;
40
51
  private readonly captureSimulatorScreenshot;
41
52
  private readonly recordSimulatorScreen;
53
+ private readonly spawnSimulatorLogStream;
42
54
  constructor(dependencies?: IosSimulatorTransportDependencies);
43
55
  listDevices(): DeviceInfo[] | null;
44
56
  selectDevice(serial: string | null): DevicePick;
@@ -55,10 +67,21 @@ export declare class IosSimulatorTransport implements DeviceTransport {
55
67
  resetState(): void;
56
68
  dropForward(): void;
57
69
  getLastForwardError(): string | null;
70
+ private prepareActivation;
71
+ private enableRadar;
58
72
  activate(timeoutMinutes: number): void;
73
+ activateAsync(timeoutMinutes: number): Promise<void>;
74
+ getLastActivateError(): string | null;
75
+ acceptsRadarPeer(ping: Record<string, unknown>): boolean;
59
76
  getTimeoutMinutes(): number;
60
77
  getActiveUserId(): string | null;
61
78
  resolveActiveUser(): string;
79
+ getRecentLogs(tag: string, limit: number, grep?: string): LogResult;
80
+ /**
81
+ * End this session's capture and drop what it retained. get_recent_logs promises lines
82
+ * captured since the session was enabled, so a later enable must not replay these.
83
+ */
84
+ stopLogCapture(): void;
62
85
  screenshot(fullRes: boolean): string;
63
86
  recordScreen(durationS: number): string;
64
87
  private reconcileSelectedDevice;
@@ -1,7 +1,11 @@
1
1
  import { execFileSync, spawnSync } from "child_process";
2
+ import http from "node:http";
2
3
  import { chmodSync, mkdtempSync, rmSync, statSync, } from "node:fs";
3
4
  import { tmpdir } from "node:os";
4
5
  import path from "node:path";
6
+ import { formatIosLogFrame, parseIosUnifiedLog, SLACK_IOS_PACKAGE, spawnIosUnifiedLogStream, } from "./ios-logs.js";
7
+ import { RADAR_HOST, RADAR_PORT, RADAR_VERSION } from "./constants.js";
8
+ import { LogSession } from "./log-session.js";
5
9
  const IOS_SIMULATOR_UDID_ENV = "SLACK_RADAR_IOS_SIMULATOR_UDID";
6
10
  /** Convert a CoreSimulator runtime identifier into the label users see in Xcode. */
7
11
  export function simulatorRuntimeLabel(identifier) {
@@ -93,15 +97,25 @@ export function recordIosSimulatorScreen(simulatorUdid, outputPath, durationSeco
93
97
  /** Host-side transport for iOS Simulators. */
94
98
  export class IosSimulatorTransport {
95
99
  platform = "ios";
96
- // Simulator capture works through simctl, but no iOS Radar HTTP server exists yet.
97
- supportsRadarHttpTools = false;
100
+ logPackage = SLACK_IOS_PACKAGE;
101
+ supportsHostLogs = true;
102
+ // The iOS app serves Radar directly on the Simulator's host loopback. acceptsRadarPeer keeps
103
+ // that shared address from being confused with an Android adb forward on the same port.
104
+ supportsRadarHttpTools = true;
105
+ radarListenerHint = "Open the Slack app on the Simulator with Radar enabled, then retry.";
106
+ supportsDeviceDashboard = true;
107
+ logSession;
98
108
  forwarded = false;
109
+ logIdSequence = 0;
99
110
  timeoutMinutes = 5;
100
111
  selectedDevice = null;
112
+ logSimulatorUdid = null;
101
113
  lastForwardError = null;
114
+ lastActivateError = null;
102
115
  readBootedSimulators;
103
116
  captureSimulatorScreenshot;
104
117
  recordSimulatorScreen;
118
+ spawnSimulatorLogStream;
105
119
  constructor(dependencies = {}) {
106
120
  this.readBootedSimulators = dependencies.readBootedSimulators ?? (() => execFileSync("xcrun", ["simctl", "list", "devices", "booted", "--json"], {
107
121
  timeout: 10_000,
@@ -111,6 +125,22 @@ export class IosSimulatorTransport {
111
125
  this.captureSimulatorScreenshot = dependencies.captureScreenshot ??
112
126
  captureIosSimulatorScreenshot;
113
127
  this.recordSimulatorScreen = dependencies.recordScreen ?? recordIosSimulatorScreen;
128
+ this.spawnSimulatorLogStream = dependencies.spawnLogStream ?? spawnIosUnifiedLogStream;
129
+ this.logSession = new LogSession(() => {
130
+ if (!this.logSimulatorUdid) {
131
+ const selection = this.resolveDevice(null);
132
+ if (!selection.ok)
133
+ throw new Error(selection.error);
134
+ if (!selection.serial) {
135
+ throw new Error("No booted iOS Simulator found. Open one in Xcode and retry.");
136
+ }
137
+ this.logSimulatorUdid = selection.serial;
138
+ }
139
+ return this.spawnSimulatorLogStream(this.logSimulatorUdid);
140
+ }, (line) => {
141
+ const frame = parseIosUnifiedLog(line);
142
+ return frame ? { ...frame, id: ++this.logIdSequence } : null;
143
+ });
114
144
  }
115
145
  listDevices() {
116
146
  try {
@@ -149,7 +179,9 @@ export class IosSimulatorTransport {
149
179
  if (commit) {
150
180
  if (this.selectedDevice && this.selectedDevice.serial !== device.serial) {
151
181
  this.forwarded = false;
182
+ this.logSession.restart();
152
183
  }
184
+ this.logSimulatorUdid = device.serial;
153
185
  this.selectedDevice = { serial: device.serial, label: device.label };
154
186
  }
155
187
  return {
@@ -234,6 +266,7 @@ export class IosSimulatorTransport {
234
266
  resetState() {
235
267
  this.forwarded = false;
236
268
  this.lastForwardError = null;
269
+ this.lastActivateError = null;
237
270
  }
238
271
  dropForward() {
239
272
  this.forwarded = false;
@@ -242,8 +275,88 @@ export class IosSimulatorTransport {
242
275
  getLastForwardError() {
243
276
  return this.lastForwardError;
244
277
  }
245
- activate(timeoutMinutes) {
278
+ prepareActivation(timeoutMinutes) {
246
279
  this.timeoutMinutes = timeoutMinutes || this.timeoutMinutes;
280
+ this.logSession.registerCleanup();
281
+ // Best effort, and deliberately not a gate on enableRadar: a Simulator whose `log stream`
282
+ // will not start still has Radar HTTP, screenshots and record_screen. The failure stays on
283
+ // the log session, where get_recent_logs reports it.
284
+ this.logSession.start();
285
+ }
286
+ enableRadar() {
287
+ if (!this.selectedDevice) {
288
+ return Promise.reject(new Error("No booted iOS Simulator selected"));
289
+ }
290
+ const body = JSON.stringify({
291
+ timeout_minutes: this.timeoutMinutes,
292
+ mcp_version: RADAR_VERSION,
293
+ });
294
+ return new Promise((resolve, reject) => {
295
+ let settled = false;
296
+ const done = (error) => {
297
+ if (settled)
298
+ return;
299
+ settled = true;
300
+ if (error)
301
+ reject(error);
302
+ else
303
+ resolve();
304
+ };
305
+ const req = http.request({
306
+ host: RADAR_HOST,
307
+ port: RADAR_PORT,
308
+ path: "/api/enable",
309
+ method: "POST",
310
+ headers: {
311
+ "Content-Type": "application/json",
312
+ "Content-Length": Buffer.byteLength(body),
313
+ },
314
+ timeout: 5000,
315
+ }, (res) => {
316
+ res.resume();
317
+ res.on("end", () => {
318
+ const status = res.statusCode ?? 0;
319
+ if (status >= 200 && status < 300)
320
+ done();
321
+ else
322
+ done(new Error(`iOS Radar enable returned HTTP ${status}`));
323
+ });
324
+ res.on("error", done);
325
+ });
326
+ req.on("error", done);
327
+ req.on("timeout", () => {
328
+ req.destroy();
329
+ done(new Error("iOS Radar enable timed out"));
330
+ });
331
+ req.end(body);
332
+ });
333
+ }
334
+ activate(timeoutMinutes) {
335
+ this.prepareActivation(timeoutMinutes);
336
+ void this.enableRadar().catch((error) => {
337
+ this.lastActivateError = error instanceof Error ? error.message : String(error);
338
+ });
339
+ }
340
+ async activateAsync(timeoutMinutes) {
341
+ this.prepareActivation(timeoutMinutes);
342
+ try {
343
+ await this.enableRadar();
344
+ this.lastActivateError = null;
345
+ }
346
+ catch (error) {
347
+ this.lastActivateError = error instanceof Error ? error.message : String(error);
348
+ }
349
+ }
350
+ getLastActivateError() {
351
+ return this.lastActivateError;
352
+ }
353
+ acceptsRadarPeer(ping) {
354
+ if (typeof ping.platform === "string") {
355
+ return ping.platform.toLowerCase() === "ios";
356
+ }
357
+ // Keep compatibility with an iOS build that identifies the app by bundle id but predates
358
+ // the explicit platform field. An unidentified listener is not safe to accept.
359
+ return ping.package === SLACK_IOS_PACKAGE;
247
360
  }
248
361
  getTimeoutMinutes() {
249
362
  return this.timeoutMinutes;
@@ -254,6 +367,44 @@ export class IosSimulatorTransport {
254
367
  resolveActiveUser() {
255
368
  return "";
256
369
  }
370
+ getRecentLogs(tag, limit, grep) {
371
+ // An exit since the last read is reported once. With nothing retained it is the whole
372
+ // answer (and needs no simctl call); otherwise the history the ring still holds is valid
373
+ // and the failure rides along with it.
374
+ const priorFailure = this.logSession.takeLastFailure();
375
+ const priorError = priorFailure ? `iOS Simulator log capture ${priorFailure}` : null;
376
+ if (priorError && this.logSession.bufferSize() === 0)
377
+ throw new Error(priorError);
378
+ const selection = this.resolveDevice(null);
379
+ if (!selection.ok)
380
+ throw new Error(selection.error);
381
+ if (!selection.serial)
382
+ throw new Error("No booted iOS Simulator found. Open one in Xcode and retry.");
383
+ if (this.logSimulatorUdid && this.logSimulatorUdid !== selection.serial) {
384
+ this.logSession.restart();
385
+ }
386
+ this.logSimulatorUdid = selection.serial;
387
+ let captureError = priorError;
388
+ if (!this.logSession.start()) {
389
+ const failure = this.logSession.takeLastFailure();
390
+ captureError = `iOS Simulator log capture ${failure ?? "could not start"}`;
391
+ if (this.logSession.bufferSize() === 0)
392
+ throw new Error(captureError);
393
+ }
394
+ const lines = this.logSession.recent(tag, limit, grep).map(formatIosLogFrame);
395
+ return {
396
+ lines,
397
+ source: "ios_unified_capture",
398
+ ...(captureError ? { capture_error: captureError } : {}),
399
+ };
400
+ }
401
+ /**
402
+ * End this session's capture and drop what it retained. get_recent_logs promises lines
403
+ * captured since the session was enabled, so a later enable must not replay these.
404
+ */
405
+ stopLogCapture() {
406
+ this.logSession.restart();
407
+ }
257
408
  screenshot(fullRes) {
258
409
  const selection = this.selectDevice(null);
259
410
  if (!selection.ok)
@@ -321,6 +472,9 @@ export class IosSimulatorTransport {
321
472
  }
322
473
  clearSelectedDevice() {
323
474
  this.forwarded = false;
475
+ if (this.selectedDevice)
476
+ this.logSession.restart();
477
+ this.logSimulatorUdid = null;
324
478
  this.selectedDevice = null;
325
479
  }
326
480
  describeDevices(devices) {