digital-ai-testing-mcp 2.2.1 → 2.3.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 (97) hide show
  1. package/README.md +28 -16
  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-runs.d.ts +5 -0
  22. package/dist/api/test-runs.d.ts.map +1 -1
  23. package/dist/api/test-runs.js.map +1 -1
  24. package/dist/api/webdriver.d.ts +23 -2
  25. package/dist/api/webdriver.d.ts.map +1 -1
  26. package/dist/api/webdriver.js +142 -13
  27. package/dist/api/webdriver.js.map +1 -1
  28. package/dist/index.js +1 -1
  29. package/dist/tools/boilerplate-tools.d.ts +22 -0
  30. package/dist/tools/boilerplate-tools.d.ts.map +1 -1
  31. package/dist/tools/boilerplate-tools.js +323 -44
  32. package/dist/tools/boilerplate-tools.js.map +1 -1
  33. package/dist/tools/device-group-tools.js +2 -2
  34. package/dist/tools/device-group-tools.js.map +1 -1
  35. package/dist/tools/device-tools.js +3 -3
  36. package/dist/tools/device-tools.js.map +1 -1
  37. package/dist/tools/inspection-tools.d.ts +24 -0
  38. package/dist/tools/inspection-tools.d.ts.map +1 -1
  39. package/dist/tools/inspection-tools.js +129 -13
  40. package/dist/tools/inspection-tools.js.map +1 -1
  41. package/dist/tools/meta-tools.d.ts +1 -1
  42. package/dist/tools/meta-tools.d.ts.map +1 -1
  43. package/dist/tools/meta-tools.js +3 -2
  44. package/dist/tools/meta-tools.js.map +1 -1
  45. package/dist/tools/prompt-tools.d.ts.map +1 -1
  46. package/dist/tools/prompt-tools.js +4 -0
  47. package/dist/tools/prompt-tools.js.map +1 -1
  48. package/dist/tools/reporting-tools.d.ts.map +1 -1
  49. package/dist/tools/reporting-tools.js +27 -8
  50. package/dist/tools/reporting-tools.js.map +1 -1
  51. package/dist/tools/repository-tools.d.ts.map +1 -1
  52. package/dist/tools/repository-tools.js +5 -3
  53. package/dist/tools/repository-tools.js.map +1 -1
  54. package/dist/tools/test-run-tools.d.ts.map +1 -1
  55. package/dist/tools/test-run-tools.js +107 -6
  56. package/dist/tools/test-run-tools.js.map +1 -1
  57. package/dist/tools/usage-report-tools.d.ts.map +1 -1
  58. package/dist/tools/usage-report-tools.js +6 -4
  59. package/dist/tools/usage-report-tools.js.map +1 -1
  60. package/dist/tools/web-inspection-tools.d.ts.map +1 -1
  61. package/dist/tools/web-inspection-tools.js +116 -13
  62. package/dist/tools/web-inspection-tools.js.map +1 -1
  63. package/dist/types/digital-ai.d.ts +6 -1
  64. package/dist/types/digital-ai.d.ts.map +1 -1
  65. package/dist/utils/adb-shell.d.ts +25 -0
  66. package/dist/utils/adb-shell.d.ts.map +1 -0
  67. package/dist/utils/adb-shell.js +87 -0
  68. package/dist/utils/adb-shell.js.map +1 -0
  69. package/dist/utils/credential-env.d.ts +36 -0
  70. package/dist/utils/credential-env.d.ts.map +1 -0
  71. package/dist/utils/credential-env.js +57 -0
  72. package/dist/utils/credential-env.js.map +1 -0
  73. package/dist/utils/failure-triage.d.ts +13 -0
  74. package/dist/utils/failure-triage.d.ts.map +1 -0
  75. package/dist/utils/failure-triage.js +53 -0
  76. package/dist/utils/failure-triage.js.map +1 -0
  77. package/dist/utils/locator-recommend.d.ts +27 -0
  78. package/dist/utils/locator-recommend.d.ts.map +1 -0
  79. package/dist/utils/locator-recommend.js +59 -0
  80. package/dist/utils/locator-recommend.js.map +1 -0
  81. package/dist/utils/response-formatter.d.ts +8 -0
  82. package/dist/utils/response-formatter.d.ts.map +1 -1
  83. package/dist/utils/response-formatter.js +26 -0
  84. package/dist/utils/response-formatter.js.map +1 -1
  85. package/dist/utils/usage-report-summary.d.ts +2 -0
  86. package/dist/utils/usage-report-summary.d.ts.map +1 -1
  87. package/dist/utils/usage-report-summary.js +5 -1
  88. package/dist/utils/usage-report-summary.js.map +1 -1
  89. package/package.json +13 -6
  90. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio-oss.conf.js +1 -0
  91. package/resources/boilerplate/Android-Native/Python/AndroidNative-oss.py +3 -2
  92. package/resources/boilerplate/Android-Native/Python/pip-oss +1 -1
  93. package/resources/boilerplate/Android-Native/Robot Framework/AndroidNative-oss.robot +1 -1
  94. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio-oss.conf.js +1 -0
  95. package/resources/boilerplate/iOS-Native/Python/iOSNative-oss.py +3 -2
  96. package/resources/boilerplate/iOS-Native/Python/pip-oss.txt +1 -1
  97. 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)), '..', '..');
