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