digital-ai-testing-mcp 2.2.2 → 2.3.1

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 (102) hide show
  1. package/README.md +27 -15
  2. package/dist/api/browser-events.d.ts +48 -0
  3. package/dist/api/browser-events.d.ts.map +1 -0
  4. package/dist/api/browser-events.js +155 -0
  5. package/dist/api/browser-events.js.map +1 -0
  6. package/dist/api/browser-inspection.d.ts +21 -0
  7. package/dist/api/browser-inspection.d.ts.map +1 -1
  8. package/dist/api/browser-inspection.js +113 -20
  9. package/dist/api/browser-inspection.js.map +1 -1
  10. package/dist/api/playwright-runs.d.ts +42 -0
  11. package/dist/api/playwright-runs.d.ts.map +1 -0
  12. package/dist/api/playwright-runs.js +207 -0
  13. package/dist/api/playwright-runs.js.map +1 -0
  14. package/dist/api/reporting.d.ts.map +1 -1
  15. package/dist/api/reporting.js +4 -2
  16. package/dist/api/reporting.js.map +1 -1
  17. package/dist/api/repository.d.ts +13 -1
  18. package/dist/api/repository.d.ts.map +1 -1
  19. package/dist/api/repository.js +39 -4
  20. package/dist/api/repository.js.map +1 -1
  21. package/dist/api/test-requests.d.ts +4 -0
  22. package/dist/api/test-requests.d.ts.map +1 -1
  23. package/dist/api/test-requests.js +2 -0
  24. package/dist/api/test-requests.js.map +1 -1
  25. package/dist/api/test-runs.d.ts +5 -0
  26. package/dist/api/test-runs.d.ts.map +1 -1
  27. package/dist/api/test-runs.js.map +1 -1
  28. package/dist/api/webdriver.d.ts +25 -2
  29. package/dist/api/webdriver.d.ts.map +1 -1
  30. package/dist/api/webdriver.js +163 -11
  31. package/dist/api/webdriver.js.map +1 -1
  32. package/dist/index.js +1 -1
  33. package/dist/tools/boilerplate-tools.d.ts +22 -0
  34. package/dist/tools/boilerplate-tools.d.ts.map +1 -1
  35. package/dist/tools/boilerplate-tools.js +321 -43
  36. package/dist/tools/boilerplate-tools.js.map +1 -1
  37. package/dist/tools/device-group-tools.js +2 -2
  38. package/dist/tools/device-group-tools.js.map +1 -1
  39. package/dist/tools/device-tools.d.ts.map +1 -1
  40. package/dist/tools/device-tools.js +63 -11
  41. package/dist/tools/device-tools.js.map +1 -1
  42. package/dist/tools/inspection-tools.d.ts +24 -0
  43. package/dist/tools/inspection-tools.d.ts.map +1 -1
  44. package/dist/tools/inspection-tools.js +159 -14
  45. package/dist/tools/inspection-tools.js.map +1 -1
  46. package/dist/tools/meta-tools.d.ts +1 -1
  47. package/dist/tools/meta-tools.d.ts.map +1 -1
  48. package/dist/tools/meta-tools.js +3 -2
  49. package/dist/tools/meta-tools.js.map +1 -1
  50. package/dist/tools/prompt-tools.d.ts.map +1 -1
  51. package/dist/tools/prompt-tools.js +4 -0
  52. package/dist/tools/prompt-tools.js.map +1 -1
  53. package/dist/tools/reporting-tools.d.ts.map +1 -1
  54. package/dist/tools/reporting-tools.js +27 -8
  55. package/dist/tools/reporting-tools.js.map +1 -1
  56. package/dist/tools/repository-tools.d.ts.map +1 -1
  57. package/dist/tools/repository-tools.js +5 -3
  58. package/dist/tools/repository-tools.js.map +1 -1
  59. package/dist/tools/test-run-tools.d.ts.map +1 -1
  60. package/dist/tools/test-run-tools.js +107 -6
  61. package/dist/tools/test-run-tools.js.map +1 -1
  62. package/dist/tools/usage-report-tools.d.ts.map +1 -1
  63. package/dist/tools/usage-report-tools.js +6 -4
  64. package/dist/tools/usage-report-tools.js.map +1 -1
  65. package/dist/tools/web-inspection-tools.d.ts.map +1 -1
  66. package/dist/tools/web-inspection-tools.js +116 -13
  67. package/dist/tools/web-inspection-tools.js.map +1 -1
  68. package/dist/types/digital-ai.d.ts +6 -1
  69. package/dist/types/digital-ai.d.ts.map +1 -1
  70. package/dist/utils/adb-shell.d.ts +25 -0
  71. package/dist/utils/adb-shell.d.ts.map +1 -0
  72. package/dist/utils/adb-shell.js +87 -0
  73. package/dist/utils/adb-shell.js.map +1 -0
  74. package/dist/utils/credential-env.d.ts +36 -0
  75. package/dist/utils/credential-env.d.ts.map +1 -0
  76. package/dist/utils/credential-env.js +57 -0
  77. package/dist/utils/credential-env.js.map +1 -0
  78. package/dist/utils/failure-triage.d.ts +13 -0
  79. package/dist/utils/failure-triage.d.ts.map +1 -0
  80. package/dist/utils/failure-triage.js +53 -0
  81. package/dist/utils/failure-triage.js.map +1 -0
  82. package/dist/utils/locator-recommend.d.ts +27 -0
  83. package/dist/utils/locator-recommend.d.ts.map +1 -0
  84. package/dist/utils/locator-recommend.js +59 -0
  85. package/dist/utils/locator-recommend.js.map +1 -0
  86. package/dist/utils/response-formatter.d.ts +8 -0
  87. package/dist/utils/response-formatter.d.ts.map +1 -1
  88. package/dist/utils/response-formatter.js +34 -2
  89. package/dist/utils/response-formatter.js.map +1 -1
  90. package/dist/utils/usage-report-summary.d.ts +2 -0
  91. package/dist/utils/usage-report-summary.d.ts.map +1 -1
  92. package/dist/utils/usage-report-summary.js +5 -1
  93. package/dist/utils/usage-report-summary.js.map +1 -1
  94. package/package.json +8 -1
  95. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio-oss.conf.js +1 -0
  96. package/resources/boilerplate/Android-Native/Python/AndroidNative-oss.py +3 -2
  97. package/resources/boilerplate/Android-Native/Python/pip-oss +1 -1
  98. package/resources/boilerplate/Android-Native/Robot Framework/AndroidNative-oss.robot +1 -1
  99. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio-oss.conf.js +1 -0
  100. package/resources/boilerplate/iOS-Native/Python/iOSNative-oss.py +3 -2
  101. package/resources/boilerplate/iOS-Native/Python/pip-oss.txt +1 -1
  102. package/resources/boilerplate/iOS-Native/Robot Framework/iOSNative-oss.robot +1 -1
@@ -6,12 +6,13 @@ import { join, dirname } from 'path';
6
6
  import { fileURLToPath } from 'url';
7
7
  import { getMyAccountInfo } from '../api/users.js';
8
8
  import { getApplicationInfo } from '../api/applications.js';
9
- import { getActiveAccessKey, getActiveUrl } from '../api/client.js';
9
+ import { getActiveUrl } from '../api/client.js';
10
10
  import { listActiveSessions, AUTOMOTIVE_RESOLUTIONS } from '../api/webdriver.js';
11
11
  import { outputFormatParam, respond } from '../utils/output-format.js';
12
12
  import { staleBuildRemedy, serverFsInstallNotice, serverFsProjectDirParam } from '../utils/locality.js';
13
13
  import { isLocalFilesystem } from '../utils/deployment-mode.js';
14
14
  import { validateOutputPath } from '../utils/path-guard.js';
15
+ import { ACCESS_KEY_ENV, JAVA_KEY_EXPR, PYTHON_KEY_EXPR, JS_KEY_EXPR, JS_KEY_GUARD, ROBOT_KEY_EXPR, ensurePythonImportOs, addJsKeyGuard, ENV_EXAMPLE_FILE, CREDENTIAL_SETUP, CREDENTIAL_SETUP_TEXT, } from '../utils/credential-env.js';
15
16
  import { AGENT_PROJECT_PATH, CONFIG_TEMPLATE_PATH, GITIGNORE_ADVICE, JDK_TRUST_NOTE, LIB_GITIGNORE, LIB_GITIGNORE_PATH, ORCHESTRATOR_GITIGNORE, ORCHESTRATOR_GITIGNORE_PATH, addOrchestrationToGradle, addOrchestrationToMaven, buildConfigTemplate, decideOrchestration, resolveMaxRetryAttempts, } from '../utils/test-orchestrator.js';
