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