digital-ai-testing-mcp 1.2.2
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.
- package/LICENSE +197 -0
- package/README.md +984 -0
- package/dist/api/agents.d.ts +5 -0
- package/dist/api/agents.d.ts.map +1 -0
- package/dist/api/agents.js +33 -0
- package/dist/api/agents.js.map +1 -0
- package/dist/api/applications.d.ts +35 -0
- package/dist/api/applications.d.ts.map +1 -0
- package/dist/api/applications.js +162 -0
- package/dist/api/applications.js.map +1 -0
- package/dist/api/backup.d.ts +4 -0
- package/dist/api/backup.d.ts.map +1 -0
- package/dist/api/backup.js +13 -0
- package/dist/api/backup.js.map +1 -0
- package/dist/api/browser-inspection.d.ts +33 -0
- package/dist/api/browser-inspection.d.ts.map +1 -0
- package/dist/api/browser-inspection.js +273 -0
- package/dist/api/browser-inspection.js.map +1 -0
- package/dist/api/browsers.d.ts +20 -0
- package/dist/api/browsers.d.ts.map +1 -0
- package/dist/api/browsers.js +31 -0
- package/dist/api/browsers.js.map +1 -0
- package/dist/api/client.d.ts +33 -0
- package/dist/api/client.d.ts.map +1 -0
- package/dist/api/client.js +200 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/device-groups.d.ts +15 -0
- package/dist/api/device-groups.d.ts.map +1 -0
- package/dist/api/device-groups.js +106 -0
- package/dist/api/device-groups.js.map +1 -0
- package/dist/api/devices.d.ts +32 -0
- package/dist/api/devices.d.ts.map +1 -0
- package/dist/api/devices.js +192 -0
- package/dist/api/devices.js.map +1 -0
- package/dist/api/license.d.ts +3 -0
- package/dist/api/license.d.ts.map +1 -0
- package/dist/api/license.js +11 -0
- package/dist/api/license.js.map +1 -0
- package/dist/api/nv-servers.d.ts +4 -0
- package/dist/api/nv-servers.d.ts.map +1 -0
- package/dist/api/nv-servers.js +20 -0
- package/dist/api/nv-servers.js.map +1 -0
- package/dist/api/projects.d.ts +36 -0
- package/dist/api/projects.d.ts.map +1 -0
- package/dist/api/projects.js +246 -0
- package/dist/api/projects.js.map +1 -0
- package/dist/api/provisioning-profiles.d.ts +7 -0
- package/dist/api/provisioning-profiles.d.ts.map +1 -0
- package/dist/api/provisioning-profiles.js +54 -0
- package/dist/api/provisioning-profiles.js.map +1 -0
- package/dist/api/regions.d.ts +4 -0
- package/dist/api/regions.d.ts.map +1 -0
- package/dist/api/regions.js +20 -0
- package/dist/api/regions.js.map +1 -0
- package/dist/api/reporter-projects.d.ts +3 -0
- package/dist/api/reporter-projects.d.ts.map +1 -0
- package/dist/api/reporter-projects.js +13 -0
- package/dist/api/reporter-projects.js.map +1 -0
- package/dist/api/reporting.d.ts +28 -0
- package/dist/api/reporting.d.ts.map +1 -0
- package/dist/api/reporting.js +340 -0
- package/dist/api/reporting.js.map +1 -0
- package/dist/api/repository.d.ts +17 -0
- package/dist/api/repository.d.ts.map +1 -0
- package/dist/api/repository.js +81 -0
- package/dist/api/repository.js.map +1 -0
- package/dist/api/reservations.d.ts +9 -0
- package/dist/api/reservations.d.ts.map +1 -0
- package/dist/api/reservations.js +72 -0
- package/dist/api/reservations.js.map +1 -0
- package/dist/api/sessions.d.ts +3 -0
- package/dist/api/sessions.d.ts.map +1 -0
- package/dist/api/sessions.js +12 -0
- package/dist/api/sessions.js.map +1 -0
- package/dist/api/test-views.d.ts +9 -0
- package/dist/api/test-views.d.ts.map +1 -0
- package/dist/api/test-views.js +77 -0
- package/dist/api/test-views.js.map +1 -0
- package/dist/api/transactions.d.ts +4 -0
- package/dist/api/transactions.d.ts.map +1 -0
- package/dist/api/transactions.js +28 -0
- package/dist/api/transactions.js.map +1 -0
- package/dist/api/usage-reports.d.ts +24 -0
- package/dist/api/usage-reports.d.ts.map +1 -0
- package/dist/api/usage-reports.js +47 -0
- package/dist/api/usage-reports.js.map +1 -0
- package/dist/api/users.d.ts +14 -0
- package/dist/api/users.d.ts.map +1 -0
- package/dist/api/users.js +77 -0
- package/dist/api/users.js.map +1 -0
- package/dist/api/webdriver.d.ts +97 -0
- package/dist/api/webdriver.d.ts.map +1 -0
- package/dist/api/webdriver.js +1183 -0
- package/dist/api/webdriver.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +130 -0
- package/dist/index.js.map +1 -0
- package/dist/tools/agent-tools.d.ts +3 -0
- package/dist/tools/agent-tools.d.ts.map +1 -0
- package/dist/tools/agent-tools.js +74 -0
- package/dist/tools/agent-tools.js.map +1 -0
- package/dist/tools/application-tools.d.ts +3 -0
- package/dist/tools/application-tools.d.ts.map +1 -0
- package/dist/tools/application-tools.js +816 -0
- package/dist/tools/application-tools.js.map +1 -0
- package/dist/tools/backup-tools.d.ts +3 -0
- package/dist/tools/backup-tools.d.ts.map +1 -0
- package/dist/tools/backup-tools.js +33 -0
- package/dist/tools/backup-tools.js.map +1 -0
- package/dist/tools/boilerplate-tools.d.ts +9 -0
- package/dist/tools/boilerplate-tools.d.ts.map +1 -0
- package/dist/tools/boilerplate-tools.js +1365 -0
- package/dist/tools/boilerplate-tools.js.map +1 -0
- package/dist/tools/browser-tools.d.ts +3 -0
- package/dist/tools/browser-tools.d.ts.map +1 -0
- package/dist/tools/browser-tools.js +108 -0
- package/dist/tools/browser-tools.js.map +1 -0
- package/dist/tools/coverage-tools.d.ts +3 -0
- package/dist/tools/coverage-tools.d.ts.map +1 -0
- package/dist/tools/coverage-tools.js +148 -0
- package/dist/tools/coverage-tools.js.map +1 -0
- package/dist/tools/debug-tools.d.ts +3 -0
- package/dist/tools/debug-tools.d.ts.map +1 -0
- package/dist/tools/debug-tools.js +315 -0
- package/dist/tools/debug-tools.js.map +1 -0
- package/dist/tools/device-group-tools.d.ts +3 -0
- package/dist/tools/device-group-tools.d.ts.map +1 -0
- package/dist/tools/device-group-tools.js +284 -0
- package/dist/tools/device-group-tools.js.map +1 -0
- package/dist/tools/device-tools.d.ts +3 -0
- package/dist/tools/device-tools.d.ts.map +1 -0
- package/dist/tools/device-tools.js +757 -0
- package/dist/tools/device-tools.js.map +1 -0
- package/dist/tools/health-tools.d.ts +3 -0
- package/dist/tools/health-tools.d.ts.map +1 -0
- package/dist/tools/health-tools.js +368 -0
- package/dist/tools/health-tools.js.map +1 -0
- package/dist/tools/inspection-tools.d.ts +3 -0
- package/dist/tools/inspection-tools.d.ts.map +1 -0
- package/dist/tools/inspection-tools.js +1170 -0
- package/dist/tools/inspection-tools.js.map +1 -0
- package/dist/tools/meta-tools.d.ts +4 -0
- package/dist/tools/meta-tools.d.ts.map +1 -0
- package/dist/tools/meta-tools.js +412 -0
- package/dist/tools/meta-tools.js.map +1 -0
- package/dist/tools/nv-server-tools.d.ts +3 -0
- package/dist/tools/nv-server-tools.d.ts.map +1 -0
- package/dist/tools/nv-server-tools.js +67 -0
- package/dist/tools/nv-server-tools.js.map +1 -0
- package/dist/tools/performance-tools.d.ts +3 -0
- package/dist/tools/performance-tools.d.ts.map +1 -0
- package/dist/tools/performance-tools.js +295 -0
- package/dist/tools/performance-tools.js.map +1 -0
- package/dist/tools/project-tools.d.ts +3 -0
- package/dist/tools/project-tools.d.ts.map +1 -0
- package/dist/tools/project-tools.js +577 -0
- package/dist/tools/project-tools.js.map +1 -0
- package/dist/tools/prompt-tools.d.ts +3 -0
- package/dist/tools/prompt-tools.d.ts.map +1 -0
- package/dist/tools/prompt-tools.js +570 -0
- package/dist/tools/prompt-tools.js.map +1 -0
- package/dist/tools/provisioning-profile-tools.d.ts +3 -0
- package/dist/tools/provisioning-profile-tools.d.ts.map +1 -0
- package/dist/tools/provisioning-profile-tools.js +169 -0
- package/dist/tools/provisioning-profile-tools.js.map +1 -0
- package/dist/tools/region-tools.d.ts +3 -0
- package/dist/tools/region-tools.d.ts.map +1 -0
- package/dist/tools/region-tools.js +46 -0
- package/dist/tools/region-tools.js.map +1 -0
- package/dist/tools/reporting-tools.d.ts +3 -0
- package/dist/tools/reporting-tools.d.ts.map +1 -0
- package/dist/tools/reporting-tools.js +1105 -0
- package/dist/tools/reporting-tools.js.map +1 -0
- package/dist/tools/repository-tools.d.ts +3 -0
- package/dist/tools/repository-tools.d.ts.map +1 -0
- package/dist/tools/repository-tools.js +208 -0
- package/dist/tools/repository-tools.js.map +1 -0
- package/dist/tools/reservation-tools.d.ts +3 -0
- package/dist/tools/reservation-tools.d.ts.map +1 -0
- package/dist/tools/reservation-tools.js +199 -0
- package/dist/tools/reservation-tools.js.map +1 -0
- package/dist/tools/resources.d.ts +3 -0
- package/dist/tools/resources.d.ts.map +1 -0
- package/dist/tools/resources.js +91 -0
- package/dist/tools/resources.js.map +1 -0
- package/dist/tools/test-view-tools.d.ts +3 -0
- package/dist/tools/test-view-tools.d.ts.map +1 -0
- package/dist/tools/test-view-tools.js +242 -0
- package/dist/tools/test-view-tools.js.map +1 -0
- package/dist/tools/transaction-tools.d.ts +3 -0
- package/dist/tools/transaction-tools.d.ts.map +1 -0
- package/dist/tools/transaction-tools.js +391 -0
- package/dist/tools/transaction-tools.js.map +1 -0
- package/dist/tools/usage-report-tools.d.ts +3 -0
- package/dist/tools/usage-report-tools.d.ts.map +1 -0
- package/dist/tools/usage-report-tools.js +160 -0
- package/dist/tools/usage-report-tools.js.map +1 -0
- package/dist/tools/user-tools.d.ts +3 -0
- package/dist/tools/user-tools.d.ts.map +1 -0
- package/dist/tools/user-tools.js +279 -0
- package/dist/tools/user-tools.js.map +1 -0
- package/dist/tools/web-inspection-tools.d.ts +3 -0
- package/dist/tools/web-inspection-tools.d.ts.map +1 -0
- package/dist/tools/web-inspection-tools.js +416 -0
- package/dist/tools/web-inspection-tools.js.map +1 -0
- package/dist/tools/workflow-tools.d.ts +3 -0
- package/dist/tools/workflow-tools.d.ts.map +1 -0
- package/dist/tools/workflow-tools.js +1136 -0
- package/dist/tools/workflow-tools.js.map +1 -0
- package/dist/types/digital-ai.d.ts +691 -0
- package/dist/types/digital-ai.d.ts.map +1 -0
- package/dist/types/digital-ai.js +3 -0
- package/dist/types/digital-ai.js.map +1 -0
- package/dist/utils/csv.d.ts +6 -0
- package/dist/utils/csv.d.ts.map +1 -0
- package/dist/utils/csv.js +77 -0
- package/dist/utils/csv.js.map +1 -0
- package/dist/utils/destructive-guard.d.ts +2 -0
- package/dist/utils/destructive-guard.d.ts.map +1 -0
- package/dist/utils/destructive-guard.js +13 -0
- package/dist/utils/destructive-guard.js.map +1 -0
- package/dist/utils/device-resolver.d.ts +22 -0
- package/dist/utils/device-resolver.d.ts.map +1 -0
- package/dist/utils/device-resolver.js +69 -0
- package/dist/utils/device-resolver.js.map +1 -0
- package/dist/utils/download-command.d.ts +18 -0
- package/dist/utils/download-command.d.ts.map +1 -0
- package/dist/utils/download-command.js +54 -0
- package/dist/utils/download-command.js.map +1 -0
- package/dist/utils/locality.d.ts +9 -0
- package/dist/utils/locality.d.ts.map +1 -0
- package/dist/utils/locality.js +22 -0
- package/dist/utils/locality.js.map +1 -0
- package/dist/utils/output-format.d.ts +13 -0
- package/dist/utils/output-format.d.ts.map +1 -0
- package/dist/utils/output-format.js +13 -0
- package/dist/utils/output-format.js.map +1 -0
- package/dist/utils/pagination.d.ts +12 -0
- package/dist/utils/pagination.d.ts.map +1 -0
- package/dist/utils/pagination.js +24 -0
- package/dist/utils/pagination.js.map +1 -0
- package/dist/utils/path-guard.d.ts +17 -0
- package/dist/utils/path-guard.d.ts.map +1 -0
- package/dist/utils/path-guard.js +41 -0
- package/dist/utils/path-guard.js.map +1 -0
- package/dist/utils/performance-comparison.d.ts +53 -0
- package/dist/utils/performance-comparison.d.ts.map +1 -0
- package/dist/utils/performance-comparison.js +286 -0
- package/dist/utils/performance-comparison.js.map +1 -0
- package/dist/utils/performance-stats.d.ts +72 -0
- package/dist/utils/performance-stats.d.ts.map +1 -0
- package/dist/utils/performance-stats.js +124 -0
- package/dist/utils/performance-stats.js.map +1 -0
- package/dist/utils/profile-loader.d.ts +37 -0
- package/dist/utils/profile-loader.d.ts.map +1 -0
- package/dist/utils/profile-loader.js +80 -0
- package/dist/utils/profile-loader.js.map +1 -0
- package/dist/utils/response-formatter.d.ts +27 -0
- package/dist/utils/response-formatter.d.ts.map +1 -0
- package/dist/utils/response-formatter.js +493 -0
- package/dist/utils/response-formatter.js.map +1 -0
- package/dist/utils/timestamp.d.ts +12 -0
- package/dist/utils/timestamp.d.ts.map +1 -0
- package/dist/utils/timestamp.js +22 -0
- package/dist/utils/timestamp.js.map +1 -0
- package/dist/utils/tool-registry.d.ts +21 -0
- package/dist/utils/tool-registry.d.ts.map +1 -0
- package/dist/utils/tool-registry.js +137 -0
- package/dist/utils/tool-registry.js.map +1 -0
- package/dist/utils/upload-command.d.ts +20 -0
- package/dist/utils/upload-command.d.ts.map +1 -0
- package/dist/utils/upload-command.js +64 -0
- package/dist/utils/upload-command.js.map +1 -0
- package/dist/utils/usage-report-guard.d.ts +48 -0
- package/dist/utils/usage-report-guard.d.ts.map +1 -0
- package/dist/utils/usage-report-guard.js +88 -0
- package/dist/utils/usage-report-guard.js.map +1 -0
- package/dist/utils/usage-report-summary.d.ts +20 -0
- package/dist/utils/usage-report-summary.d.ts.map +1 -0
- package/dist/utils/usage-report-summary.js +48 -0
- package/dist/utils/usage-report-summary.js.map +1 -0
- package/dist/utils/version.d.ts +2 -0
- package/dist/utils/version.d.ts.map +1 -0
- package/dist/utils/version.js +24 -0
- package/dist/utils/version.js.map +1 -0
- package/package.json +73 -0
- package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative-oss.java +58 -0
- package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative.java +67 -0
- package/resources/boilerplate/Android-Native/Java JUnit5/gradle +10 -0
- package/resources/boilerplate/Android-Native/Java JUnit5/gradle-oss +10 -0
- package/resources/boilerplate/Android-Native/Java JUnit5/maven +42 -0
- package/resources/boilerplate/Android-Native/Java JUnit5/maven-oss +42 -0
- package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/AndroidNative.js +30 -0
- package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/Shell +19 -0
- package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/Shell-oss +19 -0
- package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/package-oss.json +12 -0
- package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/package.json +12 -0
- package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio-oss.conf.js +40 -0
- package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio.conf.js +44 -0
- package/resources/boilerplate/Android-Native/Python/AndroidNative-oss.py +49 -0
- package/resources/boilerplate/Android-Native/Python/AndroidNative.py +69 -0
- package/resources/boilerplate/Android-Native/Python/pip +2 -0
- package/resources/boilerplate/Android-Native/Python/pip-oss +1 -0
- package/resources/boilerplate/Android-Native/java TestNG/AndroidNative-oss.java +58 -0
- package/resources/boilerplate/Android-Native/java TestNG/AndroidNative.java +67 -0
- package/resources/boilerplate/Android-Native/java TestNG/gradle +13 -0
- package/resources/boilerplate/Android-Native/java TestNG/gradle-oss +13 -0
- package/resources/boilerplate/Android-Native/java TestNG/maven +42 -0
- package/resources/boilerplate/Android-Native/java TestNG/maven-oss +42 -0
- package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/Shell-oss.txt +19 -0
- package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/Shell.txt +19 -0
- package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/iOSNative.js +30 -0
- package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/package-oss.json +12 -0
- package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/package.json +12 -0
- package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio-oss.conf.js +35 -0
- package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio.conf.js +39 -0
- package/resources/boilerplate/iOS-Native/Python/iOSNative-oss.py +44 -0
- package/resources/boilerplate/iOS-Native/Python/iOSNative.py +62 -0
- package/resources/boilerplate/iOS-Native/Python/pip-oss.txt +1 -0
- package/resources/boilerplate/iOS-Native/Python/pip.txt +2 -0
- package/resources/boilerplate/iOS-Native/java-JUnit5/gradle +10 -0
- package/resources/boilerplate/iOS-Native/java-JUnit5/gradle-oss +10 -0
- package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative-oss.java +52 -0
- package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative.java +59 -0
- package/resources/boilerplate/iOS-Native/java-JUnit5/maven +42 -0
- package/resources/boilerplate/iOS-Native/java-JUnit5/maven-oss +42 -0
- package/resources/boilerplate/iOS-Native/java-TestNG/gradle +13 -0
- package/resources/boilerplate/iOS-Native/java-TestNG/gradle-oss +13 -0
- package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative-oss.java +52 -0
- package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative.java +59 -0
- package/resources/boilerplate/iOS-Native/java-TestNG/maven +42 -0
- package/resources/boilerplate/iOS-Native/java-TestNG/maven-oss +42 -0
|
@@ -0,0 +1,1183 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
import { deleteTests } from './reporting.js';
|
|
3
|
+
import { getMyAccountInfo } from './users.js';
|
|
4
|
+
import { getActiveKeyType, getActiveUrl, getActiveAccessKey } from './client.js';
|
|
5
|
+
// In-process session registry — cleared on MCP server restart
|
|
6
|
+
const sessionRegistry = new Map();
|
|
7
|
+
// All report IDs created this process lifetime, mapped to the project name they
|
|
8
|
+
// were created under — for orphan cleanup. Sessions started under a non-default
|
|
9
|
+
// profile create reports in that project's reporter instance; deleting them
|
|
10
|
+
// later (e.g. after switching back to the admin JWT) MUST scope by projectName
|
|
11
|
+
// or the same numeric test_id in the default reporter scope gets deleted instead.
|
|
12
|
+
const allReports = new Map();
|
|
13
|
+
function gridBase() {
|
|
14
|
+
// getActiveUrl (not process.env) — the Grid must follow switch_environment.
|
|
15
|
+
const base = getActiveUrl();
|
|
16
|
+
if (!base)
|
|
17
|
+
throw new Error('DIGITAL_AI_BASE_URL not configured');
|
|
18
|
+
return `${base}/wd/hub`;
|
|
19
|
+
}
|
|
20
|
+
function makeClient() {
|
|
21
|
+
return axios.create({
|
|
22
|
+
baseURL: gridBase(),
|
|
23
|
+
timeout: 120_000,
|
|
24
|
+
headers: { 'Content-Type': 'application/json' },
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
export async function createInspectionSession(opts) {
|
|
28
|
+
// getActiveAccessKey (not process.env) — the session must be created with the
|
|
29
|
+
// active profile's credential so it matches canDeleteReport's key-type check.
|
|
30
|
+
const accessKey = getActiveAccessKey();
|
|
31
|
+
if (!accessKey)
|
|
32
|
+
throw new Error('DIGITAL_AI_ACCESS_KEY not configured');
|
|
33
|
+
// Capture the active profile's project — the session's report is created in
|
|
34
|
+
// this project's reporter instance and any later delete must scope to it.
|
|
35
|
+
let projectName;
|
|
36
|
+
try {
|
|
37
|
+
projectName = (await getMyAccountInfo()).project?.name;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Non-fatal — deletes fall back to the default reporter scope
|
|
41
|
+
}
|
|
42
|
+
const platform = opts.platform ?? 'android';
|
|
43
|
+
let query = opts.deviceQuery ??
|
|
44
|
+
(platform === 'ios' ? "@os='iOS' and @category='PHONE'" : "@os='android' and @category='PHONE'");
|
|
45
|
+
if (opts.region)
|
|
46
|
+
query = `${query} and @region='${opts.region}'`;
|
|
47
|
+
const desiredCapabilities = {
|
|
48
|
+
'digitalai:accessKey': accessKey,
|
|
49
|
+
'digitalai:deviceQuery': query,
|
|
50
|
+
'digitalai:testName': opts.testName ?? '[MCP Inspection]',
|
|
51
|
+
'platformName': platform === 'ios' ? 'iOS' : 'Android',
|
|
52
|
+
'noReset': opts.noReset ?? true,
|
|
53
|
+
};
|
|
54
|
+
if (opts.app) {
|
|
55
|
+
desiredCapabilities['app'] = opts.app;
|
|
56
|
+
if (opts.appPackage)
|
|
57
|
+
desiredCapabilities['appPackage'] = opts.appPackage;
|
|
58
|
+
if (opts.appActivity)
|
|
59
|
+
desiredCapabilities['appActivity'] = opts.appActivity;
|
|
60
|
+
}
|
|
61
|
+
else if (opts.appPackage) {
|
|
62
|
+
desiredCapabilities['appPackage'] = opts.appPackage;
|
|
63
|
+
if (opts.appActivity)
|
|
64
|
+
desiredCapabilities['appActivity'] = opts.appActivity;
|
|
65
|
+
}
|
|
66
|
+
// Dual-protocol session request: the proprietary Grid (JWP) reads
|
|
67
|
+
// desiredCapabilities; standard Appium Server (W3C) reads capabilities.alwaysMatch
|
|
68
|
+
// and requires non-standard caps to carry the appium: vendor prefix.
|
|
69
|
+
const W3C_STANDARD_CAPS = new Set(['platformName', 'browserName', 'browserVersion']);
|
|
70
|
+
const alwaysMatch = {};
|
|
71
|
+
for (const [key, value] of Object.entries(desiredCapabilities)) {
|
|
72
|
+
if (W3C_STANDARD_CAPS.has(key) || key.includes(':')) {
|
|
73
|
+
alwaysMatch[key] = value;
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
alwaysMatch[`appium:${key}`] = value;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const client = makeClient();
|
|
80
|
+
let res;
|
|
81
|
+
try {
|
|
82
|
+
res = await client.post('/session', {
|
|
83
|
+
desiredCapabilities,
|
|
84
|
+
capabilities: { alwaysMatch, firstMatch: [{}] },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
// The Grid often returns a bare 500 with no body when the device agent pool
|
|
89
|
+
// is saturated (v36) — give the caller a diagnosis path instead of a status code.
|
|
90
|
+
throw new Error(`Session creation failed: ${describeWdError(e)}. Diagnostics: ` +
|
|
91
|
+
`(1) run check_${platform === 'ios' ? 'ios' : 'android'}_readiness — if available is 0, the device pool or platform agents are busy; ` +
|
|
92
|
+
`(2) if launching an app, verify it is assigned to your ACTIVE project (get_application_info → projectsInfo) — a successful install does NOT imply the session can use the app; ` +
|
|
93
|
+
`(3) specific-device queries (@name/@serialNumber) can time out — prefer a generic @os/@category query with the region param. ` +
|
|
94
|
+
`A bare 500 usually means platform load — retry shortly.`);
|
|
95
|
+
}
|
|
96
|
+
// JWP response: { sessionId: "CLOUD-SID:...", value: { caps... }, status: 0 }
|
|
97
|
+
// W3C response: { value: { sessionId: "uuid...", capabilities: { caps... } } }
|
|
98
|
+
const isW3c = res.data.value?.capabilities != null;
|
|
99
|
+
const caps = res.data.value?.capabilities ?? res.data.value ?? {};
|
|
100
|
+
const rawId = caps['digitalai:reportTestId'];
|
|
101
|
+
const reportTestId = rawId ? parseInt(String(rawId), 10) : 0;
|
|
102
|
+
// Track the report before any validation throw — if the session response is
|
|
103
|
+
// malformed the Grid session times out on its own, but the reporter record is
|
|
104
|
+
// permanent and must stay reachable by cleanup_inspection_sessions.
|
|
105
|
+
if (reportTestId > 0)
|
|
106
|
+
allReports.set(reportTestId, projectName);
|
|
107
|
+
const gridSessionId = res.data.sessionId ?? res.data.value?.sessionId ?? '';
|
|
108
|
+
if (!gridSessionId) {
|
|
109
|
+
throw new Error('Session created but no sessionId in response' +
|
|
110
|
+
(reportTestId > 0
|
|
111
|
+
? ` — orphaned report ${reportTestId} is tracked; run cleanup_inspection_sessions to delete it`
|
|
112
|
+
: ''));
|
|
113
|
+
}
|
|
114
|
+
// POST /reporter/api/tests/delete is CSRF-blocked for project-level keys (Project Admin and Project User).
|
|
115
|
+
// Only Cloud Admin credentials (JWT Bearer token) bypass the CSRF check on reporter mutation endpoints.
|
|
116
|
+
const canDeleteReport = getActiveKeyType() === 'jwt';
|
|
117
|
+
const handle = crypto.randomUUID().slice(0, 8).toUpperCase();
|
|
118
|
+
// Field names differ: JWP Grid uses dot-notation (device.name, device.os),
|
|
119
|
+
// W3C Appium 2.x uses flat names (digitalai:cloudDeviceName, platformName, platformVersion).
|
|
120
|
+
const session = {
|
|
121
|
+
handle,
|
|
122
|
+
gridSessionId,
|
|
123
|
+
reportTestId,
|
|
124
|
+
reportUrl: String(caps['digitalai:reportUrl'] ?? ''),
|
|
125
|
+
cloudViewLink: caps['digitalai:cloudViewLink'] ? String(caps['digitalai:cloudViewLink']) : null,
|
|
126
|
+
deviceUDID: String(caps['deviceUDID'] ?? caps['device.serialNumber'] ?? caps['udid'] ?? ''),
|
|
127
|
+
deviceName: String(caps['device.name'] ?? caps['digitalai:cloudDeviceName'] ?? ''),
|
|
128
|
+
deviceModel: String(caps['device.model'] ?? caps['digitalai:publicModel'] ?? ''),
|
|
129
|
+
deviceOs: String(caps['device.os'] ?? caps['platformName'] ?? 'Android'),
|
|
130
|
+
deviceVersion: String(caps['device.version'] ?? caps['platformVersion'] ?? ''),
|
|
131
|
+
appPackage: String(caps['appPackage'] ?? opts.appPackage ?? ''),
|
|
132
|
+
startedAt: Date.now(),
|
|
133
|
+
lastUsedAt: Date.now(),
|
|
134
|
+
canDeleteReport,
|
|
135
|
+
sessionFormat: isW3c ? 'w3c' : 'jwp',
|
|
136
|
+
platform,
|
|
137
|
+
projectName,
|
|
138
|
+
};
|
|
139
|
+
sessionRegistry.set(handle, session);
|
|
140
|
+
return session;
|
|
141
|
+
}
|
|
142
|
+
export async function quitInspectionSession(handle, keepReport = false) {
|
|
143
|
+
const session = requireSession(handle);
|
|
144
|
+
const client = makeClient();
|
|
145
|
+
try {
|
|
146
|
+
await client.delete(`/session/${session.gridSessionId}`, { timeout: 30_000 });
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
// Best-effort — session may already be expired
|
|
150
|
+
}
|
|
151
|
+
sessionRegistry.delete(handle);
|
|
152
|
+
let reportDeleted = false;
|
|
153
|
+
let reportKept = false;
|
|
154
|
+
if (session.reportTestId > 0 && keepReport) {
|
|
155
|
+
// Deliberately preserved (e.g. for the platform's session video recording) —
|
|
156
|
+
// remove from the orphan registry so cleanup_inspection_sessions won't delete it.
|
|
157
|
+
allReports.delete(session.reportTestId);
|
|
158
|
+
reportKept = true;
|
|
159
|
+
}
|
|
160
|
+
else if (session.reportTestId > 0 && session.canDeleteReport) {
|
|
161
|
+
try {
|
|
162
|
+
// Scope to the project the session was created under — without projectName
|
|
163
|
+
// the delete resolves the test_id in the default reporter scope.
|
|
164
|
+
await deleteTests([session.reportTestId], undefined, session.projectName);
|
|
165
|
+
allReports.delete(session.reportTestId);
|
|
166
|
+
reportDeleted = true;
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
// Non-fatal — user can delete via reporter UI
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
reportDeleted,
|
|
174
|
+
reportKept,
|
|
175
|
+
canDeleteReport: session.canDeleteReport,
|
|
176
|
+
reportTestId: session.reportTestId,
|
|
177
|
+
reportUrl: session.reportUrl,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
export async function captureScreenshot(handle) {
|
|
181
|
+
const session = requireSession(handle);
|
|
182
|
+
const client = makeClient();
|
|
183
|
+
let res;
|
|
184
|
+
try {
|
|
185
|
+
res = await client.get(`/session/${session.gridSessionId}/screenshot`, {
|
|
186
|
+
timeout: 30_000,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
catch (e) {
|
|
190
|
+
throw new Error(sessionAwareError(e, handle));
|
|
191
|
+
}
|
|
192
|
+
if (!res.data.value)
|
|
193
|
+
throw new Error('Screenshot returned empty response');
|
|
194
|
+
const data = res.data.value;
|
|
195
|
+
// Detect image format from base64 prefix — Grid returns PNG, OSS Appium may return JPEG
|
|
196
|
+
const mimeType = data.startsWith('/9j/') ? 'image/jpeg' : 'image/png';
|
|
197
|
+
return { data, mimeType };
|
|
198
|
+
}
|
|
199
|
+
// Augment a WebDriver error with a dead-session hint — a 404 on an established
|
|
200
|
+
// session almost always means the Grid/agent terminated it (timeout, WDA crash).
|
|
201
|
+
function sessionAwareError(e, handle) {
|
|
202
|
+
const detail = describeWdError(e);
|
|
203
|
+
const err = e;
|
|
204
|
+
if (err.response?.status === 404) {
|
|
205
|
+
const s = sessionRegistry.get(handle);
|
|
206
|
+
const idleNote = s?.lastIdleMs != null && s.lastIdleMs > 60_000
|
|
207
|
+
? ` The session was idle for ${Math.round(s.lastIdleMs / 60_000)} minute(s) before this command — Grid sessions expire after ~4 minutes of inactivity.`
|
|
208
|
+
: '';
|
|
209
|
+
return (`${detail} — the Grid session has likely been terminated (idle timeout or agent crash).${idleNote} ` +
|
|
210
|
+
`The handle "${handle}" is no longer usable: call stop_inspection_session to clean up, ` +
|
|
211
|
+
`then start_inspection_session for a fresh session.`);
|
|
212
|
+
}
|
|
213
|
+
return detail;
|
|
214
|
+
}
|
|
215
|
+
export async function getPageSource(handle) {
|
|
216
|
+
const session = requireSession(handle);
|
|
217
|
+
const client = makeClient();
|
|
218
|
+
const res = await client.get(`/session/${session.gridSessionId}/source`, {
|
|
219
|
+
timeout: 30_000,
|
|
220
|
+
});
|
|
221
|
+
return res.data.value ?? '';
|
|
222
|
+
}
|
|
223
|
+
export async function findElements(handle, using, value) {
|
|
224
|
+
const session = requireSession(handle);
|
|
225
|
+
const client = makeClient();
|
|
226
|
+
const sid = session.gridSessionId;
|
|
227
|
+
let res;
|
|
228
|
+
try {
|
|
229
|
+
res = await client.post(`/session/${sid}/elements`, { using, value }, { timeout: 20_000 });
|
|
230
|
+
}
|
|
231
|
+
catch (e) {
|
|
232
|
+
throw new Error(sessionAwareError(e, handle));
|
|
233
|
+
}
|
|
234
|
+
const rawList = res.data.value ?? [];
|
|
235
|
+
const elements = [];
|
|
236
|
+
for (const raw of rawList) {
|
|
237
|
+
const elementId = raw['ELEMENT'] ?? raw['element-6066-11e4-a52e-4f735466cecf'];
|
|
238
|
+
if (!elementId)
|
|
239
|
+
continue;
|
|
240
|
+
if (session.platform === 'ios') {
|
|
241
|
+
// iOS attribute model: name/label/value/type. XCUITest rejects Android
|
|
242
|
+
// names (class, text, bounds) outright; the Grid exposes `class` instead
|
|
243
|
+
// of `type` — fetch both and take whichever resolves.
|
|
244
|
+
const [name, label, val, type, cls, enabled, visible] = await Promise.allSettled([
|
|
245
|
+
getAttr(client, sid, elementId, 'name'),
|
|
246
|
+
getAttr(client, sid, elementId, 'label'),
|
|
247
|
+
getAttr(client, sid, elementId, 'value'),
|
|
248
|
+
getAttr(client, sid, elementId, 'type'),
|
|
249
|
+
getAttr(client, sid, elementId, 'class'),
|
|
250
|
+
getAttr(client, sid, elementId, 'enabled'),
|
|
251
|
+
getAttr(client, sid, elementId, 'visible'),
|
|
252
|
+
]).then((rs) => rs.map((r) => (r.status === 'fulfilled' ? r.value : null)));
|
|
253
|
+
let bounds = null;
|
|
254
|
+
try {
|
|
255
|
+
const { x, y, width, height } = await elementRect(client, session, elementId);
|
|
256
|
+
bounds = `[${x},${y}][${x + width},${y + height}]`;
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
// Non-fatal — element is still usable without geometry
|
|
260
|
+
}
|
|
261
|
+
elements.push({
|
|
262
|
+
elementId,
|
|
263
|
+
className: type ?? cls,
|
|
264
|
+
resourceId: null,
|
|
265
|
+
contentDesc: null,
|
|
266
|
+
text: null,
|
|
267
|
+
bounds,
|
|
268
|
+
clickable: visible === 'true' ? true : visible === 'false' ? false : null,
|
|
269
|
+
enabled: enabled === 'true' ? true : enabled === 'false' ? false : null,
|
|
270
|
+
name,
|
|
271
|
+
label,
|
|
272
|
+
value: val,
|
|
273
|
+
});
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
// Android: Appium 1.x JWP uses XML-matching hyphenated attribute names
|
|
277
|
+
const [className, resourceId, contentDesc, text, bounds, clickable, enabled] = await Promise.allSettled([
|
|
278
|
+
getAttr(client, sid, elementId, 'class'),
|
|
279
|
+
getAttr(client, sid, elementId, 'resource-id'),
|
|
280
|
+
getAttr(client, sid, elementId, 'content-desc'),
|
|
281
|
+
getAttr(client, sid, elementId, 'text'),
|
|
282
|
+
getAttr(client, sid, elementId, 'bounds'),
|
|
283
|
+
getAttr(client, sid, elementId, 'clickable'),
|
|
284
|
+
getAttr(client, sid, elementId, 'enabled'),
|
|
285
|
+
]).then((rs) => rs.map((r) => (r.status === 'fulfilled' ? r.value : null)));
|
|
286
|
+
elements.push({
|
|
287
|
+
elementId,
|
|
288
|
+
className,
|
|
289
|
+
resourceId,
|
|
290
|
+
contentDesc,
|
|
291
|
+
text,
|
|
292
|
+
bounds,
|
|
293
|
+
clickable: clickable === 'true' ? true : clickable === 'false' ? false : null,
|
|
294
|
+
enabled: enabled === 'true' ? true : enabled === 'false' ? false : null,
|
|
295
|
+
name: null,
|
|
296
|
+
label: null,
|
|
297
|
+
value: null,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
return elements;
|
|
301
|
+
}
|
|
302
|
+
// Lightweight single-element lookup: one round trip via the singular /element
|
|
303
|
+
// route, no attribute enrichment. Returns null when nothing matches ("no such
|
|
304
|
+
// element" 404). Used by internal helpers (e.g. press_back's nav-bar lookup)
|
|
305
|
+
// where the full findElements enrichment (~9 requests/element) is wasteful.
|
|
306
|
+
export async function findFirstElementId(handle, using, value) {
|
|
307
|
+
const session = requireSession(handle);
|
|
308
|
+
const client = makeClient();
|
|
309
|
+
try {
|
|
310
|
+
const res = await client.post(`/session/${session.gridSessionId}/element`, { using, value }, { timeout: 20_000 });
|
|
311
|
+
const raw = res.data.value ?? {};
|
|
312
|
+
return raw['ELEMENT'] ?? raw['element-6066-11e4-a52e-4f735466cecf'] ?? null;
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
const detail = describeWdError(e).toLowerCase();
|
|
316
|
+
if (detail.includes('no such element') || detail.includes('an element could not be located')) {
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
throw new Error(describeWdError(e));
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// Element geometry that works on every agent: W3C agents route GET /element/{id}/rect;
|
|
323
|
+
// JWP agents (incl. the Grid, both platforms — confirmed live) route /location + /size.
|
|
324
|
+
async function elementRect(client, session, elementId) {
|
|
325
|
+
const sid = session.gridSessionId;
|
|
326
|
+
const rect = async () => {
|
|
327
|
+
const r = await client.get(`/session/${sid}/element/${elementId}/rect`, { timeout: 10_000 });
|
|
328
|
+
const v = r.data.value;
|
|
329
|
+
if (v?.width == null)
|
|
330
|
+
throw new Error('rect route returned no geometry');
|
|
331
|
+
return { x: Number(v.x), y: Number(v.y), width: Number(v.width), height: Number(v.height) };
|
|
332
|
+
};
|
|
333
|
+
const locSize = async () => {
|
|
334
|
+
const [loc, size] = await Promise.all([
|
|
335
|
+
client.get(`/session/${sid}/element/${elementId}/location`, { timeout: 10_000 }),
|
|
336
|
+
client.get(`/session/${sid}/element/${elementId}/size`, { timeout: 10_000 }),
|
|
337
|
+
]);
|
|
338
|
+
return {
|
|
339
|
+
x: Number(loc.data.value?.x),
|
|
340
|
+
y: Number(loc.data.value?.y),
|
|
341
|
+
width: Number(size.data.value?.width),
|
|
342
|
+
height: Number(size.data.value?.height),
|
|
343
|
+
};
|
|
344
|
+
};
|
|
345
|
+
const [primary, fallback] = session.sessionFormat === 'w3c' ? [rect, locSize] : [locSize, rect];
|
|
346
|
+
try {
|
|
347
|
+
return await primary();
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
return await fallback();
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
async function getAttr(client, sessionId, elementId, attr) {
|
|
354
|
+
try {
|
|
355
|
+
const res = await client.get(`/session/${sessionId}/element/${elementId}/attribute/${attr}`, { timeout: 10_000 });
|
|
356
|
+
return res.data.value != null ? String(res.data.value) : null;
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
export async function tapElement(handle, elementId) {
|
|
363
|
+
const session = requireSession(handle);
|
|
364
|
+
const client = makeClient();
|
|
365
|
+
await client.post(`/session/${session.gridSessionId}/element/${elementId}/click`, {}, { timeout: 15_000 });
|
|
366
|
+
}
|
|
367
|
+
export async function typeIntoElement(handle, elementId, text) {
|
|
368
|
+
const session = requireSession(handle);
|
|
369
|
+
const client = makeClient();
|
|
370
|
+
// Send both formats: JWP (value: charArray) and W3C (text: string)
|
|
371
|
+
// Appium accepts both across protocol versions
|
|
372
|
+
await client.post(`/session/${session.gridSessionId}/element/${elementId}/value`, { value: text.split(''), text }, { timeout: 15_000 });
|
|
373
|
+
}
|
|
374
|
+
export async function clearElement(handle, elementId) {
|
|
375
|
+
const session = requireSession(handle);
|
|
376
|
+
const client = makeClient();
|
|
377
|
+
await client.post(`/session/${session.gridSessionId}/element/${elementId}/clear`, {}, { timeout: 15_000 });
|
|
378
|
+
}
|
|
379
|
+
// ─── Gestures & app management ───────────────────────────────────────────────
|
|
380
|
+
// Ported from the official appium/appium-mcp implementation patterns.
|
|
381
|
+
// W3C agents (Appium 2/3) use POST /actions and `mobile:` execute commands —
|
|
382
|
+
// Appium 3 removed every legacy JWP route (touch/perform, /appium/device/*).
|
|
383
|
+
// JWP agents (Appium 1.x) only have the legacy routes — the `mobile:` gesture
|
|
384
|
+
// family arrived in the Appium 1.22 era. Each helper tries the session's
|
|
385
|
+
// native format first and falls back to the other on unknown-command errors,
|
|
386
|
+
// because the Digital.ai Grid proxy does not always match the agent's protocol.
|
|
387
|
+
// Extract a readable error from an Axios/WebDriver failure — the agent's actual
|
|
388
|
+
// message (e.g. "No alert is present on the screen") lives in the response body,
|
|
389
|
+
// which axios's default "Request failed with status code N" hides entirely.
|
|
390
|
+
function describeWdError(e) {
|
|
391
|
+
const err = e;
|
|
392
|
+
const status = err.response?.status;
|
|
393
|
+
if (!status)
|
|
394
|
+
return err.message ?? String(e);
|
|
395
|
+
const data = err.response?.data;
|
|
396
|
+
const detail = data?.value?.message ?? data?.value?.error;
|
|
397
|
+
return detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`;
|
|
398
|
+
}
|
|
399
|
+
function isUnknownCommand(e) {
|
|
400
|
+
const err = e;
|
|
401
|
+
const status = err.response?.status;
|
|
402
|
+
if (status === 404 || status === 405 || status === 501)
|
|
403
|
+
return true;
|
|
404
|
+
const text = JSON.stringify(err.response?.data ?? '').toLowerCase();
|
|
405
|
+
return (text.includes('unknown command') ||
|
|
406
|
+
text.includes('unknown mobile command') ||
|
|
407
|
+
text.includes('not implemented') ||
|
|
408
|
+
text.includes('could not find a route'));
|
|
409
|
+
}
|
|
410
|
+
export async function getWindowSize(handle) {
|
|
411
|
+
const session = requireSession(handle);
|
|
412
|
+
const client = makeClient();
|
|
413
|
+
// W3C route first, JWP route as fallback
|
|
414
|
+
try {
|
|
415
|
+
const res = await client.get(`/session/${session.gridSessionId}/window/rect`, {
|
|
416
|
+
timeout: 15_000,
|
|
417
|
+
});
|
|
418
|
+
const v = res.data.value;
|
|
419
|
+
if (v?.width != null)
|
|
420
|
+
return { width: Number(v.width), height: Number(v.height) };
|
|
421
|
+
}
|
|
422
|
+
catch (e) {
|
|
423
|
+
if (!isUnknownCommand(e))
|
|
424
|
+
throw e;
|
|
425
|
+
}
|
|
426
|
+
const res = await client.get(`/session/${session.gridSessionId}/window/current/size`, { timeout: 15_000 });
|
|
427
|
+
return { width: Number(res.data.value.width), height: Number(res.data.value.height) };
|
|
428
|
+
}
|
|
429
|
+
export async function swipeScreen(handle, startX, startY, endX, endY, durationMs = 300) {
|
|
430
|
+
const session = requireSession(handle);
|
|
431
|
+
const client = makeClient();
|
|
432
|
+
const sid = session.gridSessionId;
|
|
433
|
+
// W3C Actions — the initial 200ms pause after pointerDown makes the gesture
|
|
434
|
+
// register as a drag/scroll rather than a fling (appium-mcp swipe pattern).
|
|
435
|
+
const w3c = () => client.post(`/session/${sid}/actions`, {
|
|
436
|
+
actions: [
|
|
437
|
+
{
|
|
438
|
+
type: 'pointer',
|
|
439
|
+
id: 'finger1',
|
|
440
|
+
parameters: { pointerType: 'touch' },
|
|
441
|
+
actions: [
|
|
442
|
+
{ type: 'pointerMove', duration: 0, x: startX, y: startY },
|
|
443
|
+
{ type: 'pointerDown', button: 0 },
|
|
444
|
+
{ type: 'pause', duration: 200 },
|
|
445
|
+
{ type: 'pointerMove', duration: durationMs, x: endX, y: endY },
|
|
446
|
+
{ type: 'pointerUp', button: 0 },
|
|
447
|
+
],
|
|
448
|
+
},
|
|
449
|
+
],
|
|
450
|
+
}, { timeout: 30_000 });
|
|
451
|
+
// JWP TouchAction — moveTo coordinates are absolute since Appium 1.8.0.
|
|
452
|
+
const jwp = () => client.post(`/session/${sid}/touch/perform`, {
|
|
453
|
+
actions: [
|
|
454
|
+
{ action: 'press', options: { x: startX, y: startY } },
|
|
455
|
+
{ action: 'wait', options: { ms: durationMs } },
|
|
456
|
+
{ action: 'moveTo', options: { x: endX, y: endY } },
|
|
457
|
+
{ action: 'release', options: {} },
|
|
458
|
+
],
|
|
459
|
+
}, { timeout: 30_000 });
|
|
460
|
+
if (session.sessionFormat === 'w3c') {
|
|
461
|
+
try {
|
|
462
|
+
await w3c();
|
|
463
|
+
return 'w3c-actions';
|
|
464
|
+
}
|
|
465
|
+
catch (e) {
|
|
466
|
+
if (!isUnknownCommand(e))
|
|
467
|
+
throw e;
|
|
468
|
+
await jwp();
|
|
469
|
+
return 'jwp-touch';
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
try {
|
|
473
|
+
await jwp();
|
|
474
|
+
return 'jwp-touch';
|
|
475
|
+
}
|
|
476
|
+
catch (e) {
|
|
477
|
+
if (!isUnknownCommand(e))
|
|
478
|
+
throw e;
|
|
479
|
+
await w3c();
|
|
480
|
+
return 'w3c-actions';
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
export async function launchApp(handle, packageName, activity) {
|
|
484
|
+
const session = requireSession(handle);
|
|
485
|
+
const client = makeClient();
|
|
486
|
+
const sid = session.gridSessionId;
|
|
487
|
+
const errors = [];
|
|
488
|
+
const tryAll = async (mechanisms) => {
|
|
489
|
+
for (const [desc, fn] of mechanisms) {
|
|
490
|
+
try {
|
|
491
|
+
await fn();
|
|
492
|
+
return desc;
|
|
493
|
+
}
|
|
494
|
+
catch (e) {
|
|
495
|
+
const err = e;
|
|
496
|
+
const detail = err.response?.data
|
|
497
|
+
? JSON.stringify(err.response.data).slice(0, 200)
|
|
498
|
+
: err.message ?? String(e);
|
|
499
|
+
errors.push(`${desc}: ${detail}`);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
throw new Error(`All launch mechanisms failed:\n ${errors.join('\n ')}`);
|
|
503
|
+
};
|
|
504
|
+
if (session.platform === 'ios') {
|
|
505
|
+
// iOS launches by bundle ID — there is no activity concept.
|
|
506
|
+
const seetest = ['seetest:client.launch', () => client.post(`/session/${sid}/execute`, { script: 'seetest:client.launch', args: [packageName, false, true] }, { timeout: 30_000 })];
|
|
507
|
+
const w3cLaunch = ['mobile: launchApp', () => client.post(`/session/${sid}/execute/sync`, { script: 'mobile: launchApp', args: [{ bundleId: packageName }] }, { timeout: 30_000 })];
|
|
508
|
+
const w3cActivate = ['mobile: activateApp', () => client.post(`/session/${sid}/execute/sync`, { script: 'mobile: activateApp', args: [{ bundleId: packageName }] }, { timeout: 30_000 })];
|
|
509
|
+
const order = session.sessionFormat === 'w3c'
|
|
510
|
+
? [w3cLaunch, w3cActivate, seetest]
|
|
511
|
+
: [seetest, w3cLaunch, w3cActivate];
|
|
512
|
+
const used = await tryAll(order);
|
|
513
|
+
return `Launched ${packageName} via ${used}`;
|
|
514
|
+
}
|
|
515
|
+
if (activity) {
|
|
516
|
+
// Normalise: ".LoginActivity" and "com.full.path.LoginActivity" both valid.
|
|
517
|
+
const fullActivity = activity.startsWith('.') || activity.includes('.')
|
|
518
|
+
? activity
|
|
519
|
+
: `.${activity}`;
|
|
520
|
+
const activityUrl = `${packageName}/${fullActivity}`;
|
|
521
|
+
const seetest = ['seetest:client.launch', () => client.post(`/session/${sid}/execute`, { script: 'seetest:client.launch', args: [activityUrl, false, true] }, { timeout: 30_000 })];
|
|
522
|
+
const w3c = ['mobile: startActivity', () => client.post(`/session/${sid}/execute/sync`, { script: 'mobile: startActivity', args: [{ intent: activityUrl, wait: true }] }, { timeout: 30_000 })];
|
|
523
|
+
const legacy = ['legacy start_activity', () => client.post(`/session/${sid}/appium/device/start_activity`, { appPackage: packageName, appActivity: fullActivity }, { timeout: 30_000 })];
|
|
524
|
+
const order = session.sessionFormat === 'w3c' ? [w3c, seetest, legacy] : [seetest, w3c, legacy];
|
|
525
|
+
const used = await tryAll(order);
|
|
526
|
+
return `Launched ${activityUrl} via ${used}`;
|
|
527
|
+
}
|
|
528
|
+
// No activity — bring an installed app to the foreground. NOTE: the Digital.ai
|
|
529
|
+
// Grid has no activate-by-package command — pass the activity for Grid sessions.
|
|
530
|
+
const w3cActivate = ['mobile: activateApp', () => client.post(`/session/${sid}/execute/sync`, { script: 'mobile: activateApp', args: [{ appId: packageName }] }, { timeout: 30_000 })];
|
|
531
|
+
const legacyActivate = ['legacy activate_app', () => client.post(`/session/${sid}/appium/device/activate_app`, { appId: packageName }, { timeout: 30_000 })];
|
|
532
|
+
const order = session.sessionFormat === 'w3c'
|
|
533
|
+
? [w3cActivate, legacyActivate]
|
|
534
|
+
: [legacyActivate, w3cActivate];
|
|
535
|
+
const used = await tryAll(order);
|
|
536
|
+
return `Activated ${packageName} via ${used} (foregrounded)`;
|
|
537
|
+
}
|
|
538
|
+
export async function pressBack(handle) {
|
|
539
|
+
const session = requireSession(handle);
|
|
540
|
+
if (session.platform === 'ios') {
|
|
541
|
+
// iOS has no Back button. Primary: tap the navigation bar's back button —
|
|
542
|
+
// present on every pushed screen (single cheap lookup, no enrichment).
|
|
543
|
+
// Fallback: the left-edge swipe, which only helps in gesture-driven apps
|
|
544
|
+
// (synthetic touches often don't trigger the system edge recognizer —
|
|
545
|
+
// confirmed live on the Grid).
|
|
546
|
+
try {
|
|
547
|
+
const backButton = await findFirstElementId(handle, 'xpath', '//XCUIElementTypeNavigationBar/XCUIElementTypeButton[1]');
|
|
548
|
+
if (backButton) {
|
|
549
|
+
await tapElement(handle, backButton);
|
|
550
|
+
return 'Tapped the navigation bar back button';
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
// Fall through to the edge swipe
|
|
555
|
+
}
|
|
556
|
+
const { width, height } = await getWindowSize(handle);
|
|
557
|
+
const midY = Math.round(height / 2);
|
|
558
|
+
await swipeScreen(handle, 2, midY, Math.round(width * 0.6), midY, 300);
|
|
559
|
+
return 'No navigation bar back button found — attempted the left-edge back swipe (may not navigate in all apps; if the screen is unchanged, look for an on-screen close/back element)';
|
|
560
|
+
}
|
|
561
|
+
const client = makeClient();
|
|
562
|
+
// POST /back is a standard WebDriver route — works on JWP and W3C alike.
|
|
563
|
+
await client.post(`/session/${session.gridSessionId}/back`, {}, { timeout: 15_000 });
|
|
564
|
+
return 'Back pressed';
|
|
565
|
+
}
|
|
566
|
+
// Execute a script via the protocol-appropriate endpoint.
|
|
567
|
+
// JWP agents route /execute; W3C agents (Appium 2/3) only route /execute/sync.
|
|
568
|
+
function execScript(client, session, script, args) {
|
|
569
|
+
const path = session.sessionFormat === 'w3c' ? 'execute/sync' : 'execute';
|
|
570
|
+
return client.post(`/session/${session.gridSessionId}/${path}`, { script, args }, { timeout: 30_000 });
|
|
571
|
+
}
|
|
572
|
+
// Start or end a Digital.ai performance transaction inside a live inspection
|
|
573
|
+
// session. The platform records CPU/memory/battery/network + Speed Index for
|
|
574
|
+
// the window between start and end; the agent runs the UI steps to measure in
|
|
575
|
+
// between using the normal tap/type/launch tools.
|
|
576
|
+
//
|
|
577
|
+
// These are seetest:client.* commands — the Digital.ai cloud proxy interprets
|
|
578
|
+
// them, not Appium, so they route through execScript on both Grid (/execute)
|
|
579
|
+
// and Appium Server / OSS (/execute/sync). The Grid execute parser cannot
|
|
580
|
+
// express a zero-argument seetest command, so start REQUIRES a network profile.
|
|
581
|
+
export async function performanceTransaction(handle, action, opts) {
|
|
582
|
+
const session = requireSession(handle);
|
|
583
|
+
const client = makeClient();
|
|
584
|
+
try {
|
|
585
|
+
if (action === 'start') {
|
|
586
|
+
if (!opts.networkProfile) {
|
|
587
|
+
throw new Error('networkProfile is required to start a performance transaction. Use "Monitor" to observe WITHOUT ' +
|
|
588
|
+
'throttling (the usual choice when you just want to measure current performance). Throttling profiles ' +
|
|
589
|
+
'("3G-average", "wifi", etc.) apply network conditions and must exist on your NV server — obtain valid ' +
|
|
590
|
+
'names from your platform admin; only "Monitor" is broadly guaranteed. The NV server for the device\'s ' +
|
|
591
|
+
'region must be ONLINE and tunnel-connected (verify with list_nv_servers) or the transaction records nothing.');
|
|
592
|
+
}
|
|
593
|
+
await execScript(client, session, 'seetest:client.startPerformanceTransaction', [opts.networkProfile]);
|
|
594
|
+
const isMonitor = opts.networkProfile.toLowerCase() === 'monitor';
|
|
595
|
+
const throttleNote = isMonitor
|
|
596
|
+
? `"Monitor" is pass-through — no throttling is applied, so there is no ANR risk from network shaping. `
|
|
597
|
+
: `⚠️ NV throttling is now ACTIVE — if the app makes background network calls during this window it may ANR/crash; keep the measured window tight. `;
|
|
598
|
+
return (`Started performance transaction with NV profile "${opts.networkProfile}". ` +
|
|
599
|
+
throttleNote +
|
|
600
|
+
`Perform ONLY the UI steps you want measured, then call action:"end".`);
|
|
601
|
+
}
|
|
602
|
+
if (!opts.transactionName) {
|
|
603
|
+
throw new Error('transactionName is required to end a performance transaction.');
|
|
604
|
+
}
|
|
605
|
+
const res = await execScript(client, session, 'seetest:client.endPerformanceTransaction', [opts.transactionName]);
|
|
606
|
+
const value = res?.data?.value;
|
|
607
|
+
const perfJson = typeof value === 'string' ? value : JSON.stringify(value ?? '');
|
|
608
|
+
return (`Ended performance transaction "${opts.transactionName}". The platform is writing the record — it appears in ` +
|
|
609
|
+
`the reporter within ~1 minute (not instantly). Retrieve it with list_transactions(transactionName:"${opts.transactionName}", ` +
|
|
610
|
+
`deviceName, startDate=today) then get_transaction(id) for the Speed Index and telemetry. ` +
|
|
611
|
+
`Raw perf payload (truncated): ${perfJson.slice(0, 400)}`);
|
|
612
|
+
}
|
|
613
|
+
catch (e) {
|
|
614
|
+
throw new Error(sessionAwareError(e, handle));
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
async function resolvePoint(client, session, opts) {
|
|
618
|
+
if (opts.elementId) {
|
|
619
|
+
const { x, y, width, height } = await elementRect(client, session, opts.elementId);
|
|
620
|
+
return { x: Math.round(x + width / 2), y: Math.round(y + height / 2) };
|
|
621
|
+
}
|
|
622
|
+
if (opts.x != null && opts.y != null)
|
|
623
|
+
return { x: opts.x, y: opts.y };
|
|
624
|
+
throw new Error('Provide either elementId or both x and y.');
|
|
625
|
+
}
|
|
626
|
+
export async function longPress(handle, opts, durationMs = 1500) {
|
|
627
|
+
const session = requireSession(handle);
|
|
628
|
+
const client = makeClient();
|
|
629
|
+
const { x, y } = await resolvePoint(client, session, opts);
|
|
630
|
+
const sid = session.gridSessionId;
|
|
631
|
+
const jwp = () => client.post(`/session/${sid}/touch/perform`, {
|
|
632
|
+
actions: [
|
|
633
|
+
{ action: 'longPress', options: { x, y } },
|
|
634
|
+
{ action: 'wait', options: { ms: durationMs } },
|
|
635
|
+
{ action: 'release', options: {} },
|
|
636
|
+
],
|
|
637
|
+
}, { timeout: 30_000 });
|
|
638
|
+
const w3c = () => client.post(`/session/${sid}/actions`, {
|
|
639
|
+
actions: [
|
|
640
|
+
{
|
|
641
|
+
type: 'pointer',
|
|
642
|
+
id: 'finger1',
|
|
643
|
+
parameters: { pointerType: 'touch' },
|
|
644
|
+
actions: [
|
|
645
|
+
{ type: 'pointerMove', duration: 0, x, y },
|
|
646
|
+
{ type: 'pointerDown', button: 0 },
|
|
647
|
+
{ type: 'pause', duration: durationMs },
|
|
648
|
+
{ type: 'pointerUp', button: 0 },
|
|
649
|
+
],
|
|
650
|
+
},
|
|
651
|
+
],
|
|
652
|
+
}, { timeout: 30_000 });
|
|
653
|
+
const [primary, fallback] = session.sessionFormat === 'w3c' ? [w3c, jwp] : [jwp, w3c];
|
|
654
|
+
try {
|
|
655
|
+
await primary();
|
|
656
|
+
}
|
|
657
|
+
catch (e) {
|
|
658
|
+
if (!isUnknownCommand(e))
|
|
659
|
+
throw e;
|
|
660
|
+
await fallback();
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
export async function doubleTap(handle, opts) {
|
|
664
|
+
const session = requireSession(handle);
|
|
665
|
+
const client = makeClient();
|
|
666
|
+
const { x, y } = await resolvePoint(client, session, opts);
|
|
667
|
+
const sid = session.gridSessionId;
|
|
668
|
+
// JWP TouchAction tap supports a count option.
|
|
669
|
+
const jwp = () => client.post(`/session/${sid}/touch/perform`, { actions: [{ action: 'tap', options: { x, y, count: 2 } }] }, { timeout: 30_000 });
|
|
670
|
+
const w3c = () => client.post(`/session/${sid}/actions`, {
|
|
671
|
+
actions: [
|
|
672
|
+
{
|
|
673
|
+
type: 'pointer',
|
|
674
|
+
id: 'finger1',
|
|
675
|
+
parameters: { pointerType: 'touch' },
|
|
676
|
+
actions: [
|
|
677
|
+
{ type: 'pointerMove', duration: 0, x, y },
|
|
678
|
+
{ type: 'pointerDown', button: 0 },
|
|
679
|
+
{ type: 'pointerUp', button: 0 },
|
|
680
|
+
{ type: 'pause', duration: 100 },
|
|
681
|
+
{ type: 'pointerDown', button: 0 },
|
|
682
|
+
{ type: 'pointerUp', button: 0 },
|
|
683
|
+
],
|
|
684
|
+
},
|
|
685
|
+
],
|
|
686
|
+
}, { timeout: 30_000 });
|
|
687
|
+
const [primary, fallback] = session.sessionFormat === 'w3c' ? [w3c, jwp] : [jwp, w3c];
|
|
688
|
+
try {
|
|
689
|
+
await primary();
|
|
690
|
+
}
|
|
691
|
+
catch (e) {
|
|
692
|
+
if (!isUnknownCommand(e))
|
|
693
|
+
throw e;
|
|
694
|
+
await fallback();
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
export async function dragAndDrop(handle, startX, startY, endX, endY, holdMs = 600, moveMs = 1200) {
|
|
698
|
+
const session = requireSession(handle);
|
|
699
|
+
const client = makeClient();
|
|
700
|
+
const sid = session.gridSessionId;
|
|
701
|
+
const jwp = () => client.post(`/session/${sid}/touch/perform`, {
|
|
702
|
+
actions: [
|
|
703
|
+
{ action: 'longPress', options: { x: startX, y: startY } },
|
|
704
|
+
{ action: 'wait', options: { ms: holdMs } },
|
|
705
|
+
{ action: 'moveTo', options: { x: endX, y: endY } },
|
|
706
|
+
{ action: 'wait', options: { ms: 150 } },
|
|
707
|
+
{ action: 'release', options: {} },
|
|
708
|
+
],
|
|
709
|
+
}, { timeout: 30_000 });
|
|
710
|
+
const w3c = () => client.post(`/session/${sid}/actions`, {
|
|
711
|
+
actions: [
|
|
712
|
+
{
|
|
713
|
+
type: 'pointer',
|
|
714
|
+
id: 'finger1',
|
|
715
|
+
parameters: { pointerType: 'touch' },
|
|
716
|
+
actions: [
|
|
717
|
+
{ type: 'pointerMove', duration: 0, x: startX, y: startY },
|
|
718
|
+
{ type: 'pointerDown', button: 0 },
|
|
719
|
+
{ type: 'pause', duration: holdMs },
|
|
720
|
+
{ type: 'pointerMove', duration: moveMs, x: endX, y: endY },
|
|
721
|
+
{ type: 'pause', duration: 150 },
|
|
722
|
+
{ type: 'pointerUp', button: 0 },
|
|
723
|
+
],
|
|
724
|
+
},
|
|
725
|
+
],
|
|
726
|
+
}, { timeout: 30_000 });
|
|
727
|
+
const [primary, fallback] = session.sessionFormat === 'w3c' ? [w3c, jwp] : [jwp, w3c];
|
|
728
|
+
try {
|
|
729
|
+
await primary();
|
|
730
|
+
}
|
|
731
|
+
catch (e) {
|
|
732
|
+
if (!isUnknownCommand(e))
|
|
733
|
+
throw e;
|
|
734
|
+
await fallback();
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
export async function pinchZoom(handle, direction, centerX, centerY, distance = 300, durationMs = 400) {
|
|
738
|
+
const session = requireSession(handle);
|
|
739
|
+
// Confirmed live: the Grid's JWP proxy 501s multi-touch (touch/multi/perform)
|
|
740
|
+
// and does not route /actions — pinch is Appium Server (W3C) only.
|
|
741
|
+
if (session.sessionFormat === 'jwp') {
|
|
742
|
+
throw new Error('Pinch/zoom is not supported on Appium Grid sessions (the Grid rejects multi-touch). ' +
|
|
743
|
+
'It works on Appium Server (OSS) project sessions.');
|
|
744
|
+
}
|
|
745
|
+
const client = makeClient();
|
|
746
|
+
const sid = session.gridSessionId;
|
|
747
|
+
let cx = centerX;
|
|
748
|
+
let cy = centerY;
|
|
749
|
+
if (cx == null || cy == null) {
|
|
750
|
+
const { width, height } = await getWindowSize(handle);
|
|
751
|
+
cx = Math.round(width / 2);
|
|
752
|
+
cy = Math.round(height / 2);
|
|
753
|
+
}
|
|
754
|
+
// 'in' = zoom in = fingers diverge from center; 'out' = zoom out = fingers converge.
|
|
755
|
+
const near = 60;
|
|
756
|
+
const [f1Start, f1End, f2Start, f2End] = direction === 'in'
|
|
757
|
+
? [cx - near, cx - near - distance, cx + near, cx + near + distance]
|
|
758
|
+
: [cx - near - distance, cx - near, cx + near + distance, cx + near];
|
|
759
|
+
const finger = (id, startX, endX) => ({
|
|
760
|
+
type: 'pointer',
|
|
761
|
+
id,
|
|
762
|
+
parameters: { pointerType: 'touch' },
|
|
763
|
+
actions: [
|
|
764
|
+
{ type: 'pointerMove', duration: 0, x: startX, y: cy },
|
|
765
|
+
{ type: 'pointerDown', button: 0 },
|
|
766
|
+
{ type: 'pause', duration: 100 },
|
|
767
|
+
{ type: 'pointerMove', duration: durationMs, x: endX, y: cy },
|
|
768
|
+
{ type: 'pointerUp', button: 0 },
|
|
769
|
+
],
|
|
770
|
+
});
|
|
771
|
+
await client.post(`/session/${sid}/actions`, { actions: [finger('finger1', f1Start, f1End), finger('finger2', f2Start, f2End)] }, { timeout: 30_000 });
|
|
772
|
+
}
|
|
773
|
+
export async function scrollToElement(handle, using, value, direction = 'up', maxSwipes = 8) {
|
|
774
|
+
const session = requireSession(handle);
|
|
775
|
+
const { width, height } = await getWindowSize(handle);
|
|
776
|
+
const midX = Math.round(width / 2);
|
|
777
|
+
// 'up' finger movement scrolls content forward/down — the common case for lists.
|
|
778
|
+
const [startY, endY] = direction === 'up'
|
|
779
|
+
? [Math.round(height * 0.7), Math.round(height * 0.3)]
|
|
780
|
+
: [Math.round(height * 0.3), Math.round(height * 0.7)];
|
|
781
|
+
let swipesUsed = 0;
|
|
782
|
+
let lastSource = '';
|
|
783
|
+
for (let i = 0; i <= maxSwipes; i++) {
|
|
784
|
+
const found = await findElements(handle, using, value);
|
|
785
|
+
if (found.length > 0)
|
|
786
|
+
return { found: true, element: found[0], swipesUsed, reachedEnd: false };
|
|
787
|
+
if (i === maxSwipes)
|
|
788
|
+
break;
|
|
789
|
+
const source = await getPageSource(session.handle);
|
|
790
|
+
if (source === lastSource) {
|
|
791
|
+
// Screen unchanged after a swipe — end of scrollable content.
|
|
792
|
+
return { found: false, element: null, swipesUsed, reachedEnd: true };
|
|
793
|
+
}
|
|
794
|
+
lastSource = source;
|
|
795
|
+
await swipeScreen(handle, midX, startY, midX, endY, 500);
|
|
796
|
+
swipesUsed++;
|
|
797
|
+
await new Promise((r) => setTimeout(r, 600)); // let the scroll settle
|
|
798
|
+
}
|
|
799
|
+
return { found: false, element: null, swipesUsed, reachedEnd: false };
|
|
800
|
+
}
|
|
801
|
+
// ─── Keys & keyboard ─────────────────────────────────────────────────────────
|
|
802
|
+
export const ANDROID_KEYCODES = {
|
|
803
|
+
HOME: 3,
|
|
804
|
+
BACK: 4,
|
|
805
|
+
VOLUME_UP: 24,
|
|
806
|
+
VOLUME_DOWN: 25,
|
|
807
|
+
POWER: 26,
|
|
808
|
+
TAB: 61,
|
|
809
|
+
ENTER: 66,
|
|
810
|
+
DELETE: 67,
|
|
811
|
+
MENU: 82,
|
|
812
|
+
SEARCH: 84,
|
|
813
|
+
APP_SWITCH: 187,
|
|
814
|
+
};
|
|
815
|
+
// iOS physical buttons: XCUITest `mobile: pressButton` name → SeeTest deviceAction label.
|
|
816
|
+
const IOS_BUTTONS = {
|
|
817
|
+
HOME: { w3c: 'home', grid: 'Home' },
|
|
818
|
+
VOLUME_UP: { w3c: 'volumeup', grid: 'Volume Up' },
|
|
819
|
+
VOLUME_DOWN: { w3c: 'volumedown', grid: 'Volume Down' },
|
|
820
|
+
POWER: { w3c: 'power', grid: 'Lock' },
|
|
821
|
+
};
|
|
822
|
+
export async function pressKey(handle, key, keycode) {
|
|
823
|
+
const session = requireSession(handle);
|
|
824
|
+
const client = makeClient();
|
|
825
|
+
const sid = session.gridSessionId;
|
|
826
|
+
if (session.platform === 'ios') {
|
|
827
|
+
const button = key ? IOS_BUTTONS[key] : undefined;
|
|
828
|
+
if (!button) {
|
|
829
|
+
throw new Error(`${key ?? `keycode ${keycode}`} is not available on iOS. Supported: HOME, VOLUME_UP, VOLUME_DOWN, POWER. ` +
|
|
830
|
+
`For ENTER, type "\\n" with type_into_element; iOS has no BACK button — press_back performs the edge-swipe instead.`);
|
|
831
|
+
}
|
|
832
|
+
const w3c = () => execScript(client, session, 'mobile: pressButton', [{ name: button.w3c }]);
|
|
833
|
+
const grid = () => client.post(`/session/${sid}/execute`, { script: 'seetest:client.deviceAction', args: [button.grid] }, { timeout: 15_000 });
|
|
834
|
+
const [primary, fallback] = session.sessionFormat === 'w3c' ? [w3c, grid] : [grid, w3c];
|
|
835
|
+
try {
|
|
836
|
+
await primary();
|
|
837
|
+
}
|
|
838
|
+
catch (e) {
|
|
839
|
+
try {
|
|
840
|
+
await fallback();
|
|
841
|
+
}
|
|
842
|
+
catch (e2) {
|
|
843
|
+
throw new Error(`pressKey failed: ${describeWdError(e)}; fallback: ${describeWdError(e2)}`);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
return key;
|
|
847
|
+
}
|
|
848
|
+
const code = keycode ?? (key ? ANDROID_KEYCODES[key] : undefined);
|
|
849
|
+
if (code == null)
|
|
850
|
+
throw new Error('Provide a named key or an Android keycode.');
|
|
851
|
+
// Confirmed live: the Grid routes the legacy press_keycode endpoint.
|
|
852
|
+
const jwp = () => client.post(`/session/${sid}/appium/device/press_keycode`, { keycode: code }, { timeout: 15_000 });
|
|
853
|
+
const w3c = () => execScript(client, session, 'mobile: pressKey', [{ keycode: code }]);
|
|
854
|
+
const [primary, fallback] = session.sessionFormat === 'w3c' ? [w3c, jwp] : [jwp, w3c];
|
|
855
|
+
try {
|
|
856
|
+
await primary();
|
|
857
|
+
}
|
|
858
|
+
catch (e) {
|
|
859
|
+
if (!isUnknownCommand(e))
|
|
860
|
+
throw e;
|
|
861
|
+
await fallback();
|
|
862
|
+
}
|
|
863
|
+
return key ?? `keycode ${code}`;
|
|
864
|
+
}
|
|
865
|
+
export async function isKeyboardShown(handle) {
|
|
866
|
+
const session = requireSession(handle);
|
|
867
|
+
const client = makeClient();
|
|
868
|
+
const sid = session.gridSessionId;
|
|
869
|
+
const w3c = async () => {
|
|
870
|
+
const res = await execScript(client, session, 'mobile: isKeyboardShown', [{}]);
|
|
871
|
+
return Boolean(res.data.value);
|
|
872
|
+
};
|
|
873
|
+
const jwp = async () => {
|
|
874
|
+
const res = await client.get(`/session/${sid}/appium/device/is_keyboard_shown`, {
|
|
875
|
+
timeout: 15_000,
|
|
876
|
+
});
|
|
877
|
+
return Boolean(res.data.value);
|
|
878
|
+
};
|
|
879
|
+
const [primary, fallback] = session.sessionFormat === 'w3c' ? [w3c, jwp] : [jwp, w3c];
|
|
880
|
+
try {
|
|
881
|
+
return await primary();
|
|
882
|
+
}
|
|
883
|
+
catch (e) {
|
|
884
|
+
try {
|
|
885
|
+
return await fallback();
|
|
886
|
+
}
|
|
887
|
+
catch (e2) {
|
|
888
|
+
throw new Error(`isKeyboardShown failed: ${describeWdError(e)}; fallback: ${describeWdError(e2)}`);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
export async function hideKeyboard(handle) {
|
|
893
|
+
const session = requireSession(handle);
|
|
894
|
+
const client = makeClient();
|
|
895
|
+
const sid = session.gridSessionId;
|
|
896
|
+
const w3c = () => execScript(client, session, 'mobile: hideKeyboard', [{}]);
|
|
897
|
+
const jwp = () => client.post(`/session/${sid}/appium/device/hide_keyboard`, {}, { timeout: 15_000 });
|
|
898
|
+
const [primary, fallback] = session.sessionFormat === 'w3c' ? [w3c, jwp] : [jwp, w3c];
|
|
899
|
+
try {
|
|
900
|
+
await primary();
|
|
901
|
+
}
|
|
902
|
+
catch (e) {
|
|
903
|
+
try {
|
|
904
|
+
await fallback();
|
|
905
|
+
}
|
|
906
|
+
catch (e2) {
|
|
907
|
+
throw new Error(`hideKeyboard failed: ${describeWdError(e)}; fallback: ${describeWdError(e2)}`);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
const APP_STATE_LABELS = {
|
|
912
|
+
0: 'not installed',
|
|
913
|
+
1: 'not running',
|
|
914
|
+
2: 'running in background (suspended)',
|
|
915
|
+
3: 'running in background',
|
|
916
|
+
4: 'running in foreground',
|
|
917
|
+
};
|
|
918
|
+
export async function appControl(handle, action, packageName, url) {
|
|
919
|
+
const session = requireSession(handle);
|
|
920
|
+
const client = makeClient();
|
|
921
|
+
const sid = session.gridSessionId;
|
|
922
|
+
const isW3c = session.sessionFormat === 'w3c';
|
|
923
|
+
const isIos = session.platform === 'ios';
|
|
924
|
+
switch (action) {
|
|
925
|
+
case 'terminate': {
|
|
926
|
+
if (!packageName)
|
|
927
|
+
throw new Error('terminate requires packageName (Android) or bundleIdentifier (iOS).');
|
|
928
|
+
if (isW3c) {
|
|
929
|
+
const args = isIos ? { bundleId: packageName } : { appId: packageName };
|
|
930
|
+
const res = await execScript(client, session, 'mobile: terminateApp', [args]);
|
|
931
|
+
return res.data.value
|
|
932
|
+
? `Terminated ${packageName}.`
|
|
933
|
+
: `${packageName} was not running.`;
|
|
934
|
+
}
|
|
935
|
+
await execScript(client, session, 'seetest:client.applicationClose', [packageName]);
|
|
936
|
+
return `Closed ${packageName}.`;
|
|
937
|
+
}
|
|
938
|
+
case 'clear_data': {
|
|
939
|
+
if (!packageName)
|
|
940
|
+
throw new Error('clear_data requires packageName.');
|
|
941
|
+
if (isIos) {
|
|
942
|
+
throw new Error('iOS cannot clear app data (XCUITest has no equivalent of Android clearApp). ' +
|
|
943
|
+
'Uninstall and reinstall the app instead: uninstall_application_by_package, then install_application.');
|
|
944
|
+
}
|
|
945
|
+
if (isW3c) {
|
|
946
|
+
await execScript(client, session, 'mobile: clearApp', [{ appId: packageName }]);
|
|
947
|
+
}
|
|
948
|
+
else {
|
|
949
|
+
await execScript(client, session, 'seetest:client.applicationClearData', [packageName]);
|
|
950
|
+
}
|
|
951
|
+
return `Cleared app data for ${packageName}. The app is back to first-launch state.`;
|
|
952
|
+
}
|
|
953
|
+
case 'query_state': {
|
|
954
|
+
if (!packageName)
|
|
955
|
+
throw new Error('query_state requires packageName (Android) or bundleIdentifier (iOS).');
|
|
956
|
+
if (isW3c) {
|
|
957
|
+
const args = isIos ? { bundleId: packageName } : { appId: packageName };
|
|
958
|
+
const res = await execScript(client, session, 'mobile: queryAppState', [args]);
|
|
959
|
+
const code = Number(res.data.value);
|
|
960
|
+
return `${packageName}: ${APP_STATE_LABELS[code] ?? `state ${code}`} (code ${code}).`;
|
|
961
|
+
}
|
|
962
|
+
if (isIos) {
|
|
963
|
+
throw new Error('query_state is not supported on Grid iOS sessions (no current-activity equivalent). ' +
|
|
964
|
+
'Use take_inspection_screenshot to check what is in the foreground.');
|
|
965
|
+
}
|
|
966
|
+
// The Android Grid has no queryAppState — report the foreground check instead.
|
|
967
|
+
const res = await client.get(`/session/${sid}/appium/device/current_activity`, {
|
|
968
|
+
timeout: 15_000,
|
|
969
|
+
});
|
|
970
|
+
const activity = String(res.data.value ?? '');
|
|
971
|
+
const fg = activity.startsWith(packageName) || activity.startsWith('.')
|
|
972
|
+
? `current activity is "${activity}" — compare against the app's activities`
|
|
973
|
+
: `current activity is "${activity}"`;
|
|
974
|
+
return `${packageName}: Grid sessions can only check the foreground activity — ${fg}.`;
|
|
975
|
+
}
|
|
976
|
+
case 'deep_link': {
|
|
977
|
+
if (!url)
|
|
978
|
+
throw new Error('deep_link requires url.');
|
|
979
|
+
if (isW3c) {
|
|
980
|
+
const args = { url };
|
|
981
|
+
// Android needs the handler package; iOS routes through the system.
|
|
982
|
+
if (packageName && !isIos)
|
|
983
|
+
args['package'] = packageName;
|
|
984
|
+
await execScript(client, session, 'mobile: deepLink', [args]);
|
|
985
|
+
return `Opened deep link ${url}.`;
|
|
986
|
+
}
|
|
987
|
+
// Best-effort on the Grid: seetest:client.launch accepts URLs but depends
|
|
988
|
+
// on the device's default handler being in a usable state.
|
|
989
|
+
await execScript(client, session, 'seetest:client.launch', [url, false, true]);
|
|
990
|
+
return `Opened ${url} via seetest:client.launch (best-effort on Grid — depends on the device's default URL handler).`;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
// ─── Device control ──────────────────────────────────────────────────────────
|
|
995
|
+
export async function getOrientation(handle) {
|
|
996
|
+
const session = requireSession(handle);
|
|
997
|
+
const client = makeClient();
|
|
998
|
+
const res = await client.get(`/session/${session.gridSessionId}/orientation`, {
|
|
999
|
+
timeout: 15_000,
|
|
1000
|
+
});
|
|
1001
|
+
return String(res.data.value ?? '').toUpperCase();
|
|
1002
|
+
}
|
|
1003
|
+
export async function setOrientation(handle, orientation) {
|
|
1004
|
+
const session = requireSession(handle);
|
|
1005
|
+
const client = makeClient();
|
|
1006
|
+
await client.post(`/session/${session.gridSessionId}/orientation`, { orientation }, { timeout: 15_000 });
|
|
1007
|
+
}
|
|
1008
|
+
export async function getClipboard(handle) {
|
|
1009
|
+
const session = requireSession(handle);
|
|
1010
|
+
const client = makeClient();
|
|
1011
|
+
let b64;
|
|
1012
|
+
try {
|
|
1013
|
+
if (session.sessionFormat === 'w3c') {
|
|
1014
|
+
const res = await execScript(client, session, 'mobile: getClipboard', [
|
|
1015
|
+
{ contentType: 'plaintext' },
|
|
1016
|
+
]);
|
|
1017
|
+
b64 = String(res.data.value ?? '');
|
|
1018
|
+
}
|
|
1019
|
+
else {
|
|
1020
|
+
const res = await client.post(`/session/${session.gridSessionId}/appium/device/get_clipboard`, { contentType: 'plaintext' }, { timeout: 15_000 });
|
|
1021
|
+
b64 = String(res.data.value ?? '');
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
catch (e) {
|
|
1025
|
+
// Grid iOS devices report "This option is not supported on this device".
|
|
1026
|
+
throw new Error(describeWdError(e));
|
|
1027
|
+
}
|
|
1028
|
+
return b64 ? Buffer.from(b64, 'base64').toString('utf8') : '';
|
|
1029
|
+
}
|
|
1030
|
+
export async function setClipboard(handle, text) {
|
|
1031
|
+
const session = requireSession(handle);
|
|
1032
|
+
const client = makeClient();
|
|
1033
|
+
const content = Buffer.from(text, 'utf8').toString('base64');
|
|
1034
|
+
try {
|
|
1035
|
+
if (session.sessionFormat === 'w3c') {
|
|
1036
|
+
await execScript(client, session, 'mobile: setClipboard', [
|
|
1037
|
+
{ content, contentType: 'plaintext' },
|
|
1038
|
+
]);
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
await client.post(`/session/${session.gridSessionId}/appium/device/set_clipboard`, { content, contentType: 'plaintext' }, { timeout: 15_000 });
|
|
1042
|
+
}
|
|
1043
|
+
catch (e) {
|
|
1044
|
+
throw new Error(describeWdError(e));
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
export async function setGeolocation(handle, latitude, longitude) {
|
|
1048
|
+
const session = requireSession(handle);
|
|
1049
|
+
const client = makeClient();
|
|
1050
|
+
if (session.sessionFormat === 'w3c') {
|
|
1051
|
+
// Legacy POST /location 500s on Appium Server. XCUITest uses
|
|
1052
|
+
// setSimulatedLocation; UiAutomator2 uses setGeolocation — both confirmed live.
|
|
1053
|
+
const script = session.platform === 'ios' ? 'mobile: setSimulatedLocation' : 'mobile: setGeolocation';
|
|
1054
|
+
await execScript(client, session, script, [{ latitude, longitude }]);
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
// Confirmed live on the Grid (both platforms): seetest:client.setLocation, string args.
|
|
1058
|
+
await execScript(client, session, 'seetest:client.setLocation', [
|
|
1059
|
+
String(latitude),
|
|
1060
|
+
String(longitude),
|
|
1061
|
+
]);
|
|
1062
|
+
}
|
|
1063
|
+
export async function resetGeolocation(handle) {
|
|
1064
|
+
const session = requireSession(handle);
|
|
1065
|
+
if (session.sessionFormat === 'jwp') {
|
|
1066
|
+
// seetest:client.clearLocation exists but the Grid's execute parser cannot
|
|
1067
|
+
// express 0-arg commands — confirmed live.
|
|
1068
|
+
throw new Error('Geolocation reset is not supported on Appium Grid sessions. ' +
|
|
1069
|
+
'Set explicit coordinates instead, or use an Appium Server (OSS) project session.');
|
|
1070
|
+
}
|
|
1071
|
+
const client = makeClient();
|
|
1072
|
+
const script = session.platform === 'ios' ? 'mobile: resetSimulatedLocation' : 'mobile: resetGeolocation';
|
|
1073
|
+
await execScript(client, session, script, [{}]);
|
|
1074
|
+
}
|
|
1075
|
+
export async function handleAlert(handle, action) {
|
|
1076
|
+
const session = requireSession(handle);
|
|
1077
|
+
if (session.sessionFormat === 'jwp') {
|
|
1078
|
+
// Confirmed live: all alert routes 501 on the Grid.
|
|
1079
|
+
throw new Error('Alert handling is not supported on Appium Grid sessions (the Grid returns 501 Not Implemented). ' +
|
|
1080
|
+
'On Android, dialogs are regular UI elements — use get_element_tree to find the button and tap_element to dismiss it.');
|
|
1081
|
+
}
|
|
1082
|
+
const client = makeClient();
|
|
1083
|
+
try {
|
|
1084
|
+
await client.post(`/session/${session.gridSessionId}/alert/${action}`, {}, { timeout: 15_000 });
|
|
1085
|
+
}
|
|
1086
|
+
catch (e) {
|
|
1087
|
+
const detail = describeWdError(e).toLowerCase();
|
|
1088
|
+
if (detail.includes('no alert') ||
|
|
1089
|
+
detail.includes('noalertopen') ||
|
|
1090
|
+
detail.includes('modal dialog when one was not open')) {
|
|
1091
|
+
throw new Error('No alert is present on the screen — nothing to accept/dismiss.');
|
|
1092
|
+
}
|
|
1093
|
+
throw new Error(describeWdError(e));
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
export async function pushFileToDevice(handle, remotePath, base64Data) {
|
|
1097
|
+
const session = requireSession(handle);
|
|
1098
|
+
const client = makeClient();
|
|
1099
|
+
if (session.sessionFormat === 'w3c') {
|
|
1100
|
+
await execScript(client, session, 'mobile: pushFile', [
|
|
1101
|
+
{ remotePath, payload: base64Data },
|
|
1102
|
+
]);
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
await client.post(`/session/${session.gridSessionId}/appium/device/push_file`, { path: remotePath, data: base64Data }, { timeout: 60_000 });
|
|
1106
|
+
}
|
|
1107
|
+
export async function pullFileFromDevice(handle, remotePath) {
|
|
1108
|
+
const session = requireSession(handle);
|
|
1109
|
+
const client = makeClient();
|
|
1110
|
+
if (session.sessionFormat === 'w3c') {
|
|
1111
|
+
const res = await execScript(client, session, 'mobile: pullFile', [{ remotePath }]);
|
|
1112
|
+
return String(res.data.value ?? '');
|
|
1113
|
+
}
|
|
1114
|
+
const res = await client.post(`/session/${session.gridSessionId}/appium/device/pull_file`, { path: remotePath }, { timeout: 60_000 });
|
|
1115
|
+
return String(res.data.value ?? '');
|
|
1116
|
+
}
|
|
1117
|
+
// ─── Biometric authentication mock ───────────────────────────────────────────
|
|
1118
|
+
export async function mockAuthentication(handle, reply, delayMs) {
|
|
1119
|
+
const session = requireSession(handle);
|
|
1120
|
+
if (session.platform === 'web')
|
|
1121
|
+
throw new Error('mock_authentication is not available for browser sessions.');
|
|
1122
|
+
const client = makeClient();
|
|
1123
|
+
// Android uses string enum values; iOS uses LAError numeric codes.
|
|
1124
|
+
const replyValue = session.platform === 'ios'
|
|
1125
|
+
? { success: 1, failed: -1, cancel: -2, clear: 0 }[reply]
|
|
1126
|
+
: { success: 'AUTHENTICATION_SUCCEEDED', failed: 'AUTHENTICATION_FAILED', cancel: 'ERROR_CANCELED', clear: 'CLEAR_MOCK' }[reply];
|
|
1127
|
+
await execScript(client, session, 'seetest:client.setAuthenticationReply', [replyValue, delayMs]);
|
|
1128
|
+
const label = reply === 'clear' ? 'cleared (no mock active)' : `staged as "${reply}"`;
|
|
1129
|
+
return (`Authentication response ${label}. ` +
|
|
1130
|
+
`The next biometric prompt in the instrumented app will respond automatically.`);
|
|
1131
|
+
}
|
|
1132
|
+
export function registerSession(session) {
|
|
1133
|
+
sessionRegistry.set(session.handle, session);
|
|
1134
|
+
if (session.reportTestId > 0)
|
|
1135
|
+
allReports.set(session.reportTestId, session.projectName);
|
|
1136
|
+
}
|
|
1137
|
+
export function requireSession(handle) {
|
|
1138
|
+
const s = sessionRegistry.get(handle);
|
|
1139
|
+
if (!s)
|
|
1140
|
+
throw new Error(`No active inspection session "${handle}". Use list_inspection_sessions to see active sessions.`);
|
|
1141
|
+
// Track idle gaps — Grid sessions expire after ~4 minutes without a command,
|
|
1142
|
+
// so the gap preceding a failure is the key diagnostic (v36).
|
|
1143
|
+
const now = Date.now();
|
|
1144
|
+
s.lastIdleMs = now - s.lastUsedAt;
|
|
1145
|
+
s.lastUsedAt = now;
|
|
1146
|
+
return s;
|
|
1147
|
+
}
|
|
1148
|
+
export function listActiveSessions() {
|
|
1149
|
+
return [...sessionRegistry.values()];
|
|
1150
|
+
}
|
|
1151
|
+
export function getPendingReportIds() {
|
|
1152
|
+
return [...allReports.keys()];
|
|
1153
|
+
}
|
|
1154
|
+
export async function deleteAllTrackedReports() {
|
|
1155
|
+
if (allReports.size === 0)
|
|
1156
|
+
return { deleted: [], failed: [] };
|
|
1157
|
+
// Group by originating project — each project's reports live in its own
|
|
1158
|
+
// reporter instance and must be deleted with a matching projectName scope.
|
|
1159
|
+
const byProject = new Map();
|
|
1160
|
+
for (const [id, project] of allReports) {
|
|
1161
|
+
const list = byProject.get(project) ?? [];
|
|
1162
|
+
list.push(id);
|
|
1163
|
+
byProject.set(project, list);
|
|
1164
|
+
}
|
|
1165
|
+
// Tolerate per-project failures: one project's delete failing must not abort
|
|
1166
|
+
// the rest, and failed reports stay tracked so a later cleanup can retry them.
|
|
1167
|
+
const deleted = [];
|
|
1168
|
+
const failed = [];
|
|
1169
|
+
for (const [project, ids] of byProject) {
|
|
1170
|
+
try {
|
|
1171
|
+
await deleteTests(ids, undefined, project);
|
|
1172
|
+
for (const id of ids) {
|
|
1173
|
+
allReports.delete(id);
|
|
1174
|
+
deleted.push(id);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
catch {
|
|
1178
|
+
failed.push(...ids);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
return { deleted, failed };
|
|
1182
|
+
}
|
|
1183
|
+
//# sourceMappingURL=webdriver.js.map
|