Skip to content

Commit 4a1a9c0

Browse files
authored
refactor(daemon): extract boot handling from session-state dispatcher (#3455)
* refactor(daemon): move boot handling into its own module handleSessionStateCommands carries CC 34, keeping CRAP at 34 even at 96% coverage. Boot now answers its own domain question in session-boot.ts (device resolution, headless plan handling, runtime admission, and the booted-device response); the session-state entry routes boot there. The boot test file is renamed to match its subject; shutdown tests leave in the next layer. No behavior change. Part of #3424. * chore(gates): register the boot handler module in the daemon layer manifest session-boot.ts joins the daemon-sessions layer in the R81 manifest.
1 parent f9a0012 commit 4a1a9c0

7 files changed

Lines changed: 238 additions & 185 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@
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-boot.ts",
195196
"src/daemon/handlers/session-command-input.ts",
196197
"src/daemon/handlers/session-doctor-app.ts",
197198
"src/daemon/handlers/session-doctor-device.ts",

src/daemon/handlers/__tests__/session-state-boot-warmup.test.ts renamed to src/daemon/handlers/__tests__/session-boot-warmup.test.ts

File renamed without changes.

src/daemon/handlers/__tests__/session-boot-shutdown.test.ts renamed to src/daemon/handlers/__tests__/session-boot.test.ts

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ import {
1818
mockInspectDeviceRuntimeFacts,
1919
mockShutdownTargetRuntime,
2020
} from './session-command-harness.ts';
21+
import { createUnavailablePlatformRuntimeFacts } from '@agent-device/contracts/platform-runtime-unavailable';
22+
import { applicationLifecycleOperationFacts } from '@agent-device/contracts/application-lifecycle-runtime';
23+
import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime';
24+
import { handleSessionStateCommands } from '../session-state.ts';
2125
import { mkdtempForTestSync } from '../../../__tests__/test-utils/tmp-dir.ts';
2226
import { testCreateCommandSurface } from '../../__tests__/command-surface-fixture.ts';
2327

@@ -666,3 +670,78 @@ test('shutdown returns an error response when selected target shutdown fails', a
666670
});
667671
}
668672
});
673+
674+
test('boot rejects --headless outside Android directly', async () => {
675+
const device = {
676+
platform: 'apple' as const,
677+
appleOs: 'ios' as const,
678+
id: 'sim-1',
679+
name: 'iPhone',
680+
kind: 'simulator' as const,
681+
target: 'mobile' as const,
682+
booted: false,
683+
};
684+
mockResolveTargetDevice.mockResolvedValue(device);
685+
const response = await handleSessionStateCommands({
686+
platformServices: daemonPlatformServicesFixture(),
687+
req: {
688+
token: 't',
689+
session: 'default',
690+
command: 'boot',
691+
positionals: [],
692+
flags: { platform: 'ios', headless: true },
693+
},
694+
sessionName: 'default',
695+
sessionStore: makeSessionStore(),
696+
inspectFacts: async () =>
697+
createUnavailablePlatformRuntimeFacts(device, localRuntimeOwner('apple'), {
698+
appLog: { available: false, reason: 'owner-capability-missing' },
699+
network: { available: false, reason: 'owner-capability-missing' },
700+
screenshot: { available: false, reason: 'owner-capability-missing' },
701+
viewport: { available: false, reason: 'owner-capability-missing' },
702+
focus: { available: false, reason: 'owner-capability-missing' },
703+
gesture: { available: false, reason: 'owner-capability-missing' },
704+
scroll: { available: false, reason: 'owner-capability-missing' },
705+
typeText: { available: false, reason: 'owner-capability-missing' },
706+
touch: { available: false, reason: 'owner-capability-missing' },
707+
elementText: { available: false, reason: 'owner-capability-missing' },
708+
back: { available: false, reason: 'owner-capability-missing' },
709+
orientation: { available: false, reason: 'owner-capability-missing' },
710+
tvRemote: { available: false, reason: 'owner-capability-missing' },
711+
keyboard: { available: false, reason: 'owner-capability-missing' },
712+
clipboard: { available: false, reason: 'owner-capability-missing' },
713+
systemButton: { available: false, reason: 'owner-capability-missing' },
714+
fold: { available: false, reason: 'owner-capability-missing' },
715+
triggerAppEvent: { available: false, reason: 'owner-capability-missing' },
716+
settings: { available: false, reason: 'owner-capability-missing' },
717+
readAlert: { available: false, reason: 'owner-capability-missing' },
718+
awaitAlert: { available: false, reason: 'owner-capability-missing' },
719+
acceptAlert: { available: false, reason: 'owner-capability-missing' },
720+
dismissAlert: { available: false, reason: 'owner-capability-missing' },
721+
audioProbeCapture: { available: false, reason: 'owner-capability-missing' },
722+
audioProbeQuery: { available: false, reason: 'owner-capability-missing' },
723+
readiness: { available: false, reason: 'unsupported-device-kind' },
724+
lifecycle: applicationLifecycleOperationFacts({
725+
resolveOpenTarget: { available: false, reason: 'owner-capability-missing' },
726+
prepareApplicationOpen: { available: false, reason: 'owner-capability-missing' },
727+
openApplication: { available: false, reason: 'owner-capability-missing' },
728+
applyRuntimeHints: { available: false, reason: 'owner-capability-missing' },
729+
clearRuntimeHints: { available: false, reason: 'owner-capability-missing' },
730+
closeApplication: { available: false, reason: 'owner-capability-missing' },
731+
finalizeApplicationClose: { available: false, reason: 'owner-capability-missing' },
732+
prepareAppleRunner: { available: false, reason: 'owner-capability-missing' },
733+
configureProviderPortReverse: {
734+
available: false,
735+
reason: 'owner-capability-missing',
736+
},
737+
}),
738+
}),
739+
});
740+
741+
expect(response).toBeTruthy();
742+
expect(response?.ok).toBe(false);
743+
if (response && !response.ok) {
744+
expect(response.error.code).toBe('INVALID_ARGS');
745+
expect(response.error.message).toMatch(/supported only for Android emulators/i);
746+
}
747+
});