16
17
  import { buildAgentDownloadCommands, installAgentIntoProject, resolveAgentSource, } from '../api/test-orchestrator.js';
17
18
  const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
@@ -302,6 +303,11 @@ function wrapWithReporting(language, indent, core, isAppiumOss) {
302
303
  // The Grid parses arguments out of the script string, so a 0-arg command is written inline there.
303
304
  isAppiumOss ? `${indent} driver.executeScript("seetest:client.stopStepsGroup");` : `${indent} driver.executeScript("seetest:client.stopStepsGroup()");`,
304
305
  `${indent} driver.executeScript("seetest:client.setReportStatus", "Passed", "All steps completed");`,
306
+ // A skipped test (JUnit 5 Assumptions / TestNG SkipException) is a RuntimeException — report Skipped, not Failed
307
+ // (the platform accepts "Skipped", verified live 2026-11-12).
308
+ `${indent}} catch (${language === 'java-testng' ? 'org.testng.SkipException' : 'org.opentest4j.TestAbortedException'} e) {`,
309
+ `${indent} try { driver.executeScript("seetest:client.setReportStatus", "Skipped", String.valueOf(e.getMessage())); } catch (RuntimeException ignored) {}`,
310
+ `${indent} throw e;`,
305
311
  `${indent}} catch (RuntimeException | AssertionError e) {`,
306
312
  `${indent} try { driver.executeScript("seetest:client.setReportStatus", "Failed", String.valueOf(e.getMessage())); } catch (RuntimeException ignored) {}`,
307
313
  `${indent} throw e;`,
@@ -316,6 +322,12 @@ function wrapWithReporting(language, indent, core, isAppiumOss) {
316
322
  inner,
317
323
  isAppiumOss ? `${indent} self.driver.execute_script("seetest:client.stopStepsGroup")` : `${indent} self.driver.execute_script("seetest:client.stopStepsGroup()")`,
318
324
  `${indent} self.driver.execute_script("seetest:client.setReportStatus", "Passed", "All steps completed")`,
325
+ `${indent}except unittest.SkipTest as e:`,
326
+ `${indent} try:`,
327
+ `${indent} self.driver.execute_script("seetest:client.setReportStatus", "Skipped", str(e)[:500])`,
328
+ `${indent} except Exception:`,
329
+ `${indent} pass`,
330
+ `${indent} raise`,
319
331
  `${indent}except Exception as e:`,
320
332
  `${indent} try:`,
321
333
  `${indent} self.driver.execute_script("seetest:client.setReportStatus", "Failed", str(e)[:500])`,
@@ -332,7 +344,9 @@ function wrapWithReporting(language, indent, core, isAppiumOss) {
332
344
  isAppiumOss ? `${indent} await browser.execute('seetest:client.stopStepsGroup');` : `${indent} await browser.execute('seetest:client.stopStepsGroup()');`,
333
345
  `${indent} await browser.execute('seetest:client.setReportStatus', 'Passed', 'All steps completed');`,
334
346
  `${indent}} catch (e) {`,
335
- `${indent} await browser.execute('seetest:client.setReportStatus', 'Failed', String(e && e.message).slice(0, 500)).catch(() => {});`,
347
+ `${indent} // this.skip() throws mocha's Pending — report Skipped, not Failed.`,
348
+ `${indent} const skipped = !!(e && e.constructor && e.constructor.name === 'Pending');`,
349
+ `${indent} await browser.execute('seetest:client.setReportStatus', skipped ? 'Skipped' : 'Failed', String(e && e.message).slice(0, 500)).catch(() => {});`,
336
350
  `${indent} throw e;`,
337
351
  `${indent}}`,
338
352
  ].join('\n');
@@ -348,7 +362,36 @@ export const REPORT_KEY_VALUE_RE = /^(?=.{1,100}$)[A-Za-z0-9_.:/@+-]+(?: [A-Za-z
348
362
  export const RESERVED_REPORT_KEYS = new Set([
349
363
  'accessKey', 'testName', 'deviceQuery', 'appiumVersion', 'newSessionWaitTimeout', 'automotiveProjection',
350
364
  'instrumentCluster', 'instrumentApp', 'reportTestId', 'reportUrl', 'releaseDevice', 'report.disable',
365
+ 'reservationDuration', 'devicePool', 'commandScreenshot', 'dontGoHomeOnQuit',
351
366
  ].map((k) => k.toLowerCase()));
367
+ /**
368
+ * Remove the `app` capability line (`options.setApp("cloud:…")`, `'appium:app': 'cloud:…'`, `appium:app=cloud:…`, …).
369
+ * With it the platform uninstalls and reinstalls the app at EVERY session start — firstInstallTime equalled the session
370
+ * start on two phones, with and without noReset (verified live 2026-11-12) — so keeping app data means launching the
371
+ * already-installed app by package / bundle id instead.
372
+ */
373
+ export function removeAppCapability(content) {
374
+ return content.replace(/\n[^\n]*(?:setApp\(|MobileCapabilityType\.APP,|['"](?:appium:)?app['"]\s*[:,\]]|appium:app=)[^\n]*cloud:[^\n]*/, '');
375
+ }
376
+ /** "en_US" / "en-US" → Android (language en + locale US) and iOS (language en + locale en_US) capabilities. */
377
+ export const DEVICE_LANGUAGE_RE = /^([a-z]{2,3})[_-]([A-Z]{2})$/;
378
+ export function languageCaps(platform, tag) {
379
+ const m = DEVICE_LANGUAGE_RE.exec(tag);
380
+ if (!m)
381
+ return {};
382
+ return { 'appium:language': m[1], 'appium:locale': platform === 'android' ? m[2] : `${m[1]}_${m[2]}` };
383
+ }
384
+ /**
385
+ * Platform options (digitalai:* session capabilities from the platform's supported-capabilities page) that generated
386
+ * tests may set. A typed allow-list, so a typo fails here instead of becoming a silently ignored capability.
387
+ */
388
+ export const PLATFORM_OPTION_DESCRIPTIONS = {
389
+ releaseDevice: 'boolean (default true) — false keeps a SHARED device reserved after the test for the next test in a sequence; the last test sets true (or call release_device)',
390
+ reservationDuration: 'integer minutes — how long the shared device is reserved for this session; above the project maximum the start fails with "Reservation time in minutes too long"',
391
+ devicePool: '"shared" | "dedicated" | "any" — which device pool to allocate from ("any" prefers dedicated)',
392
+ commandScreenshot: 'boolean — a screenshot before and after every command in the report (slower, larger reports)',
393
+ dontGoHomeOnQuit: "boolean — leave the device on the app's last screen instead of going home at the end",
394
+ };
352
395
  /**
353
396
  * Add capabilities next to the existing ones, for every language and both server modes (the same anchors the Axe
354
397
  * option uses: the driver construction line for Java/Python, the deviceQuery entry in the wdio config for Node).
@@ -358,14 +401,16 @@ function injectCapabilities(content, language, isAppiumOss, caps) {
358
401
  const entries = Object.entries(caps);
359
402
  if (entries.length === 0)
360
403
  return content;
361
- const lit = (v, q) => (typeof v === 'number' ? String(v) : `${q}${v}${q}`);
404
+ const lit = (v, q) => typeof v === 'boolean' ? (language === 'python' ? (v ? 'True' : 'False') : String(v))
405
+ : typeof v === 'number' ? String(v) : `${q}${v}${q}`;
362
406
  if (language === 'robot') {
363
- // &{CAPABILITIES} dictionary rows; numbers as ${n} so Robot passes an int, not a string.
364
- return content.replace(/(\n(\.\.\. +)digitalai:deviceQuery=[^\n]*)/, (m, _line, cont) => m + entries.map(([k, v]) => `\n${cont}${k}=${typeof v === 'number' ? `\${${v}}` : v}`).join(''));
407
+ // &{CAPABILITIES} dictionary rows; numbers/booleans as ${…} so Robot passes an int/bool, not a string.
408
+ const robotLit = (v) => (typeof v === 'number' ? `\${${v}}` : typeof v === 'boolean' ? `\${${v ? 'True' : 'False'}}` : v);
409
+ return content.replace(/(\n(\.\.\. +)digitalai:deviceQuery=[^\n]*)/, (m, _line, cont) => m + entries.map(([k, v]) => `\n${cont}${k}=${robotLit(v)}`).join(''));
365
410
  }
366
411
  if (language === 'java-junit5' || language === 'java-testng') {
367
412
  const obj = isAppiumOss ? 'options' : 'dc';
368
- return content.replace(/\n( +)(driver = new (?:Android|iOS)Driver)/, (_m, sp, line) => '\n' + entries.map(([k, v]) => `${sp}${obj}.setCapability("${k}", ${lit(v, '"')});\n`).join('') + `${sp}${line}`);
413
+ return content.replace(/\n( +)(driver = new (?:Android|IOS|iOS)Driver)/, (_m, sp, line) => '\n' + entries.map(([k, v]) => `${sp}${obj}.setCapability("${k}", ${lit(v, '"')});\n`).join('') + `${sp}${line}`);
369
414
  }
370
415
  if (language === 'python') {
371
416
  const viaOptions = content.includes('options=options');
@@ -459,6 +504,11 @@ function buildPlaceholder(language, platform, indent, isAppiumOss = true, pageOb
459
504
  `${indent}${c} const btn = await find('id=<resource-id from get_element_tree>'); await btn.click();`,
460
505
  `${indent}${c} const field = await find('id=<resource-id>'); await field.setValue('<value>');`,
461
506
  `${indent}${c} await expect($('//*[@text="<visible text>"]')).toBeDisplayed();`,
507
+ // wdio 9 native gesture, verified live 2026-11-12 on Appium Server: without scrollableElement it looks for an
508
+ // android.widget.ScrollView and fails on a ListView/RecyclerView ("Default scrollable element ... was not found").
509
+ ...(isAppiumOss ? [`${indent}${c} await driver.swipe({ direction: 'up', scrollableElement: await $('<scrollable list from get_element_tree>') });`] : []),
510
+ // element.scrollIntoView, verified live 2026-11-12 (Pixel 7, Android Settings): reached an off-screen item in 8.9 s.
511
+ ...(isAppiumOss ? [`${indent}${c} await $('<off-screen item>').scrollIntoView({ direction: 'up', maxScrolls: 15, scrollableElement: $('<scrollable list>') });`] : []),
462
512
  ];
463
513
  }
464
514
  else {
@@ -542,8 +592,17 @@ function substitute(content, language, platform, vars) {
542
592
  result = result.replace(/\n[^\S\n]*(?:\/\/|#) \[END_DEMO_STEPS\]/, '');
543
593
  }
544
594
  }
595
+ // The key is read from DIGITAL_AI_ACCESS_KEY at run time — no generated file carries it (src/utils/credential-env.ts).
596
+ const hadKeyPlaceholder = result.includes('[Enter Your Access key here]');
597
+ result = result
598
+ .replaceAll(`%{${ACCESS_KEY_ENV}=[Enter Your Access key here]}`, ROBOT_KEY_EXPR)
599
+ .replaceAll('"[Enter Your Access key here]"', language === 'python' ? PYTHON_KEY_EXPR : JAVA_KEY_EXPR)
600
+ .replaceAll("'[Enter Your Access key here]'", JS_KEY_EXPR);
601
+ if (hadKeyPlaceholder && language === 'python')
602
+ result = ensurePythonImportOs(result);
603
+ if (hadKeyPlaceholder && language === 'nodejs')
604
+ result = addJsKeyGuard(result);
545
605
  result = result
546
- .replaceAll('[Enter Your Access key here]', vars.accessKey)
547
606
  .replaceAll('[Enter Instance here]', vars.instanceUrl)
548
607
  .replaceAll('[Enter Instance HOST here]', vars.instanceHost)
549
608
  .replaceAll('[Enter Test Name here]', vars.testName)
@@ -561,13 +620,13 @@ function substitute(content, language, platform, vars) {
561
620
  }
562
621
  if (vars.region) {
563
622
  // Append region to the deviceQuery — fires after the PHONE/TABLET substitution has already run.
564
- result = result.replace(/@category='(PHONE|TABLET)'/g, `@category='$1' and @region='${vars.region}'`);
623
+ result = result.replace(/@category='(PHONE|TABLET|FOLDABLE)'/g, `@category='$1' and @region='${vars.region}'`);
565
624
  }
566
625
  if (vars.axeScan) {
567
626
  const automationName = platform === 'android' ? 'AxeUiAutomator2' : 'AxeXCUITest';
568
627
  if (language === 'java-junit5' || language === 'java-testng') {
569
628
  const obj = vars.isAppiumOss ? 'options' : 'dc';
570
- result = result.replace(/\n( +)(driver = new (?:Android|iOS)Driver)/, (_m, sp, line) => `\n${sp}${obj}.setCapability("appium:automationName", "${automationName}");\n` +
629
+ result = result.replace(/\n( +)(driver = new (?:Android|IOS|iOS)Driver)/, (_m, sp, line) => `\n${sp}${obj}.setCapability("appium:automationName", "${automationName}");\n` +
571
630
  `${sp}${obj}.setCapability("${vars.isAppiumOss ? 'digitalai:appiumVersion' : 'appiumVersion'}", "2.16.2");\n` +
572
631
  `${sp}${line}`);
573
632
  }
@@ -584,13 +643,15 @@ function substitute(content, language, platform, vars) {
584
643
  }
585
644
  }
586
645
  else if (language === 'nodejs') {
646
+ // The Appium Server wdio configs already name the driver — drop that line so the Axe driver is the only one.
647
+ result = result.replace(/\n[ \t]*'appium:automationName': '(?:UiAutomator2|XCUITest)',/, '');
587
648
  result = result.replace(/('digitalai:deviceQuery': [^\n]+)/, (match) => `${match}\n 'appium:automationName': '${automationName}',\n '${vars.isAppiumOss ? 'digitalai:appiumVersion' : 'appiumVersion'}': '2.16.2',`);
588
649
  }
589
650
  }
590
651
  if (vars.automotiveProjection) {
591
652
  const res = vars.automotiveProjection;
592
653
  if (language === 'java-junit5' || language === 'java-testng') {
593
- result = result.replace(/\n( +)(driver = new (?:Android|iOS)Driver)/, (_m, sp, line) => `\n${sp}options.setCapability("digitalai:automotiveProjection", "${res}");\n${sp}${line}`);
654
+ result = result.replace(/\n( +)(driver = new (?:Android|IOS|iOS)Driver)/, (_m, sp, line) => `\n${sp}options.setCapability("digitalai:automotiveProjection", "${res}");\n${sp}${line}`);
594
655
  }
595
656
  else if (language === 'python') {
596
657
  result = result.replace(/\n( +)(self\.driver = webdriver\.Remote\()/, (_m, sp, line) => `\n${sp}options.set_capability('digitalai:automotiveProjection', '${res}')\n${sp}${line}`);
@@ -599,8 +660,16 @@ function substitute(content, language, platform, vars) {
599
660
  result = result.replace(/('digitalai:deviceQuery': [^\n]+)/, (match) => `${match}\n 'digitalai:automotiveProjection': '${res}',`);
600
661
  }
601
662
  }
602
- if (vars.extraCaps)
603
- result = injectCapabilities(result, language, !!vars.isAppiumOss, vars.extraCaps);
663
+ let extraCaps = vars.extraCaps;
664
+ if (vars.keepAppData) {
665
+ result = removeAppCapability(result);
666
+ // The Java Appium Server iOS templates name the app only through setApp — keep-data needs the bundle id instead.
667
+ if (platform === 'ios' && !/bundleId|BundleId/.test(result)) {
668
+ extraCaps = { 'appium:bundleId': vars.bundleIdentifier ?? 'com.experitest.ExperiBank', ...(extraCaps ?? {}) };
669
+ }
670
+ }
671
+ if (extraCaps)
672
+ result = injectCapabilities(result, language, !!vars.isAppiumOss, extraCaps);
604
673
  return result;
605
674
  }
606
675
  /**
@@ -612,7 +681,7 @@ function parallelNote(language, isAppiumOss) {
612
681
  const cap = 'Check the project\'s concurrency limit first (get_project_admin_settings → maxDevelopmentLicense) and that enough matching devices are free (find_available_device): a worker that finds no device waits for newSessionWaitTimeout and then fails.';
613
682
  switch (language) {
614
683
  case 'python':
615
- return `Each test method has its own setUp/tearDown session — no code changes needed. pip install pytest-xdist, then: pytest -n auto -v (one worker per test). ${cap}`;
684
+ return `Each test method has its own setUp/tearDown session — no code changes needed. pip install pytest-xdist, then: pytest -n auto -v <test file>.py (name the file — pytest only collects test_*.py on its own; one worker per test). ${cap}`;
616
685
  case 'java-junit5':
617
686
  return `Each @Test has its own @BeforeEach/@AfterEach session. Enable JUnit 5 parallelism with src/test/resources/junit-platform.properties: junit.jupiter.execution.parallel.enabled=true, junit.jupiter.execution.parallel.mode.default=concurrent, junit.jupiter.execution.parallel.config.strategy=fixed, junit.jupiter.execution.parallel.config.fixed.parallelism=<workers>. Never make the driver static. ${cap}`;
618
687
  case 'java-testng':
@@ -683,21 +752,24 @@ function setupNote(language, isAppiumOss, projectType, emitted = []) {
683
752
  ' session request; wdio v8+ sends W3C capabilities only. The package.json above pins wdio v7.40.0, the last\n' +
684
753
  ' release that still sends them (verified live: v9 refused, v7.40 runs). Appium Server projects use wdio v9.');
685
754
  }
686
- case 'python':
755
+ case 'python': {
756
+ // pytest collects only test_*.py / *_test.py on its own; the generated module is AndroidNative.py / iOSNative.py,
757
+ // so a bare "python -m pytest" ran nothing ("no tests ran", found live 2026-11-12). Name the file.
758
+ const py = emitted.find((e) => e.endsWith('.py')) ?? '<test file>.py';
687
759
  return isAppiumOss
688
- ? 'Install the dependency with: pip install -r requirements.txt (Appium-Python-Client>=4.0.0), then run: python -m pytest\n\n' +
760
+ ? `Install the dependency with: pip install -r requirements.txt (Appium-Python-Client ~=6.0), then run: python -m pytest ${py}\n\n` +
689
761
  'Waits: every step goes through find(), an explicit WebDriverWait — there is no implicit wait, and adding one would make every miss wait both timeouts.\n\n' +
690
762
  'Parallel execution (recommended on device farms — each test gets its own device):\n' +
691
763
  ' pip install pytest-xdist\n' +
692
- ' pytest -n auto -v # spawns one worker per test method; each creates its own Appium session'
764
+ ` pytest -n auto -v ${py} # spawns one worker per test method; each creates its own Appium session`
693
765
  : '⚠️ APPIUM GRID (LEGACY): This project uses Appium Grid — a legacy Digital.ai framework\n' +
694
766
  'that predates the W3C WebDriver standard. It is NOT the same as standard Appium Server.\n' +
695
767
  'All workarounds below exist because of this protocol difference, not Python version conflicts.\n\n' +
696
768
  'Install: pip install -r requirements.txt (appium-python-client==2.2.0 + selenium==4.9.0)\n' +
697
- 'Run: python -m pytest\n\n' +
769
+ `Run: python -m pytest ${py}\n\n` +
698
770
  'Parallel execution (recommended — each test method gets its own device from the farm pool):\n' +
699
771
  ' pip install pytest-xdist\n' +
700
- ' pytest -n auto -v # safe: each worker process creates its own setUp/tearDown session\n' +
772
+ ` pytest -n auto -v ${py} # safe: each worker process creates its own setUp/tearDown session\n` +
701
773
  ' Check project concurrency limits first: get_project_admin_settings → maxDevelopmentLicense\n\n' +
702
774
  'Protocol requirements (Appium Grid only):\n' +
703
775
  ' • desired_capabilities= dict (JWP format) — W3C options= triggers grid rejection\n' +
@@ -706,6 +778,7 @@ function setupNote(language, isAppiumOss, projectType, emitted = []) {
706
778
  ' • Use appium.webdriver.webelement.WebElement (not selenium\'s) for is_displayed()\n\n' +
707
779
  'If you can migrate this project to Appium Server, all of these workarounds go away.\n' +
708
780
  'Error "Cant run Appium Grid with Appium client 8+" = W3C format rejected by grid (not a version issue).';
781
+ }
709
782
  case 'robot':
710
783
  return ('Save the files in this layout:\n' +
711
784
  ' requirements.txt ← project root\n' +
@@ -714,8 +787,7 @@ function setupNote(language, isAppiumOss, projectType, emitted = []) {
714
787
  'Then run:\n' +
715
788
  ' pip install -r requirements.txt (robotframework 7.5 + robotframework-appiumlibrary 3.2.1)\n' +
716
789
  ' robot --outputdir results tests/\n\n' +
717
- 'The access key is read from DIGITAL_AI_ACCESS_KEY when set; the value after "=" in ${ACCESS_KEY} is the fallback — ' +
718
- 'remove it before committing. The Test Teardown sets the platform report to Passed / Failed / Skipped from Robot\'s ' +
790
+ 'Set DIGITAL_AI_ACCESS_KEY first — the suite reads the access key from it and stops if it is missing. The Test Teardown sets the platform report to Passed / Failed / Skipped from Robot\'s ' +
719
791
  'own result, and the steps run inside a named steps group. Run suites in parallel with pabot (pip install robotframework-pabot).');
720
792
  }
721
793
  }
@@ -831,10 +903,10 @@ export function registerBoilerplateTools(server) {
831
903
  'steps with guided placeholder comments — because element IDs are app-specific and cannot be pre-filled. ' +
832
904
  'Recommended for any real app.'),
833
905
  deviceCategory: z
834
- .enum(['PHONE', 'TABLET'])
906
+ .enum(['PHONE', 'TABLET', 'FOLDABLE'])
835
907
  .optional()
836
908
  .default('PHONE')
837
- .describe("Device form factor to target: 'PHONE' (default) or 'TABLET'."),
909
+ .describe("Device form factor to target: 'PHONE' (default), 'TABLET' or 'FOLDABLE' (platform 26.10+; foldables are not in PHONE)."),
838
910
  testName: z
839
911
  .string()
840
912
  .optional()
@@ -847,7 +919,10 @@ export function registerBoilerplateTools(server) {
847
919
  mainActivity: z
848
920
  .string()
849
921
  .optional()
850
- .describe('(Android only) Main activity, e.g. .MainActivity or com.mycompany.app.MainActivity. Pre-fills the appActivity capability. Requires packageName.'),
922
+ .describe('(Android only) Main activity, e.g. .MainActivity or com.mycompany.app.MainActivity. Pre-fills the appActivity capability. Requires packageName. ' +
923
+ 'If the app shows a splash or login activity before the one Appium waits for, add appWaitActivity to the generated ' +
924
+ 'capabilities (the real activity, a comma list, or "*"). A WRONG appWaitActivity fails the session start with an ' +
925
+ 'opaque "The Appium server failed to respond" / "Could not forward request" (seen live) — check it first when that appears.'),
851
926
  bundleIdentifier: z
852
927
  .string()
853
928
  .optional()
@@ -918,7 +993,8 @@ export function registerBoilerplateTools(server) {
918
993
  .optional()
919
994
  .describe('Appium Server projects only: pin the Appium version the session runs on (digitalai:appiumVersion). Omit to use ' +
920
995
  'the platform default. An unavailable version fails the session at start with the list of versions the platform ' +
921
- 'offers. Not combinable with includeAxeScan, which pins 2.16.2 itself.'),
996
+ 'offers. 3.8.1 (platform 26.9+) needs iOS 17+ — on iOS 15/16 the session fails after about a minute with ' +
997
+ '"DeviceOSVersionTooLow"; use 3.8.0 there. Not combinable with includeAxeScan, which pins 2.16.2 itself.'),
922
998
  newSessionWaitTimeout: z
923
999
  .number()
924
1000
  .int()
@@ -935,6 +1011,42 @@ export function registerBoilerplateTools(server) {
935
1011
  .describe('Custom report keys, e.g. {"runId": "nightly-42", "build": "1.4.0"}. Each is sent as a digitalai:<key> capability and ' +
936
1012
  'stored on the platform report — find the runs later with list_test_reports filter [{property: "runId", operator: "=", ' +
937
1013
  'value: "nightly-42"}] (and keys: ["runId"] to see the value). Works on Appium Server and Appium Grid.'),
1014
+ appReset: z
1015
+ .enum(['reinstall', 'keep-data'])
1016
+ .optional()
1017
+ .describe('Appium Server projects only. "reinstall" (default — what the templates do): the test names the app ' +
1018
+ '(app: cloud:…) and the platform uninstalls and reinstalls it at EVERY session start, so each test starts ' +
1019
+ 'with clean app data — noReset cannot change that. "keep-data": the app capability is dropped and the ' +
1020
+ 'ALREADY-INSTALLED app is launched by package / bundle id with appium:noReset=true, so logins and settings ' +
1021
+ 'from the previous test survive; install it first (install_application, or one "reinstall" run). ' +
1022
+ 'fullReset is forced to false by the platform; there is no separate "clear data" mode — reinstall already clears it.'),
1023
+ deviceLanguage: z
1024
+ .string()
1025
+ .regex(DEVICE_LANGUAGE_RE, 'Use language_COUNTRY, e.g. "en_US", "fr_FR", "de_DE".')
1026
+ .optional()
1027
+ .describe('Appium Server projects only: pin the language the app runs in, e.g. "en_US", so a shared device someone left ' +
1028
+ 'in French does not break text-based locators. iOS: applies to the app under test only (appium:language + ' +
1029
+ 'appium:locale; the next session is back to the device language). ANDROID: changes the WHOLE DEVICE and the ' +
1030
+ 'change PERSISTS after the test (verified live) — on shared devices pin the language you expect, usually ' +
1031
+ 'en_US, and pin it back after a localisation run.'),
1032
+ autoAcceptAlerts: z
1033
+ .boolean()
1034
+ .optional()
1035
+ .describe('iOS, Appium Server projects only — opt in: appium:autoAcceptAlerts accepts every native alert as it appears ' +
1036
+ '(permission prompts, JavaScript alerts). Convenient for flows that are not ABOUT the alert, but it also hides ' +
1037
+ 'alerts the test should check, so it is off by default. The Android templates already dismiss alerts ' +
1038
+ '(autoDismissAlerts) and grant permissions (autoGrantPermissions).'),
1039
+ platformOptions: z
1040
+ .strictObject({
1041
+ releaseDevice: z.boolean().optional(),
1042
+ reservationDuration: z.number().int().min(1).max(1440).optional(),
1043
+ devicePool: z.enum(['shared', 'dedicated', 'any']).optional(),
1044
+ commandScreenshot: z.boolean().optional(),
1045
+ dontGoHomeOnQuit: z.boolean().optional(),
1046
+ })
1047
+ .optional()
1048
+ .describe('Appium Server projects only: Digital.ai session options, each sent as digitalai:<name>. ' +
1049
+ Object.entries(PLATFORM_OPTION_DESCRIPTIONS).map(([k, v]) => `${k}: ${v}`).join('. ') + '.'),
938
1050
  automotiveProjection: z
939
1051
  .enum(AUTOMOTIVE_RESOLUTIONS)
940
1052
  .optional()
@@ -971,7 +1083,7 @@ export function registerBoilerplateTools(server) {
971
1083
  .describe('Orchestrated projects only: run.maxRetryAttempts in the agent config. Default 2 — or 0 when the test body is ' +
972
1084
  'a placeholder (fails by design) or includePerformanceTransactions is set (retries would skew samples).'),
973
1085
  outputFormat: outputFormatParam,
974
- }, async ({ platform, language, appId, deviceCategory, testName, packageName, mainActivity, bundleIdentifier, structure, projectType, region, includePerformanceTransactions, includeAxeScan, reportStatus, appiumVersion, newSessionWaitTimeout, reportKeys, automotiveProjection, confirmSelectorsVerified, orchestration, orchestrationMaxRetries, outputFormat }) => {
1086
+ }, async ({ platform, language, appId, deviceCategory, testName, packageName, mainActivity, bundleIdentifier, structure, projectType, region, includePerformanceTransactions, includeAxeScan, reportStatus, appiumVersion, newSessionWaitTimeout, reportKeys, appReset, deviceLanguage, autoAcceptAlerts, platformOptions, automotiveProjection, confirmSelectorsVerified, orchestration, orchestrationMaxRetries, outputFormat }) => {
975
1087
  // ── Inspection gate (v42) ────────────────────────────────────────────────
976
1088
  // Advisory guards (warning text, a requiresVerifiedSelectors flag, an in-code
977
1089
  // fail() guard) all lost to task-completion momentum: the agent stripped the
@@ -1014,10 +1126,8 @@ export function registerBoilerplateTools(server) {
1014
1126
  ].join('\n');
1015
1127
  return { ...respond(outputFormat, blocked, human), isError: true };
1016
1128
  }
1017
- // Active-profile accessors (not process.env) — generated boilerplate must
1018
- // embed the active profile's credential, not the default profile's. With
1019
- // env vars, switching to a project profile still embedded the admin credential.
1020
- const accessKey = getActiveAccessKey();
1129
+ // Active-profile accessor (not process.env) — the generated files point at the active profile's cloud. No access
1130
+ // key is read here: generated files never carry one (src/utils/credential-env.ts).
1021
1131
  const rawBaseUrl = getActiveUrl();
1022
1132
  let instanceHost = rawBaseUrl;
1023
1133
  try {
@@ -1080,6 +1190,39 @@ export function registerBoilerplateTools(server) {
1080
1190
  extraCaps['digitalai:newSessionWaitTimeout'] = newSessionWaitTimeout;
1081
1191
  for (const [k, v] of Object.entries(reportKeys ?? {}))
1082
1192
  extraCaps[`digitalai:${k}`] = v;
1193
+ // Session options verified on Appium Server only (2026-11-12) — a Grid project gets the classic output with a note.
1194
+ const serverOnly = [
1195
+ appReset === 'keep-data' && 'appReset',
1196
+ deviceLanguage && 'deviceLanguage',
1197
+ autoAcceptAlerts && 'autoAcceptAlerts',
1198
+ platformOptions && Object.keys(platformOptions).length > 0 && 'platformOptions',
1199
+ ].filter(Boolean);
1200
+ const keepAppData = isAppiumOss && appReset === 'keep-data';
1201
+ if (!isAppiumOss && serverOnly.length) {
1202
+ capNotes.push(`${serverOnly.join(', ')} ignored: verified on Appium Server projects only, and this project runs on Appium Grid.`);
1203
+ }
1204
+ else {
1205
+ if (keepAppData) {
1206
+ extraCaps['appium:noReset'] = true;
1207
+ capNotes.push('appReset keep-data: the app capability is removed and the INSTALLED app is launched with noReset — install it on the devices first (install_application), or the launch fails.');
1208
+ }
1209
+ if (deviceLanguage) {
1210
+ Object.assign(extraCaps, languageCaps(platform, deviceLanguage));
1211
+ if (platform === 'android')
1212
+ capNotes.push(`deviceLanguage ${deviceLanguage}: on Android this changes the whole device and stays after the test — on shared devices pin back to the usual language afterwards.`);
1213
+ }
1214
+ if (autoAcceptAlerts) {
1215
+ if (platform === 'ios')
1216
+ extraCaps['appium:autoAcceptAlerts'] = true;
1217
+ else
1218
+ capNotes.push('autoAcceptAlerts ignored on Android: the template already sets autoDismissAlerts and autoGrantPermissions.');
1219
+ }
1220
+ for (const [k, v] of Object.entries(platformOptions ?? {}))
1221
+ if (v !== undefined)
1222
+ extraCaps[`digitalai:${k}`] = v;
1223
+ if (platformOptions?.releaseDevice === false)
1224
+ capNotes.push('releaseDevice false: the shared device stays reserved after the test — the last test of the sequence should set it true, or release it with release_device.');
1225
+ }
1083
1226
  if (reportKeys && Object.keys(reportKeys).length > 0) {
1084
1227
  const [k, v] = Object.entries(reportKeys)[0];
1085
1228
  capNotes.push(`Report keys set (${Object.keys(reportKeys).join(', ')}). Find these runs with list_test_reports filter [{"property":"${k}","operator":"=","value":"${v}"}], keys ["${k}"].`);
@@ -1124,7 +1267,6 @@ export function registerBoilerplateTools(server) {
1124
1267
  : 'structure: "page-objects" needs an Appium Server project for Java (java-client 11 / Selenium 4); this Grid project is generated flat.')
1125
1268
  : undefined;
1126
1269
  const vars = {
1127
- accessKey,
1128
1270
  instanceUrl: rawBaseUrl,
1129
1271
  instanceHost,
1130
1272
  testName,
@@ -1141,6 +1283,7 @@ export function registerBoilerplateTools(server) {
1141
1283
  automotiveProjection: automotive?.applied ? automotive.resolution : undefined,
1142
1284
  reportStatus: reportStatus !== false,
1143
1285
  extraCaps,
1286
+ keepAppData,
1144
1287
  pageObjects: pageObjectsApplied,
1145
1288
  };
1146
1289
  const files = getFilesForVariant(platform, language, isAppiumOss, projectType, pageObjectsApplied ? 'page-objects' : 'flat', clearTestBody);
@@ -1250,7 +1393,7 @@ export function registerBoilerplateTools(server) {
1250
1393
  serverModeNote: isAppiumOss
1251
1394
  ? 'Appium Server (OSS) — standard W3C WebDriver protocol. ' +
1252
1395
  'Java: java-client 11.x + selenium-java 4.51 (Java 17+), UiAutomator2Options/XCUITestOptions, AppiumBy, URI.create(...).toURL() (no DesiredCapabilities, no MobileBy). ' +
1253
- 'Python: appium-python-client 4.x+, AppiumOptions. ' +
1396
+ 'Python: Appium-Python-Client 6.x, UiAutomator2Options / XCUITestOptions. ' +
1254
1397
  'If you need Grid mode, switch to a Grid-enabled profile and regenerate — the APIs are incompatible.'
1255
1398
  : 'Appium Grid (legacy) — Digital.ai JWP-era protocol, NOT standard Appium Server. ' +
1256
1399
  'Java: java-client 7.6.0, Java 8+, DesiredCapabilities + AndroidElement. ' +
@@ -1266,14 +1409,14 @@ export function registerBoilerplateTools(server) {
1266
1409
  projectType: projectType ?? 'standalone-gradle',
1267
1410
  structure: pageObjectsApplied ? 'page-objects' : 'flat',
1268
1411
  ...(structureNote ? { structureNote } : {}),
1269
- files: resolved.map(f => ({ filename: f.filename, content: f.content })),
1412
+ files: [...resolved.map(f => ({ filename: f.filename, content: f.content })), ENV_EXAMPLE_FILE],
1270
1413
  orchestration: orchestrationInfo,
1271
1414
  ...(automotive ? { automotive } : {}),
1272
1415
  ...(capNotes.length ? { capabilityNotes: capNotes } : {}),
1273
1416
  setupNote: setupNote(language, isAppiumOss, projectType, resolved.filter((f) => !f.isInstructions).map((f) => f.filename)),
1274
1417
  appNote: appNote(platform, vars.packageName, vars.bundleIdentifier, vars.mainActivity, resolvedFromAppId),
1275
1418
  parallelNote: parallelNote(language, isAppiumOss),
1276
- credentialWarning: '⚠️ SECURITY: The access key embedded in these files is a live credential. Move it to an environment variable (DIGITAL_AI_ACCESS_KEY) and reference it from code before committing to source control.',
1419
+ credentialSetup: CREDENTIAL_SETUP,
1277
1420
  // v38: when a custom app is targeted the test body is a placeholder, NOT a finished test.
1278
1421
  requiresVerifiedSelectors: clearTestBody,
1279
1422
  ...(clearTestBody && {
@@ -1300,7 +1443,7 @@ export function registerBoilerplateTools(server) {
1300
1443
  `> **Setup:** ${setupNote(language, isAppiumOss, projectType, resolved.filter((f) => !f.isInstructions).map((f) => f.filename))}`,
1301
1444
  `> **App:** ${appNote(platform, vars.packageName, vars.bundleIdentifier, vars.mainActivity, resolvedFromAppId)}`,
1302
1445
  `> **Device query:** ${regionLabel}${region ? '' : ' — re-call with region=<value> from find_available_device to scope to healthy devices only.'}`,
1303
- `> ⚠️ **Security:** These files contain a live credential — move the access key to an environment variable (\`DIGITAL_AI_ACCESS_KEY\`) before committing to source control.`,
1446
+ `> ${CREDENTIAL_SETUP_TEXT}`,
1304
1447
  '',
1305
1448
  ];
1306
1449
  if (orchestrationInfo.enabled && orchestrationInfo.agent) {
@@ -1497,8 +1640,8 @@ export function registerBoilerplateTools(server) {
1497
1640
  'When shadowDomSupport is enabled, a shadowQuery() helper is included for interacting with elements ' +
1498
1641
  'inside Shadow DOM trees (React, Angular, Web Components).', {
1499
1642
  language: z
1500
- .enum(['java-junit5', 'java-testng', 'nodejs', 'python', 'robot'])
1501
- .describe('Target language and test framework. "robot" = Robot Framework + SeleniumLibrary (no shadowQuery helper; Opera unsupported).'),
1643
+ .enum(['java-junit5', 'java-testng', 'nodejs', 'python', 'robot', 'playwright'])
1644
+ .describe('Target language and test framework. "robot" = Robot Framework + SeleniumLibrary (no shadowQuery helper; Opera unsupported). "playwright" = Playwright Test driving Chrome or Edge on the Digital.ai Selenium agent (EXPERIMENTAL platform feature; verified with @playwright/test 1.65.0 — the cloud report shows Passed even when a test fails, trust the Playwright report). For firefox/webkit or cloud-side runs use execute_playwright_run.'),
1502
1645
  testName: z
1503
1646
  .string()
1504
1647
  .optional()
@@ -1527,9 +1670,16 @@ export function registerBoilerplateTools(server) {
1527
1670
  .describe('Set to true when CSS selectors were captured from a live browser inspection session ' +
1528
1671
  '(get_page_dom / find_web_elements) or authoritative source. Required when url is provided and no ' +
1529
1672
  'live browser session exists.'),
1673
+ acceptInsecureCerts: z
1674
+ .boolean()
1675
+ .optional()
1676
+ .describe('Add the W3C acceptInsecureCerts capability so the test can open a site with a self-signed, expired or ' +
1677
+ 'untrusted-CA certificate (staging/dev). Verified on Chrome, Firefox, MicrosoftEdge and Safari. Omit for ' +
1678
+ 'sites with a valid certificate.'),
1530
1679
  outputFormat: outputFormatParam,
1531
1680
  }, async (args) => {
1532
1681
  const language = args.language;
1682
+ const insecure = args.acceptInsecureCerts === true;
1533
1683
  const testName = args.testName ?? 'WebTest';
1534
1684
  const targetUrl = args.url ?? '';
1535
1685
  // The grid matches browserName case-sensitively: "microsoftedge" → 400 "No browser found matching the desired
@@ -1563,7 +1713,7 @@ export function registerBoilerplateTools(server) {
1563
1713
  return { ...respond(args.outputFormat, structured, structured.message), isError: true };
1564
1714
  }
1565
1715
  }
1566
- const accessKey = getActiveAccessKey() || '[Enter Your Access key here]';
1716
+ // No access key in any generated file — every template reads DIGITAL_AI_ACCESS_KEY (src/utils/credential-env.ts).
1567
1717
  const baseUrl = getActiveUrl() || '[Enter Instance here]';
1568
1718
  const gridUrl = `${baseUrl}/wd/hub`;
1569
1719
  // Decide whether to include shadow DOM helper.
@@ -1634,6 +1784,15 @@ export function registerBoilerplateTools(server) {
1634
1784
  `${indent}${c} self.find(By.ID, "<id from get_page_dom>").click() # find() waits up to 20 s — never add sleeps`,
1635
1785
  ].join('\n');
1636
1786
  }
1787
+ else if (lang === 'playwright') {
1788
+ examples = [
1789
+ `${indent}${c} Example shape — replace <…> with selectors from get_page_dom / find_web_elements:`,
1790
+ `${indent}${c} await page.goto(${nav});`,
1791
+ `${indent}${c} await page.locator('<CSS selector from find_web_elements>').click();`,
1792
+ `${indent}${c} await page.locator("input[name='<name attr>']").fill('<value>');`,
1793
+ `${indent}${c} await expect(page.locator('#<id from get_page_dom>')).toBeVisible(); // auto-waits — never add sleeps`,
1794
+ ].join('\n');
1795
+ }
1637
1796
  else {
1638
1797
  examples = [
1639
1798
  `${indent}${c} Example shape — replace <…> with selectors from get_page_dom / find_web_elements:`,
@@ -1761,7 +1920,7 @@ export function registerBoilerplateTools(server) {
1761
1920
  ``,
1762
1921
  ` private RemoteWebDriver driver;`,
1763
1922
  ``,
1764
- ` private static final String ACCESS_KEY = "${accessKey}";`,
1923
+ ` private static final String ACCESS_KEY = ${JAVA_KEY_EXPR};`,
1765
1924
  ` private static final String GRID_URL = "${gridUrl}";`,
1766
1925
  ``,
1767
1926
  ` ${beforeAnn}`,
@@ -1769,6 +1928,7 @@ export function registerBoilerplateTools(server) {
1769
1928
  `${browserCap}`,
1770
1929
  ` caps.setCapability("digitalai:accessKey", ACCESS_KEY);`,
1771
1930
  ` caps.setCapability("digitalai:testName", "${testName}");`,
1931
+ ...(insecure ? [` caps.setCapability("acceptInsecureCerts", true); // site uses a self-signed/untrusted certificate`] : []),
1772
1932
  ``,
1773
1933
  ` driver = new RemoteWebDriver(new URL(GRID_URL), caps);`,
1774
1934
  ` driver.manage().window().maximize();`,
@@ -1830,7 +1990,9 @@ export function registerBoilerplateTools(server) {
1830
1990
  files: [
1831
1991
  { filename, language: 'java', content: code },
1832
1992
  { filename: 'pom.xml', language: 'xml', content: pom },
1993
+ ENV_EXAMPLE_FILE,
1833
1994
  ],
1995
+ credentialSetup: CREDENTIAL_SETUP,
1834
1996
  guidance: [
1835
1997
  'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
1836
1998
  'Set BROWSER=chrome (or firefox/MicrosoftEdge/safari) in your environment to choose the browser at runtime.',
@@ -1839,6 +2001,7 @@ export function registerBoilerplateTools(server) {
1839
2001
  ].filter(Boolean),
1840
2002
  };
1841
2003
  const humanText = [
2004
+ CREDENTIAL_SETUP_TEXT,
1842
2005
  `Generated: ${filename}`,
1843
2006
  `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
1844
2007
  includeShadowHelper ? 'Shadow DOM helper: included' : '',
@@ -1879,7 +2042,7 @@ export function registerBoilerplateTools(server) {
1879
2042
  ``,
1880
2043
  `class ${testClass}(unittest.TestCase):`,
1881
2044
  ``,
1882
- ` ACCESS_KEY = "${accessKey}"`,
2045
+ ` ACCESS_KEY = ${PYTHON_KEY_EXPR}`,
1883
2046
  ` GRID_URL = "${gridUrl}"`,
1884
2047
  ``,
1885
2048
  ` def setUp(self):`,
@@ -1887,6 +2050,7 @@ export function registerBoilerplateTools(server) {
1887
2050
  ` ${browserCap}`,
1888
2051
  ` caps["digitalai:accessKey"] = self.ACCESS_KEY`,
1889
2052
  ` caps["digitalai:testName"] = "${testName}"`,
2053
+ ...(insecure ? [` caps["acceptInsecureCerts"] = True # site uses a self-signed/untrusted certificate`] : []),
1890
2054
  ``,
1891
2055
  ` # Selenium 4.10+ removed desired_capabilities — capabilities go through an Options object.`,
1892
2056
  ` options = ArgOptions()`,
@@ -1922,7 +2086,9 @@ export function registerBoilerplateTools(server) {
1922
2086
  files: [
1923
2087
  { filename, language: 'python', content: code },
1924
2088
  { filename: 'requirements.txt', language: 'text', content: requirements },
2089
+ ENV_EXAMPLE_FILE,
1925
2090
  ],
2091
+ credentialSetup: CREDENTIAL_SETUP,
1926
2092
  guidance: [
1927
2093
  'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
1928
2094
  'Set BROWSER=chrome (or firefox / MicrosoftEdge / safari / opera) in your environment.',
@@ -1930,6 +2096,7 @@ export function registerBoilerplateTools(server) {
1930
2096
  ],
1931
2097
  };
1932
2098
  const humanText = [
2099
+ CREDENTIAL_SETUP_TEXT,
1933
2100
  `Generated: ${filename}`,
1934
2101
  `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
1935
2102
  ``,
@@ -1963,8 +2130,8 @@ export function registerBoilerplateTools(server) {
1963
2130
  ``,
1964
2131
  `*** Variables ***`,
1965
2132
  `\${GRID_URL} ${gridUrl}`,
1966
- `# The DIGITAL_AI_ACCESS_KEY environment variable wins; the value after "=" is the fallback. Remove it before committing.`,
1967
- `\${ACCESS_KEY} %{DIGITAL_AI_ACCESS_KEY=${accessKey}}`,
2133
+ `# The access key comes from the DIGITAL_AI_ACCESS_KEY environment variable (Robot stops if it is not set).`,
2134
+ `\${ACCESS_KEY} ${ROBOT_KEY_EXPR}`,
1968
2135
  slBrowser
1969
2136
  ? `\${BROWSER} ${slBrowser}`
1970
2137
  : `# BROWSER-NEUTRAL: set BROWSER=chrome / firefox / edge / safari (SeleniumLibrary names) at run time.\n\${BROWSER} %{BROWSER=chrome}`,
@@ -1979,7 +2146,7 @@ export function registerBoilerplateTools(server) {
1979
2146
  `*** Keywords ***`,
1980
2147
  `Open Cloud Browser`,
1981
2148
  ` Open Browser about:blank \${BROWSER} remote_url=\${GRID_URL}`,
1982
- ` ... options=set_capability("digitalai:accessKey", "\${ACCESS_KEY}");set_capability("digitalai:testName", "\${TEST_NAME}")`,
2149
+ ` ... options=set_capability("digitalai:accessKey", "\${ACCESS_KEY}");set_capability("digitalai:testName", "\${TEST_NAME}")${insecure ? ';set_capability("acceptInsecureCerts", True)' : ''}`,
1983
2150
  ``,
1984
2151
  `Close Cloud Browser`,
1985
2152
  ` # Report the real outcome: without this a failed step or assertion can still show as Passed in the platform report.`,
@@ -1997,7 +2164,9 @@ export function registerBoilerplateTools(server) {
1997
2164
  { filename: suiteFile, language: 'robotframework', content: suite },
1998
2165
  { filename: 'tests/DigitalAiWebReport.py', language: 'python', content: library },
1999
2166
  { filename: 'requirements.txt', language: 'text', content: requirements },
2167
+ ENV_EXAMPLE_FILE,
2000
2168
  ],
2169
+ credentialSetup: CREDENTIAL_SETUP,
2001
2170
  guidance: [
2002
2171
  'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
2003
2172
  'pip install -r requirements.txt, then robot --outputdir results tests/',
@@ -2006,6 +2175,7 @@ export function registerBoilerplateTools(server) {
2006
2175
  ],
2007
2176
  };
2008
2177
  const humanText = [
2178
+ CREDENTIAL_SETUP_TEXT,
2009
2179
  `Generated: ${suiteFile}, tests/DigitalAiWebReport.py, requirements.txt`,
2010
2180
  `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
2011
2181
  '',
@@ -2017,6 +2187,109 @@ export function registerBoilerplateTools(server) {
2017
2187
  ].join('\n');
2018
2188
  return respond(args.outputFormat, structured, humanText);
2019
2189
  }
2190
+ // Playwright on the Selenium agent (EXPERIMENTAL platform feature — Chrome and Edge only). Verified live
2191
+ // 2026-11-12 with @playwright/test 1.65.0 against Chrome 158 / Edge 157: SELENIUM_REMOTE_URL +
2192
+ // SELENIUM_REMOTE_CAPABILITIES ('digitalai:options': { accessKey, testName }) runs the tests with no local
2193
+ // browser; the documented connectOptions.wsEndpoint = <cloud>/wd/hub fails (Playwright looks for its own server
2194
+ // and gets a 404 on /wd/hub/json). The cloud keeps ONE report per worker session, Passed even when a test failed.
2195
+ if (language === 'playwright') {
2196
+ if (targetBrowser && targetBrowser !== 'chrome' && targetBrowser !== 'MicrosoftEdge') {
2197
+ return { content: [{ type: 'text', text: `Error: Playwright on the Digital.ai Selenium agent drives chrome or MicrosoftEdge only (got ${targetBrowser}). For firefox/webkit run the project in the cloud's Playwright containers with execute_playwright_run.` }], isError: true };
2198
+ }
2199
+ const specFile = `tests/${testName.replace(/[^\w-]/g, '_')}.spec.js`;
2200
+ const placeholder = webPlaceholderBody(language, ' ', targetUrl);
2201
+ // Two targets from one config: the Selenium agent (default; key required) or Playwright's own browsers — inside
2202
+ // the Playwright container execute_playwright_run uses (Microsoft's image sets PLAYWRIGHT_BROWSERS_PATH; there is
2203
+ // no key there) or locally with DIGITAL_AI_PLAYWRIGHT_TARGET=local. Before this, the agent-only config would
2204
+ // throw for the missing key / reach for the Selenium agent from inside the container (Playwright-Issues #9).
2205
+ const pwConfig = [
2206
+ `// playwright.config.js — two targets:`,
2207
+ `// • Digital.ai Selenium agent (default; EXPERIMENTAL platform feature): Chrome or Edge in the cloud, driven from`,
2208
+ `// this machine — npx playwright test, no local browser. Needs ${ACCESS_KEY_ENV}; DIGITAL_AI_CLOUD_URL and`,
2209
+ `// BROWSER (chrome | MicrosoftEdge) override the defaults below.`,
2210
+ `// • Playwright's own browsers (chromium, firefox, webkit): automatically inside the Playwright container that`,
2211
+ `// execute_playwright_run uploads this project to, or locally with DIGITAL_AI_PLAYWRIGHT_TARGET=local.`,
2212
+ `const { defineConfig, devices } = require('@playwright/test');`,
2213
+ ``,
2214
+ `const IN_PLAYWRIGHT_CONTAINER = !!process.env.PLAYWRIGHT_BROWSERS_PATH; // set by Microsoft's Playwright image`,
2215
+ `const ON_SELENIUM_AGENT = !IN_PLAYWRIGHT_CONTAINER && process.env.DIGITAL_AI_PLAYWRIGHT_TARGET !== 'local';`,
2216
+ `const BROWSER = process.env.BROWSER || '${targetBrowser ?? 'chrome'}';`,
2217
+ ``,
2218
+ `if (ON_SELENIUM_AGENT) {`,
2219
+ ` ${JS_KEY_GUARD}`,
2220
+ ` const CLOUD_URL = process.env.DIGITAL_AI_CLOUD_URL || '${baseUrl}';`,
2221
+ ` const ACCESS_KEY = ${JS_KEY_EXPR};`,
2222
+ ` // Playwright launches Chromium-family browsers on a Selenium Grid when these are set (read by every worker).`,
2223
+ ` process.env.SELENIUM_REMOTE_URL = \`\${CLOUD_URL}/wd/hub\`;`,
2224
+ ` process.env.SELENIUM_REMOTE_CAPABILITIES = JSON.stringify({`,
2225
+ ` browserName: BROWSER,`,
2226
+ ` 'digitalai:options': { accessKey: ACCESS_KEY, testName: '${testName}' },`,
2227
+ ...(insecure ? [` acceptInsecureCerts: true, // site uses a self-signed/untrusted certificate`] : []),
2228
+ ` });`,
2229
+ `}`,
2230
+ ``,
2231
+ `module.exports = defineConfig({`,
2232
+ ` testDir: './tests',`,
2233
+ ` timeout: 60_000,`,
2234
+ ` reporter: [['list'], ['html', { open: 'never' }]],`,
2235
+ ` use: { trace: 'retain-on-failure'${insecure ? ', ignoreHTTPSErrors: true' : ''} },`,
2236
+ ` projects: ON_SELENIUM_AGENT`,
2237
+ ` ? [BROWSER === 'MicrosoftEdge'`,
2238
+ ` ? { name: 'edge', use: { ...devices['Desktop Edge'], channel: 'msedge' } }`,
2239
+ ` : { name: 'chrome', use: { ...devices['Desktop Chrome'], channel: 'chrome' } }]`,
2240
+ ` : [`,
2241
+ ` { name: 'chromium', use: { ...devices['Desktop Chrome'] } },`,
2242
+ ` { name: 'firefox', use: { ...devices['Desktop Firefox'] } },`,
2243
+ ` { name: 'webkit', use: { ...devices['Desktop Safari'] } },`,
2244
+ ` ],`,
2245
+ `});`,
2246
+ ].join('\n');
2247
+ code = [
2248
+ `// ${specFile}`,
2249
+ `const { test, expect } = require('@playwright/test');`,
2250
+ ``,
2251
+ `test('${testName}', async ({ page }) => {`,
2252
+ placeholder,
2253
+ `});`,
2254
+ ].join('\n');
2255
+ const pkg = JSON.stringify({ scripts: { test: 'playwright test' }, devDependencies: { '@playwright/test': '1.65.0' } }, null, 2);
2256
+ const guidance = [
2257
+ 'EXPERIMENTAL platform feature: Playwright drives Chrome or Edge on the Digital.ai Selenium agent.',
2258
+ 'npm install, then npx playwright test — no "npx playwright install" needed (the browser runs in the cloud).',
2259
+ 'The Digital.ai report is one record per browser session and shows Passed even when a test failed — the Playwright list/HTML report is the source of truth.',
2260
+ 'Keep @playwright/test close to the cloud browser version (Playwright talks CDP); 1.65.0 was verified against Chrome 158 and Edge 157.',
2261
+ 'The same project runs with execute_playwright_run too: inside the Playwright container the config switches to chromium, firefox and webkit and needs no key. Locally, DIGITAL_AI_PLAYWRIGHT_TARGET=local does the same (after npx playwright install).',
2262
+ 'Replace the placeholder with selectors from get_page_dom / find_web_elements. Playwright CSS locators pierce shadow DOM on their own.',
2263
+ ];
2264
+ const structured = {
2265
+ language,
2266
+ testName,
2267
+ targetBrowser: targetBrowser ?? 'chrome (BROWSER env var: chrome | MicrosoftEdge)',
2268
+ experimental: true,
2269
+ files: [
2270
+ { filename: 'playwright.config.js', language: 'javascript', content: pwConfig },
2271
+ { filename: specFile, language: 'javascript', content: code },
2272
+ { filename: 'package.json', language: 'json', content: pkg },
2273
+ ENV_EXAMPLE_FILE,
2274
+ ],
2275
+ credentialSetup: CREDENTIAL_SETUP,
2276
+ guidance,
2277
+ };
2278
+ const humanText = [
2279
+ CREDENTIAL_SETUP_TEXT,
2280
+ `Generated: playwright.config.js, ${specFile}, package.json (Playwright → Digital.ai Selenium agent, EXPERIMENTAL)`,
2281
+ ...guidance.map((g) => `• ${g}`),
2282
+ '',
2283
+ '```javascript',
2284
+ pwConfig,
2285
+ '```',
2286
+ '',
2287
+ '```javascript',
2288
+ code,
2289
+ '```',
2290
+ ].join('\n');
2291
+ return respond(args.outputFormat, structured, humanText);
2292
+ }
2020
2293
  // Node.js / WebdriverIO
2021
2294
  filename = `test.${testName.toLowerCase()}.js`;
2022
2295
  const shadowHelper = includeShadowHelper ? '\n\n' + shadowHelperNodejs() : '';
@@ -2029,6 +2302,7 @@ export function registerBoilerplateTools(server) {
2029
2302
  ].join('\n ');
2030
2303
  const wdioConf = [
2031
2304
  `// wdio.conf.js — Digital.ai Selenium Grid configuration`,
2305
+ JS_KEY_GUARD,
2032
2306
  `exports.config = {`,
2033
2307
  ` hostname: '${baseUrl.replace(/^https?:\/\//, '')}',`,
2034
2308
  ` path: '/wd/hub',`,
@@ -2036,8 +2310,9 @@ export function registerBoilerplateTools(server) {
2036
2310
  ` protocol: 'https',`,
2037
2311
  ` capabilities: [{`,
2038
2312
  ` ${browserCapNode},`,
2039
- ` 'digitalai:accessKey': '${accessKey}',`,
2313
+ ` 'digitalai:accessKey': ${JS_KEY_EXPR},`,
2040
2314
  ` 'digitalai:testName': '${testName}',`,
2315
+ ...(insecure ? [` acceptInsecureCerts: true, // site uses a self-signed/untrusted certificate`] : []),
2041
2316
  ` }],`,
2042
2317
  ` framework: 'mocha',`,
2043
2318
  ` reporters: ['spec'],`,
@@ -2065,7 +2340,9 @@ export function registerBoilerplateTools(server) {
2065
2340
  { filename: 'wdio.conf.js', language: 'javascript', content: wdioConf },
2066
2341
  { filename, language: 'javascript', content: code },
2067
2342
  { filename: 'package.json', language: 'json', content: JSON.stringify({ scripts: { test: 'npx wdio run wdio.conf.js' }, devDependencies: { '@wdio/cli': '^8.0.0', '@wdio/local-runner': '^8.0.0', '@wdio/mocha-framework': '^8.0.0', '@wdio/spec-reporter': '^8.0.0' } }, null, 2) },
2343
+ ENV_EXAMPLE_FILE,
2068
2344
  ],
2345
+ credentialSetup: CREDENTIAL_SETUP,
2069
2346
  guidance: [
2070
2347
  'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
2071
2348
  'Set BROWSER=chrome (or firefox/MicrosoftEdge/safari) in your environment.',
@@ -2073,6 +2350,7 @@ export function registerBoilerplateTools(server) {
2073
2350
  ],
2074
2351
  };
2075
2352
  const humanText = [
2353
+ CREDENTIAL_SETUP_TEXT,
2076
2354
  `Generated: ${filename}`,
2077
2355
  `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
2078
2356
  ``,