Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
411 lines (388 loc) · 14.6 KB
/
Copy pathindex.ts
File metadata and controls
411 lines (388 loc) · 14.6 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
export { RUNNER_STARTUP_TIMEOUT_MS } from './runner-startup-transport.ts';
export {
createRunnerPreparation,
createRunnerCommandExecutor,
createRunnerCommandSession,
type RunnerCommandSession,
} from './runner-lifecycle.ts';
import type * as RunnerExchange from './runner-exchange.ts';
export { advanceRunnerSessionState } from './runner-session-types.ts';
/** Loads the exchange and failure diagnostics only when a command uses the runner. */
export async function executeRunnerExchange(
...args: Parameters<typeof RunnerExchange.executeRunnerExchange>
): ReturnType<typeof RunnerExchange.executeRunnerExchange> {
const { executeRunnerExchange: execute } = await import('./runner-exchange.ts');
return await execute(...args);
}
/**
* @agent-device/apple-runner - the Apple XCUITest runner client.
*
* The package entry names its whole surface. Host-bound operations evaluate the implementation, so
* they reach their host capabilities through the `AppleRunnerHost` port, which `platform-apple`
* binds once through `bindAppleRunnerHost` before any operation runs. The one operation outside
* this closure, `runApplePressSeries`, and the legacy device-set restore stay behind function-scoped
* imports so the entry evaluates only what a host-bound operation needs.
*/
export {
bindAppleRunnerHost,
type AppleRunnerHost,
type RunnerDeviceClaimAuthorityProbe,
} from './host.ts';
export type {
IosDeveloperDiskImageState,
IosDeveloperModeState,
IosDeviceReadiness,
IosDeviceReadinessRemedies,
IosPhysicalDeviceBackend,
IosPhysicalDeviceRunnerControl,
} from './runner-physical-device.ts';
export {
mintRunnerToken,
RUNNER_READY_PREFLIGHT_TIMEOUT_MS,
SCROLL_KEYBOARD_OCCLUDES_SURFACE_RUNNER_CODE,
buildRunnerSequenceCommand,
parseRunnerSequenceResult,
type RunnerCommand,
callerDeadlineExpired,
resolveRunnerStartupSignal,
resolveRunnerRequestSignal,
} from './runner-contract.ts';
export { isRunnerMainThreadTimeoutError } from './runner-error-classification.ts';
export {
withAppleRunnerProvider,
type AppleRunnerCommandExecutor,
type AppleRunnerLifecycleOptions,
type AppleRunnerCommandOptions,
type AppleRunnerProvider,
} from './runner-provider.ts';
export {
requireRunnerBuildSettingsMatchBuildLog,
resolveExpectedRunnerCacheMetadata,
resolveRunnerArchBuildSettings,
resolveRunnerBundleBuildSettings,
resolveRunnerContainerBundleIds,
resolveRunnerPerformanceBuildSettings,
resolveRunnerSandboxBuildArgs,
resolveRunnerSigningBuildSettings,
} from './runner-cache-metadata.ts';
export {
SHARED_FOREGROUND_GEOMETRY_HEADER_FILENAME,
resolveRunnerDerivedOverride,
} from './apple-runner-platform.ts';
export {
requireCertifiedRunnerCacheArtifacts,
writeRunnerCacheMetadataForArtifacts,
} from './runner-cache.ts';
export { findXctestrun as findRunnerXctestrun } from './runner-artifact.ts';
export { resolveExistingXctestrunProductPaths as resolveExistingRunnerProductPaths } from './runner-xctestrun-products.ts';
export { hasCachedAppleRunnerArtifact, resolveRunnerAppBundleId } from './runner-xctestrun.ts';
export { applyXctestRunnerAppIconFromDerivedPath } from './runner-icon.ts';
export { runnerLeaseCleanupAdapter } from './runner-disposal.ts';
export {
cleanupRunnerLeasesForOwner,
readStaleRunnerLease,
verifyLeaseRunnerPidIdentity,
} from './runner-lease.ts';
export {
assertExpectedRunnerSession,
detachIosRunnerSessionsForShutdown,
readRunnerSessionLiveness,
releaseIosRunnerOnClose,
stopAllIosRunnerSessions,
stopIosRunnerSession,
} from './runner-session.ts';
import type * as LegacyXctestDeviceSet from './legacy-xctest-device-set.ts';
import type * as RunnerSequence from './runner-sequence.ts';
import { retryWithPolicy, emitDiagnostic, hasScopedAppleToolProvider } from './host.ts';
import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device';
import {
ensureRunnerSession,
readRunnerSessionLiveness,
stopIosRunnerSession,
validateRunnerDevice,
releaseSpeculativeIosRunnerSession,
} from './runner-session.ts';
import {
assertRunnerRequestActive,
callerDeadlineExpired,
resolveRunnerRequestSignal,
withRunnerCommandId,
type RunnerCommand,
} from './runner-contract.ts';
import { isRetryableRunnerError, isRunnerBusyError } from './runner-error-classification.ts';
import { isReadOnlyRunnerCommand } from './runner-command-traits.ts';
import {
createLocalAppleRunnerProvider,
resolveAppleRunnerProvider,
type AppleRunnerCommandOptions,
type AppleRunnerPrewarmOptions,
type AppleRunnerProvider,
} from './runner-provider.ts';
import { createRunnerPhaseBudget, ensureXctestrunArtifact } from './runner-xctestrun.ts';
import {
executeRunnerCommand,
prepareLocalIosRunner,
type PrepareIosRunnerOptions,
type PrepareIosRunnerResult,
} from './runner-lifecycle.ts';
import { RUNNER_COMMAND_TIMEOUT_MS } from './runner-transport.ts';
// --- Runner command execution ---
/**
* Attempts a read-only command may spend on one error class; 1 means no resend. A `RUNNER_BUSY`
* refusal is the runner refusing fast on purpose while it drains abandoned XCTest work (#1105), so
* that budget has to outlast the drain. The window is a heuristic, not a measurement: 200ms doubling
* to a 1s cap, no jitter, is 5.4s of delay across eight attempts before round trips, and a drain
* that outlives it still surfaces as `RUNNER_BUSY` (the runner's own `abandonedForSeconds=` marker
* in runner.log is the evidence for tuning it). Transport failures keep the pre-existing three
* attempts. The budget is positional: the error on each attempt sets how many attempts the loop may
* reach in total, so three busy refusals followed by a transport failure resend no further.
*/
const RUNNER_BUSY_RESEND_ATTEMPTS = 8;
const TRANSPORT_RESEND_ATTEMPTS = 3;
const READ_ONLY_RESEND_POLICY = {
maxAttempts: RUNNER_BUSY_RESEND_ATTEMPTS,
baseDelayMs: 200,
maxDelayMs: 1_000,
jitter: 0,
};
function readOnlyResendBudget(error: unknown): number {
if (isRunnerBusyError(error)) return RUNNER_BUSY_RESEND_ATTEMPTS;
return isRetryableRunnerError(error) ? TRANSPORT_RESEND_ATTEMPTS : 1;
}
export async function runAppleRunnerCommand(
device: DeviceInfo,
command: RunnerCommand,
options: AppleRunnerCommandOptions = {},
): Promise<Record<string, unknown>> {
validateRunnerDevice(device);
assertRunnerRequestActive(options.requestId);
const runnerCommand = withRunnerCommandId(command);
const provider = resolveAppleRunnerRuntime(device, options);
if (!isReadOnlyRunnerCommand(runnerCommand)) {
return provider.runCommand(device, runnerCommand, options);
}
let lastBusyRefusal: unknown;
try {
return await retryWithPolicy(
() => {
assertRunnerRequestActive(options.requestId);
return provider.runCommand(device, runnerCommand, options);
},
{
...READ_ONLY_RESEND_POLICY,
shouldRetry: (error, attempt) => {
assertRunnerRequestActive(options.requestId);
if (isRunnerBusyError(error)) lastBusyRefusal = error;
return attempt < readOnlyResendBudget(error);
},
},
// The busy window is seconds long, so an abort must wake the delay instead of sleeping it
// out and sending one more attempt.
{ signal: resolveRunnerRequestSignal(options) },
);
} catch (error) {
// A caller's deadline (a `wait` poll bounding this capture) that lands mid-window still has an
// answer: the runner refused, and that typed refusal is what the caller can act on. Only a
// cancelled request reports as a bare cancellation.
if (lastBusyRefusal && callerDeadlineExpired(options)) throw lastBusyRefusal;
throw error;
}
}
export async function notifyIosRunnerAppRelaunched(
device: DeviceInfo,
options: AppleRunnerCommandOptions = {},
): Promise<void> {
if (!isIosFamily(device)) return;
try {
await runAppleRunnerCommand(device, { command: 'targetReset' }, options);
} catch (error) {
emitDiagnostic({
level: 'warn',
phase: 'ios_runner_target_reset_failed',
data: { deviceId: device.id, error: error instanceof Error ? error.message : String(error) },
});
await stopIosRunnerSession(device.id);
}
}
type PrewarmIosRunnerOptions = AppleRunnerPrewarmOptions & {
propagateError?: boolean;
};
/** Speculative host build: a request whose Apple tooling a provider serves has none to warm. */
export function prewarmAppleRunnerCache(
device: DeviceInfo,
options: PrewarmIosRunnerOptions = {},
): Promise<void> | undefined {
if (!isIosFamily(device)) {
return undefined;
}
if (hasScopedAppleToolProvider()) {
emitDiagnostic({
level: 'debug',
phase: 'ios_runner_cache_prewarm_unavailable',
data: { deviceId: device.id },
});
return undefined;
}
return runBestEffortIosRunnerPrewarm({
device,
options,
failurePhase: 'ios_runner_cache_prewarm_failed',
task: async (runnerOptions) => {
// A cache prewarm owns the build phase it starts: one budget for the
// `xcodebuild` the cache decision may call for.
await ensureXctestrunArtifact(device, {
...runnerOptions,
budget: createRunnerPhaseBudget(runnerOptions.buildTimeoutMs, runnerOptions.signal),
});
},
});
}
export function prewarmIosRunnerSession(
device: DeviceInfo,
options: PrewarmIosRunnerOptions = {},
): Promise<void> | undefined {
if (!isIosFamily(device)) {
return undefined;
}
const provider = resolveAppleRunnerRuntime(device, options);
const prewarmRunner = provider.prewarm;
if (!prewarmRunner) {
emitDiagnostic({
level: 'debug',
phase: 'ios_runner_session_prewarm_unavailable',
data: { deviceId: device.id },
});
return undefined;
}
return runBestEffortIosRunnerPrewarm({
device,
options,
failurePhase: 'ios_runner_session_prewarm_failed',
task: async (taskOptions) => {
await prewarmRunner(device, taskOptions);
},
});
}
function runBestEffortIosRunnerPrewarm(params: {
device: DeviceInfo;
options: PrewarmIosRunnerOptions;
failurePhase: 'ios_runner_cache_prewarm_failed' | 'ios_runner_session_prewarm_failed';
task: (options: AppleRunnerPrewarmOptions) => Promise<void>;
}): Promise<void> {
const { device, options, failurePhase, task } = params;
const { propagateError = false, ...runnerOptions } = options;
const prewarm = task(runnerOptions).catch((error: unknown) => {
emitDiagnostic({
level: 'warn',
phase: failurePhase,
data: {
deviceId: device.id,
error: error instanceof Error ? error.message : String(error),
},
});
if (propagateError) {
throw error;
}
});
void prewarm;
return prewarm;
}
export async function prepareIosRunner(
device: DeviceInfo,
options: PrepareIosRunnerOptions,
): Promise<PrepareIosRunnerResult> {
validateRunnerDevice(device);
assertRunnerRequestActive(options.requestId);
const command = withRunnerCommandId({ command: 'uptime' });
const provider = resolveAppleRunnerRuntime(device, options);
if (provider.prepare) {
return await provider.prepare(device, options);
}
const healthStartedAt = Date.now();
const runner = await provider.runCommand(device, command, options);
return {
runner,
connectMs: 0,
healthCheckMs: Math.max(0, Date.now() - healthStartedAt),
};
}
function resolveAppleRunnerRuntime(
device: DeviceInfo,
options: { requestId?: string },
): AppleRunnerProvider {
return resolveAppleRunnerProvider(device, LOCAL_APPLE_RUNNER_RUNTIME, {
requestId: options.requestId,
});
}
/**
* Whether asking this device's runner now would be answered without a startup wait. Only a
* session in the `ready` state counts: one that is registered but has not answered yet is still
* starting, so sending it a command would queue behind its connection retries, and one already
* going away would be asked to work while it is being taken down. Observation paths use this to
* stay runner-free until the runner is ready.
*/
export function hasLiveIosRunnerSession(
device: DeviceInfo,
options: { requestId?: string } = {},
): boolean {
if (!isIosFamily(device)) return false;
return resolveAppleRunnerRuntime(device, options).hasLiveSession(device);
}
/** Releases the runner a prewarm started for `device` if no command has used it; false otherwise. */
export async function releaseSpeculativeIosRunnerSessionFor(
device: DeviceInfo,
options: { requestId?: string } = {},
): Promise<boolean> {
if (!isIosFamily(device)) return false;
const release = resolveAppleRunnerRuntime(device, options).releaseSpeculativeSession;
return release ? await release(device) : false;
}
const LOCAL_APPLE_RUNNER_RUNTIME = createLocalAppleRunnerProvider(executeRunnerCommand, {
prepare: prepareLocalIosRunner,
hasLiveSession: (device) => readRunnerSessionLiveness(device.id)?.liveness === 'ready',
releaseSpeculativeSession: async (device) => await releaseSpeculativeIosRunnerSession(device.id),
prewarm: async (device, options) => {
const { healthCheck, ...runnerOptions } = options;
if (healthCheck === false) {
await ensureRunnerSession(device, { ...runnerOptions, speculative: true });
return;
}
await prepareLocalIosRunner(device, {
...runnerOptions,
speculative: true,
healthTimeoutMs: RUNNER_COMMAND_TIMEOUT_MS,
});
},
});
/**
* A press series runs through the sequence driver, which stays outside the entry's eager closure
* until a series is requested.
*/
export async function runApplePressSeries(
...args: Parameters<typeof RunnerSequence.runApplePressSeries>
): Promise<Record<string, unknown>> {
const { runApplePressSeries: run } = await import('./runner-sequence.ts');
return await run(...args);
}
/** Restores a legacy XCTest device-set redirect; the parser module loads on first use. */
export async function restoreLegacyXctestDeviceSetRedirect(
...args: Parameters<typeof LegacyXctestDeviceSet.restoreLegacyXctestDeviceSetRedirect>
): Promise<void> {
const { restoreLegacyXctestDeviceSetRedirect: restore } =
await import('./legacy-xctest-device-set.ts');
await restore(...args);
}
/** Uses the shared idle and outstanding-work policy for a provider-owned runner. */
export async function retainRunnerSession(
...args: Parameters<typeof import('./runner-retention.ts').retainRunnerSession>
): Promise<boolean> {
const { retainRunnerSession: retain } = await import('./runner-retention.ts');
return await retain(...args);
}
export { logChunk as logRunnerOutput, flushRunnerLogAppends } from './runner-io.ts';
export {
fenceRunnerStartAdmissionsForTeardown,
assertRunnerStartAdmitsPreparation,
} from './runner-xctestrun.ts';
export { runnerListenerEnv } from './runner-contract.ts';
export { RUNNER_XCTESTRUN_CAPTURE_OPTIONS } from './runner-xctestrun-config.ts';