‎src/daemon/handlers/__tests__/session-state.test.ts‎

Lines changed: 0 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -20,84 +20,6 @@ import { createUnavailablePlatformRuntimeFacts } from '@agent-device/contracts/p
2020
import { deviceShape, type DeviceInfo } from '@agent-device/kernel/device';
2121
import type { BindDeviceRuntime } from '../../request-runtime-binding.ts';
2222

23-
test('boot rejects --headless outside Android directly', async () => {
24-
const device = {
25-
platform: 'apple' as const,
26-
appleOs: 'ios' as const,
27-
id: 'sim-1',
28-
name: 'iPhone',
29-
kind: 'simulator' as const,
30-
target: 'mobile' as const,
31-
booted: false,
32-
};
33-
const response = await withTestDeviceInventory(
34-
{ local: async () => [device] },
35-
async () =>
36-
await handleSessionStateCommands({
37-
platformServices: daemonPlatformServicesFixture(),
38-
req: {
39-
token: 't',
40-
session: 'default',
41-
command: 'boot',
42-
positionals: [],
43-
flags: { platform: 'ios', headless: true },
44-
},
45-
sessionName: 'default',
46-
sessionStore: makeSessionStore('agent-device-session-state-'),
47-
inspectFacts: async () =>
48-
createUnavailablePlatformRuntimeFacts(device, localRuntimeOwner('apple'), {
49-
appLog: { available: false, reason: 'owner-capability-missing' },
50-
network: { available: false, reason: 'owner-capability-missing' },
51-
screenshot: { available: false, reason: 'owner-capability-missing' },
52-
viewport: { available: false, reason: 'owner-capability-missing' },
53-
focus: { available: false, reason: 'owner-capability-missing' },
54-
gesture: { available: false, reason: 'owner-capability-missing' },
55-
scroll: { available: false, reason: 'owner-capability-missing' },
56-
typeText: { available: false, reason: 'owner-capability-missing' },
57-
touch: { available: false, reason: 'owner-capability-missing' },
58-
elementText: { available: false, reason: 'owner-capability-missing' },
59-
back: { available: false, reason: 'owner-capability-missing' },
60-
orientation: { available: false, reason: 'owner-capability-missing' },
61-
tvRemote: { available: false, reason: 'owner-capability-missing' },
62-
keyboard: { available: false, reason: 'owner-capability-missing' },
63-
clipboard: { available: false, reason: 'owner-capability-missing' },
64-
systemButton: { available: false, reason: 'owner-capability-missing' },
65-
fold: { available: false, reason: 'owner-capability-missing' },
66-
triggerAppEvent: { available: false, reason: 'owner-capability-missing' },
67-
settings: { available: false, reason: 'owner-capability-missing' },
68-
readAlert: { available: false, reason: 'owner-capability-missing' },
69-
awaitAlert: { available: false, reason: 'owner-capability-missing' },
70-
acceptAlert: { available: false, reason: 'owner-capability-missing' },
71-
dismissAlert: { available: false, reason: 'owner-capability-missing' },
72-
audioProbeCapture: { available: false, reason: 'owner-capability-missing' },
73-
audioProbeQuery: { available: false, reason: 'owner-capability-missing' },
74-
readiness: { available: false, reason: 'unsupported-device-kind' },
75-
lifecycle: applicationLifecycleOperationFacts({
76-
resolveOpenTarget: { available: false, reason: 'owner-capability-missing' },
77-
prepareApplicationOpen: { available: false, reason: 'owner-capability-missing' },
78-
openApplication: { available: false, reason: 'owner-capability-missing' },
79-
applyRuntimeHints: { available: false, reason: 'owner-capability-missing' },
80-
clearRuntimeHints: { available: false, reason: 'owner-capability-missing' },
81-
closeApplication: { available: false, reason: 'owner-capability-missing' },
82-
finalizeApplicationClose: { available: false, reason: 'owner-capability-missing' },
83-
prepareAppleRunner: { available: false, reason: 'owner-capability-missing' },
84-
configureProviderPortReverse: {
85-
available: false,
86-
reason: 'owner-capability-missing',
87-
},
88-
}),
89-
}),
90-
}),
91-
);
92-
93-
expect(response).toBeTruthy();
94-
expect(response?.ok).toBe(false);
95-
if (response && !response.ok) {
96-
expect(response.error.code).toBe('INVALID_ARGS');
97-
expect(response.error.message).toMatch(/supported only for Android emulators/i);
98-
}
99-
});
100-
10123
test('appstate returns missing-session error for explicit session flag', async () => {
10224
const response = await handleSessionStateCommands({
10325
platformServices: daemonPlatformServicesFixture(),
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import { resolveDeviceReadinessRuntimePlan } from '@agent-device/contracts/platform-runtime-operations';
2+
import {
3+
isApplePlatform,
4+
publicPlatformString,
5+
type DeviceInfo,
6+
} from '@agent-device/kernel/device';
7+
import { asAppError } from '@agent-device/kernel/errors';
8+
import { errorResponse } from '@agent-device/kernel/contracts';
9+
import { resolveAndroidSerialAllowlist } from '@agent-device/kernel/device-isolation';
10+
import {
11+
requireSessionOrExplicitSelector,
12+
resolveCommandDevice,
13+
} from '../session-device-resolution.ts';
14+
import { admitRuntimeOperations, type UnavailableRuntimeResponse } from '../runtime-admission.ts';
15+
import { startupDeadlineAtMs } from '../startup-deadline.ts';
16+
import type { RuntimeCommandHandlerParams } from '../session-runtime-admission.ts';
17+
import type { DaemonResponse } from '../daemon-request.ts';
18+
19+
/** `boot --headless` reports an unsupported cell as a request error, not a device capability gap. */
20+
function bootUnavailableResponse(headless: boolean): UnavailableRuntimeResponse {
21+
return (unavailable) =>
22+
errorResponse(
23+
headless ? 'INVALID_ARGS' : 'UNSUPPORTED_OPERATION',
24+
headless
25+
? 'boot --headless is supported only for Android emulators.'
26+
: 'boot is not supported on this device',
27+
undefined,
28+
unavailable.hint ? { hint: unavailable.hint } : undefined,
29+
);
30+
}
31+
32+
function hasAndroidAvdIdentity(
33+
selectedName: string | undefined,
34+
sessionDevice: DeviceInfo | undefined,
35+
): boolean {
36+
return Boolean(
37+
selectedName?.trim() ||
38+
(sessionDevice?.platform === 'android' && sessionDevice.kind === 'emulator'),
39+
);
40+
}
41+
42+
/**
43+
* Which device this boot targets. A headless plan whose selector carries no Android AVD identity
44+
* turns the resolver's `DEVICE_NOT_FOUND` into the argument error that names the missing
45+
* `--device <avd-name>`; every other resolution failure propagates unchanged.
46+
*/
47+
async function resolveBootTargetDevice(
48+
params: RuntimeCommandHandlerParams,
49+
headless: boolean,
50+
): Promise<DeviceInfo | { refusal: DaemonResponse }> {
51+
const { sessionName, sessionStore, req, platformServices } = params;
52+
const session = sessionStore.get(sessionName);
53+
const flags = req.flags ?? {};
54+
try {
55+
const device = await resolveCommandDevice({
56+
session,
57+
flags,
58+
androidAvdSelection: 'include-stopped',
59+
platformServices,
60+
});
61+
if (flags.target && (device.target ?? 'mobile') !== flags.target) {
62+
return {
63+
refusal: errorResponse(
64+
'DEVICE_NOT_FOUND',
65+
`No ${device.platform} device found matching --target ${flags.target}.`,
66+
),
67+
};
68+
}
69+
return device;
70+
} catch (error) {
71+
if (
72+
headless &&
73+
!hasAndroidAvdIdentity(flags.device, session?.device) &&
74+
asAppError(error).code === 'DEVICE_NOT_FOUND'
75+
) {
76+
return {
77+
refusal: errorResponse(
78+
'INVALID_ARGS',
79+
'boot --headless requires --device <avd-name> (or an Android emulator session target).',
80+
),
81+
};
82+
}
83+
throw error;
84+
}
85+
}
86+
87+
/** The device the runtime now reports as booted, in the wire shape `boot` publishes. */
88+
function bootedDeviceResponse(device: DeviceInfo): DaemonResponse {
89+
return {
90+
ok: true,
91+
data: {
92+
platform: publicPlatformString(device),
93+
target: device.target ?? 'mobile',
94+
device: device.name,
95+
id: device.id,
96+
kind: device.kind,
97+
booted: true,
98+
// Additive Apple-OS discriminant; Apple devices only. Gate on the platform
99+
// (not just field presence) so a non-Apple record with a stray appleOs never
100+
// surfaces it.
101+
...(isApplePlatform(device.platform) && device.appleOs ? { appleOs: device.appleOs } : {}),
102+
},
103+
};
104+
}
105+
106+
/** Brings the selected device up, headless for an Android AVD plan, through one admitted runtime. */
107+
export async function handleBootCommand(
108+
params: RuntimeCommandHandlerParams,
109+
): Promise<DaemonResponse> {
110+
const flags = params.req.flags ?? {};
111+
const guard = requireSessionOrExplicitSelector(
112+
params.req.command,
113+
params.sessionStore.get(params.sessionName),
114+
flags,
115+
);
116+
if (guard) return guard;
117+
118+
const resolvedAndroidSerialAllowlist = resolveAndroidSerialAllowlist(
119+
flags.androidDeviceAllowlist,
120+
);
121+
const androidSerialAllowlist = resolvedAndroidSerialAllowlist
122+
? [...resolvedAndroidSerialAllowlist].sort()
123+
: undefined;
124+
const plan = resolveDeviceReadinessRuntimePlan({ headless: flags.headless === true });
125+
126+
const target = await resolveBootTargetDevice(params, plan.kind === 'boot-target-headless');
127+
if ('refusal' in target) return target.refusal;
128+
129+
const admitted = await admitRuntimeOperations({
130+
command: 'boot',
131+
device: target,
132+
required: plan.use.required,
133+
inspectFacts: params.inspectFacts,
134+
platformServices: params.platformServices,
135+
bindDevice: params.bindDevice,
136+
unavailableResponse: bootUnavailableResponse(plan.kind === 'boot-target-headless'),
137+
});
138+
if (admitted.type === 'response') return admitted.response;
139+
140+
const input = {
141+
serial: flags.serial,
142+
androidSerialAllowlist,
143+
deadlineAtMs: startupDeadlineAtMs(flags.timeoutMs),
144+
};
145+
const device =
146+
plan.kind === 'boot-target-headless'
147+
? await (await admitted.bind(target, plan.use)).operations.bootTargetHeadless(input)
148+
: await (await admitted.bind(target, plan.use)).operations.bootTarget(input);
149+
150+
return bootedDeviceResponse(device);
151+
}

0 commit comments

Comments
 (0)