agent-device 0.1.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.
- package/LICENSE +21 -0
- package/README.md +99 -0
- package/bin/agent-device.mjs +14 -0
- package/bin/axsnapshot +0 -0
- package/dist/src/861.js +1 -0
- package/dist/src/bin.js +50 -0
- package/dist/src/daemon.js +5 -0
- package/ios-runner/AXSnapshot/Package.swift +18 -0
- package/ios-runner/AXSnapshot/Sources/AXSnapshot/main.swift +167 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.swift +17 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AccentColor.colorset/Contents.json +11 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/Contents.json +36 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/logo.jpg +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Contents.json +6 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/Contents.json +21 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/logo.jpg +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/Contents.json +21 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/powered-by.png +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/ContentView.swift +34 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +461 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/xcshareddata/xcschemes/AgentDeviceRunner.xcscheme +102 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +696 -0
- package/ios-runner/README.md +11 -0
- package/package.json +66 -0
- package/src/bin.ts +3 -0
- package/src/cli.ts +160 -0
- package/src/core/dispatch.ts +259 -0
- package/src/daemon-client.ts +166 -0
- package/src/daemon.ts +842 -0
- package/src/platforms/android/devices.ts +59 -0
- package/src/platforms/android/index.ts +442 -0
- package/src/platforms/ios/ax-snapshot.ts +154 -0
- package/src/platforms/ios/devices.ts +65 -0
- package/src/platforms/ios/index.ts +218 -0
- package/src/platforms/ios/runner-client.ts +534 -0
- package/src/utils/args.ts +175 -0
- package/src/utils/device.ts +84 -0
- package/src/utils/errors.ts +35 -0
- package/src/utils/exec.ts +229 -0
- package/src/utils/interactive.ts +4 -0
- package/src/utils/interactors.ts +72 -0
- package/src/utils/output.ts +146 -0
- package/src/utils/snapshot.ts +63 -0
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { AppError } from '../../utils/errors.ts';
|
|
6
|
+
import { runCmd, runCmdStreaming, type ExecResult } from '../../utils/exec.ts';
|
|
7
|
+
import type { DeviceInfo } from '../../utils/device.ts';
|
|
8
|
+
import net from 'node:net';
|
|
9
|
+
|
|
10
|
+
export type RunnerCommand = {
|
|
11
|
+
command: 'tap' | 'type' | 'swipe' | 'findText' | 'listTappables' | 'snapshot' | 'rect' | 'shutdown';
|
|
12
|
+
appBundleId?: string;
|
|
13
|
+
text?: string;
|
|
14
|
+
x?: number;
|
|
15
|
+
y?: number;
|
|
16
|
+
direction?: 'up' | 'down' | 'left' | 'right';
|
|
17
|
+
interactiveOnly?: boolean;
|
|
18
|
+
compact?: boolean;
|
|
19
|
+
depth?: number;
|
|
20
|
+
scope?: string;
|
|
21
|
+
raw?: boolean;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type RunnerSession = {
|
|
25
|
+
device: DeviceInfo;
|
|
26
|
+
deviceId: string;
|
|
27
|
+
port: number;
|
|
28
|
+
xctestrunPath: string;
|
|
29
|
+
jsonPath: string;
|
|
30
|
+
testPromise: Promise<ExecResult>;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const runnerSessions = new Map<string, RunnerSession>();
|
|
34
|
+
|
|
35
|
+
export type RunnerSnapshotNode = {
|
|
36
|
+
index: number;
|
|
37
|
+
type?: string;
|
|
38
|
+
label?: string;
|
|
39
|
+
value?: string;
|
|
40
|
+
identifier?: string;
|
|
41
|
+
rect?: { x: number; y: number; width: number; height: number };
|
|
42
|
+
enabled?: boolean;
|
|
43
|
+
hittable?: boolean;
|
|
44
|
+
depth?: number;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export async function runIosRunnerCommand(
|
|
48
|
+
device: DeviceInfo,
|
|
49
|
+
command: RunnerCommand,
|
|
50
|
+
options: { verbose?: boolean; logPath?: string } = {},
|
|
51
|
+
): Promise<Record<string, unknown>> {
|
|
52
|
+
if (device.kind !== 'simulator') {
|
|
53
|
+
throw new AppError('UNSUPPORTED_OPERATION', 'iOS runner only supports simulators in v1');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
const session = await ensureRunnerSession(device, options);
|
|
58
|
+
const response = await waitForRunner(device, session.port, command, options.logPath);
|
|
59
|
+
const text = await response.text();
|
|
60
|
+
|
|
61
|
+
let json: any = {};
|
|
62
|
+
try {
|
|
63
|
+
json = JSON.parse(text);
|
|
64
|
+
} catch {
|
|
65
|
+
throw new AppError('COMMAND_FAILED', 'Invalid runner response', { text });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (!json.ok) {
|
|
69
|
+
throw new AppError('COMMAND_FAILED', json.error?.message ?? 'Runner error', {
|
|
70
|
+
runner: json,
|
|
71
|
+
xcodebuild: {
|
|
72
|
+
exitCode: 1,
|
|
73
|
+
stdout: '',
|
|
74
|
+
stderr: '',
|
|
75
|
+
},
|
|
76
|
+
logPath: options.logPath,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return json.data ?? {};
|
|
81
|
+
} catch (err) {
|
|
82
|
+
const appErr = err instanceof AppError ? err : new AppError('COMMAND_FAILED', String(err));
|
|
83
|
+
if (
|
|
84
|
+
appErr.code === 'COMMAND_FAILED' &&
|
|
85
|
+
typeof appErr.message === 'string' &&
|
|
86
|
+
appErr.message.includes('Runner did not accept connection')
|
|
87
|
+
) {
|
|
88
|
+
await stopIosRunnerSession(device.id);
|
|
89
|
+
const session = await ensureRunnerSession(device, options);
|
|
90
|
+
const response = await waitForRunner(device, session.port, command, options.logPath);
|
|
91
|
+
const text = await response.text();
|
|
92
|
+
let json: any = {};
|
|
93
|
+
try {
|
|
94
|
+
json = JSON.parse(text);
|
|
95
|
+
} catch {
|
|
96
|
+
throw new AppError('COMMAND_FAILED', 'Invalid runner response', { text });
|
|
97
|
+
}
|
|
98
|
+
if (!json.ok) {
|
|
99
|
+
throw new AppError('COMMAND_FAILED', json.error?.message ?? 'Runner error', {
|
|
100
|
+
runner: json,
|
|
101
|
+
xcodebuild: {
|
|
102
|
+
exitCode: 1,
|
|
103
|
+
stdout: '',
|
|
104
|
+
stderr: '',
|
|
105
|
+
},
|
|
106
|
+
logPath: options.logPath,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return json.data ?? {};
|
|
110
|
+
}
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function stopIosRunnerSession(deviceId: string): Promise<void> {
|
|
116
|
+
const session = runnerSessions.get(deviceId);
|
|
117
|
+
if (!session) return;
|
|
118
|
+
try {
|
|
119
|
+
await waitForRunner(session.device, session.port, {
|
|
120
|
+
command: 'shutdown',
|
|
121
|
+
} as RunnerCommand);
|
|
122
|
+
} catch {
|
|
123
|
+
// ignore
|
|
124
|
+
}
|
|
125
|
+
try {
|
|
126
|
+
await session.testPromise;
|
|
127
|
+
} catch {
|
|
128
|
+
// ignore
|
|
129
|
+
}
|
|
130
|
+
cleanupTempFile(session.xctestrunPath);
|
|
131
|
+
cleanupTempFile(session.jsonPath);
|
|
132
|
+
runnerSessions.delete(deviceId);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function ensureBooted(udid: string): Promise<void> {
|
|
136
|
+
await runCmd('xcrun', ['simctl', 'bootstatus', udid, '-b'], { allowFailure: true });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function ensureRunnerSession(
|
|
140
|
+
device: DeviceInfo,
|
|
141
|
+
options: { verbose?: boolean; logPath?: string },
|
|
142
|
+
): Promise<RunnerSession> {
|
|
143
|
+
const existing = runnerSessions.get(device.id);
|
|
144
|
+
if (existing) return existing;
|
|
145
|
+
|
|
146
|
+
await ensureBooted(device.id);
|
|
147
|
+
const xctestrun = await ensureXctestrun(device.id, options);
|
|
148
|
+
const port = await getFreePort();
|
|
149
|
+
const runnerTimeout = process.env.AGENT_DEVICE_RUNNER_TIMEOUT ?? '300';
|
|
150
|
+
const { xctestrunPath, jsonPath } = await prepareXctestrunWithEnv(
|
|
151
|
+
xctestrun,
|
|
152
|
+
{ AGENT_DEVICE_RUNNER_PORT: String(port), AGENT_DEVICE_RUNNER_TIMEOUT: runnerTimeout },
|
|
153
|
+
`session-${device.id}-${port}`,
|
|
154
|
+
);
|
|
155
|
+
const testPromise = runCmdStreaming(
|
|
156
|
+
'xcodebuild',
|
|
157
|
+
[
|
|
158
|
+
'test-without-building',
|
|
159
|
+
'-only-testing',
|
|
160
|
+
'AgentDeviceRunnerUITests/RunnerTests/testCommand',
|
|
161
|
+
'-parallel-testing-enabled',
|
|
162
|
+
'NO',
|
|
163
|
+
'-maximum-concurrent-test-simulator-destinations',
|
|
164
|
+
'1',
|
|
165
|
+
'-xctestrun',
|
|
166
|
+
xctestrunPath,
|
|
167
|
+
'-destination',
|
|
168
|
+
`platform=iOS Simulator,id=${device.id}`,
|
|
169
|
+
],
|
|
170
|
+
{
|
|
171
|
+
onStdoutChunk: (chunk) => {
|
|
172
|
+
logChunk(chunk, options.logPath, options.verbose);
|
|
173
|
+
},
|
|
174
|
+
onStderrChunk: (chunk) => {
|
|
175
|
+
logChunk(chunk, options.logPath, options.verbose);
|
|
176
|
+
},
|
|
177
|
+
allowFailure: true,
|
|
178
|
+
env: { ...process.env, AGENT_DEVICE_RUNNER_PORT: String(port), AGENT_DEVICE_RUNNER_TIMEOUT: runnerTimeout },
|
|
179
|
+
},
|
|
180
|
+
);
|
|
181
|
+
|
|
182
|
+
const session: RunnerSession = {
|
|
183
|
+
device,
|
|
184
|
+
deviceId: device.id,
|
|
185
|
+
port,
|
|
186
|
+
xctestrunPath,
|
|
187
|
+
jsonPath,
|
|
188
|
+
testPromise,
|
|
189
|
+
};
|
|
190
|
+
runnerSessions.set(device.id, session);
|
|
191
|
+
return session;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
async function ensureXctestrun(
|
|
196
|
+
udid: string,
|
|
197
|
+
options: { verbose?: boolean; logPath?: string },
|
|
198
|
+
): Promise<string> {
|
|
199
|
+
const base = path.join(os.homedir(), '.agent-device', 'ios-runner');
|
|
200
|
+
const derived = path.join(base, 'derived');
|
|
201
|
+
if (shouldCleanDerived()) {
|
|
202
|
+
try {
|
|
203
|
+
fs.rmSync(derived, { recursive: true, force: true });
|
|
204
|
+
} catch {
|
|
205
|
+
// ignore
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const existing = findXctestrun(derived);
|
|
209
|
+
if (existing) return existing;
|
|
210
|
+
|
|
211
|
+
const projectRoot = findProjectRoot();
|
|
212
|
+
const projectPath = path.join(projectRoot, 'ios-runner', 'AgentDeviceRunner', 'AgentDeviceRunner.xcodeproj');
|
|
213
|
+
|
|
214
|
+
if (!fs.existsSync(projectPath)) {
|
|
215
|
+
throw new AppError('COMMAND_FAILED', 'iOS runner project not found', { projectPath });
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
try {
|
|
219
|
+
await runCmdStreaming(
|
|
220
|
+
'xcodebuild',
|
|
221
|
+
[
|
|
222
|
+
'build-for-testing',
|
|
223
|
+
'-project',
|
|
224
|
+
projectPath,
|
|
225
|
+
'-scheme',
|
|
226
|
+
'AgentDeviceRunner',
|
|
227
|
+
'-parallel-testing-enabled',
|
|
228
|
+
'NO',
|
|
229
|
+
'-maximum-concurrent-test-simulator-destinations',
|
|
230
|
+
'1',
|
|
231
|
+
'-destination',
|
|
232
|
+
`platform=iOS Simulator,id=${udid}`,
|
|
233
|
+
'-derivedDataPath',
|
|
234
|
+
derived,
|
|
235
|
+
],
|
|
236
|
+
{
|
|
237
|
+
onStdoutChunk: (chunk) => {
|
|
238
|
+
logChunk(chunk, options.logPath, options.verbose);
|
|
239
|
+
},
|
|
240
|
+
onStderrChunk: (chunk) => {
|
|
241
|
+
logChunk(chunk, options.logPath, options.verbose);
|
|
242
|
+
},
|
|
243
|
+
},
|
|
244
|
+
);
|
|
245
|
+
} catch (err) {
|
|
246
|
+
const appErr = err instanceof AppError ? err : new AppError('COMMAND_FAILED', String(err));
|
|
247
|
+
throw new AppError('COMMAND_FAILED', 'xcodebuild build-for-testing failed', {
|
|
248
|
+
error: appErr.message,
|
|
249
|
+
details: appErr.details,
|
|
250
|
+
logPath: options.logPath,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const built = findXctestrun(derived);
|
|
255
|
+
if (!built) {
|
|
256
|
+
throw new AppError('COMMAND_FAILED', 'Failed to locate .xctestrun after build');
|
|
257
|
+
}
|
|
258
|
+
return built;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function findXctestrun(root: string): string | null {
|
|
262
|
+
if (!fs.existsSync(root)) return null;
|
|
263
|
+
const candidates: { path: string; mtimeMs: number }[] = [];
|
|
264
|
+
const stack: string[] = [root];
|
|
265
|
+
while (stack.length > 0) {
|
|
266
|
+
const current = stack.pop() as string;
|
|
267
|
+
const entries = fs.readdirSync(current, { withFileTypes: true });
|
|
268
|
+
for (const entry of entries) {
|
|
269
|
+
const full = path.join(current, entry.name);
|
|
270
|
+
if (entry.isDirectory()) {
|
|
271
|
+
stack.push(full);
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (entry.isFile() && entry.name.endsWith('.xctestrun')) {
|
|
275
|
+
try {
|
|
276
|
+
const stat = fs.statSync(full);
|
|
277
|
+
candidates.push({ path: full, mtimeMs: stat.mtimeMs });
|
|
278
|
+
} catch {
|
|
279
|
+
// ignore
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (candidates.length === 0) return null;
|
|
285
|
+
candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
286
|
+
return candidates[0]?.path ?? null;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function findProjectRoot(): string {
|
|
290
|
+
const start = path.dirname(fileURLToPath(import.meta.url));
|
|
291
|
+
let current = start;
|
|
292
|
+
for (let i = 0; i < 6; i += 1) {
|
|
293
|
+
const pkgPath = path.join(current, 'package.json');
|
|
294
|
+
if (fs.existsSync(pkgPath)) return current;
|
|
295
|
+
current = path.dirname(current);
|
|
296
|
+
}
|
|
297
|
+
return start;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function logChunk(chunk: string, logPath?: string, verbose?: boolean): void {
|
|
301
|
+
if (logPath) {
|
|
302
|
+
fs.appendFileSync(logPath, chunk);
|
|
303
|
+
}
|
|
304
|
+
if (verbose) {
|
|
305
|
+
process.stderr.write(chunk);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function shouldCleanDerived(): boolean {
|
|
310
|
+
const value = process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED;
|
|
311
|
+
if (!value) return false;
|
|
312
|
+
return ['1', 'true', 'yes', 'on'].includes(value.toLowerCase());
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function waitForRunner(
|
|
316
|
+
device: DeviceInfo,
|
|
317
|
+
port: number,
|
|
318
|
+
command: RunnerCommand,
|
|
319
|
+
logPath?: string,
|
|
320
|
+
): Promise<Response> {
|
|
321
|
+
if (logPath) {
|
|
322
|
+
await waitForRunnerReady(logPath, 4000);
|
|
323
|
+
}
|
|
324
|
+
const start = Date.now();
|
|
325
|
+
let lastError: unknown = null;
|
|
326
|
+
while (Date.now() - start < 8000) {
|
|
327
|
+
try {
|
|
328
|
+
const response = await fetch(`http://127.0.0.1:${port}/command`, {
|
|
329
|
+
method: 'POST',
|
|
330
|
+
headers: { 'Content-Type': 'application/json' },
|
|
331
|
+
body: JSON.stringify(command),
|
|
332
|
+
});
|
|
333
|
+
return response;
|
|
334
|
+
} catch (err) {
|
|
335
|
+
lastError = err;
|
|
336
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (device.kind === 'simulator') {
|
|
340
|
+
const simResponse = await postCommandViaSimulator(device.id, port, command);
|
|
341
|
+
return new Response(simResponse.body, { status: simResponse.status });
|
|
342
|
+
}
|
|
343
|
+
const fallbackPort = logPath ? extractPortFromLog(logPath) : null;
|
|
344
|
+
if (fallbackPort && fallbackPort !== port) {
|
|
345
|
+
try {
|
|
346
|
+
const response = await fetch(`http://127.0.0.1:${fallbackPort}/command`, {
|
|
347
|
+
method: 'POST',
|
|
348
|
+
headers: { 'Content-Type': 'application/json' },
|
|
349
|
+
body: JSON.stringify(command),
|
|
350
|
+
});
|
|
351
|
+
return response;
|
|
352
|
+
} catch (err) {
|
|
353
|
+
lastError = err;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
throw new AppError('COMMAND_FAILED', 'Runner did not accept connection', {
|
|
358
|
+
port,
|
|
359
|
+
fallbackPort,
|
|
360
|
+
logPath,
|
|
361
|
+
lastError: lastError ? String(lastError) : undefined,
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async function postCommandViaSimulator(
|
|
366
|
+
udid: string,
|
|
367
|
+
port: number,
|
|
368
|
+
command: RunnerCommand,
|
|
369
|
+
): Promise<{ status: number; body: string }> {
|
|
370
|
+
const payload = JSON.stringify(command);
|
|
371
|
+
const result = await runCmd(
|
|
372
|
+
'xcrun',
|
|
373
|
+
[
|
|
374
|
+
'simctl',
|
|
375
|
+
'spawn',
|
|
376
|
+
udid,
|
|
377
|
+
'/usr/bin/curl',
|
|
378
|
+
'-s',
|
|
379
|
+
'-X',
|
|
380
|
+
'POST',
|
|
381
|
+
'-H',
|
|
382
|
+
'Content-Type: application/json',
|
|
383
|
+
'--data',
|
|
384
|
+
payload,
|
|
385
|
+
`http://127.0.0.1:${port}/command`,
|
|
386
|
+
],
|
|
387
|
+
{ allowFailure: true },
|
|
388
|
+
);
|
|
389
|
+
const body = result.stdout as string;
|
|
390
|
+
if (result.exitCode !== 0) {
|
|
391
|
+
throw new AppError('COMMAND_FAILED', 'Runner did not accept connection (simctl spawn)', {
|
|
392
|
+
port,
|
|
393
|
+
stdout: result.stdout,
|
|
394
|
+
stderr: result.stderr,
|
|
395
|
+
exitCode: result.exitCode,
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
return { status: 200, body };
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async function getFreePort(): Promise<number> {
|
|
402
|
+
return await new Promise((resolve, reject) => {
|
|
403
|
+
const server = net.createServer();
|
|
404
|
+
server.listen(0, '127.0.0.1', () => {
|
|
405
|
+
const address = server.address();
|
|
406
|
+
server.close();
|
|
407
|
+
if (typeof address === 'object' && address?.port) {
|
|
408
|
+
resolve(address.port);
|
|
409
|
+
} else {
|
|
410
|
+
reject(new AppError('COMMAND_FAILED', 'Failed to allocate port'));
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
server.on('error', reject);
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
async function waitForRunnerReady(logPath: string, timeoutMs: number): Promise<void> {
|
|
418
|
+
if (!fs.existsSync(logPath)) return;
|
|
419
|
+
const start = Date.now();
|
|
420
|
+
let offset = 0;
|
|
421
|
+
while (Date.now() - start < timeoutMs) {
|
|
422
|
+
if (!fs.existsSync(logPath)) return;
|
|
423
|
+
const stats = fs.statSync(logPath);
|
|
424
|
+
if (stats.size > offset) {
|
|
425
|
+
const fd = fs.openSync(logPath, 'r');
|
|
426
|
+
const buffer = Buffer.alloc(stats.size - offset);
|
|
427
|
+
fs.readSync(fd, buffer, 0, buffer.length, offset);
|
|
428
|
+
fs.closeSync(fd);
|
|
429
|
+
offset = stats.size;
|
|
430
|
+
const text = buffer.toString('utf8');
|
|
431
|
+
if (
|
|
432
|
+
text.includes('AGENT_DEVICE_RUNNER_LISTENER_READY') ||
|
|
433
|
+
text.includes('AGENT_DEVICE_RUNNER_PORT=')
|
|
434
|
+
) {
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function extractPortFromLog(logPath: string): number | null {
|
|
443
|
+
try {
|
|
444
|
+
if (!fs.existsSync(logPath)) return null;
|
|
445
|
+
const text = fs.readFileSync(logPath, 'utf8');
|
|
446
|
+
const match = text.match(/AGENT_DEVICE_RUNNER_PORT=(\d+)/);
|
|
447
|
+
if (match) return Number(match[1]);
|
|
448
|
+
} catch {
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async function prepareXctestrunWithEnv(
|
|
455
|
+
xctestrunPath: string,
|
|
456
|
+
envVars: Record<string, string>,
|
|
457
|
+
suffix: string,
|
|
458
|
+
): Promise<{ xctestrunPath: string; jsonPath: string }> {
|
|
459
|
+
const dir = path.dirname(xctestrunPath);
|
|
460
|
+
const safeSuffix = suffix.replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
461
|
+
const tmpJsonPath = path.join(dir, `AgentDeviceRunner.env.${safeSuffix}.json`);
|
|
462
|
+
const tmpXctestrunPath = path.join(dir, `AgentDeviceRunner.env.${safeSuffix}.xctestrun`);
|
|
463
|
+
|
|
464
|
+
const jsonResult = await runCmd('plutil', ['-convert', 'json', '-o', '-', xctestrunPath], {
|
|
465
|
+
allowFailure: true,
|
|
466
|
+
});
|
|
467
|
+
if (jsonResult.exitCode !== 0 || !jsonResult.stdout.trim()) {
|
|
468
|
+
throw new AppError('COMMAND_FAILED', 'Failed to read xctestrun plist', {
|
|
469
|
+
xctestrunPath,
|
|
470
|
+
stderr: jsonResult.stderr,
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
let parsed: Record<string, any>;
|
|
475
|
+
try {
|
|
476
|
+
parsed = JSON.parse(jsonResult.stdout) as Record<string, any>;
|
|
477
|
+
} catch (err) {
|
|
478
|
+
throw new AppError('COMMAND_FAILED', 'Failed to parse xctestrun JSON', {
|
|
479
|
+
xctestrunPath,
|
|
480
|
+
error: String(err),
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const applyEnvToTarget = (target: Record<string, any>) => {
|
|
485
|
+
target.EnvironmentVariables = { ...(target.EnvironmentVariables ?? {}), ...envVars };
|
|
486
|
+
target.UITestEnvironmentVariables = { ...(target.UITestEnvironmentVariables ?? {}), ...envVars };
|
|
487
|
+
target.UITargetAppEnvironmentVariables = {
|
|
488
|
+
...(target.UITargetAppEnvironmentVariables ?? {}),
|
|
489
|
+
...envVars,
|
|
490
|
+
};
|
|
491
|
+
target.TestingEnvironmentVariables = { ...(target.TestingEnvironmentVariables ?? {}), ...envVars };
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
const configs = parsed.TestConfigurations;
|
|
495
|
+
if (Array.isArray(configs)) {
|
|
496
|
+
for (const config of configs) {
|
|
497
|
+
if (!config || typeof config !== 'object') continue;
|
|
498
|
+
const targets = config.TestTargets;
|
|
499
|
+
if (!Array.isArray(targets)) continue;
|
|
500
|
+
for (const target of targets) {
|
|
501
|
+
if (!target || typeof target !== 'object') continue;
|
|
502
|
+
applyEnvToTarget(target);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
508
|
+
if (value && typeof value === 'object' && value.TestBundlePath) {
|
|
509
|
+
applyEnvToTarget(value);
|
|
510
|
+
parsed[key] = value;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
fs.writeFileSync(tmpJsonPath, JSON.stringify(parsed, null, 2));
|
|
515
|
+
const plistResult = await runCmd('plutil', ['-convert', 'xml1', '-o', tmpXctestrunPath, tmpJsonPath], {
|
|
516
|
+
allowFailure: true,
|
|
517
|
+
});
|
|
518
|
+
if (plistResult.exitCode !== 0) {
|
|
519
|
+
throw new AppError('COMMAND_FAILED', 'Failed to write xctestrun plist', {
|
|
520
|
+
tmpXctestrunPath,
|
|
521
|
+
stderr: plistResult.stderr,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
return { xctestrunPath: tmpXctestrunPath, jsonPath: tmpJsonPath };
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function cleanupTempFile(filePath: string): void {
|
|
529
|
+
try {
|
|
530
|
+
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
|
531
|
+
} catch {
|
|
532
|
+
// ignore
|
|
533
|
+
}
|
|
534
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { AppError } from './errors.ts';
|
|
2
|
+
|
|
3
|
+
export type ParsedArgs = {
|
|
4
|
+
command: string | null;
|
|
5
|
+
positionals: string[];
|
|
6
|
+
flags: {
|
|
7
|
+
json: boolean;
|
|
8
|
+
platform?: 'ios' | 'android';
|
|
9
|
+
device?: string;
|
|
10
|
+
udid?: string;
|
|
11
|
+
serial?: string;
|
|
12
|
+
out?: string;
|
|
13
|
+
session?: string;
|
|
14
|
+
verbose?: boolean;
|
|
15
|
+
snapshotInteractiveOnly?: boolean;
|
|
16
|
+
snapshotCompact?: boolean;
|
|
17
|
+
snapshotDepth?: number;
|
|
18
|
+
snapshotScope?: string;
|
|
19
|
+
snapshotRaw?: boolean;
|
|
20
|
+
snapshotBackend?: 'ax' | 'xctest';
|
|
21
|
+
noRecord?: boolean;
|
|
22
|
+
recordJson?: boolean;
|
|
23
|
+
help: boolean;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export function parseArgs(argv: string[]): ParsedArgs {
|
|
28
|
+
const flags: ParsedArgs['flags'] = { json: false, help: false };
|
|
29
|
+
const positionals: string[] = [];
|
|
30
|
+
|
|
31
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
32
|
+
const arg = argv[i];
|
|
33
|
+
if (arg === '--json') {
|
|
34
|
+
flags.json = true;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (arg === '--help' || arg === '-h') {
|
|
38
|
+
flags.help = true;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (arg === '--verbose' || arg === '-v') {
|
|
42
|
+
flags.verbose = true;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (arg === '-i') {
|
|
46
|
+
flags.snapshotInteractiveOnly = true;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (arg === '-c') {
|
|
50
|
+
flags.snapshotCompact = true;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (arg === '--raw') {
|
|
54
|
+
flags.snapshotRaw = true;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (arg === '--no-record') {
|
|
58
|
+
flags.noRecord = true;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (arg === '--record-json') {
|
|
62
|
+
flags.recordJson = true;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (arg.startsWith('--backend')) {
|
|
66
|
+
const value = arg.includes('=')
|
|
67
|
+
? arg.split('=')[1]
|
|
68
|
+
: argv[i + 1];
|
|
69
|
+
if (!arg.includes('=')) i += 1;
|
|
70
|
+
if (value !== 'ax' && value !== 'xctest') {
|
|
71
|
+
throw new AppError('INVALID_ARGS', `Invalid backend: ${value}`);
|
|
72
|
+
}
|
|
73
|
+
flags.snapshotBackend = value;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (arg.startsWith('--')) {
|
|
77
|
+
const [key, valueInline] = arg.split('=');
|
|
78
|
+
const value = valueInline ?? argv[i + 1];
|
|
79
|
+
if (!valueInline) i += 1;
|
|
80
|
+
|
|
81
|
+
switch (key) {
|
|
82
|
+
case '--platform':
|
|
83
|
+
if (value !== 'ios' && value !== 'android') {
|
|
84
|
+
throw new AppError('INVALID_ARGS', `Invalid platform: ${value}`);
|
|
85
|
+
}
|
|
86
|
+
flags.platform = value;
|
|
87
|
+
break;
|
|
88
|
+
case '--depth': {
|
|
89
|
+
const parsed = Number(value);
|
|
90
|
+
if (!Number.isFinite(parsed) || parsed < 0) {
|
|
91
|
+
throw new AppError('INVALID_ARGS', `Invalid depth: ${value}`);
|
|
92
|
+
}
|
|
93
|
+
flags.snapshotDepth = Math.floor(parsed);
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
case '--scope':
|
|
97
|
+
flags.snapshotScope = value;
|
|
98
|
+
break;
|
|
99
|
+
case '--device':
|
|
100
|
+
flags.device = value;
|
|
101
|
+
break;
|
|
102
|
+
case '--udid':
|
|
103
|
+
flags.udid = value;
|
|
104
|
+
break;
|
|
105
|
+
case '--serial':
|
|
106
|
+
flags.serial = value;
|
|
107
|
+
break;
|
|
108
|
+
case '--out':
|
|
109
|
+
flags.out = value;
|
|
110
|
+
break;
|
|
111
|
+
case '--session':
|
|
112
|
+
flags.session = value;
|
|
113
|
+
break;
|
|
114
|
+
default:
|
|
115
|
+
throw new AppError('INVALID_ARGS', `Unknown flag: ${key}`);
|
|
116
|
+
}
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (arg === '-d') {
|
|
120
|
+
const value = argv[i + 1];
|
|
121
|
+
i += 1;
|
|
122
|
+
const parsed = Number(value);
|
|
123
|
+
if (!Number.isFinite(parsed) || parsed < 0) {
|
|
124
|
+
throw new AppError('INVALID_ARGS', `Invalid depth: ${value}`);
|
|
125
|
+
}
|
|
126
|
+
flags.snapshotDepth = Math.floor(parsed);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (arg === '-s') {
|
|
130
|
+
const value = argv[i + 1];
|
|
131
|
+
i += 1;
|
|
132
|
+
flags.snapshotScope = value;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
positionals.push(arg);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const command = positionals.shift() ?? null;
|
|
139
|
+
return { command, positionals, flags };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function usage(): string {
|
|
143
|
+
return `agent-device <command> [args] [--json]
|
|
144
|
+
|
|
145
|
+
Commands:
|
|
146
|
+
open <app>
|
|
147
|
+
close [app]
|
|
148
|
+
snapshot [-i] [-c] [-d <depth>] [-s <scope>] [--raw] [--backend ax|xctest]
|
|
149
|
+
click <@ref>
|
|
150
|
+
get text <@ref>
|
|
151
|
+
get attrs <@ref>
|
|
152
|
+
replay <path>
|
|
153
|
+
press <x> <y>
|
|
154
|
+
long-press <x> <y> [durationMs]
|
|
155
|
+
focus <x> <y>
|
|
156
|
+
type <text>
|
|
157
|
+
fill <x> <y> <text> | fill <@ref> <text>
|
|
158
|
+
scroll <direction> [amount]
|
|
159
|
+
scrollintoview <text>
|
|
160
|
+
screenshot [--out path]
|
|
161
|
+
session list
|
|
162
|
+
|
|
163
|
+
Flags:
|
|
164
|
+
--platform ios|android
|
|
165
|
+
--device <name>
|
|
166
|
+
--udid <udid>
|
|
167
|
+
--serial <serial>
|
|
168
|
+
--out <path>
|
|
169
|
+
--session <name>
|
|
170
|
+
--verbose
|
|
171
|
+
--json
|
|
172
|
+
--no-record
|
|
173
|
+
--record-json
|
|
174
|
+
`;
|
|
175
|
+
}
|