digital-ai-testing-mcp 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +18 -13
  2. package/dist/api/browser-inspection.d.ts.map +1 -1
  3. package/dist/api/browser-inspection.js +7 -1
  4. package/dist/api/browser-inspection.js.map +1 -1
  5. package/dist/api/reporting.d.ts +10 -1
  6. package/dist/api/reporting.d.ts.map +1 -1
  7. package/dist/api/reporting.js +30 -9
  8. package/dist/api/reporting.js.map +1 -1
  9. package/dist/api/webdriver.d.ts +61 -3
  10. package/dist/api/webdriver.d.ts.map +1 -1
  11. package/dist/api/webdriver.js +659 -33
  12. package/dist/api/webdriver.js.map +1 -1
  13. package/dist/index.js +1 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/tools/boilerplate-tools.d.ts +1 -1
  16. package/dist/tools/boilerplate-tools.d.ts.map +1 -1
  17. package/dist/tools/boilerplate-tools.js +155 -52
  18. package/dist/tools/boilerplate-tools.js.map +1 -1
  19. package/dist/tools/inspection-tools.d.ts.map +1 -1
  20. package/dist/tools/inspection-tools.js +217 -23
  21. package/dist/tools/inspection-tools.js.map +1 -1
  22. package/dist/tools/meta-tools.d.ts +7 -1
  23. package/dist/tools/meta-tools.d.ts.map +1 -1
  24. package/dist/tools/meta-tools.js +21 -7
  25. package/dist/tools/meta-tools.js.map +1 -1
  26. package/dist/tools/performance-tools.d.ts.map +1 -1
  27. package/dist/tools/performance-tools.js +6 -1
  28. package/dist/tools/performance-tools.js.map +1 -1
  29. package/dist/tools/reporting-tools.d.ts.map +1 -1
  30. package/dist/tools/reporting-tools.js +4 -2
  31. package/dist/tools/reporting-tools.js.map +1 -1
  32. package/dist/tools/transaction-tools.d.ts.map +1 -1
  33. package/dist/tools/transaction-tools.js +24 -5
  34. package/dist/tools/transaction-tools.js.map +1 -1
  35. package/dist/types/digital-ai.d.ts +8 -0
  36. package/dist/types/digital-ai.d.ts.map +1 -1
  37. package/dist/utils/test-orchestrator.d.ts +2 -0
  38. package/dist/utils/test-orchestrator.d.ts.map +1 -1
  39. package/dist/utils/test-orchestrator.js +2 -0
  40. package/dist/utils/test-orchestrator.js.map +1 -1
  41. package/package.json +3 -1
  42. package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative-oss-po.java +48 -0
  43. package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative-oss.java +23 -13
  44. package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative.java +19 -10
  45. package/resources/boilerplate/Android-Native/Java JUnit5/gradle-oss +4 -1
  46. package/resources/boilerplate/Android-Native/Java JUnit5/maven-oss +7 -1
  47. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/AndroidNative-po.js +13 -0
  48. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/AndroidNative.js +17 -11
  49. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio-oss.conf.js +7 -2
  50. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio.conf.js +10 -4
  51. package/resources/boilerplate/Android-Native/Python/AndroidNative-oss.py +30 -14
  52. package/resources/boilerplate/Android-Native/Python/AndroidNative.py +21 -5
  53. package/resources/boilerplate/Android-Native/Robot Framework/AndroidNative-oss.robot +28 -11
  54. package/resources/boilerplate/Android-Native/java TestNG/AndroidNative-oss-po.java +48 -0
  55. package/resources/boilerplate/Android-Native/java TestNG/AndroidNative-oss.java +23 -13
  56. package/resources/boilerplate/Android-Native/java TestNG/AndroidNative.java +19 -10
  57. package/resources/boilerplate/Android-Native/java TestNG/gradle-oss +4 -1
  58. package/resources/boilerplate/Android-Native/java TestNG/maven-oss +7 -1
  59. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/iOSNative-po.js +13 -0
  60. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/iOSNative.js +17 -11
  61. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio-oss.conf.js +4 -1
  62. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio.conf.js +2 -0
  63. package/resources/boilerplate/iOS-Native/Python/iOSNative-oss.py +31 -14
  64. package/resources/boilerplate/iOS-Native/Python/iOSNative.py +36 -15
  65. package/resources/boilerplate/iOS-Native/Robot Framework/iOSNative-oss.robot +28 -11
  66. package/resources/boilerplate/iOS-Native/java-JUnit5/gradle-oss +4 -1
  67. package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative-oss-po.java +45 -0
  68. package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative-oss.java +24 -13
  69. package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative.java +21 -11
  70. package/resources/boilerplate/iOS-Native/java-JUnit5/maven-oss +7 -1
  71. package/resources/boilerplate/iOS-Native/java-TestNG/gradle-oss +4 -1
  72. package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative-oss-po.java +45 -0
  73. package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative-oss.java +24 -13
  74. package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative.java +21 -11
  75. package/resources/boilerplate/iOS-Native/java-TestNG/maven-oss +7 -1
  76. package/resources/boilerplate/shared/java-screens/AppScreen.java +27 -0
  77. package/resources/boilerplate/shared/java-screens/BaseScreen.java +40 -0
  78. package/resources/boilerplate/shared/java-screens/DashboardScreen.java +16 -0
  79. package/resources/boilerplate/shared/java-screens/LoginScreen.java +21 -0
  80. package/resources/boilerplate/shared/java-screens/PaymentScreen.java +32 -0
  81. package/resources/boilerplate/shared/node-screens/AppScreen.js +27 -0
  82. package/resources/boilerplate/shared/node-screens/DashboardScreen.js +13 -0
  83. package/resources/boilerplate/shared/node-screens/LoginScreen.js +18 -0
  84. package/resources/boilerplate/shared/node-screens/PaymentScreen.js +28 -0
  85. package/resources/boilerplate/shared/node-screens/PlaceholderScreen.js +21 -0
@@ -96,16 +96,18 @@ export async function createInspectionSession(opts) {
96
96
  'platformName': platform === 'ios' ? 'iOS' : 'Android',
97
97
  'noReset': opts.noReset ?? true,
98
98
  };
99
+ // iOS identifies the app by bundleId (XCUITest capability reference); appPackage/appActivity are Android-only.
100
+ const appIdCap = platform === 'ios' ? 'bundleId' : 'appPackage';
99
101
  if (opts.app) {
100
102
  desiredCapabilities['app'] = opts.app;
101
103
  if (opts.appPackage)
102
- desiredCapabilities['appPackage'] = opts.appPackage;
103
- if (opts.appActivity)
104
+ desiredCapabilities[appIdCap] = opts.appPackage;
105
+ if (opts.appActivity && platform !== 'ios')
104
106
  desiredCapabilities['appActivity'] = opts.appActivity;
105
107
  }
106
108
  else if (opts.appPackage) {
107
- desiredCapabilities['appPackage'] = opts.appPackage;
108
- if (opts.appActivity)
109
+ desiredCapabilities[appIdCap] = opts.appPackage;
110
+ if (opts.appActivity && platform !== 'ios')
109
111
  desiredCapabilities['appActivity'] = opts.appActivity;
110
112
  }
111
113
  if (opts.automotiveProjection)
