Skip to content

Commit a56cffd

Browse files
authored
refactor(host): read every configuration value from an explicit host (#3794) (#3798)
* refactor(host): make the host explicit on contracts, host-kit and shared test-kit (#3794) * refactor(host): read Apple platform configuration from an explicit host (#3794) * refactor(host): read Linux, Vega, web and HarmonyOS configuration from an explicit host (#3794) * refactor(host): compose platforms with the runtime host at the root (#3794)
1 parent 2b8dc2c commit a56cffd

212 files changed

Lines changed: 3190 additions & 1130 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/contracts/src/platform-plugin.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { DeviceInfo, Platform, PlatformSelector } from '@agent-device/kernel/device';
2+
import type { HostEnvironment } from '@agent-device/kernel/source-value';
23
import type { PlatformGatedProviderResolverKey } from './platform-providers.ts';
34
import type { Interactor, RunnerContext } from './interactor-types.ts';
45

@@ -31,8 +32,18 @@ export type PlatformPlugin = {
3132
readonly platforms: readonly Platform[];
3233
/** The multi-platform family selector, when the plugin owns more than one leaf (`apple`). */
3334
readonly familySelector?: PlatformSelector;
34-
/** Lazily builds the {@link Interactor} for `device` — wraps today's `getInteractor` switch arm. */
35-
createInteractor(device: DeviceInfo, runner: RunnerContext): Promise<Interactor>;
35+
/**
36+
* Lazily builds the {@link Interactor} for `device` — wraps today's `getInteractor` switch arm.
37+
* `host` is the environment the calling runtime captured at its entry point. Plugins are
38+
* module-level and shared by every runtime in a process, so the host arrives per call — never
39+
* bound at plugin construction — and is the same object the runtime's deps and request-bound
40+
* facets carry.
41+
*/
42+
createInteractor(
43+
device: DeviceInfo,
44+
runner: RunnerContext,
45+
host: HostEnvironment,
46+
): Promise<Interactor>;
3647
/**
3748
* The request-scope provider facet (issue #974). `platformGatedResolvers`
3849
* declares which PLATFORM-GATED request provider resolvers apply to this family's

‎packages/contracts/src/platform-runtime-host.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ import type { DeviceInfo, Platform } from '@agent-device/kernel/device';
22
import type { JsonObject, JsonValue } from './json.ts';
33
import type { AndroidClipboardShellSupport } from './android-clipboard-support.ts';
44

5+
// The composition root names the runtime host through this contract rather than the kernel
6+
// substrate directly (R13): one host object is the whole configuration surface a runtime reads.
7+
export type { HostEnvironment } from '@agent-device/kernel/source-value';
8+
59
export type HostCommandRequest = Readonly<{
610
executable: string;
711
args: readonly string[];
@@ -153,7 +157,12 @@ export type DeviceInventoryHost = Readonly<{
153157
files: DeviceInventoryFileHost;
154158
hostOs: HostOperatingSystem;
155159
hostName: string;
156-
homeDirectory: string;
160+
/**
161+
* The home this host names, or undefined when it names none (HOME and USERPROFILE both
162+
* absent). A host with no home still inventories: only default paths derived from the home
163+
* turn off, never the whole host.
164+
*/
165+
homeDirectory: string | undefined;
157166
observations: DeviceObservationSink;
158167
}>;
159168

‎packages/contracts/src/platform-runtime-operations.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { AppLogRuntimeHost, AppLogRuntimeOperations } from './app-log-runtime.ts';
22
import type { AppInventoryRuntimeOperations } from './app-inventory-runtime.ts';
3+
import type { HostEnvironment } from '@agent-device/kernel/source-value';
34
import type {
45
AndroidAppDeploymentExecutor,
56
AppDeploymentRuntimeOperations,
@@ -830,6 +831,11 @@ export const keyboardRuntimePlanUses = Object.freeze([
830831
export type PlatformRuntimeHost = AppLogRuntimeHost &
831832
NetworkRuntimeHost &
832833
Readonly<{
834+
/**
835+
* The host this runtime's entry point captured. Owners read configuration from it; it is the
836+
* same object the runtime's deps carry, never a re-capture.
837+
*/
838+
hostEnvironment: HostEnvironment;
833839
/** Focused native ports; deployment semantics remain in the owning family packages. */
834840
appleDeployment: AppleAppDeploymentExecutor;
835841
androidDeployment: AndroidAppDeploymentExecutor;

‎packages/daemon/src/__tests__/support/platform-services-fixture.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ import { unavailableDeviceRuntimeGateway } from './unavailable-device-runtime-ga
1212
* that cares about one ask overrides just that member — per case through the `overrides`
1313
* argument, or by mocking this module's exported spy — and asserts the daemon's branching on
1414
* the answer. What the composed members actually do (surface, open-target, readiness, and boot
15-
* rules over the platform packages) is owned by the composition lane, which builds the real
16-
* port through `src/__tests__/daemon-composition/platform-services-fixture.ts`. Members are
15+
* rules over the platform packages) is owned by the composition lane, which builds the real port
16+
* in `src/daemon-composition.ts`. Members are
1717
* module-level stable references so two fixture instances deep-compare equal.
1818
*/
1919
export function daemonPlatformServicesFixture(

‎packages/daemon/src/__tests__/support/snapshot-runtime-fixture.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,10 @@ export function snapshotRuntimeFixture(requestId?: string): Readonly<{
113113
// runner underneath is the suite's own mock.
114114
const runnerOptions = { signal: requestSignal };
115115
const appleInteractor = isApplePlatform(device.platform)
116-
? await applePlugin.createInteractor(device, runnerOptions)
116+
? await applePlugin.createInteractor(device, runnerOptions, {
117+
env: process.env,
118+
cwd: process.cwd(),
119+
})
117120
: undefined;
118121
const alertOptions = (input: AlertRuntimeInput) => ({
119122
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),

‎packages/host-kit/src/host-file.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export {
1111
hostFileStat,
1212
hostFileStatSync,
1313
hostHomeDirectory,
14+
hostHomeDirectoryFromEnv,
1415
hostTemporaryDirectory,
1516
makeHostTemporaryDirectory,
1617
readHostBinaryFile,

‎packages/host-kit/src/internal/host-file.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,18 @@ export function hostHomeDirectory(): string {
77
return os.homedir();
88
}
99

10+
/**
11+
* The home directory a named host names for itself: its own HOME (or USERPROFILE on Windows).
12+
* Returns undefined when the host env names no home; callers must fail closed or skip the
13+
* home-bound lookup, never fall back to `os.homedir()`, because the process home is an ambient
14+
* read that #3753 forbids. Derive per-runtime home config through this (#3794).
15+
*/
16+
export function hostHomeDirectoryFromEnv(
17+
env: Record<string, string | undefined>,
18+
): string | undefined {
19+
return env['HOME'] ?? env['USERPROFILE'];
20+
}
21+
1022
export function hostTemporaryDirectory(): string {
1123
return os.tmpdir();
1224
}

‎packages/platform-android/src/inventory.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,32 @@ test('Android inventory prepares the legacy toolchain before an ANDROID_HOME-onl
224224
assert.deepEqual(preparedFamilies, ['android']);
225225
});
226226

227+
test('Android inventory omits the home SDK root when the host names no home', async () => {
228+
// The rule: a host that names no home turns off only the home-derived default paths. Discovery
229+
// must still resolve adb from PATH and list devices, not fail the family (#3794 review).
230+
const probed: string[] = [];
231+
const host: DeviceInventoryHostFor<'android'> = {
232+
...createHost(async () => result('List of devices attached\n')),
233+
homeDirectory: undefined,
234+
files: {
235+
isExecutable: async (candidate) => {
236+
probed.push(candidate);
237+
return false;
238+
},
239+
createTemporaryTextFile: async () => {
240+
throw new Error('unused');
241+
},
242+
},
243+
};
244+
245+
await createAndroidInventory(host, { sdkRoots: ['/configured-sdk'] }).discover({}, scope);
246+
247+
// The configured root is still probed; only the home-derived default root turns off. Without
248+
// the guard, path.join(undefined, 'Android', 'Sdk') throws before adb is ever resolved.
249+
assert.ok(probed.includes('/configured-sdk/platform-tools/adb'));
250+
assert.ok(probed.every((candidate) => !candidate.includes('Android')));
251+
});
252+
227253
test('Android inventory classifies a killed adb probe as a timeout', async () => {
228254
// The exec layer kills a wedged adb with `timeoutMs` in details and no stderr, so discovery
229255
// must classify it rather than report an unclassified command failure.

‎packages/platform-android/src/inventory.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,12 @@ async function discoverAndroidDevices(
5858
scope: PlatformRequestScope,
5959
): Promise<readonly DeviceInfo[]> {
6060
await host.toolchains.prepare('android');
61-
const sdkRoots = [...config.sdkRoots, path.join(host.homeDirectory, 'Android', 'Sdk')];
61+
// The ~/Android/Sdk default root exists only when the host names a home; a host with no home
62+
// discovers from the configured roots and PATH instead of failing the whole inventory.
63+
const sdkRoots = [
64+
...config.sdkRoots,
65+
...(host.homeDirectory === undefined ? [] : [path.join(host.homeDirectory, 'Android', 'Sdk')]),
66+
];
6267
const adb = await resolveTool(host, 'adb', sdkRoots, ['platform-tools', 'adb']);
6368
if (!adb) throw new AppError('TOOL_MISSING', 'adb not found in PATH');
6469
const emulator = await resolveTool(host, 'emulator', sdkRoots, ['emulator', 'emulator']);

‎packages/platform-apple/src/__tests__/alert.test.ts‎

Lines changed: 80 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ afterEach(() => {
4343
test('a read spends the family default, not the caller window', async () => {
4444
mockRunner.mockResolvedValue({ title: 'Camera Access' });
4545

46-
await readAppleAlert(IOS_SIMULATOR, runnerOptions, { timeoutMs: 37 });
46+
await readAppleAlert(IOS_SIMULATOR, runnerOptions, { timeoutMs: 37 }, process.env);
4747

4848
assert.equal(mockRunner.mock.calls.length, 1);
4949
assert.deepEqual(mockRunner.mock.calls[0]?.[1], {
@@ -62,7 +62,12 @@ test('a wait polls until one attempt answers, and the first attempt gets the who
6262
return { title: 'Camera Access' };
6363
});
6464

65-
const result = await awaitAppleAlert(IOS_SIMULATOR, runnerOptions, { timeoutMs: 5_000 });
65+
const result = await awaitAppleAlert(
66+
IOS_SIMULATOR,
67+
runnerOptions,
68+
{ timeoutMs: 5_000 },
69+
process.env,
70+
);
6671

6772
assert.deepEqual(result, { title: 'Camera Access' });
6873
assert.equal(calls, 2);
@@ -76,7 +81,12 @@ test('a wait that never sees an alert reports the timeout rather than the last a
7681
vi.useFakeTimers();
7782
mockRunner.mockRejectedValue(runnerAbsence());
7883

79-
const outcome = awaitAppleAlert(IOS_SIMULATOR, runnerOptions, { timeoutMs: 900 }).then(
84+
const outcome = awaitAppleAlert(
85+
IOS_SIMULATOR,
86+
runnerOptions,
87+
{ timeoutMs: 900 },
88+
process.env,
89+
).then(
8090
() => undefined,
8191
(error: unknown) => error,
8292
);
@@ -93,7 +103,13 @@ test('an accept retries only while the backend says the alert is not there yet',
93103
throw new AppError('COMMAND_FAILED', 'runner crashed');
94104
});
95105

96-
const outcome = actOnAppleAlert(IOS_SIMULATOR, runnerOptions, 'accept').then(
106+
const outcome = actOnAppleAlert(
107+
IOS_SIMULATOR,
108+
runnerOptions,
109+
'accept',
110+
undefined,
111+
process.env,
112+
).then(
97113
() => undefined,
98114
(error: unknown) => error,
99115
);
@@ -107,7 +123,13 @@ test('an exhausted accept carries the scoped-snapshot fallback the agent needs n
107123
vi.useFakeTimers();
108124
mockRunner.mockRejectedValue(runnerAbsence());
109125

110-
const outcome = actOnAppleAlert(IOS_SIMULATOR, runnerOptions, 'accept').then(
126+
const outcome = actOnAppleAlert(
127+
IOS_SIMULATOR,
128+
runnerOptions,
129+
'accept',
130+
undefined,
131+
process.env,
132+
).then(
111133
() => undefined,
112134
(error: unknown) => error,
113135
);
@@ -130,7 +152,12 @@ test('a wait propagates a non-absence failure instead of spending it as poll bud
130152
throw new AppError('COMMAND_FAILED', 'runner transport closed: alert not found');
131153
});
132154

133-
const outcome = awaitAppleAlert(IOS_SIMULATOR, runnerOptions, { timeoutMs: 5_000 }).then(
155+
const outcome = awaitAppleAlert(
156+
IOS_SIMULATOR,
157+
runnerOptions,
158+
{ timeoutMs: 5_000 },
159+
process.env,
160+
).then(
134161
() => undefined,
135162
(error: unknown) => error,
136163
);
@@ -148,7 +175,13 @@ test('an action does not retry a failure that only reads like an absence', async
148175
throw new AppError('COMMAND_FAILED', 'no alert service on this runner');
149176
});
150177

151-
const outcome = actOnAppleAlert(IOS_SIMULATOR, runnerOptions, 'dismiss').then(
178+
const outcome = actOnAppleAlert(
179+
IOS_SIMULATOR,
180+
runnerOptions,
181+
'dismiss',
182+
undefined,
183+
process.env,
184+
).then(
152185
() => undefined,
153186
(error: unknown) => error,
154187
);
@@ -168,7 +201,13 @@ test('the macOS helper states absence as a typed reason, and the family retries
168201
throw helperAbsence();
169202
});
170203

171-
const outcome = actOnAppleAlert(MACOS_DEVICE, runnerOptions, 'accept').then(
204+
const outcome = actOnAppleAlert(
205+
MACOS_DEVICE,
206+
runnerOptions,
207+
'accept',
208+
undefined,
209+
process.env,
210+
).then(
172211
() => undefined,
173212
(error: unknown) => error,
174213
);
@@ -183,24 +222,37 @@ test('the macOS helper states absence as a typed reason, and the family retries
183222
test('the macOS host reads through its helper, and a frontmost-app session names no bundle', async () => {
184223
mockHelper.mockResolvedValue({ title: 'Allow access' });
185224

186-
await readAppleAlert(MACOS_DEVICE, runnerOptions, {
187-
surface: 'frontmost-app',
188-
appBundleId: 'com.example.app',
189-
});
225+
await readAppleAlert(
226+
MACOS_DEVICE,
227+
runnerOptions,
228+
{
229+
surface: 'frontmost-app',
230+
appBundleId: 'com.example.app',
231+
},
232+
process.env,
233+
);
190234

191235
assert.equal(mockRunner.mock.calls.length, 0);
192-
assert.deepEqual(mockHelper.mock.calls[0], ['get', { surface: 'frontmost-app' }]);
236+
assert.deepEqual(mockHelper.mock.calls[0], [
237+
'get',
238+
{ surface: 'frontmost-app', env: process.env },
239+
]);
193240
});
194241

195242
// The narrowing is the macOS helper's alone. A non-macOS Apple leaf keeps the session bundle
196243
// whatever the surface says, exactly as the retired route passed it to the XCTest runner.
197244
test('the XCTest runner keeps the session bundle even on a frontmost-app surface', async () => {
198245
mockRunner.mockResolvedValue({ title: 'Camera Access' });
199246

200-
await readAppleAlert(IOS_SIMULATOR, runnerOptions, {
201-
surface: 'frontmost-app',
202-
appBundleId: 'com.example.app',
203-
});
247+
await readAppleAlert(
248+
IOS_SIMULATOR,
249+
runnerOptions,
250+
{
251+
surface: 'frontmost-app',
252+
appBundleId: 'com.example.app',
253+
},
254+
process.env,
255+
);
204256

205257
assert.deepEqual(mockRunner.mock.calls[0]?.[1], {
206258
command: 'alert',
@@ -213,13 +265,19 @@ test('the XCTest runner keeps the session bundle even on a frontmost-app surface
213265
test('a macOS app session forwards the bundle its surface is scoped to', async () => {
214266
mockHelper.mockResolvedValue({ action: 'dismiss' });
215267

216-
await actOnAppleAlert(MACOS_DEVICE, runnerOptions, 'dismiss', {
217-
surface: 'app',
218-
appBundleId: 'com.example.app',
219-
});
268+
await actOnAppleAlert(
269+
MACOS_DEVICE,
270+
runnerOptions,
271+
'dismiss',
272+
{
273+
surface: 'app',
274+
appBundleId: 'com.example.app',
275+
},
276+
process.env,
277+
);
220278

221279
assert.deepEqual(mockHelper.mock.calls[0], [
222280
'dismiss',
223-
{ bundleId: 'com.example.app', surface: 'app' },
281+
{ bundleId: 'com.example.app', surface: 'app', env: process.env },
224282
]);
225283
});

0 commit comments

Comments
 (0)