Skip to content

Commit 364ca6d

Browse files
fix(server): device helpers use the SDK the shell environment selects later
The desktop shell environment reaches the server after startup, but LocalDeviceHost resolved the Android SDK and copied the process environment once at construction. The hub, the agent-device daemon and emulator commands kept a standard-location SDK even after the login shell selected another one. Resolve the SDK and helper environment each time a helper starts or a command runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 35ff8e9 commit 364ca6d

2 files changed

Lines changed: 98 additions & 34 deletions

File tree

‎apps/server/src/device/LocalDeviceHost.test.ts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ const agentFixture = Effect.fn("agentFixture")(function* (
4343
) => Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
4444
avdOutput: ProcessRunner.ProcessRunOutput = processOutput(0),
4545
previousDaemon?: typeof LocalDeviceHost.__testing.AgentDeviceDaemonFile.Type,
46+
environment?: NodeJS.ProcessEnv,
4647
) {
4748
const fs = yield* FileSystem.FileSystem;
4849
const path = yield* Path.Path;
@@ -68,7 +69,7 @@ const agentFixture = Effect.fn("agentFixture")(function* (
6869
}
6970
const host = yield* LocalDeviceHost.make().pipe(
7071
Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
71-
Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
72+
Effect.provideService(HostProcess.Environment, environment ?? { HOME: baseDir, PATH: "" }),
7273
Effect.provideService(HostProcess.IsExecutable, false),
7374
Effect.provideService(HostProcess.Platform, "darwin"),
7475
Effect.provideService(
@@ -165,6 +166,56 @@ describe("AgentDevice startup", () => {
165166
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
166167
);
167168

169+
it.effect("uses the SDK a later shell environment selects", () =>
170+
Effect.gen(function* () {
171+
const fs = yield* FileSystem.FileSystem;
172+
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-sdk-" });
173+
const standard = `${home}/Library/Android/sdk`;
174+
const profile = `${home}/profile-sdk`;
175+
for (const root of [standard, profile]) {
176+
for (const tool of ["platform-tools/adb", "emulator/emulator"]) {
177+
yield* fs.makeDirectory(`${root}/${tool.split("/")[0]}`, { recursive: true });
178+
yield* fs.writeFileString(`${root}/${tool}`, "");
179+
}
180+
}
181+
const environment: NodeJS.ProcessEnv = { HOME: home, PATH: "" };
182+
const { host, hub, runs } = yield* agentFixture(
183+
(stateDir) =>
184+
fs
185+
.writeFileString(
186+
`${stateDir}/daemon.json`,
187+
JSON.stringify({ httpPort: 12345, token: "token" }),
188+
)
189+
.pipe(Effect.orDie, Effect.as(processOutput(0))),
190+
processOutput(0),
191+
undefined,
192+
environment,
193+
);
194+
// The desktop shell snapshot updates the server's environment after the host exists.
195+
environment.ANDROID_HOME = profile;
196+
hub.running = false;
197+
runs.length = 0;
198+
const ready = yield* host.ensureAgentReady(() => Effect.void);
199+
yield* ready.run("emulator", ["-list-avds"]);
200+
201+
const emulator = `${profile}/emulator/emulator`;
202+
const sdkRuns = runs.filter(
203+
(run) => run.command === emulator || run.args.includes("devices"),
204+
);
205+
// Two hub camera probes, the agent-device launch, and the emulator command.
206+
expect(sdkRuns.map((run) => run.args[0])).toEqual([
207+
"-help-camera-front",
208+
"-help-camera-back",
209+
expect.stringContaining("agent-device"),
210+
"-list-avds",
211+
]);
212+
for (const run of sdkRuns) {
213+
expect(run.env?.ANDROID_HOME).toBe(profile);
214+
expect(run.env?.PATH?.split(":")[0]).toBe(`${profile}/platform-tools`);
215+
}
216+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
217+
);
218+
168219
it.effect("reports an incompatible lock immediately and retains it for manual repair", () =>
169220
Effect.gen(function* () {
170221
const result = processOutput(

‎apps/server/src/device/LocalDeviceHost.ts‎

Lines changed: 46 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -270,8 +270,16 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
270270
const environment = yield* HostProcess.Environment;
271271
const workingDirectory = yield* HostProcess.WorkingDirectory;
272272
const hostPlatform = yield* HostProcess.Platform;
273-
const sdk = yield* androidSdk;
274-
const hostEnvironment = deviceHostEnvironment(environment, sdk.root, hostPlatform, path);
273+
// Resolved per use: the desktop shell snapshot can select another SDK after the host exists.
274+
const currentSdk = androidSdk.pipe(
275+
Effect.provideService(FileSystem.FileSystem, fs),
276+
Effect.provideService(Path.Path, path),
277+
Effect.provideService(HostProcess.Environment, environment),
278+
Effect.provideService(HostProcess.Platform, hostPlatform),
279+
);
280+
const currentHostEnvironment = currentSdk.pipe(
281+
Effect.map((sdk) => deviceHostEnvironment(environment, sdk.root, hostPlatform, path)),
282+
);
275283
const startLock = yield* Semaphore.make(1);
276284
const runningRef = yield* Ref.make<RunningHost | null>(null);
277285
const restartDelayRef = yield* Ref.make(0);
@@ -433,7 +441,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
433441
shell: false,
434442
stdout: "pipe",
435443
stderr: "pipe",
436-
env: yield* hubEnvironment(hostEnvironment).pipe(
444+
env: yield* hubEnvironment(yield* currentHostEnvironment).pipe(
437445
Effect.provideService(FileSystem.FileSystem, fs),
438446
Effect.provideService(Path.Path, path),
439447
Effect.provideService(ProcessRunner.ProcessRunner, runner),
@@ -536,7 +544,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
536544
yield* fs.makeDirectory(stateDir, { recursive: true }).pipe(Effect.ignore);
537545
const existing = yield* readDaemonFile().pipe(Effect.option);
538546
const daemonEnvironment: NodeJS.ProcessEnv = {
539-
...hostEnvironment,
547+
...(yield* currentHostEnvironment),
540548
AGENT_DEVICE_STATE_DIR: stateDir,
541549
AGENT_DEVICE_DAEMON_SERVER_MODE: "http",
542550
// Disable the five-minute idle timeout; the server owns shutdown.
@@ -643,6 +651,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
643651
AGENT_DEVICE_VERSION,
644652
]);
645653
if (!entryPath) return;
654+
const hostEnvironment = yield* currentHostEnvironment;
646655
const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
647656
Effect.provideService(HostProcess.Platform, hostPlatform),
648657
);
@@ -675,7 +684,10 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
675684
const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));
676685
if (alive) return running;
677686
}
678-
const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
687+
const nodePath = yield* resolveNodeExecutable(
688+
"Local device support",
689+
yield* currentHostEnvironment,
690+
).pipe(
679691
Effect.provideService(FileSystem.FileSystem, fs),
680692
Effect.provideService(Path.Path, path),
681693
Effect.provideService(HostProcess.Platform, hostPlatform),
@@ -807,34 +819,35 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
807819
};
808820

809821
const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
810-
runner
811-
.run({
812-
command:
813-
command === "emulator" && sdk.root
814-
? path.join(
815-
sdk.root,
816-
"emulator",
817-
hostPlatform === "win32" ? "emulator.exe" : "emulator",
818-
)
819-
: command,
820-
args,
821-
cwd: workingDirectory,
822-
env: hostEnvironment,
823-
timeout: Duration.millis(options?.timeoutMs ?? 20_000),
824-
timeoutBehavior: "timedOutResult",
825-
...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
826-
...(options?.maxOutputBytes === undefined
827-
? {}
828-
: { maxOutputBytes: options.maxOutputBytes }),
829-
})
830-
.pipe(
831-
Effect.map((result) => ({
832-
stdout: result.stdout,
833-
stderr: result.stderr,
834-
code: result.timedOut ? 124 : Number(result.code ?? 127),
835-
})),
836-
Effect.catch((cause) => Effect.succeed({ stdout: "", stderr: String(cause), code: 127 })),
837-
);
822+
currentSdk.pipe(
823+
Effect.flatMap((sdk) =>
824+
runner.run({
825+
command:
826+
command === "emulator" && sdk.root
827+
? path.join(
828+
sdk.root,
829+
"emulator",
830+
hostPlatform === "win32" ? "emulator.exe" : "emulator",
831+
)
832+
: command,
833+
args,
834+
cwd: workingDirectory,
835+
env: deviceHostEnvironment(environment, sdk.root, hostPlatform, path),
836+
timeout: Duration.millis(options?.timeoutMs ?? 20_000),
837+
timeoutBehavior: "timedOutResult",
838+
...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
839+
...(options?.maxOutputBytes === undefined
840+
? {}
841+
: { maxOutputBytes: options.maxOutputBytes }),
842+
}),
843+
),
844+
Effect.map((result) => ({
845+
stdout: result.stdout,
846+
stderr: result.stderr,
847+
code: result.timedOut ? 124 : Number(result.code ?? 127),
848+
})),
849+
Effect.catch((cause) => Effect.succeed({ stdout: "", stderr: String(cause), code: 127 })),
850+
);
838851

839852
const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({
840853
hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint,

0 commit comments

Comments
 (0)