@@ -207,7 +209,7 @@ export async function createInspectionSession(opts) {
207
209
  deviceModel: String(caps['device.model'] ?? caps['digitalai:publicModel'] ?? ''),
208
210
  deviceOs: String(caps['device.os'] ?? caps['platformName'] ?? 'Android'),
209
211
  deviceVersion: String(caps['device.version'] ?? caps['platformVersion'] ?? ''),
210
- appPackage: String(caps['appPackage'] ?? opts.appPackage ?? ''),
212
+ appPackage: String(caps['appPackage'] ?? caps['bundleId'] ?? opts.appPackage ?? ''),
211
213
  startedAt: Date.now(),
212
214
  lastUsedAt: Date.now(),
213
215
  canDeleteReport,
@@ -222,6 +224,22 @@ export async function createInspectionSession(opts) {
222
224
  export async function quitInspectionSession(handle, keepReport = false) {
223
225
  const session = requireSession(handle);
224
226
  const client = makeClient();
227
+ // A HAR / device-log capture left running would never be finalised once the session is gone — stop it first
228
+ // (best-effort: the session may already be dead).
229
+ for (const [field, script] of [
230
+ ['harRecording', 'seetest:client.stopHarRecording'],
231
+ ['deviceLogRecording', 'seetest:client.stopLoggingDevice'],
232
+ ]) {
233
+ if (!session[field])
234
+ continue;
235
+ try {
236
+ await execScript(client, session, script, [], 15_000);
237
+ }
238
+ catch {
239
+ // Best-effort
240
+ }
241
+ session[field] = undefined;
242
+ }
225
243
  try {
226
244
  await client.delete(`/session/${session.gridSessionId}`, { timeout: 30_000 });
227
245
  }
@@ -230,6 +248,7 @@ export async function quitInspectionSession(handle, keepReport = false) {
230
248
  }
231
249
  sessionRegistry.delete(handle);
232
250
  let reportDeleted = false;
251
+ let reportDeleteError;
233
252
  let reportKept = false;
234
253
  if (session.reportTestId > 0 && keepReport) {
235
254
  // Deliberately preserved (e.g. for the platform's session video recording) —
@@ -245,12 +264,19 @@ export async function quitInspectionSession(handle, keepReport = false) {
245
264
  allReports.delete(session.reportTestId);
246
265
  reportDeleted = true;
247
266
  }
248
- catch {
267
+ catch (e) {
268
+ // A report that carries a performance transaction cannot be deleted while the transaction exists — the platform
269
+ // answers 400 "Persistent instance of Attachment references an unsaved transient instance of TestTransactionServer"
270
+ // (verified 2026-10-18). Keep the reason so the caller knows the record is still there.
271
+ reportDeleteError = e.message.includes('TestTransactionServer')
272
+ ? 'the report holds a performance transaction, which the platform refuses to delete (400 TransientPropertyValueException) — the report stays'
273
+ : e.message;
249
274
  // Non-fatal — user can delete via reporter UI
250
275
  }
251
276
  }
252
277
  return {
253
278
  reportDeleted,
279
+ ...(reportDeleteError ? { reportDeleteError } : {}),
254
280
  reportKept,
255
281
  canDeleteReport: session.canDeleteReport,
256
282
  reportTestId: session.reportTestId,
@@ -278,10 +304,25 @@ export async function captureScreenshot(handle) {
278
304
  }
279
305
  // Augment a WebDriver error with a dead-session hint — a 404 on an established
280
306
  // session almost always means the Grid/agent terminated it (timeout, WDA crash).
307
+ /** A 404 means a dead session only when the body says so — Appium 2/3 also answer 404 ("unknown command") for a route
308
+ * the driver lacks, and the Digital.ai proxy wraps seetest:client failures the same way (a camera-injection URL the
309
+ * platform could not fetch came back 404 and was misreported as a terminated session, 2026-10-18). */
310
+ function looksLikeDeadSession(e) {
311
+ const err = e;
312
+ if (err.response?.status !== 404)
313
+ return false;
314
+ const v = err.response.data?.value;
315
+ if (!v || (v.error == null && v.message == null))
316
+ return true; // bare route 404: nothing to proxy to
317
+ const msg = `${v.error ?? ''} ${v.message ?? ''}`.toLowerCase();
318
+ if (/invalid session id|no such session|session .*(not found|terminated|expired|does not exist|has ended|is not running)/.test(msg))
319
+ return true;
320
+ // 'unknown command' covers both a route the driver lacks and a wrapped seetest:client failure — neither is a dead session.
321
+ return v.error !== 'unknown command' && v.error !== 'no such element' && v.error !== 'no such alert' && v.error !== 'invalid argument';
322
+ }
281
323
  function sessionAwareError(e, handle) {
282
324
  const detail = describeWdError(e);
283
- const err = e;
284
- if (err.response?.status === 404) {
325
+ if (looksLikeDeadSession(e)) {
285
326
  const s = sessionRegistry.get(handle);
286
327
  const idleNote = s?.lastIdleMs != null && s.lastIdleMs > 60_000
287
328
  ? ` The session was idle for ${Math.round(s.lastIdleMs / 60_000)} minute(s) before this command — Grid sessions expire after ~4 minutes of inactivity.`
@@ -300,6 +341,39 @@ export async function getPageSource(handle) {
300
341
  });
301
342
  return res.data.value ?? '';
302
343
  }
344
+ /**
345
+ * Appium Settings API (Appium Server / W3C sessions only): one POST per session makes every `POST /elements` answer
346
+ * carry attributes inline. Verified live 2026-10-18 — what each driver honours in `elementResponseAttributes`:
347
+ * UiAutomator2: name, text, rect, enabled, displayed, selected (NOT class / resource-id / content-desc / clickable)
348
+ * XCUITest: type, label, rect, enabled, displayed (NOT value / visible / hittable; and its inline `name` is the
349
+ * element TYPE, not the accessibility id — only `label` carries the identifier-or-label)
350
+ * So the inline answer replaces 3 (Android) / 4 (iOS, incl. the rect call) of the 7–8 per-element GETs; the rest are
351
+ * still fetched. 3 ExperiBank fields: 1 275 ms → 207 ms inline on Android, 3 612 ms → 357 ms on iOS (before the GETs).
352
+ * A session where the settings call fails keeps the GET path (`inlineAttributes: false`, tried once).
353
+ */
354
+ async function ensureInlineAttributes(client, session) {
355
+ if (session.sessionFormat !== 'w3c' || session.platform === 'web')
356
+ return false;
357
+ if (session.inlineAttributes != null)
358
+ return session.inlineAttributes;
359
+ const attrs = session.platform === 'ios' ? 'type,label,rect,enabled,displayed' : 'name,text,rect,enabled,displayed';
360
+ try {
361
+ await client.post(`/session/${session.gridSessionId}/appium/settings`, { settings: { shouldUseCompactResponses: false, elementResponseAttributes: attrs } }, { timeout: 10_000 });
362
+ session.inlineAttributes = true;
363
+ }
364
+ catch {
365
+ session.inlineAttributes = false;
366
+ }
367
+ return session.inlineAttributes;
368
+ }
369
+ const rectToBounds = (r) => {
370
+ const o = r;
371
+ if (!o || o.x == null || o.width == null)
372
+ return null;
373
+ return `[${o.x},${o.y}][${o.x + o.width},${(o.y ?? 0) + (o.height ?? 0)}]`;
374
+ };
375
+ const asBool = (v) => (v === true || v === 'true' ? true : v === false || v === 'false' ? false : null);
376
+ const asStr = (v) => (v == null ? null : String(v));
303
377
  /**
304
378
  * Attribute enrichment costs 7–9 requests per element. Done one element at a time with no cap, 48 iOS home-screen
305
379
  * icons took 80–160 s (measured live 2026-10-09) — past the ~60 s MCP client timeout. So: a cap, a time budget, and
@@ -310,27 +384,91 @@ export async function findElements(handle, using, value, opts = {}) {
310
384
  const session = requireSession(handle);
311
385
  const client = makeClient();
312
386
  const sid = session.gridSessionId;
387
+ const inline = await ensureInlineAttributes(client, session);
388
+ const inWebview = isWebviewContext(session);
313
389
  let res;
314
390
  try {
315
- res = await client.post(`/session/${sid}/elements`, { using, value }, { timeout: 20_000 });
391
+ res = await client.post(`/session/${sid}/elements`, { using, value },
392
+ // A Chrome WEBVIEW find on a heavy page exceeded 20 s live (2026-10-18); native finds answer in well under 1 s.
393
+ { timeout: inWebview ? 60_000 : 20_000 });
316
394
  }
317
395
  catch (e) {
318
396
  throw new Error(sessionAwareError(e, handle));
319
397
  }
320
398
  const rawList = res.data.value ?? [];
399
+ const rawById = new Map();
321
400
  const ids = rawList
322
- .map((raw) => raw['ELEMENT'] ?? raw['element-6066-11e4-a52e-4f735466cecf'])
401
+ .map((raw) => {
402
+ const id = (raw['ELEMENT'] ?? raw['element-6066-11e4-a52e-4f735466cecf']);
403
+ if (id)
404
+ rawById.set(id, raw);
405
+ return id;
406
+ })
323
407
  .filter((id) => Boolean(id));
324
408
  const bare = (elementId) => ({
325
409
  elementId, className: null, resourceId: null, contentDesc: null, text: null, bounds: null,
326
410
  clickable: null, enabled: null, name: null, label: null, value: null, enriched: false,
327
411
  });
328
412
  const enrich = async (elementId) => {
413
+ const raw = rawById.get(elementId) ?? {};
414
+ if (inWebview) {
415
+ // Web element inside a WEBVIEW context: tag, text, id/class attributes and geometry (W3C routes).
416
+ const [tag, text, id, cls, rect] = await Promise.allSettled([
417
+ client.get(`/session/${sid}/element/${elementId}/name`, { timeout: 10_000 }).then((r) => asStr(r.data.value)),
418
+ client.get(`/session/${sid}/element/${elementId}/text`, { timeout: 10_000 }).then((r) => asStr(r.data.value)),
419
+ getAttr(client, sid, elementId, 'id'),
420
+ getAttr(client, sid, elementId, 'class'),
421
+ client.get(`/session/${sid}/element/${elementId}/rect`, { timeout: 10_000 }).then((r) => r.data.value),
422
+ ]).then((rs) => rs.map((r) => (r.status === 'fulfilled' ? r.value : null)));
423
+ return {
424
+ elementId, className: tag, resourceId: id, contentDesc: cls,
425
+ text: text, bounds: rectToBounds(rect), clickable: null, enabled: null, name: null, label: null, value: null, enriched: true,
426
+ };
427
+ }
428
+ if (session.platform === 'ios' && inline && 'type' in raw) {
429
+ // Inline: type, label, rect, enabled, displayed. Still fetched: name (identifier), value, visible, hittable.
430
+ const [name, val, visible, hittable] = await Promise.allSettled([
431
+ getAttr(client, sid, elementId, 'name'),
432
+ getAttr(client, sid, elementId, 'value'),
433
+ getAttr(client, sid, elementId, 'visible'),
434
+ getAttr(client, sid, elementId, 'hittable'),
435
+ ]).then((rs) => rs.map((r) => (r.status === 'fulfilled' ? r.value : null)));
436
+ return {
437
+ elementId,
438
+ className: asStr(raw['type']),
439
+ resourceId: null,
440
+ contentDesc: null,
441
+ text: null,
442
+ bounds: rectToBounds(raw['rect']),
443
+ clickable: visible === 'true' ? true : visible === 'false' ? false : asBool(raw['displayed']),
444
+ enabled: asBool(raw['enabled']),
445
+ name: name ?? asStr(raw['label']),
446
+ label: asStr(raw['label']),
447
+ value: val,
448
+ hittable: hittable === 'true' ? true : hittable === 'false' ? false : null,
449
+ enriched: true,
450
+ };
451
+ }
452
+ if (session.platform === 'android' && inline && 'text' in raw) {
453
+ // Inline: text, rect, enabled, displayed. Still fetched: class, resource-id, content-desc, clickable.
454
+ const [className, resourceId, contentDesc, clickable] = await Promise.allSettled([
455
+ getAttr(client, sid, elementId, 'class'),
456
+ getAttr(client, sid, elementId, 'resource-id'),
457
+ getAttr(client, sid, elementId, 'content-desc'),
458
+ getAttr(client, sid, elementId, 'clickable'),
459
+ ]).then((rs) => rs.map((r) => (r.status === 'fulfilled' ? r.value : null)));
460
+ return {
461
+ elementId, className, resourceId, contentDesc: contentDesc === 'null' ? null : contentDesc,
462
+ text: asStr(raw['text']), bounds: rectToBounds(raw['rect']),
463
+ clickable: clickable === 'true' ? true : clickable === 'false' ? false : null,
464
+ enabled: asBool(raw['enabled']), name: null, label: null, value: null, enriched: true,
465
+ };
466
+ }
329
467
  if (session.platform === 'ios') {
330
468
  // iOS attribute model: name/label/value/type. XCUITest rejects Android
331
469
  // names (class, text, bounds) outright; the Grid exposes `class` instead
332
470
  // of `type` — fetch both and take whichever resolves.
333
- const [name, label, val, type, cls, enabled, visible] = await Promise.allSettled([
471
+ const [name, label, val, type, cls, enabled, visible, hittable] = await Promise.allSettled([
334
472
  getAttr(client, sid, elementId, 'name'),
335
473
  getAttr(client, sid, elementId, 'label'),
336
474
  getAttr(client, sid, elementId, 'value'),
@@ -338,6 +476,7 @@ export async function findElements(handle, using, value, opts = {}) {
338
476
  getAttr(client, sid, elementId, 'class'),
339
477
  getAttr(client, sid, elementId, 'enabled'),
340
478
  getAttr(client, sid, elementId, 'visible'),
479
+ getAttr(client, sid, elementId, 'hittable'),
341
480
  ]).then((rs) => rs.map((r) => (r.status === 'fulfilled' ? r.value : null)));
342
481
  let bounds = null;
343
482
  try {
@@ -359,6 +498,7 @@ export async function findElements(handle, using, value, opts = {}) {
359
498
  name,
360
499
  label,
361
500
  value: val,
501
+ hittable: hittable === 'true' ? true : hittable === 'false' ? false : null,
362
502
  enriched: true,
363
503
  };
364
504
  }
@@ -703,7 +843,11 @@ export async function launchApp(handle, packageName, activity) {
703
843
  : `.${activity}`;
704
844
  const activityUrl = `${packageName}/${fullActivity}`;
705
845
  const seetest = ['seetest:client.launch', () => client.post(`/session/${sid}/execute`, { script: 'seetest:client.launch', args: [activityUrl, false, true] }, { timeout: 30_000 })];
706
- const w3c = ['mobile: startActivity', () => client.post(`/session/${sid}/execute/sync`, { script: 'mobile: startActivity', args: [{ intent: activityUrl, wait: true }] }, { timeout: 30_000 })];
846
+ const w3c = ['mobile: startActivity', () => client.post(`/session/${sid}/execute/sync`,
847
+ // stop: true — without it an already-running app only gets the intent "delivered to currently running top-most
848
+ // instance" (no restart; verified live 2026-10-17 on Android 13); with it the launch is COLD, matching the Grid's
849
+ // seetest:client.launch(..., stopIfRunning = true) used below.
850
+ { script: 'mobile: startActivity', args: [{ intent: activityUrl, wait: true, stop: true }] }, { timeout: 30_000 })];
707
851
  const legacy = ['legacy start_activity', () => client.post(`/session/${sid}/appium/device/start_activity`, { appPackage: packageName, appActivity: fullActivity }, { timeout: 30_000 })];
708
852
  const order = session.sessionFormat === 'w3c' ? [w3c, seetest, legacy] : [seetest, w3c, legacy];
709
853
  const used = await tryAll(order);
@@ -749,9 +893,15 @@ export async function pressBack(handle) {
749
893
  }
750
894
  // Execute a script via the protocol-appropriate endpoint.
751
895
  // JWP agents route /execute; W3C agents (Appium 2/3) only route /execute/sync.
752
- function execScript(client, session, script, args, timeoutMs = 30_000) {
896
+ function execScript(client, session, script, args = [{}], timeoutMs = 30_000) {
753
897
  const path = session.sessionFormat === 'w3c' ? 'execute/sync' : 'execute';
754
- return client.post(`/session/${session.gridSessionId}/${path}`, { script, args }, { timeout: timeoutMs });
898
+ // Appium Grid: a seetest:client command with NO arguments must be written inline — "seetest:client.cmd()" — because
899
+ // the Grid parses arguments out of the script string ("invalid parameters delimiter" for the bare form). Verified
900
+ // live 2026-10-19: report("x", true), startStepsGroup("g"), stopStepsGroup(), setLocation("37.33","-122.03"),
901
+ // clearLocation(), addTestProperty("k","v"), hybridClearCache() and getNetworkConnection("wifi") all run inline on the
902
+ // Grid, so every 0-arg command is reachable there after all (an earlier note said otherwise).
903
+ const inline = session.sessionFormat === 'jwp' && script.startsWith('seetest:client.') && args.length === 0 && !script.endsWith(')');
904
+ return client.post(`/session/${session.gridSessionId}/${path}`, inline ? { script: `${script}()`, args: [] } : { script, args }, { timeout: timeoutMs });
755
905
  }
756
906
  export const WAV_HEADER_ONLY_BYTES = 44;
757
907
  const cloudRef = (name) => (name.startsWith('cloud:') ? name : `cloud:${name}`);
@@ -761,7 +911,7 @@ export async function audioControl(handle, action, opts = {}, deps) {
761
911
  if (session.platform === 'web')
762
912
  throw new Error('audio_control needs a mobile inspection session, not a browser session.');
763
913
  if (session.sessionFormat === 'jwp') {
764
- throw new Error('audio_control is not available on Appium Grid sessions: stopAudioPlay / stopAudioRecording take no arguments, which the Grid cannot run, so playback and recording could be started but never stopped. Use an Appium Server project.');
914
+ throw new Error('audio_control has only been verified on Appium Server sessions — use an Appium Server project (the Grid is unverified for the audio commands).');
765
915
  }
766
916
  const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
767
917
  const client = makeClient();
@@ -924,7 +1074,8 @@ function automotiveError(e, handle) {
924
1074
  // These are seetest:client.* commands — the Digital.ai cloud proxy interprets
925
1075
  // them, not Appium, so they route through execScript on both Grid (/execute)
926
1076
  // and Appium Server / OSS (/execute/sync). The Grid execute parser cannot
927
- // express a zero-argument seetest command, so start REQUIRES a network profile.
1077
+ // express a zero-argument seetest command in the bare form (the inline "cmd()" form does run there, see execScript), and
1078
+ // the platform treats an empty profile as "3G-average" — so start REQUIRES an explicit network profile.
928
1079
  export async function performanceTransaction(handle, action, opts) {
929
1080
  const session = requireSession(handle);
930
1081
  const client = makeClient();
@@ -937,14 +1088,24 @@ export async function performanceTransaction(handle, action, opts) {
937
1088
  'names from your platform admin; only "Monitor" is broadly guaranteed. The NV server for the device\'s ' +
938
1089
  'region must be ONLINE and tunnel-connected (verify with list_nv_servers) or the transaction records nothing.');
939
1090
  }
940
- await execScript(client, session, 'seetest:client.startPerformanceTransaction', [opts.networkProfile]);
1091
+ // Per-application variant (verified live 2026-10-18, Android + iOS): CPU/memory/battery are sampled for ONE app
1092
+ // (the one named) instead of the whole device; the start call took ~18 s on both platforms (vs ~1 s for the
1093
+ // device-wide form) — the platform attaches to the process first. Platform docs: a transaction is capped at
1094
+ // 5 minutes, cancelled when the session quits, "NONE" means no NV profile, and no HAR is recorded while NV
1095
+ // tunneling is on.
1096
+ if (opts.forApplication) {
1097
+ await execScript(client, session, 'seetest:client.startPerformanceTransactionForApplication', [opts.forApplication, opts.networkProfile], 60_000);
1098
+ }
1099
+ else {
1100
+ await execScript(client, session, 'seetest:client.startPerformanceTransaction', [opts.networkProfile]);
1101
+ }
941
1102
  const isMonitor = opts.networkProfile.toLowerCase() === 'monitor';
942
1103
  const throttleNote = isMonitor
943
1104
  ? `"Monitor" is pass-through — no throttling is applied, so there is no ANR risk from network shaping. `
944
1105
  : `⚠️ NV throttling is now ACTIVE — if the app makes background network calls during this window it may ANR/crash; keep the measured window tight. `;
945
- return (`Started performance transaction with NV profile "${opts.networkProfile}". ` +
1106
+ return (`Started ${opts.forApplication ? `per-application performance transaction for ${opts.forApplication}` : 'performance transaction'} with NV profile "${opts.networkProfile}". ` +
946
1107
  throttleNote +
947
- `Perform ONLY the UI steps you want measured, then call action:"end".`);
1108
+ `Perform ONLY the UI steps you want measured, then call action:"end" (within 5 minutes — the platform cancels longer transactions, and quitting the session cancels it too).`);
948
1109
  }
949
1110
  if (!opts.transactionName) {
950
1111
  throw new Error('transactionName is required to end a performance transaction.');
@@ -1102,6 +1263,58 @@ export async function scrollToElement(handle, using, value, direction = 'up', ma
1102
1263
  ? [Math.round(height * 0.7), Math.round(height * 0.3)]
1103
1264
  : [Math.round(height * 0.3), Math.round(height * 0.7)];
1104
1265
  let swipesUsed = 0;
1266
+ const client = makeClient();
1267
+ // iOS Appium Server: XCUITest scrolls the application element to a name / predicate in ONE call (no page-source
1268
+ // polling). `mobile: scroll` only targets the app under test ("application ... is not running" when another app is
1269
+ // in front — verified live 2026-10-18), so a failure here just falls through to the swipe loop below.
1270
+ if (session.sessionFormat === 'w3c' && session.platform === 'ios' && !isWebviewContext(session) &&
1271
+ (using === 'accessibility id' || using === '-ios predicate string')) {
1272
+ const args = using === 'accessibility id' ? { name: value, direction: direction === 'up' ? 'down' : 'up' } : { predicateString: value, direction: direction === 'up' ? 'down' : 'up' };
1273
+ try {
1274
+ await execScript(client, session, 'mobile: scroll', [args], 20_000);
1275
+ const found = await findElements(handle, using, value, { maxEnriched: 1 });
1276
+ if (found.length > 0)
1277
+ return { found: true, element: found[0], swipesUsed: 1, reachedEnd: false };
1278
+ }
1279
+ catch {
1280
+ // fall through to the generic loop
1281
+ }
1282
+ }
1283
+ // Android Appium Server: `mobile: scrollGesture` answers canScrollMore, a real end-of-list signal that replaces the
1284
+ // page-source diff (one full XML dump per swipe). `mobile: scroll` (UiScrollable) was tried first and dropped: it
1285
+ // fails with "Cannot scroll to UiSelector[...]" on the first scrollable it picks (Settings on Samsung/LG, the
1286
+ // ExperiBank country dialog) — verified live 2026-10-18.
1287
+ if (session.sessionFormat === 'w3c' && session.platform === 'android' && !isWebviewContext(session)) {
1288
+ const area = { left: Math.round(width * 0.1), top: Math.round(height * 0.15), width: Math.round(width * 0.8), height: Math.round(height * 0.7) };
1289
+ for (let i = 0; i <= maxSwipes; i++) {
1290
+ const found = await findElements(handle, using, value, { maxEnriched: 1 });
1291
+ if (found.length > 0)
1292
+ return { found: true, element: found[0], swipesUsed, reachedEnd: false };
1293
+ if (i === maxSwipes)
1294
+ break;
1295
+ let canScrollMore = null;
1296
+ try {
1297
+ // direction is the FINGER direction (same convention as swipeGesture): 'up' reveals the content below. Verified
1298
+ // live 2026-10-18 — mapping it the other way ended a Settings scroll after two swipes with canScrollMore=false.
1299
+ const r = await execScript(client, session, 'mobile: scrollGesture', [{ ...area, direction, percent: 0.8 }], 20_000);
1300
+ canScrollMore = asBool(r.data.value);
1301
+ }
1302
+ catch {
1303
+ canScrollMore = null; // unknown-command (older agent) → use the raw swipe instead
1304
+ }
1305
+ if (canScrollMore == null)
1306
+ await swipeScreen(handle, midX, startY, midX, endY, 500);
1307
+ swipesUsed++;
1308
+ await new Promise((r) => setTimeout(r, 500));
1309
+ if (canScrollMore === false) {
1310
+ const last = await findElements(handle, using, value, { maxEnriched: 1 });
1311
+ return last.length > 0
1312
+ ? { found: true, element: last[0], swipesUsed, reachedEnd: false }
1313
+ : { found: false, element: null, swipesUsed, reachedEnd: true };
1314
+ }
1315
+ }
1316
+ return { found: false, element: null, swipesUsed, reachedEnd: false };
1317
+ }
1105
1318
  let lastSource = '';
1106
1319
  for (let i = 0; i <= maxSwipes; i++) {
1107
1320
  const found = await findElements(handle, using, value, { maxEnriched: 1 });
@@ -1136,11 +1349,14 @@ export const ANDROID_KEYCODES = {
1136
1349
  APP_SWITCH: 187,
1137
1350
  };
1138
1351
  // iOS physical buttons: XCUITest `mobile: pressButton` name → SeeTest deviceAction label.
1352
+ // mobile: pressButton supports only home / volumeup / volumedown on a real device ("The button 'power' is not
1353
+ // supported", verified live 2026-10-17, iPhone 13 mini / iOS 17.6). POWER is handled separately below with
1354
+ // mobile: lock / unlock (both returned OK on the same device); the Grid's deviceAction("Lock") stays as its fallback.
1139
1355
  const IOS_BUTTONS = {
1140
1356
  HOME: { w3c: 'home', grid: 'Home' },
1141
1357
  VOLUME_UP: { w3c: 'volumeup', grid: 'Volume Up' },
1142
1358
  VOLUME_DOWN: { w3c: 'volumedown', grid: 'Volume Down' },
1143
- POWER: { w3c: 'power', grid: 'Lock' },
1359
+ POWER: { w3c: null, grid: 'Lock' },
1144
1360
  };
1145
1361
  export async function pressKey(handle, key, keycode) {
1146
1362
  const session = requireSession(handle);
@@ -1152,7 +1368,17 @@ export async function pressKey(handle, key, keycode) {
1152
1368
  throw new Error(`${key ?? `keycode ${keycode}`} is not available on iOS. Supported: HOME, VOLUME_UP, VOLUME_DOWN, POWER. ` +
1153
1369
  `For ENTER, type "\\n" with type_into_element; iOS has no BACK button — press_back performs the edge-swipe instead.`);
1154
1370
  }
1155
- const w3c = () => execScript(client, session, 'mobile: pressButton', [{ name: button.w3c }]);
1371
+ let w3cResult = key;
1372
+ const w3c = async () => {
1373
+ if (button.w3c) {
1374
+ await execScript(client, session, 'mobile: pressButton', [{ name: button.w3c }]);
1375
+ return;
1376
+ }
1377
+ // POWER = toggle the lock state: lock when unlocked, unlock when locked (a physical side-button press does both).
1378
+ const locked = (await execScript(client, session, 'mobile: isLocked', [{}])).data.value === true;
1379
+ await execScript(client, session, locked ? 'mobile: unlock' : 'mobile: lock', [{}]);
1380
+ w3cResult = locked ? 'POWER (device unlocked)' : 'POWER (device locked — press POWER again to unlock)';
1381
+ };
1156
1382
  const grid = () => client.post(`/session/${sid}/execute`, { script: 'seetest:client.deviceAction', args: [button.grid] }, { timeout: 15_000 });
1157
1383
  const [primary, fallback] = session.sessionFormat === 'w3c' ? [w3c, grid] : [grid, w3c];
1158
1384
  try {
@@ -1166,7 +1392,7 @@ export async function pressKey(handle, key, keycode) {
1166
1392
  throw new Error(`pressKey failed: ${describeWdError(e)}; fallback: ${describeWdError(e2)}`);
1167
1393
  }
1168
1394
  }
1169
- return key;
1395
+ return w3cResult;
1170
1396
  }
1171
1397
  const code = keycode ?? (key ? ANDROID_KEYCODES[key] : undefined);
1172
1398
  if (code == null)
@@ -1238,18 +1464,68 @@ const APP_STATE_LABELS = {
1238
1464
  3: 'running in background',
1239
1465
  4: 'running in foreground',
1240
1466
  };
1241
- export async function appControl(handle, action, packageName, url) {
1467
+ export async function appControl(handle, action, packageName, url, opts = {}) {
1242
1468
  const session = requireSession(handle);
1243
1469
  const client = makeClient();
1244
1470
  const sid = session.gridSessionId;
1245
1471
  const isW3c = session.sessionFormat === 'w3c';
1246
1472
  const isIos = session.platform === 'ios';
1473
+ const idArg = (pkg) => (isIos ? { bundleId: pkg } : { appId: pkg });
1247
1474
  switch (action) {
1475
+ // Verified live 2026-10-18 (Appium Server, Galaxy Note 20 / iPhone 13 Pro Max): backgroundApp returns after the
1476
+ // seconds elapse and the app is in the foreground again (queryAppState 4); isAppInstalled → true/false;
1477
+ // getCurrentActivity/getCurrentPackage (Android) and activeAppInfo (iOS); `mobile: installApp {appPath: "cloud:…"}`
1478
+ // installs from the Digital.ai repository mid-session (the `app` key is rejected: "required parameter appPath").
1479
+ case 'background': {
1480
+ const seconds = Math.max(1, Math.round(opts.seconds ?? 3));
1481
+ if (!isW3c)
1482
+ throw new Error('background is not available on Appium Grid sessions — press HOME (press_key) and relaunch with launch_app instead.');
1483
+ await execScript(client, session, 'mobile: backgroundApp', [{ seconds }], (seconds + 20) * 1000);
1484
+ return `App sent to the background for ${seconds} s and brought back to the foreground. Verify the restored screen with take_inspection_screenshot.`;
1485
+ }
1486
+ case 'is_installed': {
1487
+ if (!packageName)
1488
+ throw new Error('is_installed requires packageName (Android) or bundleIdentifier (iOS).');
1489
+ if (!isW3c)
1490
+ throw new Error('is_installed is not available on Appium Grid sessions — use list_applications / get_application_info, or launch_app and read the error.');
1491
+ const r = await execScript(client, session, 'mobile: isAppInstalled', [idArg(packageName)]);
1492
+ return `${packageName} is ${r.data.value === true ? '' : 'NOT '}installed on ${session.deviceName || 'this device'}.`;
1493
+ }
1494
+ case 'current': {
1495
+ if (isW3c && isIos) {
1496
+ const r = await execScript(client, session, 'mobile: activeAppInfo');
1497
+ const v = r.data.value;
1498
+ return `Foreground app: ${v.bundleId ?? 'unknown'}${v.name ? ` (${v.name})` : ''}${v.pid != null ? `, pid ${v.pid}` : ''}.`;
1499
+ }
1500
+ if (isW3c) {
1501
+ const [act, pkg] = await Promise.all([
1502
+ execScript(client, session, 'mobile: getCurrentActivity').then((r) => String(r.data.value ?? '')),
1503
+ execScript(client, session, 'mobile: getCurrentPackage').then((r) => String(r.data.value ?? '')),
1504
+ ]);
1505
+ return `Foreground: package ${pkg}, activity ${act}.`;
1506
+ }
1507
+ if (isIos)
1508
+ throw new Error('current is not available on Grid iOS sessions — use take_inspection_screenshot.');
1509
+ const res = await client.get(`/session/${sid}/appium/device/current_activity`, { timeout: 15_000 });
1510
+ return `Foreground activity: ${String(res.data.value ?? '')} (Grid sessions report the activity only).`;
1511
+ }
1512
+ case 'install': {
1513
+ const ref = opts.appRef ?? packageName;
1514
+ if (!ref)
1515
+ throw new Error('install requires appRef — a repository reference such as "cloud:com.example.app" (Android: "cloud:com.example.app/.MainActivity"), "cloud:uniqueName=<name>" or "cloud:<package>:releaseVersion=<v>".');
1516
+ const appPath = ref.startsWith('cloud:') ? ref : `cloud:${ref}`;
1517
+ if (!isW3c)
1518
+ throw new Error('install mid-session is not available on Appium Grid sessions — install_application before the session (the device must not be reserved).');
1519
+ await execScript(client, session, 'mobile: installApp', [{ appPath }], 180_000);
1520
+ return `Installed ${appPath} from the repository onto ${session.deviceName || 'the device'}. Use launch_app to open it.`;
1521
+ }
1248
1522
  case 'terminate': {
1249
1523
  if (!packageName)
1250
1524
  throw new Error('terminate requires packageName (Android) or bundleIdentifier (iOS).');
1251
1525
  if (isW3c) {
1252
- const args = isIos ? { bundleId: packageName } : { appId: packageName };
1526
+ // timeout: how long the driver waits for the process to disappear before answering false (UiAutomator2 default
1527
+ // 500 ms — a slow-exiting app was reported "was not running"); verified live 2026-10-17 with 2000.
1528
+ const args = isIos ? { bundleId: packageName } : { appId: packageName, timeout: 3000 };
1253
1529
  const res = await execScript(client, session, 'mobile: terminateApp', [args]);
1254
1530
  return res.data.value
1255
1531
  ? `Terminated ${packageName}.`
@@ -1385,17 +1661,46 @@ export async function setGeolocation(handle, latitude, longitude) {
1385
1661
  }
1386
1662
  export async function resetGeolocation(handle) {
1387
1663
  const session = requireSession(handle);
1664
+ const client = makeClient();
1388
1665
  if (session.sessionFormat === 'jwp') {
1389
- // seetest:client.clearLocation exists but the Grid's execute parser cannot
1390
- // express 0-arg commands — confirmed live.
1391
- throw new Error('Geolocation reset is not supported on Appium Grid sessions. ' +
1392
- 'Set explicit coordinates instead, or use an Appium Server (OSS) project session.');
1666
+ // seetest:client.clearLocation() — inline 0-arg form (execScript adds the parentheses on the Grid).
1667
+ await execScript(client, session, 'seetest:client.clearLocation', []);
1668
+ return;
1393
1669
  }
1394
- const client = makeClient();
1395
1670
  const script = session.platform === 'ios' ? 'mobile: resetSimulatedLocation' : 'mobile: resetGeolocation';
1396
1671
  await execScript(client, session, script, [{}]);
1397
1672
  }
1398
- export async function handleAlert(handle, action) {
1673
+ /** Alert text and, on iOS Appium Server, its button labels (`mobile: alert getButtons` → ["Yes","No"] live 2026-10-18). */
1674
+ export async function getAlertInfo(handle) {
1675
+ const session = requireSession(handle);
1676
+ if (session.sessionFormat === 'jwp') {
1677
+ throw new Error('Alert routes are not supported on Appium Grid sessions (501) — dialogs are regular UI elements there: use get_element_tree / find_elements and tap_element.');
1678
+ }
1679
+ const client = makeClient();
1680
+ let text;
1681
+ try {
1682
+ const r = await client.get(`/session/${session.gridSessionId}/alert/text`, { timeout: 15_000 });
1683
+ text = String(r.data.value ?? '');
1684
+ }
1685
+ catch (e) {
1686
+ const detail = describeWdError(e).toLowerCase();
1687
+ if (detail.includes('no alert') || detail.includes('noalertopen') || detail.includes('modal dialog when one was not open'))
1688
+ throw new Error('No alert is present on the screen.');
1689
+ throw new Error(describeWdError(e));
1690
+ }
1691
+ let buttons = null;
1692
+ if (session.platform === 'ios') {
1693
+ try {
1694
+ const r = await execScript(client, session, 'mobile: alert', [{ action: 'getButtons' }]);
1695
+ buttons = Array.isArray(r.data.value) ? r.data.value.map(String) : null;
1696
+ }
1697
+ catch {
1698
+ buttons = null;
1699
+ }
1700
+ }
1701
+ return { text, buttons };
1702
+ }
1703
+ export async function handleAlert(handle, action, buttonLabel) {
1399
1704
  const session = requireSession(handle);
1400
1705
  if (session.sessionFormat === 'jwp') {
1401
1706
  // Confirmed live: all alert routes 501 on the Grid.
@@ -1404,6 +1709,14 @@ export async function handleAlert(handle, action) {
1404
1709
  }
1405
1710
  const client = makeClient();
1406
1711
  try {
1712
+ if (buttonLabel && session.platform === 'ios') {
1713
+ // XCUITest: pick the button by its label (plain /alert/accept presses the default one).
1714
+ await execScript(client, session, 'mobile: alert', [{ action, buttonLabel }]);
1715
+ return;
1716
+ }
1717
+ if (buttonLabel) {
1718
+ throw new Error('buttonLabel is iOS-only (mobile: alert). On Android tap the dialog button by text with find_elements + tap_element.');
1719
+ }
1407
1720
  await client.post(`/session/${session.gridSessionId}/alert/${action}`, {}, { timeout: 15_000 });
1408
1721
  }
1409
1722
  catch (e) {
@@ -1443,15 +1756,328 @@ export async function mockAuthentication(handle, reply, delayMs) {
1443
1756
  if (session.platform === 'web')
1444
1757
  throw new Error('mock_authentication is not available for browser sessions.');
1445
1758
  const client = makeClient();
1446
- // Android uses string enum values; iOS uses LAError numeric codes.
1759
+ // Both platforms take string replies (verified live 2026-10-17 — numeric LAError codes are refused on iOS:
1760
+ // "Invalid setAuthenticationReply() parameter 1 for iOS, possible values are: MockFullGUI, Success, StopMock,
1761
+ // AuthenticationFailedError, UserCancelError, UserFallbackError, SystemCancelError, PasscodeNotSetError,
1762
+ // TouchIDNotAvailableError, TouchIDNotEnrolledError, TouchIDLockoutError, AppCancelError, InvalidContextError";
1763
+ // Android: CLEAR_MOCK, AUTHENTICATION_SUCCEEDED, AUTHENTICATION_FAILED, ERROR_CANCELED, ERROR_HW_UNAVAILABLE,
1764
+ // ERROR_LOCKOUT, ERROR_NO_SPACE, ERROR_TIMEOUT, ERROR_UNABLE_TO_PROCESS, ERROR_VENDOR_BASE, FP_ACQUIRED_*).
1447
1765
  const replyValue = session.platform === 'ios'
1448
- ? { success: 1, failed: -1, cancel: -2, clear: 0 }[reply]
1766
+ ? { success: 'Success', failed: 'AuthenticationFailedError', cancel: 'UserCancelError', clear: 'StopMock' }[reply]
1449
1767
  : { success: 'AUTHENTICATION_SUCCEEDED', failed: 'AUTHENTICATION_FAILED', cancel: 'ERROR_CANCELED', clear: 'CLEAR_MOCK' }[reply];
1450
- await execScript(client, session, 'seetest:client.setAuthenticationReply', [replyValue, delayMs]);
1768
+ // The platform rejects delay 0 ("Parameter delay must be a number greater than 0") on both platforms — so a zero
1769
+ // default made EVERY call fail until 2026-10-17. 1 ms is the smallest accepted value.
1770
+ const delay = Math.max(1, Math.floor(delayMs));
1771
+ try {
1772
+ await execScript(client, session, 'seetest:client.setAuthenticationReply', [replyValue, delay]);
1773
+ }
1774
+ catch (e) {
1775
+ const detail = describeWdError(e);
1776
+ if (/not instrumented/i.test(detail)) {
1777
+ throw new Error(`${detail}. The app under test must be instrumented: re-upload it with instrument=true (upload_application_file / ` +
1778
+ `upload_application_from_url) or start the session with the digitalai:instrumentApp capability, then launch it again.`);
1779
+ }
1780
+ throw new Error(detail);
1781
+ }
1451
1782
  const label = reply === 'clear' ? 'cleared (no mock active)' : `staged as "${reply}"`;
1452
1783
  return (`Authentication response ${label}. ` +
1453
1784
  `The next biometric prompt in the instrumented app will respond automatically.`);
1454
1785
  }
1786
+ export async function sessionCapture(handle, kind, action, name) {
1787
+ const session = requireSession(handle);
1788
+ const client = makeClient();
1789
+ const field = kind === 'har' ? 'harRecording' : 'deviceLogRecording';
1790
+ if (action === 'start') {
1791
+ if (session[field])
1792
+ throw new Error(`A ${kind} capture ("${session[field]}") is already running — stop it first.`);
1793
+ const base = (name ?? `mcp-${kind}-${new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14)}`).replace(/^cloud:/, '');
1794
+ const file = kind === 'har' ? (base.endsWith('.har') ? base : `${base}.har`) : (base.endsWith('.log') ? base : `${base}.log`);
1795
+ try {
1796
+ await execScript(client, session, kind === 'har' ? 'seetest:client.startHarRecording' : 'seetest:client.startLoggingDevice', [`cloud:${file}`], 60_000);
1797
+ }
1798
+ catch (e) {
1799
+ throw new Error(sessionAwareError(e, handle));
1800
+ }
1801
+ session[field] = file;
1802
+ return { file };
1803
+ }
1804
+ const file = session[field];
1805
+ if (!file)
1806
+ throw new Error(`No ${kind} capture is running on this session — start one first.`);
1807
+ try {
1808
+ await execScript(client, session, kind === 'har' ? 'seetest:client.stopHarRecording' : 'seetest:client.stopLoggingDevice', [], 60_000);
1809
+ }
1810
+ catch (e) {
1811
+ throw new Error(sessionAwareError(e, handle));
1812
+ }
1813
+ session[field] = undefined;
1814
+ let repositoryFile;
1815
+ let note;
1816
+ try {
1817
+ const { listFiles } = await import('./repository.js');
1818
+ for (let i = 0; i < 5 && !repositoryFile; i++) {
1819
+ const hit = (await listFiles()).find((f) => f.uniqueName === file);
1820
+ if (hit)
1821
+ repositoryFile = { id: hit.id, size: Number(hit.size ?? 0) };
1822
+ else
1823
+ await new Promise((r) => setTimeout(r, 1500));
1824
+ }
1825
+ }
1826
+ catch {
1827
+ // listing is best-effort
1828
+ }
1829
+ if (kind === 'har' && repositoryFile && repositoryFile.size < 400) {
1830
+ note = 'The HAR holds no entries: the platform does not record HTTP traffic while NV tunneling is on for the device (platform docs), and this tenant tunnels every device. Use a performance transaction for network byte counts instead.';
1831
+ }
1832
+ return { file, repositoryFile, note };
1833
+ }
1834
+ export async function networkConnection(handle, kind, enabled) {
1835
+ const session = requireSession(handle);
1836
+ if (enabled != null && session.platform === 'ios') {
1837
+ throw new Error('setNetworkConnection is Android-only (platform docs) — on iOS only the read-back works.');
1838
+ }
1839
+ const client = makeClient();
1840
+ try {
1841
+ if (enabled != null) {
1842
+ await execScript(client, session, 'seetest:client.setNetworkConnection', [kind, enabled]);
1843
+ }
1844
+ const r = await execScript(client, session, 'seetest:client.getNetworkConnection', [kind]);
1845
+ return { kind, enabled: r.data.value === true };
1846
+ }
1847
+ catch (e) {
1848
+ throw new Error(sessionAwareError(e, handle));
1849
+ }
1850
+ }
1851
+ export async function setNetworkConditions(handle, profile, durationMs = 0) {
1852
+ const session = requireSession(handle);
1853
+ const client = makeClient();
1854
+ try {
1855
+ await execScript(client, session, 'seetest:client.setNetworkConditions', [profile, Math.max(0, Math.round(durationMs))]);
1856
+ }
1857
+ catch (e) {
1858
+ throw new Error(sessionAwareError(e, handle));
1859
+ }
1860
+ return `NV profile "${profile}" applied to the device's traffic${durationMs > 0 ? ` for ${Math.round(durationMs / 1000)} s` : ' until changed (apply "Monitor" or quit the session to lift it)'}. No transaction is recorded — this only shapes the network.`;
1861
+ }
1862
+ // ─── Camera image injection ──────────────────────────────────────────────────
1863
+ // seetest:client.simulateCapture(source): "cloud:<repository file>" or an http(s) URL; the platform checks the
1864
+ // extension first ("Only the following are supported:[jpg, jpeg, png]", live 2026-10-18) and needs the app under test
1865
+ // instrumented (digitalai:instrumentApp=true / instrument=true at upload) — not instrumented → "application is not
1866
+ // instrumented", the same gate as setAuthenticationReply.
1867
+ export async function injectCameraImage(handle, source) {
1868
+ const session = requireSession(handle);
1869
+ const client = makeClient();
1870
+ const src = source.trim();
1871
+ if (!/\.(jpe?g|png)(\?.*)?$/i.test(src)) {
1872
+ throw new Error(`"${src}" is not a jpg/jpeg/png — the platform accepts only those extensions (a repository file "cloud:<uniqueName>.png" or an http(s) URL ending in .jpg/.jpeg/.png).`);
1873
+ }
1874
+ if (!/^(cloud:|https?:\/\/)/i.test(src)) {
1875
+ throw new Error('source must be "cloud:<repository uniqueName>" (upload the image with upload_repository_file first) or an http(s) URL.');
1876
+ }
1877
+ try {
1878
+ await execScript(client, session, 'seetest:client.simulateCapture', [src], 60_000);
1879
+ }
1880
+ catch (e) {
1881
+ const detail = describeWdError(e);
1882
+ if (/not instrumented/i.test(detail)) {
1883
+ throw new Error(`${detail}. Camera injection needs an instrumented build: re-upload the app with instrument=true, or start the session with digitalai:instrumentApp=true, then launch it again.`);
1884
+ }
1885
+ throw new Error(sessionAwareError(e, handle));
1886
+ }
1887
+ return `Camera injection armed with ${src}: the next camera capture in the instrumented app returns this image instead of the sensor frame.`;
1888
+ }
1889
+ export async function clearWebCache(handle) {
1890
+ const session = requireSession(handle);
1891
+ try {
1892
+ await execScript(makeClient(), session, 'seetest:client.hybridClearCache', [], 60_000);
1893
+ }
1894
+ catch (e) {
1895
+ throw new Error(sessionAwareError(e, handle));
1896
+ }
1897
+ }
1898
+ // ─── Device diagnostics (Appium Server) ──────────────────────────────────────
1899
+ // Verified live 2026-10-18/19: Android `mobile: deviceInfo` (apiVersion, brand, model, locale, timeZone, realDisplaySize,
1900
+ // displayDensity, carrierName, networks), `batteryInfo` {level, state}, `getSystemBars`, `getDisplayDensity`,
1901
+ // `getDeviceTime`, `isLocked`, `getUiMode`/`setUiMode {mode:'night', value:'yes'|'no'}` (dark mode; getNotifications
1902
+ // fails to parse on Samsung — not exposed). iOS `deviceInfo` (currentLocale, timeZone, userInterfaceStyle, thermalState,
1903
+ // isSimulator, model), `batteryInfo`, `deviceScreenInfo` {statusBarSize, scale, screenSize}, `get/setAppearance
1904
+ // {style:'dark'|'light'}`, `performAccessibilityAudit` (XCTest audit — array of findings), `isLocked`.
1905
+ // NEVER use the "-image" locator strategy: a single find killed the agent's Appium process on both platforms (every
1906
+ // later command "Connection refused"); the image plugin is not loaded on the cloud agents.
1907
+ export async function deviceDiagnostics(handle) {
1908
+ const session = requireSession(handle);
1909
+ if (session.sessionFormat !== 'w3c')
1910
+ throw new Error('device_info needs an Appium Server session (mobile: deviceInfo is not available on the Grid) — get_device_detail reads the platform record instead.');
1911
+ const client = makeClient();
1912
+ const call = async (script, args = [{}]) => { try {
1913
+ return (await execScript(client, session, script, args, 20_000)).data.value;
1914
+ }
1915
+ catch {
1916
+ return undefined;
1917
+ } };
1918
+ const info = (await call('mobile: deviceInfo'));
1919
+ const battery = (await call('mobile: batteryInfo'));
1920
+ const locked = await call('mobile: isLocked');
1921
+ if (session.platform === 'ios') {
1922
+ const screen = (await call('mobile: deviceScreenInfo'));
1923
+ const appearance = (await call('mobile: getAppearance'));
1924
+ return {
1925
+ platform: 'iOS', model: info?.model, name: info?.name, locale: info?.currentLocale, timeZone: info?.timeZone,
1926
+ isSimulator: info?.isSimulator, thermalState: info?.thermalState, appearance: appearance?.style ?? info?.userInterfaceStyle,
1927
+ battery, screen, locked,
1928
+ };
1929
+ }
1930
+ const bars = await call('mobile: getSystemBars');
1931
+ const density = await call('mobile: getDisplayDensity');
1932
+ const time = await call('mobile: getDeviceTime', [{ format: 'YYYY-MM-DD HH:mm:ss Z' }]);
1933
+ const night = await call('mobile: getUiMode', [{ mode: 'night' }]);
1934
+ return {
1935
+ platform: 'Android', brand: info?.brand, model: info?.model, manufacturer: info?.manufacturer, apiVersion: info?.apiVersion,
1936
+ platformVersion: info?.platformVersion, locale: info?.locale, timeZone: info?.timeZone, carrier: info?.carrierName,
1937
+ realDisplaySize: info?.realDisplaySize, displayDensity: density ?? info?.displayDensity, systemBars: bars,
1938
+ appearance: night === 'yes' ? 'dark' : night === 'no' ? 'light' : undefined, deviceTime: time, battery, locked,
1939
+ };
1940
+ }
1941
+ export async function setAppearance(handle, style) {
1942
+ const session = requireSession(handle);
1943
+ if (session.sessionFormat !== 'w3c')
1944
+ throw new Error('appearance is Appium Server only (mobile: setAppearance / setUiMode).');
1945
+ const client = makeClient();
1946
+ if (session.platform === 'ios') {
1947
+ await execScript(client, session, 'mobile: setAppearance', [{ style }]);
1948
+ const r = await execScript(client, session, 'mobile: getAppearance', [{}]);
1949
+ return String(r.data.value?.style ?? style);
1950
+ }
1951
+ await execScript(client, session, 'mobile: setUiMode', [{ mode: 'night', value: style === 'dark' ? 'yes' : 'no' }]);
1952
+ const r = await execScript(client, session, 'mobile: getUiMode', [{ mode: 'night' }]);
1953
+ return r.data.value === 'yes' ? 'dark' : 'light';
1954
+ }
1955
+ export async function accessibilityAudit(handle) {
1956
+ const session = requireSession(handle);
1957
+ if (session.platform !== 'ios' || session.sessionFormat !== 'w3c') {
1958
+ throw new Error('accessibility_audit runs XCTest\'s audit on iOS Appium Server sessions only. For Android (or a report-attached scan on either platform) generate the test with includeAxeScan.');
1959
+ }
1960
+ const r = await execScript(makeClient(), session, 'mobile: performAccessibilityAudit', [{}], 60_000);
1961
+ return Array.isArray(r.data.value) ? r.data.value : [];
1962
+ }
1963
+ export function isWebviewContext(session) {
1964
+ return !!session.currentContext && session.currentContext !== 'NATIVE_APP';
1965
+ }
1966
+ export async function listContexts(handle, waitMs = 3000) {
1967
+ const session = requireSession(handle);
1968
+ const client = makeClient();
1969
+ if (session.sessionFormat === 'w3c') {
1970
+ try {
1971
+ const r = await execScript(client, session, 'mobile: getContexts', [{ waitForWebviewMs: waitMs }], waitMs + 20_000);
1972
+ const v = r.data.value;
1973
+ if (Array.isArray(v) && v.length) {
1974
+ const out = [];
1975
+ for (const c of v) {
1976
+ if (typeof c === 'string') {
1977
+ out.push({ id: c });
1978
+ continue;
1979
+ }
1980
+ if (c.id) {
1981
+ out.push({ id: String(c.id), title: c.title ? String(c.title) : undefined, url: c.url ? String(c.url) : undefined, bundleId: c.bundleId ? String(c.bundleId) : undefined });
1982
+ continue;
1983
+ }
1984
+ // Android shape: { webview, info: { 'Android-Package' }, pages: [{ title, url, type }] }
1985
+ const pages = c.pages?.filter((pg) => pg.type === 'page') ?? [];
1986
+ const info = c.info;
1987
+ if (!c.webview)
1988
+ continue;
1989
+ out.push({ id: String(c.webview), package: info?.['Android-Package'] ? String(info['Android-Package']) : undefined, title: pages[0]?.title ? String(pages[0].title) : undefined, url: pages[0]?.url ? String(pages[0].url) : undefined });
1990
+ }
1991
+ if (!out.some((c) => c.id === 'NATIVE_APP'))
1992
+ out.unshift({ id: 'NATIVE_APP' });
1993
+ return out;
1994
+ }
1995
+ }
1996
+ catch {
1997
+ // fall back to the plain route
1998
+ }
1999
+ }
2000
+ const r = await client.get(`/session/${session.gridSessionId}/contexts`, { timeout: 15_000 });
2001
+ return (Array.isArray(r.data.value) ? r.data.value : []).map((c) => ({ id: String(c) }));
2002
+ }
2003
+ export async function switchContext(handle, target, waitMs = 3000) {
2004
+ const session = requireSession(handle);
2005
+ const client = makeClient();
2006
+ const contexts = await listContexts(handle, target === 'native' ? 0 : waitMs);
2007
+ const ids = contexts.map((c) => c.id);
2008
+ let name;
2009
+ if (target === 'native')
2010
+ name = 'NATIVE_APP';
2011
+ else if (target === 'auto') {
2012
+ const web = ids.find((id) => /^WEBVIEW/i.test(id));
2013
+ if (!web) {
2014
+ throw new Error(`No WEBVIEW context is available (contexts: ${ids.join(', ') || 'none'}). The screen in front has no web content, ` +
2015
+ `or the webview is not debuggable (Android: WebView.setWebContentsDebuggingEnabled(true) in a debug build; ` +
2016
+ `iOS: the app must be built with web inspection allowed). Navigate to the hybrid screen first, then retry.`);
2017
+ }
2018
+ name = web;
2019
+ }
2020
+ else {
2021
+ if (!ids.includes(target))
2022
+ throw new Error(`Context "${target}" is not available (contexts: ${ids.join(', ') || 'none'}).`);
2023
+ name = target;
2024
+ }
2025
+ try {
2026
+ await client.post(`/session/${session.gridSessionId}/context`, { name }, { timeout: 30_000 });
2027
+ }
2028
+ catch (e) {
2029
+ throw new Error(`Switching to ${name} failed: ${describeWdError(e)}`);
2030
+ }
2031
+ session.currentContext = name;
2032
+ const result = { context: name, available: ids };
2033
+ if (name !== 'NATIVE_APP') {
2034
+ try {
2035
+ result.title = String((await client.get(`/session/${session.gridSessionId}/title`, { timeout: 10_000 })).data.value ?? '');
2036
+ }
2037
+ catch { /* optional */ }
2038
+ try {
2039
+ result.url = String((await client.get(`/session/${session.gridSessionId}/url`, { timeout: 10_000 })).data.value ?? '');
2040
+ }
2041
+ catch { /* optional */ }
2042
+ }
2043
+ return result;
2044
+ }
2045
+ // ─── Device log (in-session) ─────────────────────────────────────────────────
2046
+ // GET /log/types → Android: logcat, bugreport, server (Grid: logcat); iOS: syslog, crashlog, performance,
2047
+ // safariConsole, safariNetwork, server. POST /log {type} returns every line captured so far (3 580 logcat / 9 548
2048
+ // syslog lines live 2026-10-18), so the tail is cut here and `contains` filters before anything is returned.
2049
+ export async function getDeviceLog(handle, type, opts = {}) {
2050
+ const session = requireSession(handle);
2051
+ const client = makeClient();
2052
+ let types = [];
2053
+ try {
2054
+ const r = await client.get(`/session/${session.gridSessionId}/log/types`, { timeout: 15_000 });
2055
+ types = Array.isArray(r.data.value) ? r.data.value.map(String) : [];
2056
+ }
2057
+ catch {
2058
+ types = [];
2059
+ }
2060
+ const wanted = type ?? (session.platform === 'ios' ? 'syslog' : 'logcat');
2061
+ if (types.length && !types.includes(wanted)) {
2062
+ throw new Error(`Log type "${wanted}" is not available on this session. Available: ${types.join(', ')}.`);
2063
+ }
2064
+ let entries;
2065
+ try {
2066
+ const r = await client.post(`/session/${session.gridSessionId}/log`, { type: wanted }, { timeout: 60_000 });
2067
+ entries = Array.isArray(r.data.value) ? r.data.value : [];
2068
+ }
2069
+ catch (e) {
2070
+ throw new Error(`Reading the ${wanted} log failed: ${describeWdError(e)}`);
2071
+ }
2072
+ let lines = entries.map((e) => (typeof e === 'string' ? e : String(e.message ?? '')));
2073
+ const totalLines = lines.length;
2074
+ if (opts.contains) {
2075
+ const needle = opts.contains.toLowerCase();
2076
+ lines = lines.filter((l) => l.toLowerCase().includes(needle));
2077
+ }
2078
+ const tail = Math.max(1, opts.tail ?? 200);
2079
+ return { type: wanted, totalLines, lines: lines.slice(-tail), types };
2080
+ }
1455
2081
  export function registerSession(session) {
1456
2082
  sessionRegistry.set(session.handle, session);
1457
2083
  if (session.reportTestId > 0)