Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LocalDeviceHost.test.ts

919 lines36.2 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as NodePath from "@effect/platform-node/NodePath";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as Ref from "effect/Ref";
12import * as FileSystem from "effect/FileSystem";
13import * as Sink from "effect/Sink";
14import * as Stream from "effect/Stream";
15​
16import * as LocalDeviceHost from "./LocalDeviceHost.ts";
17import * as NodeServices from "@effect/platform-node/NodeServices";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19import { HttpClient, HttpClientResponse } from "effect/http";
20import * as NetService from "@t3tools/shared/Net";
21import * as ServerConfig from "../config.ts";
22import * as ProcessRunner from "../processRunner.ts";
23import {
24 AGENT_DEVICE_VERSION,
25 DEVICE_HUB_VERSION,
26 agentDeviceStateDir,
27} from "./DeviceToolchain.ts";
28​
29const processOutput = (code: number, stdout = "", stderr = "", timedOut = false) => ({
30 code: ChildProcessSpawner.ExitCode(code),
31 stdout,
32 stderr,
33 timedOut,
34 stdoutTruncated: false,
35 stderrTruncated: false,
36 stdoutInvalidUtf8: false,
37 stderrInvalidUtf8: false,
38});
39​
40const agentFixture = Effect.fn("agentFixture")(function* (
41 startup: (
42 stateDir: string,
43 ) => Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
44 avdOutput: ProcessRunner.ProcessRunOutput = processOutput(0),
45 previousDaemon?: typeof LocalDeviceHost.__testing.AgentDeviceDaemonFile.Type,
46 environment?: NodeJS.ProcessEnv,
47) {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" });
51 const hub = {
52 running: true,
53 spawnFails: false,
54 cleanup: Effect.void,
55 cameraHelp: "",
56 cameraProbes: 0,
57 spawnedEnvironments: [] as Array<NodeJS.ProcessEnv | undefined>,
58 spawnedArgs: [] as Array<ReadonlyArray<unknown>>,
59 };
60 const daemonStopRequested = yield* Deferred.make<ReadonlyArray<string>>();
61 const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata"));
62 const daemonHealthy = yield* Ref.make(true);
63 const runs: Array<ProcessRunner.ProcessRunInput> = [];
64 for (const [name, version, entry] of [
65 ["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"],
66 ["agent-device", AGENT_DEVICE_VERSION, "bin/agent-device.mjs"],
67 ]) {
68 const installDir = path.join(baseDir, "tools", name!, version!);
69 const entryPath = path.join(installDir, "node_modules", name!, entry!);
70 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
71 yield* fs.writeFileString(entryPath, "");
72 yield* fs.writeFileString(path.join(installDir, ".install-complete"), version!);
73 }
74 if (previousDaemon) {
75 yield* fs.makeDirectory(stateDir, { recursive: true });
76 yield* fs.writeFileString(path.join(stateDir, "daemon.json"), JSON.stringify(previousDaemon));
77 }
78 const host = yield* LocalDeviceHost.make().pipe(
79 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
80 Effect.provideService(HostProcess.Environment, environment ?? { HOME: baseDir, PATH: "" }),
81 Effect.provideService(HostProcess.IsExecutable, false),
82 Effect.provideService(HostProcess.Platform, "darwin"),
83 Effect.provideService(
84 ChildProcessSpawner.ChildProcessSpawner,
85 ChildProcessSpawner.make((command) =>
86 hub.spawnFails
87 ? Effect.fail(
88 PlatformError.systemError({
89 _tag: "NotFound",
90 module: "ChildProcess",
91 method: "spawn",
92 description: "Hub entry missing",
93 }),
94 )
95 : Effect.addFinalizer(() => hub.cleanup).pipe(
96 Effect.tap(() =>
97 Effect.sync(() => {
98 if (command._tag === "StandardCommand") hub.spawnedArgs.push(command.args);
99 return hub.spawnedEnvironments.push(
100 (
101 command as unknown as {
102 readonly options: { readonly env?: NodeJS.ProcessEnv };
103 }
104 ).options.env,
105 );
106 }),
107 ),
108 Effect.as(
109 ChildProcessSpawner.makeHandle({
110 pid: ChildProcessSpawner.ProcessId(123),
111 stdout: Stream.empty,
112 stderr: Stream.empty,
113 all: Stream.encodeText(
114 Stream.make(" Local: http://localhost:1/?token=hub-token\n"),
115 ),
116 exitCode: Effect.never,
117 exitStatus: Effect.never,
118 isRunning: Effect.sync(() => hub.running),
119 kill: () => Effect.void,
120 stdin: Sink.drain,
121 getInputFd: () => Sink.drain,
122 getOutputFd: () => Stream.empty,
123 unref: Effect.succeed(Effect.void),
124 }),
125 ),
126 ),
127 ),
128 ),
129 Effect.provideService(ProcessRunner.ProcessRunner, {
130 run: (input) => {
131 runs.push(input);
132 return input.args.includes("devices")
133 ? startup(stateDir)
134 : input.args.includes("daemon")
135 ? Deferred.succeed(daemonStopRequested, input.args).pipe(Effect.as(processOutput(0)))
136 : Effect.succeed(
137 input.args.includes("-list-avds")
138 ? avdOutput
139 : input.args[0]?.startsWith("-help-camera-")
140 ? (hub.cameraProbes++, processOutput(0, hub.cameraHelp))
141 : processOutput(0),
142 );
143 },
144 }),
145 Effect.provideService(
146 HttpClient.HttpClient,
147 HttpClient.make((request) =>
148 Ref.get(daemonHealthy).pipe(
149 Effect.map((healthy) =>
150 HttpClientResponse.fromWeb(
151 request,
152 new Response("ok", {
153 status: request.url.endsWith("/health") && !healthy ? 503 : 200,
154 }),
155 ),
156 ),
157 ),
158 ),
159 ),
160 );
161 yield* host.ensureReady(() => Effect.void);
162 return { host, fs, baseDir, stateDir, hub, daemonHealthy, daemonStopRequested, runs };
163});
164​
165describe("AgentDevice startup", () => {
166 it.effect("restarts a cached daemon that no longer answers its health check", () =>
167 Effect.gen(function* () {
168 const fs = yield* FileSystem.FileSystem;
169 let attempts = 0;
170 const { host, daemonHealthy } = yield* agentFixture((stateDir) =>
171 Effect.gen(function* () {
172 attempts++;
173 yield* fs
174 .writeFileString(
175 `${stateDir}/daemon.json`,
176 JSON.stringify({ httpPort: 12345 + attempts, token: `token-${attempts}` }),
177 )
178 .pipe(Effect.orDie);
179 return processOutput(0);
180 }),
181 );
182 const first = yield* host.ensureAgentReady(() => Effect.void);
183 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
184 first.agentDevice,
185 );
186 expect(attempts).toBe(1);
187​
188 yield* Ref.set(daemonHealthy, false);
189 const restarted = yield* host.ensureAgentReady(() => Effect.void);
190 expect(attempts).toBe(2);
191 expect(restarted.agentDevice).toMatchObject({
192 baseUrl: "http://127.0.0.1:12347",
193 token: "token-2",
194 });
195 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
196 );
197​
198 // regression: #41190 a daemon left by the previous pin keeps answering /health
199 it.effect("hands a daemon recorded at another agent-device version to the pinned client", () =>
200 Effect.gen(function* () {
201 const fs = yield* FileSystem.FileSystem;
202 const previous = { httpPort: 12345, token: "previous-token", version: "0.21.36" };
203 const { host, runs } = yield* agentFixture(
204 (stateDir) =>
205 fs
206 .writeFileString(
207 `${stateDir}/daemon.json`,
208 JSON.stringify({
209 httpPort: 23456,
210 token: "next-token",
211 version: AGENT_DEVICE_VERSION,
212 }),
213 )
214 .pipe(Effect.orDie, Effect.as(processOutput(0))),
215 processOutput(0),
216 previous,
217 );
218 const ready = yield* host.ensureAgentReady(() => Effect.void);
219 expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1);
220 expect(ready.agentDevice).toMatchObject({
221 baseUrl: "http://127.0.0.1:23456",
222 token: "next-token",
223 });
224 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
225 );
226​
227 it.effect("keeps a busy daemon from another version that the pinned client leaves running", () =>
228 Effect.gen(function* () {
229 const previous = { httpPort: 12345, token: "previous-token", version: "0.21.36" };
230 const { host, runs } = yield* agentFixture(
231 () => Effect.succeed(processOutput(1)),
232 processOutput(0),
233 previous,
234 );
235 const ready = yield* host.ensureAgentReady(() => Effect.void);
236 expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1);
237 expect(ready.agentDevice).toMatchObject({
238 baseUrl: "http://127.0.0.1:12345",
239 token: "previous-token",
240 });
241 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
242 );
243​
244 it.effect("reports a stopped daemon a failed replacement left registered", () =>
245 Effect.gen(function* () {
246 const fs = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 let health: Ref.Ref<boolean> | undefined;
249 const previous = {
250 httpPort: 12345,
251 token: "previous-token",
252 pid: process.pid,
253 version: "0.21.36",
254 };
255 const { host, stateDir, runs, daemonHealthy } = yield* agentFixture(
256 () => (health ? Ref.set(health, false) : Effect.void).pipe(Effect.as(processOutput(1))),
257 processOutput(0),
258 previous,
259 );
260 health = daemonHealthy;
261 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
262 expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1);
263 expect(error).toMatchObject({
264 _tag: "AgentDeviceStartError",
265 reason: "command_failed",
266 exitCode: 1,
267 });
268 expect(yield* fs.readFileString(path.join(stateDir, "daemon.json"))).toContain(
269 previous.token,
270 );
271 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
272 );
273​
274 it.effect("uses the SDK a later shell environment selects", () =>
275 Effect.gen(function* () {
276 const fs = yield* FileSystem.FileSystem;
277 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-sdk-" });
278 const standard = `${home}/Library/Android/sdk`;
279 const profile = `${home}/profile-sdk`;
280 for (const root of [standard, profile]) {
281 for (const tool of ["platform-tools/adb", "emulator/emulator"]) {
282 yield* fs.makeDirectory(`${root}/${tool.split("/")[0]}`, { recursive: true });
283 yield* fs.writeFileString(`${root}/${tool}`, "");
284 }
285 }
286 const environment: NodeJS.ProcessEnv = { HOME: home, PATH: "" };
287 const { host, hub, runs } = yield* agentFixture(
288 (stateDir) =>
289 fs
290 .writeFileString(
291 `${stateDir}/daemon.json`,
292 JSON.stringify({ httpPort: 12345, token: "token" }),
293 )
294 .pipe(Effect.orDie, Effect.as(processOutput(0))),
295 processOutput(0),
296 undefined,
297 environment,
298 );
299 // The desktop shell snapshot updates the server's environment after the host exists.
300 environment.ANDROID_HOME = profile;
301 hub.running = false;
302 runs.length = 0;
303 const ready = yield* host.ensureAgentReady(() => Effect.void);
304 yield* ready.run("emulator", ["-list-avds"]);
305​
306 const emulator = `${profile}/emulator/emulator`;
307 const sdkRuns = runs.filter(
308 (run) => run.command === emulator || run.args.includes("devices"),
309 );
310 // Two hub camera probes, the agent-device launch, and the emulator command.
311 expect(sdkRuns.map((run) => run.args[0])).toEqual([
312 "-help-camera-front",
313 "-help-camera-back",
314 expect.stringContaining("agent-device"),
315 "-list-avds",
316 ]);
317 for (const run of sdkRuns) {
318 expect(run.env?.ANDROID_HOME).toBe(profile);
319 expect(run.env?.PATH?.split(":")[0]).toBe(`${profile}/platform-tools`);
320 }
321 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
322 );
323​
324 it.effect(
325 "drops emulated camera overrides once a running hub's emulator supports image files",
326 () =>
327 Effect.gen(function* () {
328 const fs = yield* FileSystem.FileSystem;
329 const sdk = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-camera-sdk-" });
330 for (const tool of ["platform-tools/adb", "emulator/emulator"]) {
331 yield* fs.makeDirectory(`${sdk}/${tool.split("/")[0]}`, { recursive: true });
332 yield* fs.writeFileString(`${sdk}/${tool}`, "");
333 }
334 const environment: NodeJS.ProcessEnv = { HOME: sdk, PATH: "", ANDROID_HOME: sdk };
335 const { host, hub } = yield* agentFixture(
336 () => Effect.succeed(processOutput(0)),
337 processOutput(0),
338 undefined,
339 environment,
340 );
341 // ensureReady is the hub's first start; the probe ran with the fixture's empty help.
342 hub.cameraHelp = "emulated none";
343 hub.running = false;
344 yield* host.ensureReady(() => Effect.void);
345 hub.running = true;
346 expect(hub.spawnedEnvironments.at(-1)?.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(
347 "-camera-front emulated -camera-back emulated",
348 );
349​
350 // A live hub with an unchanged emulator answers without probing it.
351 const probes = hub.cameraProbes;
352 yield* host.ensureReady(() => Effect.void);
353 expect(hub.cameraProbes).toBe(probes);
354​
355 // The SDK's emulator is updated to one that renders image files while the hub keeps running.
356 yield* fs.writeFileString(`${sdk}/emulator/emulator`, "updated");
357 hub.cameraHelp = "emulated imagefile:<filename> none";
358 yield* host.ensureReady(() => Effect.void);
359 expect(hub.spawnedEnvironments.at(-1)?.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBeUndefined();
360 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
361 );
362​
363 it.effect("reports an incompatible lock immediately and retains it for manual repair", () =>
364 Effect.gen(function* () {
365 const result = processOutput(
366 1,
367 JSON.stringify({
368 success: false,
369 error: {
370 message: "private command output",
371 details: {
372 reason: "daemon_registration_unproven",
373 inspection: { state: "unproven", reason: "non-directory" },
374 },
375 },
376 }),
377 );
378 const { host, fs, stateDir } = yield* agentFixture(() => Effect.succeed(result));
379 const lock = `${stateDir}/daemon.lock`;
380 const legacyOwner = JSON.stringify({ pid: 85669, processStartTime: "old start time" });
381 yield* fs.writeFileString(lock, legacyOwner);
382 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
383 expect(error).toMatchObject({
384 _tag: "AgentDeviceStartError",
385 reason: "daemon_lock_not_directory",
386 exitCode: 1,
387 cause: result,
388 });
389 expect(error.message).toContain("Daemon registration ownership could not be verified");
390 expect(error.message).toContain("daemon.lock is not a directory");
391 expect(error.message).toContain(stateDir);
392 expect(error.message).toContain("original CLI");
393 expect(error.message).not.toContain("private command output");
394 expect(yield* fs.readFileString(lock)).toBe(legacyOwner);
395 expect(yield* host.current).not.toBeNull();
396 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
397 );
398​
399 it.effect("reports unknown nonzero exits without exposing arbitrary command output", () =>
400 Effect.gen(function* () {
401 const result = processOutput(2, "invalid JSON", "private credentials");
402 const { host, stateDir } = yield* agentFixture(() => Effect.succeed(result));
403 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
404 expect(error).toMatchObject({
405 _tag: "AgentDeviceStartError",
406 reason: "command_failed",
407 exitCode: 2,
408 cause: result,
409 });
410 expect(error.message).toContain("exit code 2");
411 expect(error.message).toContain(stateDir);
412 expect(error.message).not.toContain("private credentials");
413 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
414 );
415​
416 it.effect("preserves process execution failures instead of waiting for a daemon file", () =>
417 Effect.gen(function* () {
418 const cause = new ProcessRunner.ProcessSpawnError({
419 command: "/missing/node",
420 argumentCount: 3,
421 cause: new Error("missing executable"),
422 });
423 const { host } = yield* agentFixture(() => Effect.fail(cause));
424 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
425 expect(error).toMatchObject({
426 _tag: "DeviceHostError",
427 step: "starting agent tools",
428 cause,
429 });
430 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
431 );
432​
433 it.effect("uses a registered daemon when reading startup command output fails", () =>
434 Effect.gen(function* () {
435 const fs = yield* FileSystem.FileSystem;
436 const cause = new ProcessRunner.ProcessReadError({
437 command: process.execPath,
438 argumentCount: 3,
439 stream: "stdout",
440 cause: new Error("output read failed after registration"),
441 });
442 let attempts = 0;
443 const { host } = yield* agentFixture((stateDir) =>
444 Effect.gen(function* () {
445 attempts++;
446 yield* fs
447 .writeFileString(
448 `${stateDir}/daemon.json`,
449 JSON.stringify({ httpPort: 12345, token: "test-token" }),
450 )
451 .pipe(Effect.orDie);
452 return yield* cause;
453 }),
454 );
455 const ready = yield* host.ensureAgentReady(() => Effect.void);
456 expect(ready.agentDevice).toMatchObject({
457 baseUrl: "http://127.0.0.1:12345",
458 token: "test-token",
459 });
460 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
461 ready.agentDevice,
462 );
463 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
464 expect(attempts).toBe(1);
465 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
466 );
467​
468 it.effect("starts the hub requiring a session token and keeps the one it prints", () =>
469 Effect.gen(function* () {
470 const path = yield* Path.Path;
471 const { host, hub, baseDir } = yield* agentFixture(() => Effect.succeed(processOutput(0)));
472 expect(hub.spawnedArgs[0]).toContain("--require-token");
473 expect(hub.spawnedEnvironments[0]?.EXPO_DEVICE_HUB_STATE_DIR).toBe(
474 path.join(baseDir, "userdata", "device", "hub"),
475 );
476 expect((yield* host.current)?.hub.token).toBe("hub-token");
477 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
478 );
479​
480 it.effect("keeps releasing agent sessions while a dead hub fails to restart and after", () =>
481 Effect.gen(function* () {
482 const fs = yield* FileSystem.FileSystem;
483 const { host, hub } = yield* agentFixture((stateDir) =>
484 fs
485 .writeFileString(
486 `${stateDir}/daemon.json`,
487 JSON.stringify({ httpPort: 12345, token: "test-token" }),
488 )
489 .pipe(Effect.orDie, Effect.as(processOutput(0))),
490 );
491 yield* host.ensureAgentReady(() => Effect.void);
492 hub.running = false;
493 hub.spawnFails = true;
494 expect((yield* host.ensureReady(() => Effect.void).pipe(Effect.result))._tag).toBe("Failure");
495 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
496 hub.spawnFails = false;
497 yield* host.ensureReady(() => Effect.void);
498 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
499 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
500 );
501​
502 it.effect("stops a previous server's daemon with the agent-device version it recorded", () =>
503 Effect.gen(function* () {
504 const path = yield* Path.Path;
505 const { host, fs, baseDir, runs } = yield* agentFixture(
506 () => Effect.die("A session that never readies agent tools must not start the daemon"),
507 processOutput(0),
508 { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" },
509 );
510 const olderInstall = path.join(baseDir, "tools", "agent-device", "0.0.1");
511 const olderEntry = path.join(
512 olderInstall,
513 "node_modules",
514 "agent-device",
515 "bin",
516 "agent-device.mjs",
517 );
518 yield* fs.makeDirectory(path.dirname(olderEntry), { recursive: true });
519 yield* fs.writeFileString(olderEntry, "");
520 yield* fs.writeFileString(path.join(olderInstall, ".install-complete"), "0.0.1");
521 yield* host.stop;
522 expect(runs.find((run) => run.args.includes("daemon"))?.args[0]).toBe(olderEntry);
523 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
524 );
525​
526 // regression: #33552 a daemon left by a previous server survived every later graceful quit
527 it.effect("stops a previous server's daemon with the current pin when its version is gone", () =>
528 Effect.gen(function* () {
529 const path = yield* Path.Path;
530 const { host, baseDir, stateDir, runs } = yield* agentFixture(
531 () => Effect.die("A session that never readies agent tools must not start the daemon"),
532 processOutput(0),
533 { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" },
534 );
535 yield* host.stop;
536 expect(runs.find((run) => run.args.includes("daemon"))?.args).toEqual([
537 path.join(
538 baseDir,
539 "tools",
540 "agent-device",
541 AGENT_DEVICE_VERSION,
542 "node_modules",
543 "agent-device",
544 "bin",
545 "agent-device.mjs",
546 ),
547 "daemon",
548 "stop",
549 "--state-dir",
550 stateDir,
551 ]);
552 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
553 );
554​
555 it.effect("drops a dead daemon's record without running agent-device when the host stops", () =>
556 Effect.gen(function* () {
557 // Above the Linux and macOS PID limits, so never a live process.
558 const deadPid = 4_194_305;
559 const path = yield* Path.Path;
560 const { host, fs, stateDir, runs } = yield* agentFixture(
561 () => Effect.die("A session that never readies agent tools must not start the daemon"),
562 processOutput(0),
563 { httpPort: 12345, token: "previous-token", pid: deadPid, version: AGENT_DEVICE_VERSION },
564 );
565 yield* host.stop;
566 expect(runs.filter((run) => run.args.includes("daemon"))).toEqual([]);
567 expect(yield* fs.exists(path.join(stateDir, "daemon.json"))).toBe(false);
568 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
569 );
570​
571 it.effect("stops the agent daemon while the hub is still shutting down", () =>
572 Effect.gen(function* () {
573 const fs = yield* FileSystem.FileSystem;
574 const { host, hub, stateDir, daemonStopRequested } = yield* agentFixture((stateDir) =>
575 fs
576 .writeFileString(
577 `${stateDir}/daemon.json`,
578 JSON.stringify({ httpPort: 12345, token: "test-token" }),
579 )
580 .pipe(Effect.orDie, Effect.as(processOutput(0))),
581 );
582 yield* host.ensureAgentReady(() => Effect.void);
583 const hubExited = yield* Deferred.make<void>();
584 hub.cleanup = Deferred.await(hubExited);
585 const stopping = yield* Effect.forkChild(host.stop);
586 expect((yield* Deferred.await(daemonStopRequested)).slice(1)).toEqual([
587 "daemon",
588 "stop",
589 "--state-dir",
590 stateDir,
591 ]);
592 yield* Deferred.succeed(hubExited, undefined);
593 yield* Fiber.join(stopping);
594 expect(yield* fs.exists(`${stateDir}/hub.json`)).toBe(false);
595 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
596 );
597});
598​
599const diagnose = (
600 files: ReadonlyArray<string>,
601 environment: NodeJS.ProcessEnv,
602 platform: NodeJS.Platform = "darwin",
603) =>
604 LocalDeviceHost.__testing.platformReason("android").pipe(
605 Effect.provideService(HostProcess.Environment, environment),
606 Effect.provideService(HostProcess.Platform, platform),
607 Effect.provideService(
608 FileSystem.FileSystem,
609 FileSystem.makeNoop({
610 exists: (file) => Effect.succeed(files.includes(file)),
611 }),
612 ),
613 Effect.provide(platform === "win32" ? NodePath.layerWin32 : NodePath.layerPosix),
614 );
615​
616describe("Android SDK availability", () => {
617 it.effect("uses the standard Windows SDK without probing PATH", () =>
618 Effect.gen(function* () {
619 const root = "C:\\Users\\test\\AppData\\Local\\Android\\Sdk";
620 const probes: string[] = [];
621 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
622 Effect.provideService(HostProcess.Environment, {
623 USERPROFILE: "C:\\Users\\test",
624 LOCALAPPDATA: "C:\\Users\\test\\AppData\\Local",
625 PATH: "\\\\slow-share\\tools;C:\\other-tools",
626 }),
627 Effect.provideService(HostProcess.Platform, "win32"),
628 Effect.provideService(
629 FileSystem.FileSystem,
630 FileSystem.makeNoop({
631 exists: (file) =>
632 Effect.sync(() => {
633 probes.push(file);
634 return file === `${root}\\platform-tools\\adb.exe`;
635 }),
636 realPath: () => Effect.die("Standard SDK must not resolve PATH executables"),
637 }),
638 ),
639 Effect.provide(NodePath.layerWin32),
640 );
641 expect(sdk).toMatchObject({ root, adb: true });
642 expect(probes.filter((file) => !file.startsWith("C:\\Users\\test\\"))).toEqual([]);
643 }),
644 );
645​
646 it.effect("falls back to adb on the Windows Path without resolving missing entries", () =>
647 Effect.gen(function* () {
648 const root = "D:\\Android\\Sdk";
649 const resolved: string[] = [];
650 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
651 Effect.provideService(HostProcess.Environment, {
652 USERPROFILE: "C:\\Users\\test",
653 Path: "C:\\missing;C:\\shims",
654 }),
655 Effect.provideService(HostProcess.Platform, "win32"),
656 Effect.provideService(
657 FileSystem.FileSystem,
658 FileSystem.makeNoop({
659 exists: (file) =>
660 Effect.succeed(
661 file === "C:\\shims\\adb.exe" || file === `${root}\\platform-tools\\adb.exe`,
662 ),
663 realPath: (file) =>
664 Effect.sync(() => {
665 resolved.push(file);
666 return `${root}\\platform-tools\\adb.exe`;
667 }),
668 }),
669 ),
670 Effect.provide(NodePath.layerWin32),
671 );
672 expect(sdk).toMatchObject({ root, adb: true });
673 expect(resolved).toEqual(["C:\\shims\\adb.exe"]);
674 }),
675 );
676​
677 // regression: #30629 connected phones were hidden on hosts without emulator tooling
678 it.effect("supports connected Android devices with only Platform-Tools installed", () =>
679 Effect.gen(function* () {
680 expect(yield* diagnose(["/sdk/platform-tools/adb"], { ANDROID_HOME: "/sdk" })).toBeNull();
681 expect(yield* diagnose(["/sdk/emulator/emulator"], { ANDROID_HOME: "/sdk" })).toContain(
682 "Platform-Tools are missing from /sdk",
683 );
684 }),
685 );
686​
687 // regression: #38268 an ANDROID_HOME that is not an SDK must not stop detection
688 it.effect("falls back past an ANDROID_HOME that is not an SDK", () =>
689 Effect.gen(function* () {
690 const complete = [
691 "/parent/sdk/platform-tools/adb",
692 "/parent/sdk/emulator/emulator",
693 "/parent/sdk/cmdline-tools/latest/bin/avdmanager",
694 ];
695 for (const environment of [
696 { ANDROID_HOME: "/parent", ANDROID_SDK_ROOT: "/parent/sdk" },
697 { ANDROID_HOME: "/parent", PATH: "/parent/sdk/platform-tools" },
698 ]) {
699 expect(yield* diagnose(complete, environment)).toBeNull();
700 }
701 }),
702 );
703​
704 it.effect("discovers the standard macOS SDK without ANDROID_HOME", () =>
705 Effect.gen(function* () {
706 const root = "/test/home/Library/Android/sdk";
707 const reason = yield* diagnose(
708 [
709 `${root}/platform-tools/adb`,
710 `${root}/emulator/emulator`,
711 `${root}/cmdline-tools/latest/bin/avdmanager`,
712 ],
713 { HOME: "/test/home" },
714 );
715 expect(reason).toBeNull();
716 }),
717 );
718});
719​
720it.effect(
721 "recovers an owned Linux runtime directory without overriding explicit environments",
722 () =>
723 Effect.gen(function* () {
724 const fs = yield* FileSystem.FileSystem;
725 const directory = yield* fs.makeTempDirectoryScoped();
726 const stat = yield* fs.stat(directory);
727 for (const [platform, uid, runtimeDir, type, owner, expected] of [
728 ["linux", 1000, undefined, "Directory", 1000, "/run/user/1000"],
729 ["linux", 1000, "/custom/runtime", "Directory", 1000, "/custom/runtime"],
730 ["linux", 1000, "", "Directory", 1000, ""],
731 ["linux", 1000, undefined, "Directory", 1001, undefined],
732 ["linux", 1000, undefined, "File", 1000, undefined],
733 ["linux", undefined, undefined, "Directory", 1000, undefined],
734 ["darwin", 1000, undefined, "Directory", 1000, undefined],
735 ["win32", 1000, undefined, "Directory", 1000, undefined],
736 ] as const) {
737 const environment = { PATH: "/usr/bin", XDG_RUNTIME_DIR: runtimeDir };
738 const result = yield* LocalDeviceHost.__testing.hubEnvironment(environment).pipe(
739 Effect.provideService(HostProcess.Platform, platform),
740 Effect.provideService(HostProcess.UserId, uid),
741 Effect.provideService(
742 FileSystem.FileSystem,
743 FileSystem.makeNoop({
744 stat: (path) => {
745 expect(path).toBe("/run/user/1000");
746 return Effect.succeed({ ...stat, type, uid: Option.some(owner) });
747 },
748 }),
749 ),
750 );
751 expect(result.XDG_RUNTIME_DIR).toBe(expected);
752 expect(result.PATH).toBe("/usr/bin");
753 expect(result.FORCE_COLOR).toBe("0");
754 expect(result.NO_COLOR).toBe("1");
755 expect(environment.XDG_RUNTIME_DIR).toBe(runtimeDir);
756 }
757 const missing = yield* LocalDeviceHost.__testing
758 .hubEnvironment({})
759 .pipe(
760 Effect.provideService(HostProcess.Platform, "linux"),
761 Effect.provideService(HostProcess.UserId, 1000),
762 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
763 );
764 expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
765 }).pipe(
766 Effect.scoped,
767 Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
768 ),
769);
770​
771it.effect.each([
772 {
773 name: "old SDK",
774 front: "emulated webcam<N> none",
775 back: "emulated virtualscene none",
776 code: 0,
777 extra: undefined,
778 expected: "-camera-front emulated -camera-back emulated",
779 },
780 {
781 name: "imagefile-capable SDK",
782 front: "emulated imagefile:<path> none",
783 back: "emulated imagefile:<path> none",
784 code: 0,
785 extra: undefined,
786 expected: undefined,
787 },
788 {
789 name: "user overrides",
790 front: "emulated none",
791 back: "emulated none",
792 code: 0,
793 extra: "-memory 4096 -camera-front none",
794 expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
795 },
796 {
797 name: "different camera capabilities",
798 front: "emulated none",
799 back: "emulated imagefile:<path> none",
800 code: 0,
801 extra: undefined,
802 expected: "-camera-front emulated",
803 },
804 {
805 name: "failed help probe",
806 front: "emulated none",
807 back: "emulated none",
808 code: 1,
809 extra: undefined,
810 expected: undefined,
811 },
812])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
813 Effect.gen(function* () {
814 const result = yield* LocalDeviceHost.__testing
815 .hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
816 .pipe(
817 Effect.provideService(HostProcess.Platform, "darwin"),
818 Effect.provideService(HostProcess.UserId, 1000),
819 Effect.provideService(ProcessRunner.ProcessRunner, {
820 run: (input) => {
821 expect(input.command).toBe("/sdk/emulator/emulator");
822 expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
823 return Effect.succeed(
824 processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
825 );
826 },
827 }),
828 Effect.provide(NodeServices.layer),
829 );
830 expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
831 }),
832);
833​
834it.effect("keeps local Android and iOS available without ffmpeg", () =>
835 Effect.gen(function* () {
836 const fs = yield* FileSystem.FileSystem;
837 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-ffmpeg-" });
838 yield* fs.makeDirectory(`${baseDir}/bin`);
839 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 0\n");
840 yield* fs.chmod(`${baseDir}/bin/xcrun`, 0o755);
841 for (const [directory, tool] of [
842 ["platform-tools", "adb"],
843 ["emulator", "emulator"],
844 ["cmdline-tools/latest/bin", "avdmanager"],
845 ]) {
846 yield* fs.makeDirectory(`${baseDir}/sdk/${directory}`, { recursive: true });
847 yield* fs.writeFileString(`${baseDir}/sdk/${directory}/${tool}`, "");
848 }
849 const onTestHost = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
850 effect.pipe(
851 Effect.provideService(HostProcess.Environment, {
852 HOME: baseDir,
853 PATH: `${baseDir}/bin`,
854 ANDROID_HOME: `${baseDir}/sdk`,
855 }),
856 Effect.provideService(HostProcess.Platform, "darwin"),
857 );
858 const host = yield* LocalDeviceHost.make().pipe(
859 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
860 onTestHost,
861 Effect.provideService(
862 HttpClient.HttpClient,
863 HttpClient.make(() => Effect.die(new Error("Readiness must not make network requests"))),
864 ),
865 Effect.provideService(ProcessRunner.ProcessRunner, {
866 run: () => Effect.die("Platform availability must not probe emulator video"),
867 }),
868 );
869 expect((yield* onTestHost(host.summary)).platforms).toEqual([
870 { platform: "ios", available: true },
871 { platform: "android", available: true },
872 ]);
873 expect(yield* onTestHost(host.platformAvailability("android"))).toEqual({
874 platform: "android",
875 available: true,
876 });
877 expect(yield* onTestHost(host.platformAvailability("ios"))).toEqual({
878 platform: "ios",
879 available: true,
880 });
881 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
882);
883​
884it.effect(
885 "constructs and inspects an unconfigured host without installing or starting helpers",
886 () =>
887 Effect.gen(function* () {
888 const fs = yield* FileSystem.FileSystem;
889 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-consent-" });
890 const host = yield* LocalDeviceHost.make().pipe(
891 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
892 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
893 Effect.provideService(HostProcess.Platform, "linux"),
894 Effect.provideService(
895 ChildProcessSpawner.ChildProcessSpawner,
896 ChildProcessSpawner.make(() =>
897 Effect.die(new Error("Host construction must not spawn processes")),
898 ),
899 ),
900 Effect.provideService(ProcessRunner.ProcessRunner, {
901 run: () => Effect.die(new Error("Host construction must not run commands")),
902 }),
903 Effect.provideService(
904 HttpClient.HttpClient,
905 HttpClient.make(() =>
906 Effect.die(new Error("Host construction must not make network requests")),
907 ),
908 ),
909 );
910 expect(yield* host.current).toBeNull();
911 const error = yield* host
912 .ensureReady(() => Effect.die("Must not install without Node"))
913 .pipe(Effect.flip, Effect.provideService(HostProcess.IsExecutable, true));
914 expect(error.message).toContain("Local device support requires Node.js");
915 expect(error.message).toContain("Install Node.js");
916 yield* host.stop;
917 expect(yield* fs.exists(`${baseDir}/tools`)).toBe(false);
918 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
919);