Repository navigation
Expand file tree
/
Copy pathlifecycle.ts
More file actions
528 lines (498 loc) · 18.1 KB
/
Copy pathlifecycle.ts
File metadata and controls
528 lines (498 loc) · 18.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
528
import {
type ApplicationLifecycleRuntimeOperations,
type AppleRunnerSessionPrewarmOptions,
type CloseApplicationFinalizationInput,
type CloseApplicationInput,
type LaunchConfirmation,
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 {
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 { isApplePlatform, isIosFamily, type DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { IOS_APP_LAUNCH_TIMEOUT_MS } from './core/config.ts';
const POST_CLOSE_SETTLE_MS = 300;
let launchConfirmationModule: Promise<typeof import('./launch-confirmation.ts')> | undefined;
const loadLaunchConfirmation = () =>
(launchConfirmationModule ??= import('./launch-confirmation.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 binding = bindLocalApplicationLifecycleInteractor({
device: params.device,
signal: params.signal,
resolveInteractor: params.host.localInteractors.resolve,
});
return Object.freeze({
resolveOpenTarget: async (input) =>
await params.host.appleApplications.resolveOpenTarget(params.device, input),
prepareApplicationOpen: async (input) => {
await ensureAppleReady(params.host, params.device, params.signal, {
deadlineAtMs: input.execution.startupDeadlineAtMs,
onColdBootStart: input.prewarmRunnerOnColdBoot
? () => {
void params.host.appleApplications
.prewarmRunnerCache(params.device, input.execution, params.signal)
.catch(() => {});
}
: undefined,
});
},
openApplication: async (input) =>
await openAppleApplication(params.host, binding, input, params.observation),
applyRuntimeHints: async (input) =>
await params.host.appleApplications.applyRuntimeHints(params.device, input),
clearRuntimeHints: async (input) =>
await params.host.appleApplications.clearRuntimeHints(params.device, input),
closeApplication: async (input) => await closeAppleApplication(params.host, binding, input),
finalizeApplicationClose: async (input) =>
await finalizeAppleApplicationClose(params.host, params.device, params.signal, input),
prepareAppleRunner: async (input) =>
await prepareAppleRunner(params.host, params.device, params.signal, input),
configureProviderPortReverse: unavailable,
});
}
type BoundAppleInteractor = ReturnType<typeof bindLocalApplicationLifecycleInteractor>;
async function openAppleApplication(
host: AppleLifecycleHost,
binding: BoundAppleInteractor,
input: OpenApplicationInput,
observation: LaunchObservationPort | undefined,
): Promise<OpenApplicationOutcome> {
const timing: MutableOpenTiming = {};
const localIosSimulator = isIosSimulator(binding.device);
const launch = openLaunchPlan(binding.device, input, localIosSimulator);
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,
);
await applyAppleOpenRuntimeHints(input, timing);
await prewarmAppleRunnerBeforeOpen(runner, shouldPrewarmRunner, input.prewarmRunnerBeforeOpen);
const runnerTargetPredatesOpen = runner.wasAwaited();
const launchStartedAtMs = Date.now();
await dispatchAppleOpen(binding, input, launch, localIosSimulator, timing);
await finishAppleRunnerPrewarm(runner, shouldPrewarmRunner, policy.awaitPrewarmAfterOpen);
await notifyAppleRunnerRelaunch(
host,
binding,
input,
localIosSimulator,
runnerTargetPredatesOpen,
retainRunnerForRelaunch,
);
await settleAppleOpen(host, binding, input, localIosSimulator, observation, timing);
const launchConfirmation = await answerAppleLaunchConfirmation(
binding,
input,
launch,
launchStartedAtMs,
timing,
);
if (!launchConfirmation) return { appBundleId: input.appBundleId, timing };
await settleAppleOpen(host, binding, input, localIosSimulator, observation, timing);
return { appBundleId: input.appBundleId, timing, launchConfirmation };
} 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(
input: OpenApplicationInput,
timing: MutableOpenTiming,
): Promise<void> {
if (!hasRuntimeTransportHintValues(input.runtimeHints)) return;
if (!input.applyRuntimeHints) {
throw new AppError('COMMAND_FAILED', 'Runtime hint operation was not admitted for this open.', {
reason: 'runtime-hints-operation-missing',
});
}
const startedAtMs = Date.now();
await input.applyRuntimeHints({ appId: input.appBundleId, values: input.runtimeHints });
timing.runtimeHintsDurationMs = elapsed(startedAtMs);
}
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 execution = {
...input.execution,
clearAppState: undefined,
launchConsole: undefined,
launchArgs: undefined,
};
const startedAtMs = Date.now();
await invokeApplicationOpen({
device: binding.device,
interactor: await binding.resolveInteractor(execution, input.appBundleId),
positionals: [followUpUrl],
appBundleId: input.appBundleId,
execution,
});
timing.launchUrlDurationMs = elapsed(startedAtMs);
}
/**
* One alert read, spent only when the launch handed SpringBoard a URL it may hold behind a
* confirmation and the host AX bridge then could not observe the launched app, the state a system
* surface over the app leaves. An observed app is not covered, so its open never reaches the
* runner. The read runs within what is left of the launch budget.
*/
async function answerAppleLaunchConfirmation(
binding: BoundAppleInteractor,
input: OpenApplicationInput,
launch: AppleLaunchPlan,
launchStartedAtMs: number,
timing: MutableOpenTiming,
): Promise<LaunchConfirmation | undefined> {
if (!launch.confirmable || !input.appBundleId) return undefined;
if (timing.postOpenObservation !== 'unobservable') return undefined;
const budgetMs = IOS_APP_LAUNCH_TIMEOUT_MS - (Date.now() - launchStartedAtMs);
if (budgetMs <= 0) return undefined;
const { answerLaunchConfirmation, createLaunchConfirmationPort } = await loadLaunchConfirmation();
const interactor = await binding.resolveInteractor(input.execution, input.appBundleId);
return await answerLaunchConfirmation(
createLaunchConfirmationPort(binding.device, input.appBundleId, interactor),
budgetMs,
);
}
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 (input.ensureReady) {
await ensureAppleReady(host, binding.device, binding.signal);
}
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<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;
await ensureAppleReady(host, device, signal, { deadlineAtMs });
const timeoutMs = Math.max(1, deadlineAtMs - Date.now());
return await host.appleApplications.prepareRunner(device, { ...input, timeoutMs }, signal);
}
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. `confirmable`: an iOS Simulator hands a
* custom-scheme launch URL for the session app to SpringBoard, which may hold the launch behind an
* `Open in "<App>"?` confirmation.
*/
type AppleLaunchPlan = Readonly<{
positionals: readonly string[];
followUpUrl?: string;
confirmable: boolean;
}>;
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, confirmable: false };
}
const confirmable = isConfirmableLaunchUrl(device, input, url);
if (foldLaunchUrl && !isDirectAppLaunch(input)) {
return { positionals: [target, url], confirmable };
}
return { positionals: input.positionals, followUpUrl: url, confirmable };
}
function isConfirmableLaunchUrl(
device: DeviceInfo,
input: OpenApplicationInput,
url: string,
): boolean {
return (
device.appleOs === 'ios' &&
device.kind === 'simulator' &&
input.appBundleId !== undefined &&
!isWebUrl(url)
);
}
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.');
}