mobile-debug-mcp 0.10.0 → 0.12.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 (67) hide show
  1. package/README.md +20 -5
  2. package/dist/android/diagnostics.js +24 -0
  3. package/dist/android/interact.js +1 -145
  4. package/dist/android/manage.js +162 -0
  5. package/dist/android/observe.js +133 -88
  6. package/dist/android/run.js +187 -0
  7. package/dist/android/utils.js +137 -147
  8. package/dist/ios/interact.js +4 -175
  9. package/dist/ios/manage.js +169 -0
  10. package/dist/ios/observe.js +129 -13
  11. package/dist/ios/run.js +200 -0
  12. package/dist/ios/utils.js +138 -124
  13. package/dist/server.js +45 -17
  14. package/dist/tools/interact.js +21 -71
  15. package/dist/tools/manage.js +180 -0
  16. package/dist/tools/observe.js +23 -69
  17. package/dist/tools/run.js +180 -0
  18. package/dist/utils/diagnostics.js +25 -0
  19. package/docs/CHANGELOG.md +14 -0
  20. package/eslint.config.js +22 -1
  21. package/package.json +8 -5
  22. package/scripts/check-idb.js +83 -0
  23. package/scripts/check-idb.ts +73 -0
  24. package/scripts/idb-helper.ts +76 -0
  25. package/scripts/install-idb.js +88 -0
  26. package/scripts/install-idb.ts +90 -0
  27. package/scripts/run-ios-smoke.ts +34 -0
  28. package/scripts/run-ios-ui-tree-tap.ts +33 -0
  29. package/src/android/diagnostics.ts +23 -0
  30. package/src/android/interact.ts +2 -155
  31. package/src/android/manage.ts +157 -0
  32. package/src/android/observe.ts +129 -97
  33. package/src/android/utils.ts +147 -149
  34. package/src/ios/interact.ts +5 -181
  35. package/src/ios/manage.ts +164 -0
  36. package/src/ios/observe.ts +130 -14
  37. package/src/ios/utils.ts +127 -128
  38. package/src/server.ts +47 -17
  39. package/src/tools/interact.ts +23 -62
  40. package/src/tools/manage.ts +171 -0
  41. package/src/tools/observe.ts +24 -74
  42. package/src/types.ts +9 -0
  43. package/src/utils/diagnostics.ts +36 -0
  44. package/test/device/README.md +49 -0
  45. package/test/device/index.ts +27 -0
  46. package/test/device/manage/run-build-install-ios.ts +82 -0
  47. package/test/{integration → device/manage}/run-install-android.ts +4 -4
  48. package/test/{integration → device/manage}/run-install-ios.ts +4 -4
  49. package/test/{integration → device/observe}/logstream-real.ts +5 -4
  50. package/test/{integration → device/utils}/test-dist.ts +2 -2
  51. package/test/unit/index.ts +10 -6
  52. package/test/unit/manage/build.test.ts +83 -0
  53. package/test/unit/manage/build_and_install.test.ts +134 -0
  54. package/test/unit/manage/diagnostics.test.ts +85 -0
  55. package/test/unit/{install.test.ts → manage/install.test.ts} +27 -18
  56. package/test/unit/{logparse.test.ts → observe/logparse.test.ts} +1 -1
  57. package/test/unit/{logstream.test.ts → observe/logstream.test.ts} +9 -10
  58. package/test/unit/{wait_for_element_mock.ts → observe/wait_for_element_mock.ts} +3 -3
  59. package/test/unit/{detect-java.test.ts → utils/detect-java.test.ts} +5 -5
  60. package/tsconfig.json +2 -1
  61. package/test/integration/index.ts +0 -8
  62. package/test/integration/test-dist.mjs +0 -41
  63. /package/test/{integration → device/interact}/run-real-test.ts +0 -0
  64. /package/test/{integration → device/interact}/smoke-test.ts +0 -0
  65. /package/test/{integration → device/manage}/install.integration.ts +0 -0
  66. /package/test/{integration → device/observe}/test-ui-tree.ts +0 -0
  67. /package/test/{integration → device/observe}/wait_for_element_real.ts +0 -0
