Skip to content

Commit d6f3172

Browse files
thymikeeclaude
andauthored
refactor(replay): thread runtime host through replay and device selection (#3753) (#3827)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent df066e2 commit d6f3172

68 files changed

Lines changed: 542 additions & 274 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/ad-script/src/internal/vars.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,15 +102,18 @@ export function readReplayCliEnvEntries(raw: unknown): string[] {
102102
: [];
103103
}
104104

105-
export function readReplayShellEnvSource(raw: unknown): NodeJS.ProcessEnv {
105+
export function readReplayShellEnvSource(
106+
raw: unknown,
107+
fallbackEnv: NodeJS.ProcessEnv,
108+
): NodeJS.ProcessEnv {
106109
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
107110
const result: NodeJS.ProcessEnv = {};
108111
for (const [key, value] of Object.entries(raw)) {
109112
if (typeof value === 'string') result[key] = value;
110113
}
111114
return result;
112115
}
113-
return process.env;
116+
return fallbackEnv;
114117
}
115118

116119
// `${NAME}` / `${NAME:-fallback}` / `\${` interpolation, as a single-pass

‎packages/contracts/src/replay-backend.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { DaemonError } from '@agent-device/kernel/errors';
22
import type { DaemonResponse, SessionRuntimeHints } from '@agent-device/kernel/contracts';
33
import type { DeviceInfo } from '@agent-device/kernel/device';
4+
import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value';
45
import type { SnapshotNode, SnapshotState } from '@agent-device/kernel/snapshot';
56
import type { CommandFlags } from './command-flags.ts';
67
import type { DaemonWireRequest } from './daemon-wire-request.ts';
@@ -119,6 +120,8 @@ export type ReplayBackendSession = Readonly<{
119120
/** One replay run as a backend sees it: the prepared request, its session, and the dispatch port. */
120121
export type ReplayBackendCommand = Readonly<{
121122
request: DaemonWireRequest;
123+
/** The daemon's host facts (env and working directory); a backend never reads the process itself. */
124+
host: HostEnvironment;
122125
/**
123126
* True when the request reached the daemon over its public HTTP surface only: flow scripts are
124127
* then untrusted and `runScript` HTTP calls may not reach private addresses. Absent means a
@@ -233,6 +236,8 @@ export type ReplayBackendHost = Readonly<{
233236
req: DaemonWireRequest;
234237
sessionName: string;
235238
resolvedPath: string;
239+
/** The command's host working directory, which relative flow paths resolve against. */
240+
hostCwd: string;
236241
}): Record<string, string>;
237242
/** Reads one file out of the request's script source bundle; throws when it was not sent. */
238243
readScriptSourceFile(bundle: ReplayScriptSourceBundle, resolvedPath: string): string;
@@ -246,6 +251,7 @@ export type ReplayBackendHost = Readonly<{
246251
resolveTargetDevice(
247252
flags: CommandFlags,
248253
binding: ReplayBackendDeviceBinding,
254+
env: EnvMap,
249255
): Promise<DeviceInfo>;
250256
/** The abort signal of the in-flight daemon request. */
251257
requestSignal(requestId: string | undefined): AbortSignal | undefined;

‎packages/daemon/src/core/snapshot-session.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ export async function resolveSessionDevice(
2020
const { requireNamedSessionHoldsDevice } = await import('./explicit-session-resolution.ts');
2121
requireNamedSessionHoldsDevice({ req, sessionAddress: sessionName, session });
2222
}
23-
const device = session?.device ?? (await resolveTargetDevice(req.flags ?? {}));
23+
const device =
24+
session?.device ?? (await resolveTargetDevice(req.flags ?? {}, { env: sessionStore.host.env }));
2425
return { ref, session, device };
2526
}
2627

‎packages/daemon/src/execution/handlers/session-clipboard.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,12 @@ export async function handleSessionClipboardCommand(params: {
167167
return errorResponse('INVALID_ARGS', 'clipboard requires a subcommand: read or write');
168168
}
169169

170-
const device = await resolveCommandDevice({ session, flags, platformServices });
170+
const device = await resolveCommandDevice({
171+
session,
172+
flags,
173+
env: sessionStore.host.env,
174+
platformServices,
175+
});
171176
if (ref) sessionStore.requireCurrent(ref);
172177
const bound = await resolveBoundClipboardRuntime({
173178
device,

‎packages/daemon/src/execution/handlers/session-selector-dispatch.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ async function runSessionOrSelectorDispatch(params: {
7777
const device = await resolveCommandDevice({
7878
session,
7979
flags,
80+
env: sessionStore.host.env,
8081
platformServices: params.platformServices,
8182
});
8283
if (ref) sessionStore.requireCurrent(ref);

‎packages/daemon/src/execution/selector-runtime-backend.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,9 @@ async function resolveSelectorRuntimeDevice(
127127
});
128128
}
129129
if (!session && requireSession) return { ok: false, response: noActiveSessionError() };
130-
const device = session?.device ?? (await resolveTargetDevice(params.req.flags ?? {}));
130+
const device =
131+
session?.device ??
132+
(await resolveTargetDevice(params.req.flags ?? {}, { env: params.sessionStore.host.env }));
131133
return { ok: true, ref, session, device };
132134
}
133135

‎packages/daemon/src/resources/__tests__/session-device-resolution.test.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ async function withMockedPlatform<T>(platform: NodeJS.Platform, fn: () => Promis
7171

7272
test('refreshSessionDeviceIfNeeded keeps iOS simulator session device on non-mac hosts', async () => {
7373
const device = await withMockedPlatform('linux', async () =>
74-
refreshSessionDeviceIfNeeded(iosSimulatorSession.device, platformServices),
74+
refreshSessionDeviceIfNeeded(iosSimulatorSession.device, platformServices, process.env),
7575
);
7676

7777
expect(device).toBe(iosSimulatorSession.device);
@@ -85,6 +85,7 @@ test('resolveCommandDevice keeps an existing session for a platform-only filter'
8585
platformServices: platformServices,
8686
session: iosSimulatorSession,
8787
flags: { platform: 'ios' },
88+
env: process.env,
8889
}),
8990
);
9091

@@ -99,6 +100,7 @@ test('resolveCommandDevice does not prepare a sessionless device', async () => {
99100
await resolveCommandDevice({
100101
session: undefined,
101102
flags: { platform: 'ios' },
103+
env: process.env,
102104
platformServices: platformServices,
103105
});
104106

@@ -113,6 +115,7 @@ test('refreshSessionDeviceIfNeeded keeps provider-owned iOS simulators out of lo
113115
refreshSessionDeviceIfNeeded(
114116
{ ...iosSimulatorSession.device, id: 'limrun:ios:lease-1' },
115117
platformServices,
118+
process.env,
116119
),
117120
);
118121

@@ -127,7 +130,7 @@ test('refreshSessionDeviceIfNeeded skips re-resolve while the iOS runner session
127130
});
128131

129132
const device = await withMockedPlatform('darwin', async () =>
130-
refreshSessionDeviceIfNeeded(iosSimulatorSession.device, platformServices),
133+
refreshSessionDeviceIfNeeded(iosSimulatorSession.device, platformServices, process.env),
131134
);
132135

133136
expect(device).toEqual({ ...iosSimulatorSession.device, booted: true });
@@ -143,7 +146,7 @@ test('refreshSessionDeviceIfNeeded re-resolves when the iOS runner session is go
143146
mockResolveTargetDevice.mockResolvedValue(resolved);
144147

145148
const device = await withMockedPlatform('darwin', async () =>
146-
refreshSessionDeviceIfNeeded(iosSimulatorSession.device, platformServices),
149+
refreshSessionDeviceIfNeeded(iosSimulatorSession.device, platformServices, process.env),
147150
);
148151

149152
expect(device).toBe(resolved);

‎packages/daemon/src/resources/session-device-resolution.ts‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { DaemonResponse } from '@agent-device/kernel/contracts';
2+
import type { EnvMap } from '@agent-device/kernel/source-value';
23
import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device';
34
import { AppError, sessionOrDeviceSelectorRequiredDetails } from '@agent-device/kernel/errors';
45
import { isActiveProviderDevice } from '../core/provider-device-admission.ts';
@@ -31,22 +32,29 @@ export function requireSessionOrExplicitSelector(
3132
export async function resolveCommandDevice(params: {
3233
session: SessionState | undefined;
3334
flags: DaemonRequest['flags'] | undefined;
35+
env: EnvMap;
3436
androidAvdSelection?: 'running-only' | 'include-stopped';
3537
platformServices: DaemonPlatformServices;
3638
}): Promise<DeviceInfo> {
3739
const shouldUseExplicitIdentity = hasExplicitDeviceSelector(params.flags);
3840
const device =
3941
shouldUseExplicitIdentity || !params.session
4042
? await resolveTargetDevice(params.flags ?? {}, {
43+
env: params.env,
4144
androidAvdSelection: params.androidAvdSelection,
4245
})
43-
: await refreshSessionDeviceIfNeeded(params.session.device, params.platformServices);
46+
: await refreshSessionDeviceIfNeeded(
47+
params.session.device,
48+
params.platformServices,
49+
params.env,
50+
);
4451
return device;
4552
}
4653

4754
export async function refreshSessionDeviceIfNeeded(
4855
device: DeviceInfo,
4956
platformServices: DaemonPlatformServices,
57+
env: EnvMap,
5058
): Promise<DeviceInfo> {
5159
if (isActiveProviderDevice(device)) {
5260
return device;
@@ -71,19 +79,22 @@ export async function refreshSessionDeviceIfNeeded(
7179
...(device.simulatorSetPath ? { iosSimulatorDeviceSet: device.simulatorSetPath } : {}),
7280
};
7381
try {
74-
return await resolveTargetDevice(exactSelector);
82+
return await resolveTargetDevice(exactSelector, { env });
7583
} catch (error) {
7684
if (!(error instanceof AppError) || error.code !== 'DEVICE_NOT_FOUND') {
7785
throw error;
7886
}
7987
}
8088

81-
return await resolveTargetDevice({
82-
platform: 'ios',
83-
target: device.target,
84-
device: device.name,
85-
...(device.simulatorSetPath ? { iosSimulatorDeviceSet: device.simulatorSetPath } : {}),
86-
});
89+
return await resolveTargetDevice(
90+
{
91+
platform: 'ios',
92+
target: device.target,
93+
device: device.name,
94+
...(device.simulatorSetPath ? { iosSimulatorDeviceSet: device.simulatorSetPath } : {}),
95+
},
96+
{ env },
97+
);
8798
}
8899

89100
export function selectorTargetsSessionDevice(

‎packages/daemon/src/server/__tests__/replay-device-selection.test.ts‎

Lines changed: 50 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,17 @@ test('replay leaves deep-link opens to normal device resolution', async () => {
2020
fs.writeFileSync(replayPath, 'open demo://checkout\n');
2121

2222
expect(
23-
await buildReplayTargetDeviceResolution({
24-
token: 'test-token',
25-
session: 'default',
26-
command: 'replay',
27-
positionals: [replayPath],
28-
flags: { replayScriptSource: replayScriptSourceBundleFor(replayPath) },
29-
meta: { cwd: root },
30-
}),
23+
await buildReplayTargetDeviceResolution(
24+
{
25+
token: 'test-token',
26+
session: 'default',
27+
command: 'replay',
28+
positionals: [replayPath],
29+
flags: { replayScriptSource: replayScriptSourceBundleFor(replayPath) },
30+
meta: { cwd: root },
31+
},
32+
process.env,
33+
),
3134
).toBeUndefined();
3235
});
3336

@@ -51,14 +54,17 @@ test('native replay uses its authored Android runtime setting without an iOS app
5154
'runtime set --platform android --metro-port 8081\nopen com.example.demo\n',
5255
);
5356

54-
const resolution = await buildReplayTargetDeviceResolution({
55-
token: 'test-token',
56-
session: 'default',
57-
command: 'replay',
58-
positionals: [replayPath],
59-
flags: { replayScriptSource: replayScriptSourceBundleFor(replayPath) },
60-
meta: { cwd: root },
61-
});
57+
const resolution = await buildReplayTargetDeviceResolution(
58+
{
59+
token: 'test-token',
60+
session: 'default',
61+
command: 'replay',
62+
positionals: [replayPath],
63+
flags: { replayScriptSource: replayScriptSourceBundleFor(replayPath) },
64+
meta: { cwd: root },
65+
},
66+
process.env,
67+
);
6268

6369
// The request's own flags ride through untouched, so compare the decision this function makes:
6470
// the authored platform, and no iOS app-probe options.
@@ -81,17 +87,20 @@ test('a replay whose wire bundle has a malformed entry stays advisory', async ()
8187

8288
for (const bundle of malformedBundles) {
8389
await expect(
84-
buildReplayTargetDeviceResolution({
85-
token: 'test-token',
86-
session: 'default',
87-
command: 'replay',
88-
positionals: [],
89-
flags: {
90-
replayBackend: 'maestro',
91-
replayScriptSource: bundle,
90+
buildReplayTargetDeviceResolution(
91+
{
92+
token: 'test-token',
93+
session: 'default',
94+
command: 'replay',
95+
positionals: [],
96+
flags: {
97+
replayBackend: 'maestro',
98+
replayScriptSource: bundle,
99+
},
100+
meta: { cwd: mkdtempForTestSync('agent-device-replay-device-selection-') },
92101
},
93-
meta: { cwd: mkdtempForTestSync('agent-device-replay-device-selection-') },
94-
}),
102+
process.env,
103+
),
95104
).resolves.toBeUndefined();
96105
}
97106
});
@@ -101,19 +110,22 @@ test('a Maestro flow pre-binds an iOS replay to its static appId', async () => {
101110
const flowPath = path.join(root, 'checkout.yaml');
102111
fs.writeFileSync(flowPath, 'appId: com.example.demo\n---\n- launchApp\n');
103112

104-
const resolution = await buildReplayTargetDeviceResolution({
105-
token: 'test-token',
106-
session: 'default',
107-
command: 'replay',
108-
positionals: [flowPath],
109-
flags: {
110-
platform: 'ios',
111-
replayBackend: 'maestro',
112-
replayScriptSource: await maestroScriptSourceBundleFor(flowPath),
113+
const resolution = await buildReplayTargetDeviceResolution(
114+
{
115+
token: 'test-token',
116+
session: 'default',
117+
command: 'replay',
118+
positionals: [flowPath],
119+
flags: {
120+
platform: 'ios',
121+
replayBackend: 'maestro',
122+
replayScriptSource: await maestroScriptSourceBundleFor(flowPath),
123+
},
124+
meta: { cwd: root },
113125
},
114-
meta: { cwd: root },
115-
});
126+
process.env,
127+
);
116128

117-
expect(resolution?.options).toEqual(appTargetResolutionOptions('com.example.demo'));
129+
expect(resolution?.options).toEqual(appTargetResolutionOptions('com.example.demo', process.env));
118130
expect(resolution?.options).toBeDefined();
119131
});

‎packages/daemon/src/server/__tests__/request-router-open.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,8 @@ test('fresh open uses app-aware device selection for advisory locking and dispat
172172

173173
expect(response.ok).toBe(true);
174174
expect(mockResolveTargetDevice.mock.calls).toEqual([
175-
[{ platform: 'ios' }, { appleSimulatorAppTarget: 'com.example.demo' }],
176-
[{ platform: 'ios' }, { appleSimulatorAppTarget: 'com.example.demo' }],
175+
[{ platform: 'ios' }, { appleSimulatorAppTarget: 'com.example.demo', env: process.env }],
176+
[{ platform: 'ios' }, { appleSimulatorAppTarget: 'com.example.demo', env: process.env }],
177177
]);
178178
expect(sessionStore.get('session-app-aware')?.device.id).toBe(appDevice.id);
179179
});
@@ -208,7 +208,7 @@ test('fresh replay reserves its authored app simulator before any replay step',
208208
expect(keys).toEqual(['session:fresh-replay', 'device:SIM-WITH-APP']);
209209
expect(mockResolveTargetDevice).toHaveBeenCalledWith(
210210
expect.objectContaining({ platform: 'ios' }),
211-
{ appleSimulatorAppTarget: 'com.example.demo' },
211+
{ appleSimulatorAppTarget: 'com.example.demo', env: process.env },
212212
);
213213
});
214214

@@ -265,7 +265,7 @@ test('fresh replay preserves an authored Android platform before advisory lockin
265265
expect(keys).toEqual(['session:fresh-replay-android', 'device:ANDROID-EMULATOR']);
266266
expect(mockResolveTargetDevice).toHaveBeenCalledWith(
267267
expect.objectContaining({ platform: 'android' }),
268-
undefined,
268+
expect.objectContaining({ env: process.env }),
269269
);
270270
});
271271

0 commit comments

Comments
 (0)