Repository navigation
Expand file tree
/
Copy pathlifecycle.ts
More file actions
224 lines (216 loc) · 8.13 KB
/
Copy pathlifecycle.ts
File metadata and controls
224 lines (216 loc) · 8.13 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
import {
type ApplicationLifecycleRuntimeOperations,
type OpenApplicationInput,
type OpenApplicationOutcome,
type OpenApplicationTiming,
hasRuntimeTransportHintValues,
} from '@agent-device/contracts/application-lifecycle-runtime';
import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations';
import {
assertOpenAdmitted,
bindLocalApplicationLifecycleInteractor,
followUpRuntimeLaunchUrl,
invokeApplicationClose,
invokeApplicationOpen,
} from '@agent-device/contracts/application-lifecycle-interaction';
import { isDeepLinkTarget } from '@agent-device/contracts/command';
import { observeAndroidLaunch } from './launch-observation.ts';
import { ensureAndroidReady } from './readiness/runtime.ts';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
/** The Android package receives only the ports its lifecycle binding consumes. */
type AndroidLifecycleHost = Pick<
PlatformRuntimeHost,
| 'androidApplications'
| 'clock'
| 'commands'
| 'deviceReadiness'
| 'deviceShutdown'
| 'localInteractors'
| 'toolchains'
>;
type MutableOpenTiming = {
-readonly [Key in keyof OpenApplicationOutcome['timing']]: OpenApplicationOutcome['timing'][Key];
};
type AndroidLifecycleParams = Readonly<{
host: AndroidLifecycleHost;
device: DeviceInfo;
signal: AbortSignal;
}>;
/** Android owns lifecycle sequencing, including local adb-backed hints and durable test-IME state. */
export function bindAndroidApplicationLifecycle(
params: AndroidLifecycleParams,
): ApplicationLifecycleRuntimeOperations {
const { host, device, signal } = params;
const binding = bindLocalApplicationLifecycleInteractor({
device,
signal,
resolveInteractor: host.localInteractors.resolve,
});
return Object.freeze({
resolveOpenTarget: async (input) =>
await host.androidApplications.resolveOpenTarget(device, input),
prepareApplicationOpen: async (input) => {
await ensureAndroidReady(
host,
device,
{ headless: false, deadlineAtMs: input.execution.startupDeadlineAtMs },
signal,
);
},
openApplication: async (input) => await openAndroidApplication(host, binding, input),
applyRuntimeHints: async (input) =>
await host.androidApplications.applyRuntimeHints(device, input),
clearRuntimeHints: async (input) =>
await host.androidApplications.clearRuntimeHints(device, input),
closeApplication: async (input) => {
if (input.ensureReady) {
await ensureAndroidReady(host, device, { headless: false }, signal);
}
if (input.mode === 'kill') {
const [target] = input.positionals;
if (!target) throw new AppError('INVALID_ARGS', 'Kill requires an app target');
const { killAndroidApp } = await import('./app-lifecycle.ts');
await killAndroidApp(device, target);
return;
}
await invokeApplicationClose({
device,
interactor: await binding.resolveInteractor(input.execution, input.appBundleId),
positionals: input.positionals,
});
},
finalizeApplicationClose: async (input) => {
// The restore absorbs the settings-provider flush window before an emulator kill starts
// (#3318); it must not run concurrently with the shutdown.
await host.androidApplications.restoreTestIme(device, {
stateDir: input.stateDir,
shutdownTarget: input.shutdownTarget === true && device.kind === 'emulator',
signal,
});
const shutdown =
input.shutdownTarget && device.kind === 'emulator'
? await host.deviceShutdown.android.shutdownTarget(device, signal)
: undefined;
return shutdown === undefined ? {} : { shutdown };
},
prepareAppleRunner: unavailable,
configureProviderPortReverse: unavailable,
});
}
async function openAndroidApplication(
host: AndroidLifecycleHost,
binding: ReturnType<typeof bindLocalApplicationLifecycleInteractor>,
input: OpenApplicationInput,
): Promise<OpenApplicationOutcome> {
const timing: MutableOpenTiming = {};
assertOpenAdmitted(binding, input.execution, input.positionals);
const relaunching = input.relaunch && Boolean(input.target);
const relaunchOwner = relaunching ? input.appBundleId : undefined;
if (relaunchOwner) {
const closeStartedAtMs = Date.now();
await invokeApplicationClose({
device: binding.device,
interactor: await binding.resolveInteractor(input.execution, relaunchOwner),
positionals: [relaunchOwner],
});
timing.relaunchCloseDurationMs = elapsed(closeStartedAtMs);
}
if (hasRuntimeTransportHintValues(input.runtimeHints)) {
if (!input.applyRuntimeHints) {
throw new AppError(
'COMMAND_FAILED',
'Runtime hint operation was not admitted for this open.',
{
reason: 'runtime-hints-operation-missing',
},
);
}
const hintsStartedAtMs = Date.now();
await input.applyRuntimeHints({ appId: input.appBundleId, values: input.runtimeHints });
timing.runtimeHintsDurationMs = elapsed(hintsStartedAtMs);
}
const openStartedAtMs = Date.now();
const launch = await invokeApplicationOpen({
device: binding.device,
interactor: await binding.resolveInteractor(input.execution, input.appBundleId),
positionals: input.positionals,
appBundleId: input.appBundleId,
execution: input.execution,
terminateRunningApp: relaunching && !relaunchOwner,
});
timing.openDispatchDurationMs = elapsed(openStartedAtMs);
if (input.enableTestIme) {
// Only a failed durable-record fence rejects here; the tool reports an unobtainable helper as
// a warning so the open falls back to the ordinary text-entry path.
await host.androidApplications.activateTestIme(binding.device, {
stateDir: input.stateDir,
});
}
const runtimeLaunchUrl = followUpRuntimeLaunchUrl(input);
if (runtimeLaunchUrl) {
const launchUrlStartedAtMs = Date.now();
await invokeApplicationOpen({
device: binding.device,
interactor: await binding.resolveInteractor(
{
...input.execution,
clearAppState: undefined,
launchConsole: undefined,
launchArgs: undefined,
},
input.appBundleId,
),
positionals: [runtimeLaunchUrl],
appBundleId: input.appBundleId,
execution: {
...input.execution,
clearAppState: undefined,
launchConsole: undefined,
launchArgs: undefined,
},
});
timing.launchUrlDurationMs = elapsed(launchUrlStartedAtMs);
} else {
timing.launchUrlDurationMs = 0;
}
const appBundleId = await host.androidApplications.inferOpenedAppBundleId(
binding.device,
input.target,
input.appBundleId,
launch?.launchedAppBundleId,
);
if (appBundleId) {
await host.androidApplications.resetFramePerfStats(binding.device, appBundleId);
}
const settleStartedAtMs = Date.now();
Object.assign(timing, await observeOpenedApp(binding, input, appBundleId));
timing.postOpenSettleDurationMs = elapsed(settleStartedAtMs);
return { appBundleId, timing };
}
/** A URL or deep-link open has no launched app of its own to observe, so it reports nothing. */
async function observeOpenedApp(
binding: ReturnType<typeof bindLocalApplicationLifecycleInteractor>,
input: OpenApplicationInput,
appBundleId: string | undefined,
): Promise<Pick<OpenApplicationTiming, 'postOpenObservation' | 'postOpenObservationFailure'>> {
if (!input.target || isDeepLinkTarget(input.target)) return {};
if (!appBundleId) return { postOpenObservation: 'app-unidentified' };
const launch = await observeAndroidLaunch(
await binding.resolveInteractor(input.execution, appBundleId),
appBundleId,
binding.signal,
);
return launch.observation === 'probe-failed'
? { postOpenObservation: 'probe-failed', postOpenObservationFailure: launch.failure }
: { postOpenObservation: launch.observation };
}
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 Android.',
);
}