@@ -0,0 +1,187 @@
1
+ import { promises as fs } from 'fs';
2
+ import { spawn } from 'child_process';
3
+ import path from 'path';
4
+ import { existsSync } from 'fs';
5
+ import { execAdb, spawnAdb, getAndroidDeviceMetadata, getDeviceInfo } from './utils.js';
6
+ import { detectJavaHome } from '../utils/java.js';
7
+ export class AndroidManage {
8
+ async build(projectPath, _variant) {
9
+ void _variant;
10
+ try {
11
+ const { prepareGradle } = await import('./utils.js').catch(() => ({ prepareGradle: undefined }));
12
+ if (prepareGradle && typeof prepareGradle === 'function') {
13
+ const { execCmd, gradleArgs, spawnOpts } = await prepareGradle(projectPath);
14
+ await new Promise((resolve, reject) => {
15
+ const proc = spawn(execCmd, gradleArgs, spawnOpts);
16
+ let stderr = '';
17
+ proc.stderr?.on('data', d => stderr += d.toString());
18
+ proc.on('close', code => {
19
+ if (code === 0)
20
+ resolve();
21
+ else
22
+ reject(new Error(stderr || `Gradle failed with code ${code}`));
23
+ });
24
+ proc.on('error', err => reject(err));
25
+ });
26
+ }
27
+ else {
28
+ const gradlewPath = path.join(projectPath, 'gradlew');
29
+ const gradleCmd = existsSync(gradlewPath) ? './gradlew' : 'gradle';
30
+ const execCmd = existsSync(gradlewPath) ? gradlewPath : gradleCmd;
31
+ const gradleArgs = ['assembleDebug'];
32
+ await new Promise((resolve, reject) => {
33
+ const proc = spawn(execCmd, gradleArgs, { cwd: projectPath, shell: existsSync(gradlewPath) ? false : true });
34
+ let stderr = '';
35
+ proc.stderr?.on('data', d => stderr += d.toString());
36
+ proc.on('close', code => {
37
+ if (code === 0)
38
+ resolve();
39
+ else
40
+ reject(new Error(stderr || `Gradle failed with code ${code}`));
41
+ });
42
+ proc.on('error', err => reject(err));
43
+ });
44
+ }
45
+ async function findApk(dir) {
46
+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
47
+ for (const e of entries) {
48
+ const full = path.join(dir, e.name);
49
+ if (e.isDirectory()) {
50
+ const found = await findApk(full);
51
+ if (found)
52
+ return found;
53
+ }
54
+ else if (e.isFile() && full.endsWith('.apk')) {
55
+ return full;
56
+ }
57
+ }
58
+ return undefined;
59
+ }
60
+ const apk = await findApk(projectPath);
61
+ if (!apk)
62
+ return { error: 'Could not find APK after build' };
63
+ return { artifactPath: apk };
64
+ }
65
+ catch (e) {
66
+ return { error: e instanceof Error ? e.message : String(e) };
67
+ }
68
+ }
69
+ async installApp(apkPath, deviceId) {
70
+ const metadata = await getAndroidDeviceMetadata('', deviceId);
71
+ const deviceInfo = getDeviceInfo(deviceId || 'default', metadata);
72
+ async function findApk(dir) {
73
+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
74
+ for (const e of entries) {
75
+ const full = path.join(dir, e.name);
76
+ if (e.isDirectory()) {
77
+ const found = await findApk(full);
78
+ if (found)
79
+ return found;
80
+ }
81
+ else if (e.isFile() && full.endsWith('.apk')) {
82
+ return full;
83
+ }
84
+ }
85
+ return undefined;
86
+ }
87
+ try {
88
+ let apkToInstall = apkPath;
89
+ const stat = await fs.stat(apkPath).catch(() => null);
90
+ if (stat && stat.isDirectory()) {
91
+ const detectedJavaHome = await detectJavaHome().catch(() => undefined);
92
+ const env = Object.assign({}, process.env);
93
+ if (detectedJavaHome) {
94
+ if (env.JAVA_HOME !== detectedJavaHome) {
95
+ env.JAVA_HOME = detectedJavaHome;
96
+ env.PATH = `${path.join(detectedJavaHome, 'bin')}${path.delimiter}${env.PATH || ''}`;
97
+ console.debug('[android-run] Overriding JAVA_HOME with detected path:', detectedJavaHome);
98
+ }
99
+ }
100
+ try {
101
+ delete env.SHELL;
102
+ }
103
+ catch { }
104
+ const gradleArgs = ['assembleDebug'];
105
+ if (detectedJavaHome) {
106
+ gradleArgs.push(`-Dorg.gradle.java.home=${detectedJavaHome}`);
107
+ gradleArgs.push('--no-daemon');
108
+ env.GRADLE_JAVA_HOME = detectedJavaHome;
109
+ }
110
+ const wrapperPath = path.join(apkPath, 'gradlew');
111
+ const useWrapper = existsSync(wrapperPath);
112
+ const execCmd = useWrapper ? wrapperPath : 'gradle';
113
+ const spawnOpts = { cwd: apkPath, env };
114
+ if (useWrapper) {
115
+ await fs.chmod(wrapperPath, 0o755).catch(() => { });
116
+ spawnOpts.shell = false;
117
+ }
118
+ else
119
+ spawnOpts.shell = true;
120
+ const proc = spawn(execCmd, gradleArgs, spawnOpts);
121
+ let stderr = '';
122
+ await new Promise((resolve, reject) => {
123
+ proc.stderr?.on('data', d => stderr += d.toString());
124
+ proc.on('close', code => {
125
+ if (code === 0)
126
+ resolve();
127
+ else
128
+ reject(new Error(stderr || `Gradle build failed with code ${code}`));
129
+ });
130
+ proc.on('error', err => reject(err));
131
+ });
132
+ const built = await findApk(apkPath);
133
+ if (!built)
134
+ throw new Error('Could not locate built APK after running Gradle');
135
+ apkToInstall = built;
136
+ }
137
+ try {
138
+ const res = await spawnAdb(['install', '-r', apkToInstall], deviceId);
139
+ if (res.code === 0) {
140
+ return { device: deviceInfo, installed: true, output: res.stdout };
141
+ }
142
+ }
143
+ catch (e) {
144
+ console.debug('[android-run] adb install failed, attempting push+pm fallback:', e instanceof Error ? e.message : String(e));
145
+ }
146
+ const basename = path.basename(apkToInstall);
147
+ const remotePath = `/data/local/tmp/${basename}`;
148
+ await execAdb(['push', apkToInstall, remotePath], deviceId);
149
+ const pmOut = await execAdb(['shell', 'pm', 'install', '-r', remotePath], deviceId);
150
+ try {
151
+ await execAdb(['shell', 'rm', remotePath], deviceId);
152
+ }
153
+ catch { }
154
+ return { device: deviceInfo, installed: true, output: pmOut };
155
+ }
156
+ catch (e) {
157
+ return { device: deviceInfo, installed: false, error: e instanceof Error ? e.message : String(e) };
158
+ }
159
+ }
160
+ async startApp(appId, deviceId) {
161
+ const metadata = await getAndroidDeviceMetadata(appId, deviceId);
162
+ const deviceInfo = getDeviceInfo(deviceId || 'default', metadata);
163
+ await execAdb(['shell', 'monkey', '-p', appId, '-c', 'android.intent.category.LAUNCHER', '1'], deviceId);
164
+ return { device: deviceInfo, appStarted: true, launchTimeMs: 1000 };
165
+ }
166
+ async terminateApp(appId, deviceId) {
167
+ const metadata = await getAndroidDeviceMetadata(appId, deviceId);
168
+ const deviceInfo = getDeviceInfo(deviceId || 'default', metadata);
169
+ await execAdb(['shell', 'am', 'force-stop', appId], deviceId);
170
+ return { device: deviceInfo, appTerminated: true };
171
+ }
172
+ async restartApp(appId, deviceId) {
173
+ await this.terminateApp(appId, deviceId);
174
+ const startResult = await this.startApp(appId, deviceId);
175
+ return {
176
+ device: startResult.device,
177
+ appRestarted: startResult.appStarted,
178
+ launchTimeMs: startResult.launchTimeMs
179
+ };
180
+ }
181
+ async resetAppData(appId, deviceId) {
182
+ const metadata = await getAndroidDeviceMetadata(appId, deviceId);
183
+ const deviceInfo = getDeviceInfo(deviceId || 'default', metadata);
184
+ const output = await execAdb(['shell', 'pm', 'clear', appId], deviceId);
185
+ return { device: deviceInfo, dataCleared: output === 'Success' };
186
+ }
187
+ }
@@ -1,7 +1,46 @@
1
1
  import { spawn } from 'child_process';
