Repository navigation
Expand file tree
/
Copy pathlifecycle.ts
More file actions
615 lines (583 loc) · 20.8 KB
/
Copy pathlifecycle.ts
File metadata and controls
615 lines (583 loc) · 20.8 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics';
import {
type ApplicationLifecycleRuntimeOperations,
type AppleRunnerSessionPrewarmOptions,
type CloseApplicationFinalizationInput,
type CloseApplicationInput,
type OpenApplicationInput,
type OpenApplicationOutcome,
type PrepareAppleRunnerInput,
type PrepareAppleRunnerResult,
hasRuntimeTransportHintValues,
} from '@agent-device/contracts/application-lifecycle-runtime';
import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations';
import {
assertOpenAdmitted,
bindLocalApplicationLifecycleInteractor,
invokeApplicationClose,
invokeApplicationOpen,
} from '@agent-device/contracts/application-lifecycle-interaction';
import { isDeepLinkTarget, isWebUrl } from '@agent-device/contracts/command';
import { ensureAppleReady } from './readiness/runtime.ts';
import {
resolveRunnerPrewarmPolicy,
settleAppleOpen,
type MutableOpenTiming,
releaseSpeculativeRunner,
} from './open-policy.ts';
import type { LaunchObservationPort } from './snapshot-observability.ts';
import type { LaunchConfirmationAttempt, LaunchConfirmationTarget } from './launch-confirmation.ts';
import { isApplePlatform, isIosFamily, type DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
const POST_CLOSE_SETTLE_MS = 300;
let launchConfirmationModule: Promise<typeof import('./launch-confirmation.ts')> | undefined;
const loadLaunchConfirmation = () =>
(launchConfirmationModule ??= import('./launch-confirmation.ts'));
let expoDevClientLaunchModule: Promise<typeof import('./expo-dev-client-launch.ts')> | undefined;
const loadExpoDevClientLaunch = () =>
(expoDevClientLaunchModule ??= import('./expo-dev-client-launch.ts'));
/** The Apple package receives only the lazy tools and readiness ports it owns. */
type AppleLifecycleHost = Pick<
PlatformRuntimeHost,
| 'appleApplications'
| 'appleTools'
| 'clock'
| 'commands'
| 'deviceReadiness'
| 'deviceShutdown'
| 'localInteractors'
>;
type AppleLifecycleParams = Readonly<{
host: AppleLifecycleHost;
device: DeviceInfo;
signal: AbortSignal;
/** The Simulator bridge's launch observation, when the runtime binds one (local Simulators). */
observation?: LaunchObservationPort;
}>;
/** Apple owns its lifecycle ordering; the root host exposes only lazy runner/tool ports. */
export function bindAppleApplicationLifecycle(
params: AppleLifecycleParams,
): ApplicationLifecycleRuntimeOperations {
const bindInteractor = (device: DeviceInfo) =>
bindLocalApplicationLifecycleInteractor({
device,
signal: params.signal,
resolveInteractor: params.host.localInteractors.resolve,
});
let device = params.device;
let binding = bindInteractor(device);
const adoptReadiedDevice = (readied: DeviceInfo) => {
device = readied;
binding = bindInteractor(readied);
};
return Object.freeze({
resolveOpenTarget: async (input) =>
await params.host.appleApplications.resolveOpenTarget(device, input),
prepareApplicationOpen: async (input) => {
const readied = await ensureAppleReady(params.host, device, params.signal, {
deadlineAtMs: input.execution.startupDeadlineAtMs,
onColdBootStart: input.prewarmRunnerOnColdBoot
? () => {
void params.host.appleApplications
.prewarmRunnerCache(device, input.execution, params.signal)
.catch(() => {});
}
: undefined,
});
adoptReadiedDevice(readied);
},
openApplication: async (input) =>
await openAppleApplication(params.host, binding, input, params.observation),
applyRuntimeHints: async (input) =>
await params.host.appleApplications.applyRuntimeHints(device, input),
clearRuntimeHints: async (input) =>
await params.host.appleApplications.clearRuntimeHints(device, input),
closeApplication: async (input) => {
if (input.ensureReady) {
adoptReadiedDevice(await ensureAppleReady(params.host, device, params.signal));
}
await closeAppleApplication(params.host, binding, input);
},
finalizeApplicationClose: async (input) =>
await finalizeAppleApplicationClose(params.host, device, params.signal, input),
prepareAppleRunner: async (input) => {
const result = await prepareAppleRunner(params.host, device, params.signal, input);
adoptReadiedDevice(result.readied);
return result.prepared;
},
configureProviderPortReverse: unavailable,
});
}
type BoundAppleInteractor = ReturnType<typeof bindLocalApplicationLifecycleInteractor>;
async function openAppleApplication(
host: AppleLifecycleHost,
binding: BoundAppleInteractor,
input: OpenApplicationInput,
observation: LaunchObservationPort | undefined,
): Promise<OpenApplicationOutcome> {
const timing: MutableOpenTiming = {};
assertOpenAdmitted(binding, input.execution, input.positionals);
const localIosSimulator = isIosSimulator(binding.device);
const runner = createRunnerPrewarm(host, binding, input, timing);
const policy = resolveRunnerPrewarmPolicy(binding.device, input, localIosSimulator);
if (policy.runnerDemand) timing.runnerDemand = policy.runnerDemand;
releaseSpeculativeRunner(host, binding, input, policy);
const { shouldPrewarmRunner } = policy;
const retainRunnerForRelaunch = shouldRetainRunnerForRelaunch(
binding.device,
input,
localIosSimulator,
);
if (localIosSimulator && shouldPrewarmRunner && !input.prewarmRunnerBeforeOpen) runner.schedule();
try {
await closeAppleApplicationForRelaunch(
host,
binding,
input,
localIosSimulator,
retainRunnerForRelaunch,
timing,
);
const devClientLaunchUrl = await applyAppleOpenRuntimeHints(
binding,
input,
localIosSimulator,
timing,
);
const launch = openLaunchPlan(
binding.device,
devClientLaunchUrl ? { ...input, runtimeLaunchUrl: devClientLaunchUrl } : input,
localIosSimulator,
);
await prewarmAppleRunnerBeforeOpen(runner, shouldPrewarmRunner, input.prewarmRunnerBeforeOpen);
const runnerTargetPredatesOpen = runner.wasAwaited();
await dispatchAppleOpen(binding, input, launch, localIosSimulator, timing);
await finishAppleRunnerPrewarm(runner, shouldPrewarmRunner, policy.awaitPrewarmAfterOpen);
await notifyAppleRunnerRelaunch(
host,
binding,
input,
localIosSimulator,
runnerTargetPredatesOpen,
retainRunnerForRelaunch,
);
const launchConfirmationReport = await settleAppleOpen(
host,
binding,
input,
localIosSimulator,
{
observation,
answerConfirmation: confirmationAnswer(binding, input, launch),
redispatchLaunchUrl: confirmationRedispatch(binding, input, launch),
},
timing,
);
return {
appBundleId: input.appBundleId,
timing,
...(launchConfirmationReport ?? {}),
};
} catch (error) {
if (retainRunnerForRelaunch) {
await host.appleApplications.stopRunnerSession(binding.device.id).catch(() => {});
}
throw error;
}
}
async function closeAppleApplicationForRelaunch(
host: AppleLifecycleHost,
binding: BoundAppleInteractor,
input: OpenApplicationInput,
localIosSimulator: boolean,
retainRunnerForRelaunch: boolean,
timing: MutableOpenTiming,
): Promise<void> {
if (!shouldCloseForAppleRelaunch(input, localIosSimulator) || !input.target) return;
const startedAtMs = Date.now();
if (isApplePlatform(binding.device.platform) && !localIosSimulator && !retainRunnerForRelaunch) {
await host.appleApplications.stopRunnerSession(binding.device.id);
}
await invokeApplicationClose({
device: binding.device,
interactor: await binding.resolveInteractor(input.execution, input.appBundleId),
positionals: [input.appBundleId ?? input.target],
});
if (localIosSimulator) await host.clock.sleep(POST_CLOSE_SETTLE_MS, binding.signal);
timing.relaunchCloseDurationMs = elapsed(startedAtMs);
}
async function applyAppleOpenRuntimeHints(
binding: BoundAppleInteractor,
input: OpenApplicationInput,
localIosSimulator: boolean,
timing: MutableOpenTiming,
): Promise<string | undefined> {
if (!hasRuntimeTransportHintValues(input.runtimeHints)) return undefined;
const startedAtMs = Date.now();
const devClientLaunchUrl = localIosSimulator
? await (await loadExpoDevClientLaunch()).resolveExpoDevClientLaunchUrl(binding.device, input)
: undefined;
if (!devClientLaunchUrl) {
if (!input.applyRuntimeHints) {
throw new AppError(
'COMMAND_FAILED',
'Runtime hint operation was not admitted for this open.',
{
reason: 'runtime-hints-operation-missing',
},
);
}
await input.applyRuntimeHints({ appId: input.appBundleId, values: input.runtimeHints });
}
timing.runtimeHintsDurationMs = elapsed(startedAtMs);
return devClientLaunchUrl;
}
async function prewarmAppleRunnerBeforeOpen(
runner: RunnerPrewarm,
shouldPrewarmRunner: boolean,
prewarmBeforeOpen: boolean,
): Promise<void> {
if (!shouldPrewarmRunner || !prewarmBeforeOpen) return;
runner.schedule(true);
await runner.wait();
}
async function dispatchAppleOpen(
binding: BoundAppleInteractor,
input: OpenApplicationInput,
launch: AppleLaunchPlan,
localIosSimulator: boolean,
timing: MutableOpenTiming,
): Promise<void> {
const startedAtMs = Date.now();
await invokeApplicationOpen({
device: binding.device,
interactor: await binding.resolveInteractor(input.execution, input.appBundleId),
positionals: launch.positionals,
appBundleId: input.appBundleId,
execution: input.execution,
...(localIosSimulator && input.relaunch && !input.execution.clearAppState
? { terminateRunningApp: true }
: {}),
});
timing.openDispatchDurationMs = elapsed(startedAtMs);
await dispatchAppleLaunchUrl(binding, input, launch.followUpUrl, timing);
}
async function dispatchAppleLaunchUrl(
binding: BoundAppleInteractor,
input: OpenApplicationInput,
followUpUrl: string | undefined,
timing: MutableOpenTiming,
): Promise<void> {
if (!followUpUrl) {
timing.launchUrlDurationMs = 0;
return;
}
const startedAtMs = Date.now();
await openLaunchUrl(binding, input, followUpUrl);
timing.launchUrlDurationMs = elapsed(startedAtMs);
}
/** Hands one URL to the device on its own, whatever the open's launch sequencing was. */
async function openLaunchUrl(
binding: BoundAppleInteractor,
input: OpenApplicationInput,
url: string,
): Promise<void> {
const execution = {
...input.execution,
clearAppState: undefined,
launchConsole: undefined,
launchArgs: undefined,
};
await invokeApplicationOpen({
device: binding.device,
interactor: await binding.resolveInteractor(execution, input.appBundleId),
positionals: [url],
appBundleId: input.appBundleId,
execution,
});
}
/**
* How the settle answers a launch confirmation, present only when the launch handed SpringBoard a
* custom-scheme URL it may hold for the session app. The settle spends it on any launch the host AX
* bridge cannot read as up: a system surface over the app, or a target discovery that never
* answered.
*/
function confirmationAnswer(
binding: BoundAppleInteractor,
input: OpenApplicationInput,
{ confirmation }: AppleLaunchPlan,
): (() => Promise<LaunchConfirmationAttempt>) | undefined {
if (!confirmation) return undefined;
return async () => {
const { answerSimulatorLaunchConfirmation } = await loadLaunchConfirmation();
return await answerSimulatorLaunchConfirmation(
binding.device,
confirmation,
binding.resolveInteractor(input.execution, confirmation.appBundleId),
binding.signal,
);
};
}
/**
* Hands a confirmable launch URL to the device again. Only the settle calls it, and only once the
* bridge proves no process is running: an accept that died with the runner session that raised it
* leaves SpringBoard holding an URL whose answer is gone, and the device drops an URL it never
* delivered. Both are answered by the same `simctl openurl` the open already used.
*/
function confirmationRedispatch(
binding: BoundAppleInteractor,
input: OpenApplicationInput,
{ confirmation }: AppleLaunchPlan,
): (() => Promise<void>) | undefined {
if (!confirmation) return undefined;
return async () => {
await openLaunchUrl(binding, input, confirmation.url);
};
}
async function finishAppleRunnerPrewarm(
runner: RunnerPrewarm,
shouldPrewarmRunner: boolean,
relaunch: boolean,
): Promise<void> {
if (shouldPrewarmRunner && !runner.wasScheduled()) runner.schedule();
if (relaunch) await runner.wait();
else runner.recordUnawaited();
}
async function notifyAppleRunnerRelaunch(
host: AppleLifecycleHost,
binding: BoundAppleInteractor,
input: OpenApplicationInput,
localIosSimulator: boolean,
runnerTargetPredatesOpen: boolean,
retainRunnerForRelaunch: boolean,
): Promise<void> {
if (
!isIosFamily(binding.device) ||
(!localIosSimulator && !retainRunnerForRelaunch) ||
(!input.relaunch && !runnerTargetPredatesOpen)
) {
return;
}
// Only a runner that is already alive can hold a stale cached target. A starting runner has
// none, and asking it would await its startup; a fresh one re-resolves the target on first use.
// An awaited prewarm proved liveness already.
if (
localIosSimulator &&
!runnerTargetPredatesOpen &&
!(await host.appleApplications.hasLiveRunnerSession(binding.device, input.execution))
) {
return;
}
await host.appleApplications.notifyRunnerAppRelaunched(
binding.device,
input.execution,
binding.signal,
);
}
function shouldCloseForAppleRelaunch(
input: OpenApplicationInput,
localIosSimulator: boolean,
): boolean {
return (
Boolean(input.relaunch && input.target) &&
!(localIosSimulator && !input.execution.clearAppState)
);
}
function shouldRetainRunnerForRelaunch(
device: DeviceInfo,
input: OpenApplicationInput,
localIosSimulator: boolean,
): boolean {
return (
device.kind === 'device' &&
device.appleOs === 'ios' &&
shouldCloseForAppleRelaunch(input, localIosSimulator)
);
}
async function closeAppleApplication(
host: AppleLifecycleHost,
binding: BoundAppleInteractor,
input: CloseApplicationInput,
): Promise<void> {
if (isApplePlatform(binding.device.platform) && !isIosSimulator(binding.device)) {
await host.appleApplications.stopRunnerSession(binding.device.id);
}
await invokeApplicationClose({
device: binding.device,
interactor: await binding.resolveInteractor(input.execution, input.appBundleId),
positionals: input.positionals,
});
if (isIosSimulator(binding.device)) await host.clock.sleep(POST_CLOSE_SETTLE_MS, binding.signal);
}
async function finalizeAppleApplicationClose(
host: AppleLifecycleHost,
device: DeviceInfo,
signal: AbortSignal,
input: CloseApplicationFinalizationInput,
) {
if (input.daemonShutdown) {
await host.appleApplications.dismissCloseAlerts(device, input).catch(() => {});
} else {
// The runner module owns the retain-vs-stop decision: it keeps warm reuse for an idle runner and
// stops one whose last exchange reported main-thread work still draining, so `close` never pools
// a stalled process back out to the next `open` (#2552). Awaited so the lease is released first.
await host.appleApplications.releaseRunnerOnClose(device.id, { retain: input.retainRunner });
await host.appleApplications.dismissCloseAlerts(device, input).catch(() => {});
}
const shutdown =
input.shutdownTarget && isIosSimulator(device)
? await host.deviceShutdown.apple.shutdownTarget(device, signal)
: undefined;
return shutdown === undefined ? {} : { shutdown };
}
async function prepareAppleRunner(
host: AppleLifecycleHost,
device: DeviceInfo,
signal: AbortSignal,
input: PrepareAppleRunnerInput,
): Promise<Readonly<{ readied: DeviceInfo; prepared: PrepareAppleRunnerResult }>> {
// One budget covers the boot and the runner: a cold Simulator's boot spends part of it, and
// the runner preparation gets what is left rather than the full budget again.
const deadlineAtMs = Date.now() + input.timeoutMs;
const traceStarted = performance.now();
return await withDiagnosticTimer(
'prepare_apple_runner',
async () => {
const readied = await ensureAppleReady(host, device, signal, { deadlineAtMs });
const timeoutMs = Math.max(1, deadlineAtMs - Date.now());
emitDiagnostic({
phase: 'prepare_apple_runner',
durationMs: performance.now() - traceStarted,
data: {
event: 'runner_start',
timeoutMs: input.timeoutMs,
remainingMs: deadlineAtMs - Date.now(),
},
});
const prepared = await host.appleApplications.prepareRunner(
readied,
{ ...input, timeoutMs },
signal,
);
return { readied, prepared };
},
() => ({ timeoutMs: input.timeoutMs, remainingMs: deadlineAtMs - Date.now() }),
'readiness_start',
);
}
type RunnerPrewarm = Readonly<{
schedule(propagateError?: boolean): void;
wait(): Promise<void>;
wasAwaited(): boolean;
wasScheduled(): boolean;
recordUnawaited(): void;
}>;
function createRunnerPrewarm(
host: AppleLifecycleHost,
binding: BoundAppleInteractor,
input: OpenApplicationInput,
timing: MutableOpenTiming,
): RunnerPrewarm {
let pending: Promise<void> | undefined;
let awaited = false;
const options: AppleRunnerSessionPrewarmOptions | undefined = isUnawaitedPhysicalIosOpen(
binding.device,
input,
)
? { healthCheck: false }
: undefined;
return {
schedule: (propagateError = false) => {
if (pending) return;
timing.runnerPrewarmKind = 'session';
timing.runnerPrewarmScheduled = true;
pending = options
? host.appleApplications.prewarmRunnerSession(
binding.device,
input.execution,
binding.signal,
propagateError,
options,
)
: host.appleApplications.prewarmRunnerSession(
binding.device,
input.execution,
binding.signal,
propagateError,
);
},
wait: async () => {
if (!pending || awaited) return;
awaited = true;
const startedAtMs = Date.now();
await pending;
timing.runnerPrewarmWaited = true;
timing.runnerPrewarmDurationMs = elapsed(startedAtMs);
},
wasAwaited: () => awaited,
wasScheduled: () => pending !== undefined,
recordUnawaited: () => {
if (pending && !awaited) timing.runnerPrewarmWaited = false;
},
};
}
function isUnawaitedPhysicalIosOpen(device: DeviceInfo, input: OpenApplicationInput): boolean {
return (
device.kind === 'device' &&
device.appleOs === 'ios' &&
!input.hasExistingSession &&
!input.relaunch &&
!input.prewarmRunnerBeforeOpen
);
}
/**
* How the open dispatches its app and launch URL. `followUpUrl` is how the URL is dispatched;
* `confirmation` is whether SpringBoard may hold it, so a direct Simulator launch carries both.
* `confirmation`: the custom-scheme launch URL an iOS Simulator hands to SpringBoard for the
* session app, which may hold the launch behind an `Open in "<App>"?` confirmation.
*/
type AppleLaunchPlan = Readonly<{
positionals: readonly string[];
followUpUrl?: string;
confirmation?: LaunchConfirmationTarget;
}>;
function openLaunchPlan(
device: DeviceInfo,
input: OpenApplicationInput,
foldLaunchUrl: boolean,
): AppleLaunchPlan {
const url = input.runtimeLaunchUrl?.trim();
const target = input.positionals.length === 1 ? input.positionals[0]?.trim() : undefined;
if (!url || !target || isDeepLinkTarget(target)) return { positionals: input.positionals };
const confirmation = confirmableLaunchUrl(device, input.appBundleId, url);
const confirmable = confirmation ? { confirmation } : {};
if (foldLaunchUrl && !isDirectAppLaunch(input)) {
return { positionals: [target, url], ...confirmable };
}
return { positionals: input.positionals, followUpUrl: url, ...confirmable };
}
function confirmableLaunchUrl(
device: DeviceInfo,
appBundleId: string | undefined,
url: string,
): LaunchConfirmationTarget | undefined {
if (device.appleOs !== 'ios' || device.kind !== 'simulator') return undefined;
if (appBundleId === undefined || isWebUrl(url)) return undefined;
return { url, appBundleId };
}
function isDirectAppLaunch(input: OpenApplicationInput): boolean {
return (
input.execution.clearAppState === true ||
Boolean(input.execution.launchConsole?.trim()) ||
Boolean(input.execution.launchArgs?.length)
);
}
function isIosSimulator(device: DeviceInfo): boolean {
return isIosFamily(device) && device.kind === 'simulator';
}
function elapsed(startedAtMs: number): number {
return Math.max(0, Date.now() - startedAtMs);
}
async function unavailable(): Promise<never> {
throw new AppError('UNSUPPORTED_OPERATION', 'This lifecycle operation is unavailable for Apple.');
}