@@ -157,7 +158,8 @@ export function detectFabricationIssues(content) {
157
158
  if (sleeps)
158
159
  add('warn', 'fixed sleeps', `${sleeps.length} fixed sleep(s) (${[...new Set(sleeps.map((x) => x.trim()))].slice(0, 3).join(', ')}). Replace with an explicit wait on the element the next step needs (WebDriverWait / waitForDisplayed / Wait Until Element Is Visible).`);
159
160
  // Only XPath literals (quoted, or Robot's xpath=…) — a bare `//` would also match every Java/JS line comment with [N].
160
- const indexXpath = content.match(/(?<=['"`]|xpath=)\/\/[^'"`\n]*\[\d+\][^'"`\n]*/g);
161
+ // `\(*` also catches the grouped form "(//android.widget.EditText)[1]" (remediation 2026-10-19).
162
+ const indexXpath = content.match(/(?<=['"`]|xpath=)\(*\/\/[^'"`\n]*\[\d+\][^'"`\n]*/g);
161
163
  if (indexXpath)
162
164
  add('warn', 'index-based XPath', `Positional XPath (${[...new Set(indexXpath)].slice(0, 3).join(', ')}) breaks when siblings move or a header appears. Prefer accessibility id / resource-id, then an attribute match (@text, @label, @content-desc).`);
163
165
  const sharedDriver = content.match(/\bstatic\s+(?:final\s+)?(?:Android|IOS|Appium|Remote|Web)Driver\b[^\n;]*\bdriver\b|@Before(?:All|Suite|Class)\b[\s\S]{0,400}?driver\s*=\s*new\s+(?:Android|IOS|Appium)Driver|def setUpClass[\s\S]{0,400}?webdriver\.Remote\(/g);
@@ -301,6 +303,11 @@ function wrapWithReporting(language, indent, core, isAppiumOss) {
301
303
  // The Grid parses arguments out of the script string, so a 0-arg command is written inline there.
302
304
  isAppiumOss ? `${indent} driver.executeScript("seetest:client.stopStepsGroup");` : `${indent} driver.executeScript("seetest:client.stopStepsGroup()");`,
303
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;`,
304
311
  `${indent}} catch (RuntimeException | AssertionError e) {`,
305
312
  `${indent} try { driver.executeScript("seetest:client.setReportStatus", "Failed", String.valueOf(e.getMessage())); } catch (RuntimeException ignored) {}`,
306
313
  `${indent} throw e;`,
@@ -315,6 +322,12 @@ function wrapWithReporting(language, indent, core, isAppiumOss) {
315
322
  inner,
316
323
  isAppiumOss ? `${indent} self.driver.execute_script("seetest:client.stopStepsGroup")` : `${indent} self.driver.execute_script("seetest:client.stopStepsGroup()")`,
317
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`,
318
331
  `${indent}except Exception as e:`,
319
332
  `${indent} try:`,
320
333
  `${indent} self.driver.execute_script("seetest:client.setReportStatus", "Failed", str(e)[:500])`,
@@ -331,7 +344,9 @@ function wrapWithReporting(language, indent, core, isAppiumOss) {
331
344
  isAppiumOss ? `${indent} await browser.execute('seetest:client.stopStepsGroup');` : `${indent} await browser.execute('seetest:client.stopStepsGroup()');`,
332
345
  `${indent} await browser.execute('seetest:client.setReportStatus', 'Passed', 'All steps completed');`,
333
346
  `${indent}} catch (e) {`,
334
- `${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(() => {});`,
335
350
  `${indent} throw e;`,
336
351
  `${indent}}`,
337
352
  ].join('\n');
@@ -347,7 +362,36 @@ export const REPORT_KEY_VALUE_RE = /^(?=.{1,100}$)[A-Za-z0-9_.:/@+-]+(?: [A-Za-z
347
362
  export const RESERVED_REPORT_KEYS = new Set([
348
363
  'accessKey', 'testName', 'deviceQuery', 'appiumVersion', 'newSessionWaitTimeout', 'automotiveProjection',
349
364
  'instrumentCluster', 'instrumentApp', 'reportTestId', 'reportUrl', 'releaseDevice', 'report.disable',
365
+ 'reservationDuration', 'devicePool', 'commandScreenshot', 'dontGoHomeOnQuit',
350
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
+ };
351
395
  /**
352
396
  * Add capabilities next to the existing ones, for every language and both server modes (the same anchors the Axe
353
397
  * option uses: the driver construction line for Java/Python, the deviceQuery entry in the wdio config for Node).
@@ -357,14 +401,16 @@ function injectCapabilities(content, language, isAppiumOss, caps) {
357
401
  const entries = Object.entries(caps);
358
402
  if (entries.length === 0)
359
403
  return content;
360
- 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}`;
361
406
  if (language === 'robot') {
362
- // &{CAPABILITIES} dictionary rows; numbers as ${n} so Robot passes an int, not a string.
363
- 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(''));
364
410
  }
365
411
  if (language === 'java-junit5' || language === 'java-testng') {
366
412
  const obj = isAppiumOss ? 'options' : 'dc';
367
- 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}`);
368
414
  }
369
415
  if (language === 'python') {
370
416
  const viaOptions = content.includes('options=options');
@@ -458,6 +504,11 @@ function buildPlaceholder(language, platform, indent, isAppiumOss = true, pageOb
458
504
  `${indent}${c} const btn = await find('id=<resource-id from get_element_tree>'); await btn.click();`,
459
505
  `${indent}${c} const field = await find('id=<resource-id>'); await field.setValue('<value>');`,
460
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>') });`] : []),
461
512
  ];
462
513
  }
463
514
  else {
@@ -541,8 +592,17 @@ function substitute(content, language, platform, vars) {
541
592
  result = result.replace(/\n[^\S\n]*(?:\/\/|#) \[END_DEMO_STEPS\]/, '');
542
593
  }
543
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);
544
605
  result = result
545
- .replaceAll('[Enter Your Access key here]', vars.accessKey)
546
606
  .replaceAll('[Enter Instance here]', vars.instanceUrl)
547
607
  .replaceAll('[Enter Instance HOST here]', vars.instanceHost)
548
608
  .replaceAll('[Enter Test Name here]', vars.testName)
@@ -560,13 +620,13 @@ function substitute(content, language, platform, vars) {
560
620
  }
561
621
  if (vars.region) {
562
622
  // Append region to the deviceQuery — fires after the PHONE/TABLET substitution has already run.
563
- 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}'`);
564
624
  }
565
625
  if (vars.axeScan) {
566
626
  const automationName = platform === 'android' ? 'AxeUiAutomator2' : 'AxeXCUITest';
567
627
  if (language === 'java-junit5' || language === 'java-testng') {
568
628
  const obj = vars.isAppiumOss ? 'options' : 'dc';
569
- 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` +
570
630
  `${sp}${obj}.setCapability("${vars.isAppiumOss ? 'digitalai:appiumVersion' : 'appiumVersion'}", "2.16.2");\n` +
571
631
  `${sp}${line}`);
572
632
  }
@@ -583,13 +643,15 @@ function substitute(content, language, platform, vars) {
583
643
  }
584
644
  }
585
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)',/, '');
586
648
  result = result.replace(/('digitalai:deviceQuery': [^\n]+)/, (match) => `${match}\n 'appium:automationName': '${automationName}',\n '${vars.isAppiumOss ? 'digitalai:appiumVersion' : 'appiumVersion'}': '2.16.2',`);
587
649
  }
588
650
  }
589
651
  if (vars.automotiveProjection) {
590
652
  const res = vars.automotiveProjection;
591
653
  if (language === 'java-junit5' || language === 'java-testng') {
592
- 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}`);
593
655
  }
594
656
  else if (language === 'python') {
595
657
  result = result.replace(/\n( +)(self\.driver = webdriver\.Remote\()/, (_m, sp, line) => `\n${sp}options.set_capability('digitalai:automotiveProjection', '${res}')\n${sp}${line}`);
@@ -598,8 +660,16 @@ function substitute(content, language, platform, vars) {
598
660
  result = result.replace(/('digitalai:deviceQuery': [^\n]+)/, (match) => `${match}\n 'digitalai:automotiveProjection': '${res}',`);
599
661
  }
600
662
  }
601
- if (vars.extraCaps)
602
- 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);
603
673
  return result;
604
674
  }
605
675
  /**
@@ -611,7 +681,7 @@ function parallelNote(language, isAppiumOss) {
611
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.';
612
682
  switch (language) {
613
683
  case 'python':
614
- 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}`;
615
685
  case 'java-junit5':
616
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}`;
617
687
  case 'java-testng':
@@ -682,21 +752,24 @@ function setupNote(language, isAppiumOss, projectType, emitted = []) {
682
752
  ' session request; wdio v8+ sends W3C capabilities only. The package.json above pins wdio v7.40.0, the last\n' +
683
753
  ' release that still sends them (verified live: v9 refused, v7.40 runs). Appium Server projects use wdio v9.');
684
754
  }
685
- 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';
686
759
  return isAppiumOss
687
- ? '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` +
688
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' +
689
762
  'Parallel execution (recommended on device farms — each test gets its own device):\n' +
690
763
  ' pip install pytest-xdist\n' +
691
- ' 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`
692
765
  : '⚠️ APPIUM GRID (LEGACY): This project uses Appium Grid — a legacy Digital.ai framework\n' +
693
766
  'that predates the W3C WebDriver standard. It is NOT the same as standard Appium Server.\n' +
694
767
  'All workarounds below exist because of this protocol difference, not Python version conflicts.\n\n' +
695
768
  'Install: pip install -r requirements.txt (appium-python-client==2.2.0 + selenium==4.9.0)\n' +
696
- 'Run: python -m pytest\n\n' +
769
+ `Run: python -m pytest ${py}\n\n` +
697
770
  'Parallel execution (recommended — each test method gets its own device from the farm pool):\n' +
698
771
  ' pip install pytest-xdist\n' +
699
- ' 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` +
700
773
  ' Check project concurrency limits first: get_project_admin_settings → maxDevelopmentLicense\n\n' +
701
774
  'Protocol requirements (Appium Grid only):\n' +
702
775
  ' • desired_capabilities= dict (JWP format) — W3C options= triggers grid rejection\n' +
@@ -705,6 +778,7 @@ function setupNote(language, isAppiumOss, projectType, emitted = []) {
705
778
  ' • Use appium.webdriver.webelement.WebElement (not selenium\'s) for is_displayed()\n\n' +
706
779
  'If you can migrate this project to Appium Server, all of these workarounds go away.\n' +
707
780
  'Error "Cant run Appium Grid with Appium client 8+" = W3C format rejected by grid (not a version issue).';
781
+ }
708
782
  case 'robot':
709
783
  return ('Save the files in this layout:\n' +
710
784
  ' requirements.txt ← project root\n' +
@@ -713,8 +787,7 @@ function setupNote(language, isAppiumOss, projectType, emitted = []) {
713
787
  'Then run:\n' +
714
788
  ' pip install -r requirements.txt (robotframework 7.5 + robotframework-appiumlibrary 3.2.1)\n' +
715
789
  ' robot --outputdir results tests/\n\n' +
716
- 'The access key is read from DIGITAL_AI_ACCESS_KEY when set; the value after "=" in ${ACCESS_KEY} is the fallback — ' +
717
- '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 ' +
718
791
  'own result, and the steps run inside a named steps group. Run suites in parallel with pabot (pip install robotframework-pabot).');
719
792
  }
720
793
  }
@@ -830,10 +903,10 @@ export function registerBoilerplateTools(server) {
830
903
  'steps with guided placeholder comments — because element IDs are app-specific and cannot be pre-filled. ' +
831
904
  'Recommended for any real app.'),
832
905
  deviceCategory: z
833
- .enum(['PHONE', 'TABLET'])
906
+ .enum(['PHONE', 'TABLET', 'FOLDABLE'])
834
907
  .optional()
835
908
  .default('PHONE')
836
- .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)."),
837
910
  testName: z
838
911
  .string()
839
912
  .optional()
@@ -846,7 +919,10 @@ export function registerBoilerplateTools(server) {
846
919
  mainActivity: z
847
920
  .string()
848
921
  .optional()
849
- .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.'),
850
926
  bundleIdentifier: z
851
927
  .string()
852
928
  .optional()
@@ -917,7 +993,8 @@ export function registerBoilerplateTools(server) {
917
993
  .optional()
918
994
  .describe('Appium Server projects only: pin the Appium version the session runs on (digitalai:appiumVersion). Omit to use ' +
919
995
  'the platform default. An unavailable version fails the session at start with the list of versions the platform ' +
920
- '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.'),
921
998
  newSessionWaitTimeout: z
922
999
  .number()
923
1000
  .int()
@@ -934,6 +1011,42 @@ export function registerBoilerplateTools(server) {
934
1011
  .describe('Custom report keys, e.g. {"runId": "nightly-42", "build": "1.4.0"}. Each is sent as a digitalai:<key> capability and ' +
935
1012
  'stored on the platform report — find the runs later with list_test_reports filter [{property: "runId", operator: "=", ' +
936
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('. ') + '.'),
937
1050
  automotiveProjection: z
938
1051
  .enum(AUTOMOTIVE_RESOLUTIONS)
939
1052
  .optional()
@@ -970,7 +1083,7 @@ export function registerBoilerplateTools(server) {
970
1083
  .describe('Orchestrated projects only: run.maxRetryAttempts in the agent config. Default 2 — or 0 when the test body is ' +
971
1084
  'a placeholder (fails by design) or includePerformanceTransactions is set (retries would skew samples).'),
972
1085
  outputFormat: outputFormatParam,
973
- }, 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 }) => {
974
1087
  // ── Inspection gate (v42) ────────────────────────────────────────────────
975
1088
  // Advisory guards (warning text, a requiresVerifiedSelectors flag, an in-code
976
1089
  // fail() guard) all lost to task-completion momentum: the agent stripped the
@@ -1013,10 +1126,8 @@ export function registerBoilerplateTools(server) {
1013
1126
  ].join('\n');
1014
1127
  return { ...respond(outputFormat, blocked, human), isError: true };
1015
1128
  }
1016
- // Active-profile accessors (not process.env) — generated boilerplate must
1017
- // embed the active profile's credential, not the default profile's. With
1018
- // env vars, switching to a project profile still embedded the admin credential.
1019
- 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).
1020
1131
  const rawBaseUrl = getActiveUrl();
1021
1132
  let instanceHost = rawBaseUrl;
1022
1133
  try {
@@ -1079,6 +1190,39 @@ export function registerBoilerplateTools(server) {
1079
1190
  extraCaps['digitalai:newSessionWaitTimeout'] = newSessionWaitTimeout;
1080
1191
  for (const [k, v] of Object.entries(reportKeys ?? {}))
1081
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
+ }
1082
1226
  if (reportKeys && Object.keys(reportKeys).length > 0) {
1083
1227
  const [k, v] = Object.entries(reportKeys)[0];
1084
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}"].`);
@@ -1123,7 +1267,6 @@ export function registerBoilerplateTools(server) {
1123
1267
  : 'structure: "page-objects" needs an Appium Server project for Java (java-client 11 / Selenium 4); this Grid project is generated flat.')
1124
1268
  : undefined;
1125
1269
  const vars = {
1126
- accessKey,
1127
1270
  instanceUrl: rawBaseUrl,
1128
1271
  instanceHost,
1129
1272
  testName,
@@ -1140,6 +1283,7 @@ export function registerBoilerplateTools(server) {
1140
1283
  automotiveProjection: automotive?.applied ? automotive.resolution : undefined,
1141
1284
  reportStatus: reportStatus !== false,
1142
1285
  extraCaps,
1286
+ keepAppData,
1143
1287
  pageObjects: pageObjectsApplied,
1144
1288
  };
1145
1289
  const files = getFilesForVariant(platform, language, isAppiumOss, projectType, pageObjectsApplied ? 'page-objects' : 'flat', clearTestBody);
@@ -1249,7 +1393,7 @@ export function registerBoilerplateTools(server) {
1249
1393
  serverModeNote: isAppiumOss
1250
1394
  ? 'Appium Server (OSS) — standard W3C WebDriver protocol. ' +
1251
1395
  'Java: java-client 11.x + selenium-java 4.51 (Java 17+), UiAutomator2Options/XCUITestOptions, AppiumBy, URI.create(...).toURL() (no DesiredCapabilities, no MobileBy). ' +
1252
- 'Python: appium-python-client 4.x+, AppiumOptions. ' +
1396
+ 'Python: Appium-Python-Client 6.x, UiAutomator2Options / XCUITestOptions. ' +
1253
1397
  'If you need Grid mode, switch to a Grid-enabled profile and regenerate — the APIs are incompatible.'
1254
1398
  : 'Appium Grid (legacy) — Digital.ai JWP-era protocol, NOT standard Appium Server. ' +
1255
1399
  'Java: java-client 7.6.0, Java 8+, DesiredCapabilities + AndroidElement. ' +
@@ -1265,14 +1409,14 @@ export function registerBoilerplateTools(server) {
1265
1409
  projectType: projectType ?? 'standalone-gradle',
1266
1410
  structure: pageObjectsApplied ? 'page-objects' : 'flat',
1267
1411
  ...(structureNote ? { structureNote } : {}),
1268
- files: resolved.map(f => ({ filename: f.filename, content: f.content })),
1412
+ files: [...resolved.map(f => ({ filename: f.filename, content: f.content })), ENV_EXAMPLE_FILE],
1269
1413
  orchestration: orchestrationInfo,
1270
1414
  ...(automotive ? { automotive } : {}),
1271
1415
  ...(capNotes.length ? { capabilityNotes: capNotes } : {}),
1272
1416
  setupNote: setupNote(language, isAppiumOss, projectType, resolved.filter((f) => !f.isInstructions).map((f) => f.filename)),
1273
1417
  appNote: appNote(platform, vars.packageName, vars.bundleIdentifier, vars.mainActivity, resolvedFromAppId),
1274
1418
  parallelNote: parallelNote(language, isAppiumOss),
1275
- 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,
1276
1420
  // v38: when a custom app is targeted the test body is a placeholder, NOT a finished test.
1277
1421
  requiresVerifiedSelectors: clearTestBody,
1278
1422
  ...(clearTestBody && {
@@ -1299,7 +1443,7 @@ export function registerBoilerplateTools(server) {
1299
1443
  `> **Setup:** ${setupNote(language, isAppiumOss, projectType, resolved.filter((f) => !f.isInstructions).map((f) => f.filename))}`,
1300
1444
  `> **App:** ${appNote(platform, vars.packageName, vars.bundleIdentifier, vars.mainActivity, resolvedFromAppId)}`,
1301
1445
  `> **Device query:** ${regionLabel}${region ? '' : ' — re-call with region=<value> from find_available_device to scope to healthy devices only.'}`,
1302
- `> ⚠️ **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}`,
1303
1447
  '',
1304
1448
  ];
1305
1449
  if (orchestrationInfo.enabled && orchestrationInfo.agent) {
@@ -1496,8 +1640,8 @@ export function registerBoilerplateTools(server) {
1496
1640
  'When shadowDomSupport is enabled, a shadowQuery() helper is included for interacting with elements ' +
1497
1641
  'inside Shadow DOM trees (React, Angular, Web Components).', {
1498
1642
  language: z
1499
- .enum(['java-junit5', 'java-testng', 'nodejs', 'python', 'robot'])
1500
- .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.'),
1501
1645
  testName: z
1502
1646
  .string()
1503
1647
  .optional()
@@ -1526,9 +1670,16 @@ export function registerBoilerplateTools(server) {
1526
1670
  .describe('Set to true when CSS selectors were captured from a live browser inspection session ' +
1527
1671
  '(get_page_dom / find_web_elements) or authoritative source. Required when url is provided and no ' +
1528
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.'),
1529
1679
  outputFormat: outputFormatParam,
1530
1680
  }, async (args) => {
1531
1681
  const language = args.language;
1682
+ const insecure = args.acceptInsecureCerts === true;
1532
1683
  const testName = args.testName ?? 'WebTest';
1533
1684
  const targetUrl = args.url ?? '';
1534
1685
  // The grid matches browserName case-sensitively: "microsoftedge" → 400 "No browser found matching the desired
@@ -1562,7 +1713,7 @@ export function registerBoilerplateTools(server) {
1562
1713
  return { ...respond(args.outputFormat, structured, structured.message), isError: true };
1563
1714
  }
1564
1715
  }
1565
- 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).
1566
1717
  const baseUrl = getActiveUrl() || '[Enter Instance here]';
1567
1718
  const gridUrl = `${baseUrl}/wd/hub`;
1568
1719
  // Decide whether to include shadow DOM helper.
@@ -1633,6 +1784,15 @@ export function registerBoilerplateTools(server) {
1633
1784
  `${indent}${c} self.find(By.ID, "<id from get_page_dom>").click() # find() waits up to 20 s — never add sleeps`,
1634
1785
  ].join('\n');
1635
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
+ }
1636
1796
  else {
1637
1797
  examples = [
1638
1798
  `${indent}${c} Example shape — replace <…> with selectors from get_page_dom / find_web_elements:`,
@@ -1760,7 +1920,7 @@ export function registerBoilerplateTools(server) {
1760
1920
  ``,
1761
1921
  ` private RemoteWebDriver driver;`,
1762
1922
  ``,
1763
- ` private static final String ACCESS_KEY = "${accessKey}";`,
1923
+ ` private static final String ACCESS_KEY = ${JAVA_KEY_EXPR};`,
1764
1924
  ` private static final String GRID_URL = "${gridUrl}";`,
1765
1925
  ``,
1766
1926
  ` ${beforeAnn}`,
@@ -1768,6 +1928,7 @@ export function registerBoilerplateTools(server) {
1768
1928
  `${browserCap}`,
1769
1929
  ` caps.setCapability("digitalai:accessKey", ACCESS_KEY);`,
1770
1930
  ` caps.setCapability("digitalai:testName", "${testName}");`,
1931
+ ...(insecure ? [` caps.setCapability("acceptInsecureCerts", true); // site uses a self-signed/untrusted certificate`] : []),
1771
1932
  ``,
1772
1933
  ` driver = new RemoteWebDriver(new URL(GRID_URL), caps);`,
1773
1934
  ` driver.manage().window().maximize();`,
@@ -1829,7 +1990,9 @@ export function registerBoilerplateTools(server) {
1829
1990
  files: [
1830
1991
  { filename, language: 'java', content: code },
1831
1992
  { filename: 'pom.xml', language: 'xml', content: pom },
1993
+ ENV_EXAMPLE_FILE,
1832
1994
  ],
1995
+ credentialSetup: CREDENTIAL_SETUP,
1833
1996
  guidance: [
1834
1997
  'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
1835
1998
  'Set BROWSER=chrome (or firefox/MicrosoftEdge/safari) in your environment to choose the browser at runtime.',
@@ -1838,6 +2001,7 @@ export function registerBoilerplateTools(server) {
1838
2001
  ].filter(Boolean),
1839
2002
  };
1840
2003
  const humanText = [
2004
+ CREDENTIAL_SETUP_TEXT,
1841
2005
  `Generated: ${filename}`,
1842
2006
  `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
1843
2007
  includeShadowHelper ? 'Shadow DOM helper: included' : '',
@@ -1878,7 +2042,7 @@ export function registerBoilerplateTools(server) {
1878
2042
  ``,
1879
2043
  `class ${testClass}(unittest.TestCase):`,
1880
2044
  ``,
1881
- ` ACCESS_KEY = "${accessKey}"`,
2045
+ ` ACCESS_KEY = ${PYTHON_KEY_EXPR}`,
1882
2046
  ` GRID_URL = "${gridUrl}"`,
1883
2047
  ``,
1884
2048
  ` def setUp(self):`,
@@ -1886,6 +2050,7 @@ export function registerBoilerplateTools(server) {
1886
2050
  ` ${browserCap}`,
1887
2051
  ` caps["digitalai:accessKey"] = self.ACCESS_KEY`,
1888
2052
  ` caps["digitalai:testName"] = "${testName}"`,
2053
+ ...(insecure ? [` caps["acceptInsecureCerts"] = True # site uses a self-signed/untrusted certificate`] : []),
1889
2054
  ``,
1890
2055
  ` # Selenium 4.10+ removed desired_capabilities — capabilities go through an Options object.`,
1891
2056
  ` options = ArgOptions()`,
@@ -1921,7 +2086,9 @@ export function registerBoilerplateTools(server) {
1921
2086
  files: [
1922
2087
  { filename, language: 'python', content: code },
1923
2088
  { filename: 'requirements.txt', language: 'text', content: requirements },
2089
+ ENV_EXAMPLE_FILE,
1924
2090
  ],
2091
+ credentialSetup: CREDENTIAL_SETUP,
1925
2092
  guidance: [
1926
2093
  'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
1927
2094
  'Set BROWSER=chrome (or firefox / MicrosoftEdge / safari / opera) in your environment.',
@@ -1929,6 +2096,7 @@ export function registerBoilerplateTools(server) {
1929
2096
  ],
1930
2097
  };
1931
2098
  const humanText = [
2099
+ CREDENTIAL_SETUP_TEXT,
1932
2100
  `Generated: ${filename}`,
1933
2101
  `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
1934
2102
  ``,
@@ -1962,8 +2130,8 @@ export function registerBoilerplateTools(server) {
1962
2130
  ``,
1963
2131
  `*** Variables ***`,
1964
2132
  `\${GRID_URL} ${gridUrl}`,
1965
- `# The DIGITAL_AI_ACCESS_KEY environment variable wins; the value after "=" is the fallback. Remove it before committing.`,
1966
- `\${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}`,
1967
2135
  slBrowser
1968
2136
  ? `\${BROWSER} ${slBrowser}`
1969
2137
  : `# BROWSER-NEUTRAL: set BROWSER=chrome / firefox / edge / safari (SeleniumLibrary names) at run time.\n\${BROWSER} %{BROWSER=chrome}`,
@@ -1978,7 +2146,7 @@ export function registerBoilerplateTools(server) {
1978
2146
  `*** Keywords ***`,
1979
2147
  `Open Cloud Browser`,
1980
2148
  ` Open Browser about:blank \${BROWSER} remote_url=\${GRID_URL}`,
1981
- ` ... 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)' : ''}`,
1982
2150
  ``,
1983
2151
  `Close Cloud Browser`,
1984
2152
  ` # Report the real outcome: without this a failed step or assertion can still show as Passed in the platform report.`,
@@ -1996,7 +2164,9 @@ export function registerBoilerplateTools(server) {
1996
2164
  { filename: suiteFile, language: 'robotframework', content: suite },
1997
2165
  { filename: 'tests/DigitalAiWebReport.py', language: 'python', content: library },
1998
2166
  { filename: 'requirements.txt', language: 'text', content: requirements },
2167
+ ENV_EXAMPLE_FILE,
1999
2168
  ],
2169
+ credentialSetup: CREDENTIAL_SETUP,
2000
2170
  guidance: [
2001
2171
  'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
2002
2172
  'pip install -r requirements.txt, then robot --outputdir results tests/',
@@ -2005,6 +2175,7 @@ export function registerBoilerplateTools(server) {
2005
2175
  ],
2006
2176
  };
2007
2177
  const humanText = [
2178
+ CREDENTIAL_SETUP_TEXT,
2008
2179
  `Generated: ${suiteFile}, tests/DigitalAiWebReport.py, requirements.txt`,
2009
2180
  `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
2010
2181
  '',
@@ -2016,6 +2187,109 @@ export function registerBoilerplateTools(server) {
2016
2187
  ].join('\n');
2017
2188
  return respond(args.outputFormat, structured, humanText);
2018
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
+ }
2019
2293
  // Node.js / WebdriverIO
2020
2294
  filename = `test.${testName.toLowerCase()}.js`;
2021
2295
  const shadowHelper = includeShadowHelper ? '\n\n' + shadowHelperNodejs() : '';
@@ -2028,6 +2302,7 @@ export function registerBoilerplateTools(server) {
2028
2302
  ].join('\n ');
2029
2303
  const wdioConf = [
2030
2304
  `// wdio.conf.js — Digital.ai Selenium Grid configuration`,
2305
+ JS_KEY_GUARD,
2031
2306
  `exports.config = {`,
2032
2307
  ` hostname: '${baseUrl.replace(/^https?:\/\//, '')}',`,
2033
2308
  ` path: '/wd/hub',`,
@@ -2035,8 +2310,9 @@ export function registerBoilerplateTools(server) {
2035
2310
  ` protocol: 'https',`,
2036
2311
  ` capabilities: [{`,
2037
2312
  ` ${browserCapNode},`,
2038
- ` 'digitalai:accessKey': '${accessKey}',`,
2313
+ ` 'digitalai:accessKey': ${JS_KEY_EXPR},`,
2039
2314
  ` 'digitalai:testName': '${testName}',`,
2315
+ ...(insecure ? [` acceptInsecureCerts: true, // site uses a self-signed/untrusted certificate`] : []),
2040
2316
  ` }],`,
2041
2317
  ` framework: 'mocha',`,
2042
2318
  ` reporters: ['spec'],`,
@@ -2064,7 +2340,9 @@ export function registerBoilerplateTools(server) {
2064
2340
  { filename: 'wdio.conf.js', language: 'javascript', content: wdioConf },
2065
2341
  { filename, language: 'javascript', content: code },
2066
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,
2067
2344
  ],
2345
+ credentialSetup: CREDENTIAL_SETUP,
2068
2346
  guidance: [
2069
2347
  'Replace the placeholder test body with selectors from get_page_dom / find_web_elements.',
2070
2348
  'Set BROWSER=chrome (or firefox/MicrosoftEdge/safari) in your environment.',
@@ -2072,6 +2350,7 @@ export function registerBoilerplateTools(server) {
2072
2350
  ],
2073
2351
  };
2074
2352
  const humanText = [
2353
+ CREDENTIAL_SETUP_TEXT,
2075
2354
  `Generated: ${filename}`,
2076
2355
  `Browser: ${targetBrowser ?? 'neutral (BROWSER env var)'}`,
2077
2356
  ``,