2
- import { createWriteStream, promises as fsPromises } from 'fs';
2
+ import { promises as fsPromises, existsSync } from 'fs';
3
3
  import path from 'path';
4
- export const ADB = process.env.ADB_PATH || 'adb';
4
+ import { detectJavaHome } from '../utils/java.js';
5
+ export function getAdbCmd() { return process.env.ADB_PATH || 'adb'; }
6
+ /**
7
+ * Prepare Gradle execution options for building an Android project.
8
+ * Returns execCmd (wrapper or gradle), base gradleArgs array, and spawn options including env.
9
+ */
10
+ export async function prepareGradle(projectPath) {
11
+ const gradlewPath = path.join(projectPath, 'gradlew');
12
+ const gradleCmd = existsSync(gradlewPath) ? './gradlew' : 'gradle';
13
+ const execCmd = existsSync(gradlewPath) ? gradlewPath : gradleCmd;
14
+ const gradleArgs = ['assembleDebug'];
15
+ const detectedJavaHome = await detectJavaHome().catch(() => undefined);
16
+ const env = Object.assign({}, process.env);
17
+ if (detectedJavaHome) {
18
+ if (env.JAVA_HOME !== detectedJavaHome) {
19
+ env.JAVA_HOME = detectedJavaHome;
20
+ env.PATH = `${path.join(detectedJavaHome, 'bin')}${path.delimiter}${env.PATH || ''}`;
21
+ }
22
+ gradleArgs.push(`-Dorg.gradle.java.home=${detectedJavaHome}`);
23
+ gradleArgs.push('--no-daemon');
24
+ env.GRADLE_JAVA_HOME = detectedJavaHome;
25
+ }
26
+ try {
27
+ delete env.SHELL;
28
+ }
29
+ catch { }
30
+ const useWrapper = existsSync(gradlewPath);
31
+ const spawnOpts = { cwd: projectPath, env };
32
+ if (useWrapper) {
33
+ try {
34
+ await fsPromises.chmod(gradlewPath, 0o755);
35
+ }
36
+ catch { }
37
+ spawnOpts.shell = false;
38
+ }
39
+ else {
40
+ spawnOpts.shell = true;
41
+ }
42
+ return { execCmd, gradleArgs, spawnOpts };
43
+ }
5
44
  // Helper to construct ADB args with optional device ID
