Skip to content

Commit a57bba1

Browse files
authored
refactor(daemon): extract appstate Apple-session and device-runtime responses (#3457)
* refactor(daemon): move the Apple-session app-state answer and the device-runtime query out of session-state Two of handleAppStateCommand's three responsibilities now live beside their subjects: the Apple session record/runner answer in session-appstate-apple-session.ts and the device-runtime foreground query in session-appstate-device-runtime.ts. The Apple-session module takes a structural AppStateSessionRecord view, keeping the handler-owned R75 SessionState overlay flat. session-state.ts keeps admission inline until its own module lands next; no behavior change. Part of #3424. * chore(gates): register the Apple-session and device-runtime app-state modules in the daemon layer manifest Both modules join the daemon-sessions layer in the R81 manifest.
1 parent ac10e38 commit a57bba1

4 files changed

Lines changed: 211 additions & 135 deletions

File tree

‎scripts/layering/daemon-layer-manifest.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@
192192
"src/daemon/handlers/session-app-deployment.ts",
193193
"src/daemon/handlers/session-app-source-deployment.ts",
194194
"src/daemon/handlers/session-batch.ts",
195+
"src/daemon/handlers/session-appstate-apple-session.ts",
196+
"src/daemon/handlers/session-appstate-device-runtime.ts",
195197
"src/daemon/handlers/session-boot.ts",
196198
"src/daemon/handlers/session-command-input.ts",
197199
"src/daemon/handlers/session-doctor-app.ts",
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import type { AppleApplicationState } from '@agent-device/kernel/snapshot';
2+
import {
3+
isMacOs,
4+
isIosFamily,
5+
publicPlatformString,
6+
type DeviceInfo,
7+
} from '@agent-device/kernel/device';
8+
import type { SessionSurface } from '@agent-device/contracts/session';
9+
import { errorResponse } from '@agent-device/kernel/contracts';
10+
import { asAppError, isRequestCanceledError } from '@agent-device/kernel/errors';
11+
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
12+
import { appStateUse } from '@agent-device/contracts/platform-runtime-operations';
13+
import { admitRuntimeUse } from '../runtime-admission.ts';
14+
import type { RuntimeCommandHandlerParams } from '../session-runtime-admission.ts';
15+
import type { DaemonResponse } from '../daemon-request.ts';
16+
17+
/**
18+
* The session facts this answer is built from, as a structural view: the handler reads exactly
19+
* the fields it uses and passes no more of the session shape than this.
20+
*/
21+
type AppStateSessionRecord = Readonly<{
22+
device: DeviceInfo;
23+
surface?: SessionSurface;
24+
appBundleId?: string;
25+
appName?: string;
26+
}>;
27+
28+
const IOS_APPSTATE_SESSION_REQUIRED_MESSAGE =
29+
'iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).';
30+
const MACOS_APPSTATE_SESSION_REQUIRED_MESSAGE =
31+
'macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';
32+
33+
/**
34+
* Apple platforms answer appstate from a session and its runner, never from a bare device query:
35+
* this is the refusal for a request whose Apple target has no session to read.
36+
*/
37+
export function appleSessionRequiredRefusal(platform: 'ios' | 'macos'): DaemonResponse {
38+
return errorResponse(
39+
'SESSION_NOT_FOUND',
40+
platform === 'macos'
41+
? MACOS_APPSTATE_SESSION_REQUIRED_MESSAGE
42+
: IOS_APPSTATE_SESSION_REQUIRED_MESSAGE,
43+
);
44+
}
45+
46+
/**
47+
* The session app's state as a live runner reads it, when this device's owner admits the read;
48+
* nothing otherwise, so the session record alone answers and no state is invented. The owner never
49+
* starts a runner for it. A runner that cannot answer right now (busy, mid-restart) leaves the
50+
* session answer as it was and says so in the log; a cancelled request stays cancelled.
51+
*/
52+
async function readAppleSessionAppState(
53+
params: RuntimeCommandHandlerParams,
54+
session: Readonly<{ device: DeviceInfo; appBundleId?: string }>,
55+
): Promise<AppleApplicationState | undefined> {
56+
if (!session.appBundleId) return undefined;
57+
const admitted = await admitRuntimeUse({
58+
command: 'appstate',
59+
device: session.device,
60+
use: appStateUse,
61+
inspectFacts: params.inspectFacts,
62+
platformServices: params.platformServices,
63+
bindDevice: params.bindDevice,
64+
});
65+
if (admitted.type === 'response') return undefined;
66+
try {
67+
const read = await admitted.runtime.operations.appState({ appBundleId: session.appBundleId });
68+
return read.applicationState;
69+
} catch (error) {
70+
if (isRequestCanceledError(error)) throw error;
71+
emitDiagnostic({
72+
level: 'warn',
73+
phase: 'apple_appstate_runner_read_failed',
74+
data: { code: asAppError(error).code, message: asAppError(error).message },
75+
});
76+
return undefined;
77+
}
78+
}
79+
80+
/** A macOS desktop surface (not an app session) is answered from the session record alone. */
81+
function desktopSurfaceResponse(session: AppStateSessionRecord): DaemonResponse | undefined {
82+
if (!isMacOs(session.device) || !session.surface) return undefined;
83+
if (session.surface === 'app' || session.surface === 'frontmost-app') return undefined;
84+
return {
85+
ok: true,
86+
data: {
87+
platform: publicPlatformString(session.device),
88+
appName: session.surface,
89+
appBundleId: session.appBundleId,
90+
source: 'session',
91+
surface: session.surface,
92+
},
93+
};
94+
}
95+
96+
/**
97+
* What this Apple session currently hosts: the tracked app's live runner state when the owner
98+
* admits a read, otherwise the session record itself. A session with no tracked foreground app
99+
* says so instead of inventing one.
100+
*/
101+
export async function appleSessionAppStateResponse(
102+
params: RuntimeCommandHandlerParams,
103+
session: AppStateSessionRecord,
104+
): Promise<DaemonResponse> {
105+
if (!session.appName && !session.appBundleId) {
106+
const surface = desktopSurfaceResponse(session);
107+
if (surface) return surface;
108+
const sessionPlatform = isMacOs(session.device) ? 'macOS' : 'iOS';
109+
return errorResponse(
110+
'COMMAND_FAILED',
111+
`No foreground app is tracked for this ${sessionPlatform} session. Open an app in the session, then retry appstate.`,
112+
);
113+
}
114+
115+
const state = await readAppleSessionAppState(params, session);
116+
const appName = session.appName ?? session.appBundleId;
117+
return {
118+
ok: true,
119+
data: {
120+
platform: publicPlatformString(session.device),
121+
appName: appName ?? 'unknown',
122+
appBundleId: session.appBundleId,
123+
source: state ? 'runner' : 'session',
124+
...(state ? { state } : {}),
125+
surface: session.surface ?? 'app',
126+
...(isIosFamily(session.device)
127+
? {
128+
device_udid: session.device.id,
129+
ios_simulator_device_set: session.device.simulatorSetPath ?? null,
130+
}
131+
: {}),
132+
},
133+
};
134+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { appStateUse } from '@agent-device/contracts/platform-runtime-operations';
2+
import {
3+
isIosFamily,
4+
isMacOs,
5+
publicPlatformString,
6+
type DeviceInfo,
7+
} from '@agent-device/kernel/device';
8+
import { errorResponse, type DaemonFailureResponse } from '@agent-device/kernel/contracts';
9+
import { resolveAndroidSerialAllowlist } from '@agent-device/kernel/device-isolation';
10+
import { admitRuntimeUse } from '../runtime-admission.ts';
11+
import type { RuntimeCommandHandlerParams } from '../session-runtime-admission.ts';
12+
import type { DaemonResponse } from '../daemon-request.ts';
13+
import { appleSessionRequiredRefusal } from './session-appstate-apple-session.ts';
14+
15+
function sortedAndroidSerialAllowlist(value: string | undefined): string[] | undefined {
16+
const allowlist = resolveAndroidSerialAllowlist(value);
17+
return allowlist ? [...allowlist].sort() : undefined;
18+
}
19+
20+
function appstateUnsupportedResponse(
21+
device: DeviceInfo,
22+
hint: string | undefined,
23+
): DaemonFailureResponse {
24+
return errorResponse(
25+
'UNSUPPORTED_OPERATION',
26+
device.platform === 'web'
27+
? 'appstate is not supported on web.'
28+
: 'appstate is not supported on this device',
29+
undefined,
30+
hint ? { hint } : undefined,
31+
);
32+
}
33+
34+
/**
35+
* The foreground app a device runtime reports for a non-session target. Apple devices never
36+
* answer here — they require the session the runner is attached to — so only runtimes whose owner
37+
* admits `appState` (Android today) get their readiness warmed and queried.
38+
*/
39+
export async function queryDeviceRuntimeAppState(
40+
params: RuntimeCommandHandlerParams,
41+
device: DeviceInfo,
42+
): Promise<DaemonResponse> {
43+
if (isIosFamily(device)) return appleSessionRequiredRefusal('ios');
44+
if (isMacOs(device)) return appleSessionRequiredRefusal('macos');
45+
const flags = params.req.flags ?? {};
46+
const admitted = await admitRuntimeUse({
47+
command: 'appstate',
48+
device,
49+
use: appStateUse,
50+
inspectFacts: params.inspectFacts,
51+
platformServices: params.platformServices,
52+
bindDevice: params.bindDevice,
53+
unavailableResponse: (unavailable) => appstateUnsupportedResponse(device, unavailable.hint),
54+
});
55+
if (admitted.type === 'response') return admitted.response;
56+
const runtime = admitted.runtime;
57+
await runtime.operations.ensureReady({
58+
serial: flags.serial,
59+
androidSerialAllowlist: sortedAndroidSerialAllowlist(flags.androidDeviceAllowlist),
60+
});
61+
const state = await runtime.operations.appState();
62+
return {
63+
ok: true,
64+
data: {
65+
platform: publicPlatformString(device),
66+
package: state.package,
67+
activity: state.activity,
68+
},
69+
};
70+
}
Lines changed: 5 additions & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,26 @@
11
import type { DaemonPlatformServices } from '../platform-services.ts';
2-
import { asAppError, isRequestCanceledError } from '@agent-device/kernel/errors';
3-
import { appStateUse } from '@agent-device/contracts/platform-runtime-operations';
4-
import {
5-
isApplePlatform,
6-
isIosFamily,
7-
isMacOs,
8-
publicPlatformString,
9-
type DeviceInfo,
10-
} from '@agent-device/kernel/device';
2+
import { isApplePlatform } from '@agent-device/kernel/device';
113
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
124
import { SessionStore } from '../session-store.ts';
13-
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
14-
import type { AppleApplicationState } from '@agent-device/kernel/snapshot';
15-
import { resolveAndroidSerialAllowlist } from '@agent-device/kernel/device-isolation';
165
import {
176
hasExplicitSessionFlag,
187
requireSessionOrExplicitSelector,
198
resolveCommandDevice,
209
selectorTargetsSessionDevice,
2110
} from '../session-device-resolution.ts';
2211
import type { BindDeviceRuntime, InspectDeviceRuntimeFacts } from '../request-runtime-binding.ts';
23-
import { admitRuntimeUse } from '../runtime-admission.ts';
2412
import type { RuntimeCommandHandlerParams } from '../session-runtime-admission.ts';
2513
import { errorResponse } from '@agent-device/kernel/contracts';
2614
import { handleBootCommand } from './session-boot.ts';
2715
import { handleShutdownCommand } from './session-shutdown.ts';
16+
import { appleSessionAppStateResponse } from './session-appstate-apple-session.ts';
17+
import { queryDeviceRuntimeAppState } from './session-appstate-device-runtime.ts';
2818

2919
const IOS_APPSTATE_SESSION_REQUIRED_MESSAGE =
3020
'iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).';
3121
const MACOS_APPSTATE_SESSION_REQUIRED_MESSAGE =
3222
'macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';
3323

34-
/**
35-
* The session app's state as a live runner reads it, when this device's owner admits the read;
36-
* nothing otherwise, so the session record alone answers and no state is invented. The owner never
37-
* starts a runner for it. A runner that cannot answer right now (busy, mid-restart) leaves the
38-
* session answer as it was and says so in the log; a cancelled request stays cancelled.
39-
*/
40-
async function readAppleSessionAppState(
41-
params: RuntimeCommandHandlerParams,
42-
session: Readonly<{ device: DeviceInfo; appBundleId?: string }>,
43-
): Promise<AppleApplicationState | undefined> {
44-
if (!session.appBundleId) return undefined;
45-
const admitted = await admitRuntimeUse({
46-
command: 'appstate',
47-
device: session.device,
48-
use: appStateUse,
49-
inspectFacts: params.inspectFacts,
50-
platformServices: params.platformServices,
51-
bindDevice: params.bindDevice,
52-
});
53-
if (admitted.type === 'response') return undefined;
54-
try {
55-
const read = await admitted.runtime.operations.appState({ appBundleId: session.appBundleId });
56-
return read.applicationState;
57-
} catch (error) {
58-
if (isRequestCanceledError(error)) throw error;
59-
emitDiagnostic({
60-
level: 'warn',
61-
phase: 'apple_appstate_runner_read_failed',
62-
data: { code: asAppError(error).code, message: asAppError(error).message },
63-
});
64-
return undefined;
65-
}
66-
}
67-
6824
async function handleAppStateCommand(params: RuntimeCommandHandlerParams): Promise<DaemonResponse> {
6925
const { req, sessionName, sessionStore } = params;
7026
const session = sessionStore.get(sessionName);
@@ -95,96 +51,15 @@ async function handleAppStateCommand(params: RuntimeCommandHandlerParams): Promi
9551
}
9652

9753
if (shouldUseSessionStateForApple && session) {
98-
const appName = session.appName ?? session.appBundleId;
99-
if (!session.appName && !session.appBundleId) {
100-
if (
101-
isMacOs(session.device) &&
102-
session.surface &&
103-
session.surface !== 'app' &&
104-
session.surface !== 'frontmost-app'
105-
) {
106-
return {
107-
ok: true,
108-
data: {
109-
platform: publicPlatformString(session.device),
110-
appName: session.surface,
111-
appBundleId: session.appBundleId,
112-
source: 'session',
113-
surface: session.surface,
114-
},
115-
};
116-
}
117-
118-
const sessionPlatform = isMacOs(session.device) ? 'macOS' : 'iOS';
119-
return errorResponse(
120-
'COMMAND_FAILED',
121-
`No foreground app is tracked for this ${sessionPlatform} session. Open an app in the session, then retry appstate.`,
122-
);
123-
}
124-
125-
const state = await readAppleSessionAppState(params, session);
126-
return {
127-
ok: true,
128-
data: {
129-
platform: publicPlatformString(session.device),
130-
appName: appName ?? 'unknown',
131-
appBundleId: session.appBundleId,
132-
source: state ? 'runner' : 'session',
133-
...(state ? { state } : {}),
134-
surface: session.surface ?? 'app',
135-
...(isIosFamily(session.device)
136-
? {
137-
device_udid: session.device.id,
138-
ios_simulator_device_set: session.device.simulatorSetPath ?? null,
139-
}
140-
: {}),
141-
},
142-
};
54+
return await appleSessionAppStateResponse(params, session);
14355
}
14456

14557
const device = await resolveCommandDevice({
14658
session,
14759
flags,
14860
platformServices: params.platformServices,
14961
});
150-
if (isIosFamily(device)) {
151-
return errorResponse('SESSION_NOT_FOUND', IOS_APPSTATE_SESSION_REQUIRED_MESSAGE);
152-
}
153-
if (isMacOs(device)) {
154-
return errorResponse('SESSION_NOT_FOUND', MACOS_APPSTATE_SESSION_REQUIRED_MESSAGE);
155-
}
156-
const admitted = await admitRuntimeUse({
157-
command: 'appstate',
158-
device,
159-
use: appStateUse,
160-
inspectFacts: params.inspectFacts,
161-
platformServices: params.platformServices,
162-
bindDevice: params.bindDevice,
163-
unavailableResponse: (unavailable) =>
164-
errorResponse(
165-
'UNSUPPORTED_OPERATION',
166-
device.platform === 'web'
167-
? 'appstate is not supported on web.'
168-
: 'appstate is not supported on this device',
169-
undefined,
170-
unavailable.hint ? { hint: unavailable.hint } : undefined,
171-
),
172-
});
173-
if (admitted.type === 'response') return admitted.response;
174-
const runtime = admitted.runtime;
175-
await runtime.operations.ensureReady({
176-
serial: flags.serial,
177-
androidSerialAllowlist: resolveAndroidSerialAllowlistForAppState(flags.androidDeviceAllowlist),
178-
});
179-
const state = await runtime.operations.appState();
180-
return {
181-
ok: true,
182-
data: {
183-
platform: publicPlatformString(device),
184-
package: state.package,
185-
activity: state.activity,
186-
},
187-
};
62+
return await queryDeviceRuntimeAppState(params, device);
18863
}
18964

19065
export async function handleSessionStateCommands(params: {
@@ -232,8 +107,3 @@ export async function handleSessionStateCommands(params: {
232107

233108
return null;
234109
}
235-
236-
function resolveAndroidSerialAllowlistForAppState(value: string | undefined): string[] | undefined {
237-
const allowlist = resolveAndroidSerialAllowlist(value);
238-
return allowlist ? [...allowlist].sort() : undefined;
239-
}

0 commit comments

Comments
 (0)