Repository navigation
Expand file tree
/
Copy pathsession-state.ts
More file actions
239 lines (222 loc) · 8.48 KB
/
Copy pathsession-state.ts
File metadata and controls
239 lines (222 loc) · 8.48 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
import type { DaemonPlatformServices } from '../platform-services.ts';
import { asAppError, isRequestCanceledError } from '@agent-device/kernel/errors';
import { appStateUse } from '@agent-device/contracts/platform-runtime-operations';
import {
isApplePlatform,
isIosFamily,
isMacOs,
publicPlatformString,
type DeviceInfo,
} from '@agent-device/kernel/device';
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
import { SessionStore } from '../session-store.ts';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import type { AppleApplicationState } from '@agent-device/kernel/snapshot';
import { resolveAndroidSerialAllowlist } from '@agent-device/kernel/device-isolation';
import {
hasExplicitSessionFlag,
requireSessionOrExplicitSelector,
resolveCommandDevice,
selectorTargetsSessionDevice,
} from '../session-device-resolution.ts';
import type { BindDeviceRuntime, InspectDeviceRuntimeFacts } from '../request-runtime-binding.ts';
import { admitRuntimeUse } from '../runtime-admission.ts';
import type { RuntimeCommandHandlerParams } from '../session-runtime-admission.ts';
import { errorResponse } from '@agent-device/kernel/contracts';
import { handleBootCommand } from './session-boot.ts';
import { handleShutdownCommand } from './session-shutdown.ts';
const IOS_APPSTATE_SESSION_REQUIRED_MESSAGE =
'iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).';
const MACOS_APPSTATE_SESSION_REQUIRED_MESSAGE =
'macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';
/**
* The session app's state as a live runner reads it, when this device's owner admits the read;
* nothing otherwise, so the session record alone answers and no state is invented. The owner never
* starts a runner for it. A runner that cannot answer right now (busy, mid-restart) leaves the
* session answer as it was and says so in the log; a cancelled request stays cancelled.
*/
async function readAppleSessionAppState(
params: RuntimeCommandHandlerParams,
session: Readonly<{ device: DeviceInfo; appBundleId?: string }>,
): Promise<AppleApplicationState | undefined> {
if (!session.appBundleId) return undefined;
const admitted = await admitRuntimeUse({
command: 'appstate',
device: session.device,
use: appStateUse,
inspectFacts: params.inspectFacts,
platformServices: params.platformServices,
bindDevice: params.bindDevice,
});
if (admitted.type === 'response') return undefined;
try {
const read = await admitted.runtime.operations.appState({ appBundleId: session.appBundleId });
return read.applicationState;
} catch (error) {
if (isRequestCanceledError(error)) throw error;
emitDiagnostic({
level: 'warn',
phase: 'apple_appstate_runner_read_failed',
data: { code: asAppError(error).code, message: asAppError(error).message },
});
return undefined;
}
}
async function handleAppStateCommand(params: RuntimeCommandHandlerParams): Promise<DaemonResponse> {
const { req, sessionName, sessionStore } = params;
const session = sessionStore.get(sessionName);
const flags = req.flags ?? {};
const normalizedPlatform = flags.platform;
if (!session && hasExplicitSessionFlag(flags)) {
const message =
normalizedPlatform === 'ios'
? `No active session "${sessionName}". Run open with --session ${sessionName} first.`
: `No active session "${sessionName}". Run open with --session ${sessionName} first, or omit --session to query by device selector.`;
return errorResponse('SESSION_NOT_FOUND', message);
}
const guard = requireSessionOrExplicitSelector('appstate', session, flags);
if (guard) return guard;
const shouldUseSessionStateForApple =
isApplePlatform(session?.device.platform) && selectorTargetsSessionDevice(flags, session);
const targetsIos = normalizedPlatform === 'ios';
const targetsMacOs = normalizedPlatform === 'macos';
if (targetsIos && !shouldUseSessionStateForApple) {
return errorResponse('SESSION_NOT_FOUND', IOS_APPSTATE_SESSION_REQUIRED_MESSAGE);
}
if (targetsMacOs && !shouldUseSessionStateForApple) {
return errorResponse('SESSION_NOT_FOUND', MACOS_APPSTATE_SESSION_REQUIRED_MESSAGE);
}
if (shouldUseSessionStateForApple && session) {
const appName = session.appName ?? session.appBundleId;
if (!session.appName && !session.appBundleId) {
if (
isMacOs(session.device) &&
session.surface &&
session.surface !== 'app' &&
session.surface !== 'frontmost-app'
) {
return {
ok: true,
data: {
platform: publicPlatformString(session.device),
appName: session.surface,
appBundleId: session.appBundleId,
source: 'session',
surface: session.surface,
},
};
}
const sessionPlatform = isMacOs(session.device) ? 'macOS' : 'iOS';
return errorResponse(
'COMMAND_FAILED',
`No foreground app is tracked for this ${sessionPlatform} session. Open an app in the session, then retry appstate.`,
);
}
const state = await readAppleSessionAppState(params, session);
return {
ok: true,
data: {
platform: publicPlatformString(session.device),
appName: appName ?? 'unknown',
appBundleId: session.appBundleId,
source: state ? 'runner' : 'session',
...(state ? { state } : {}),
surface: session.surface ?? 'app',
...(isIosFamily(session.device)
? {
device_udid: session.device.id,
ios_simulator_device_set: session.device.simulatorSetPath ?? null,
}
: {}),
},
};
}
const device = await resolveCommandDevice({
session,
flags,
platformServices: params.platformServices,
});
if (isIosFamily(device)) {
return errorResponse('SESSION_NOT_FOUND', IOS_APPSTATE_SESSION_REQUIRED_MESSAGE);
}
if (isMacOs(device)) {
return errorResponse('SESSION_NOT_FOUND', MACOS_APPSTATE_SESSION_REQUIRED_MESSAGE);
}
const admitted = await admitRuntimeUse({
command: 'appstate',
device,
use: appStateUse,
inspectFacts: params.inspectFacts,
platformServices: params.platformServices,
bindDevice: params.bindDevice,
unavailableResponse: (unavailable) =>
errorResponse(
'UNSUPPORTED_OPERATION',
device.platform === 'web'
? 'appstate is not supported on web.'
: 'appstate is not supported on this device',
undefined,
unavailable.hint ? { hint: unavailable.hint } : undefined,
),
});
if (admitted.type === 'response') return admitted.response;
const runtime = admitted.runtime;
await runtime.operations.ensureReady({
serial: flags.serial,
androidSerialAllowlist: resolveAndroidSerialAllowlistForAppState(flags.androidDeviceAllowlist),
});
const state = await runtime.operations.appState();
return {
ok: true,
data: {
platform: publicPlatformString(device),
package: state.package,
activity: state.activity,
},
};
}
export async function handleSessionStateCommands(params: {
req: DaemonRequest;
sessionName: string;
sessionStore: SessionStore;
inspectFacts?: InspectDeviceRuntimeFacts;
platformServices: DaemonPlatformServices;
bindDevice?: BindDeviceRuntime;
}): Promise<DaemonResponse | null> {
const { req, sessionName, sessionStore } = params;
if (req.command === 'boot') {
return await handleBootCommand({
req,
sessionName,
sessionStore,
inspectFacts: params.inspectFacts,
platformServices: params.platformServices,
bindDevice: params.bindDevice,
});
}
if (req.command === 'shutdown') {
return await handleShutdownCommand({
req,
sessionName,
sessionStore,
inspectFacts: params.inspectFacts,
platformServices: params.platformServices,
bindDevice: params.bindDevice,
});
}
if (req.command === 'appstate') {
return await handleAppStateCommand({
req,
sessionName,
sessionStore,
inspectFacts: params.inspectFacts,
platformServices: params.platformServices,
bindDevice: params.bindDevice,
});
}
return null;
}
function resolveAndroidSerialAllowlistForAppState(value: string | undefined): string[] | undefined {
const allowlist = resolveAndroidSerialAllowlist(value);
return allowlist ? [...allowlist].sort() : undefined;
}