6
45
  function getAdbArgs(args, deviceId) {
7
46
  if (deviceId) {
@@ -33,7 +72,7 @@ export function execAdb(args, deviceId, options = {}) {
33
72
  // Extract timeout from options if present, otherwise pass options to spawn
34
73
  const { timeout: customTimeout, ...spawnOptions } = options;
35
74
  // Use spawn instead of execFile for better stream control and to avoid potential buffering hangs
36
- const child = spawn(ADB, adbArgs, spawnOptions);
75
+ const child = spawn(getAdbCmd(), adbArgs, spawnOptions);
37
76
  let stdout = '';
38
77
  let stderr = '';
39
78
  if (child.stdout) {
@@ -73,7 +112,7 @@ export function spawnAdb(args, deviceId, options = {}) {
73
112
  const adbArgs = getAdbArgs(args, deviceId);
74
113
  return new Promise((resolve, reject) => {
75
114
  const { timeout: customTimeout, ...spawnOptions } = options;
76
- const child = spawn(ADB, adbArgs, spawnOptions);
115
+ const child = spawn(getAdbCmd(), adbArgs, spawnOptions);
77
116
  let stdout = '';
78
117
  let stderr = '';
79
118
  if (child.stdout)
@@ -141,6 +180,21 @@ export async function getAndroidDeviceMetadata(appId, deviceId) {
141
180
  return { platform: 'android', id: deviceId || 'default', osVersion: '', model: '', simulator: false };
142
181
  }
143
182
  }
183
+ export async function findApk(dir) {
184
+ const entries = await fsPromises.readdir(dir, { withFileTypes: true }).catch(() => []);
185
+ for (const e of entries) {
186
+ const full = path.join(dir, e.name);
187
+ if (e.isDirectory()) {
188
+ const found = await findApk(full);
189
+ if (found)
190
+ return found;
191
+ }
192
+ else if (e.isFile() && full.endsWith('.apk')) {
193
+ return full;
194
+ }
195
+ }
196
+ return undefined;
197
+ }
144
198
  export async function listAndroidDevices(appId) {
145
199
  try {
146
200
  const devicesOutput = await execAdb(['devices', '-l']);
@@ -178,18 +232,88 @@ export async function listAndroidDevices(appId) {
178
232
  return [];
179
233
  }
180
234
  }
181
- // Log stream management (one stream per session)
182
- const activeLogStreams = new Map();
183
- // Test helper to register a pre-existing NDJSON file as the active stream for a session (used by unit tests)
184
- export function _setActiveLogStream(sessionId, file) {
185
- activeLogStreams.set(sessionId, { proc: { kill: () => { } }, file });
235
+ // UI helper utilities shared by observe/interact
236
+ export const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
237
+ export function parseBounds(bounds) {
238
+ const match = bounds.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);
239
+ if (match) {
240
+ return [parseInt(match[1]), parseInt(match[2]), parseInt(match[3]), parseInt(match[4])];
241
+ }
242
+ return [0, 0, 0, 0];
243
+ }
244
+ export function getCenter(bounds) {
245
+ const [x1, y1, x2, y2] = bounds;
246
+ return [Math.floor((x1 + x2) / 2), Math.floor((y1 + y2) / 2)];
186
247
  }
187
- export function _clearActiveLogStream(sessionId) {
188
- activeLogStreams.delete(sessionId);
248
+ export async function getScreenResolution(deviceId) {
249
+ try {
250
+ const output = await execAdb(['shell', 'wm', 'size'], deviceId);
251
+ const match = output.match(/Physical size: (\d+)x(\d+)/);
252
+ if (match) {
253
+ return { width: parseInt(match[1]), height: parseInt(match[2]) };
254
+ }
255
+ }
256
+ catch {
257
+ // ignore
258
+ }
259
+ return { width: 0, height: 0 };
260
+ }
261
+ export function traverseNode(node, elements, parentIndex = -1, depth = 0) {
262
+ if (!node)
263
+ return -1;
264
+ let currentIndex = -1;
265
+ if (node['@_class']) {
266
+ const text = node['@_text'] || null;
267
+ const contentDescription = node['@_content-desc'] || null;
268
+ const clickable = node['@_clickable'] === 'true';
269
+ const bounds = parseBounds(node['@_bounds'] || '[0,0][0,0]');
270
+ const isUseful = clickable || (text && text.length > 0) || (contentDescription && contentDescription.length > 0);
271
+ if (isUseful) {
272
+ const element = {
273
+ text,
274
+ contentDescription,
275
+ type: node['@_class'] || 'unknown',
276
+ resourceId: node['@_resource-id'] || null,
277
+ clickable,
278
+ enabled: node['@_enabled'] === 'true',
279
+ visible: true,
280
+ bounds,
281
+ center: getCenter(bounds),
282
+ depth
283
+ };
284
+ if (parentIndex !== -1) {
285
+ element.parentId = parentIndex;
286
+ }
287
+ elements.push(element);
288
+ currentIndex = elements.length - 1;
289
+ }
290
+ }
291
+ const nextParentIndex = currentIndex !== -1 ? currentIndex : parentIndex;
292
+ const nextDepth = currentIndex !== -1 ? depth + 1 : depth;
293
+ const childrenIndices = [];
294
+ if (node.node) {
295
+ if (Array.isArray(node.node)) {
296
+ node.node.forEach((child) => {
297
+ const childIndex = traverseNode(child, elements, nextParentIndex, nextDepth);
298
+ if (childIndex !== -1)
299
+ childrenIndices.push(childIndex);
300
+ });
301
+ }
302
+ else {
303
+ const childIndex = traverseNode(node.node, elements, nextParentIndex, nextDepth);
304
+ if (childIndex !== -1)
305
+ childrenIndices.push(childIndex);
306
+ }
307
+ }
308
+ if (currentIndex !== -1 && childrenIndices.length > 0) {
309
+ elements[currentIndex].children = childrenIndices;
310
+ }
311
+ return currentIndex;
189
312
  }
313
+ // Log stream management (one stream per session)
314
+ // (Legacy active stream map removed from utils during refactor; Observe modules manage their own active streams.)
190
315
  // Robust log line parser supporting multiple logcat formats
191
316
  export function parseLogLine(line) {
192
- // Collapse internal newlines so multiline stack traces are parseable as a single entry
193
317
  const rawLine = line;
194
318
  const normalizedLine = rawLine.replace(/\r?\n/g, ' ');
195
319
  const entry = { timestamp: '', level: '', tag: '', message: rawLine, _iso: null, crash: false };
@@ -292,138 +416,4 @@ export function parseLogLine(line) {
292
416
  }
293
417
  return entry;
294
418
  }
295
- export async function startAndroidLogStream(packageName, level = 'error', deviceId, sessionId = 'default') {
296
- try {
297
- // Determine PID
298
- const pidOutput = await execAdb(['shell', 'pidof', packageName], deviceId).catch(() => '');
299
- const pid = (pidOutput || '').trim();
300
- if (!pid) {
301
- return { success: false, error: 'app_not_running' };
302
- }
303
- // Map level to logcat filter
304
- const levelMap = { error: '*:E', warn: '*:W', info: '*:I', debug: '*:D' };
305
- const filter = levelMap[level] || levelMap['error'];
306
- // Prevent multiple streams per session
307
- if (activeLogStreams.has(sessionId)) {
308
- // stop existing
309
- try {
310
- activeLogStreams.get(sessionId).proc.kill();
311
- }
312
- catch { }
313
- activeLogStreams.delete(sessionId);
314
- }
315
- // Start logcat process
316
- const args = ['logcat', `--pid=${pid}`, filter];
317
- const proc = spawn(ADB, args);
318
- // Prepare output file
319
- const tmpDir = process.env.TMPDIR || '/tmp';
320
- const file = path.join(tmpDir, `mobile-debug-log-${sessionId}.ndjson`);
321
- const stream = createWriteStream(file, { flags: 'a' });
322
- proc.stdout.on('data', (chunk) => {
323
- const text = chunk.toString();
324
- const lines = text.split(/\r?\n/).filter(Boolean);
325
- for (const l of lines) {
326
- const entry = parseLogLine(l);
327
- stream.write(JSON.stringify(entry) + '\n');
328
- }
329
- });
330
- proc.stderr.on('data', (chunk) => {
331
- // write stderr lines as message with level 'E'
332
- const text = chunk.toString();
333
- const lines = text.split(/\r?\n/).filter(Boolean);
334
- for (const l of lines) {
335
- const entry = { timestamp: '', level: 'E', tag: 'adb', message: l };
336
- stream.write(JSON.stringify(entry) + '\n');
337
- }
338
- });
339
- proc.on('close', () => {
340
- stream.end();
341
- activeLogStreams.delete(sessionId);
342
- });
343
- activeLogStreams.set(sessionId, { proc, file });
344
- return { success: true, stream_started: true };
345
- }
346
- catch {
347
- return { success: false, error: 'log_stream_start_failed' };
348
- }
349
- }
350
- export async function stopAndroidLogStream(sessionId = 'default') {
351
- const entry = activeLogStreams.get(sessionId);
352
- if (!entry)
353
- return { success: true };
354
- try {
355
- entry.proc.kill();
356
- }
357
- catch { }
358
- activeLogStreams.delete(sessionId);
359
- return { success: true };
360
- }
361
- export async function readLogStreamLines(sessionId = 'default', limit = 100, since) {
362
- const entry = activeLogStreams.get(sessionId);
363
- if (!entry)
364
- return { entries: [] };
365
- try {
366
- const data = await fsPromises.readFile(entry.file, 'utf8').catch(() => '');
367
- if (!data)
368
- return { entries: [], crash_summary: { crash_detected: false } };
369
- const lines = data.split(/\r?\n/).filter(Boolean);
370
- // Parse NDJSON lines into objects. Prefer fields written by parseLogLine. For backward compatibility, if _iso or crash are missing, enrich minimally here (avoid duplicating full parse logic).
371
- const parsed = lines.map(l => {
372
- try {
373
- const obj = JSON.parse(l);
374
- // Ensure _iso: if missing, try to derive using Date()
375
- if (typeof obj._iso === 'undefined') {
376
- let iso = null;
377
- if (obj.timestamp) {
378
- const d = new Date(obj.timestamp);
379
- if (!isNaN(d.getTime()))
380
- iso = d.toISOString();
381
- }
382
- obj._iso = iso;
383
- }
384
- // Ensure crash flag: if missing, run minimal heuristic
385
- if (typeof obj.crash === 'undefined') {
386
- const msg = (obj.message || '').toString();
387
- const exMatch = msg.match(/\b([A-Za-z0-9_$.]+Exception)\b/);
388
- if (/FATAL EXCEPTION/i.test(msg) || exMatch) {
389
- obj.crash = true;
390
- if (exMatch)
391
- obj.exception = exMatch[1];
392
- }
393
- else {
394
- obj.crash = false;
395
- }
396
- }
397
- return obj;
398
- }
399
- catch {
400
- return { message: l, _iso: null, crash: false };
401
- }
402
- });
403
- // Filter by since if provided (accept ISO or epoch ms)
404
- let filtered = parsed;
405
- if (since) {
406
- let sinceMs = null;
407
- // If numeric string
408
- if (/^\d+$/.test(since))
409
- sinceMs = Number(since);
410
- else {
411
- const sDate = new Date(since);
412
- if (!isNaN(sDate.getTime()))
413
- sinceMs = sDate.getTime();
414
- }
415
- if (sinceMs !== null) {
416
- filtered = parsed.filter(p => p._iso && (new Date(p._iso).getTime() >= sinceMs));
417
- }
418
- }
419
- // Return the last `limit` entries (most recent)
420
- const entries = filtered.slice(-Math.max(0, limit));
421
- // Crash summary
422
- const crashEntry = entries.find(e => e.crash);
423
- const crash_summary = crashEntry ? { crash_detected: true, exception: crashEntry.exception, sample: crashEntry.message } : { crash_detected: false };
424
- return { entries, crash_summary };
425
- }
426
- catch {
427
- return { entries: [], crash_summary: { crash_detected: false } };
428
- }
429
- }
419
+ // Legacy readLogStreamLines shim removed. Use AndroidObserve.readLogStream(sessionId, limit, since) instead.