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

LocalDeviceHost.test.ts

767 lines29.8 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 = { running: true, spawnFails: false, cleanup: Effect.void };
52 const daemonStopRequested = yield* Deferred.make<ReadonlyArray<string>>();
53 const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata"));
54 const daemonHealthy = yield* Ref.make(true);
55 const runs: Array<ProcessRunner.ProcessRunInput> = [];
56 for (const [name, version, entry] of [
57 ["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"],
58 ["agent-device", AGENT_DEVICE_VERSION, "bin/agent-device.mjs"],
59 ]) {
60 const installDir = path.join(baseDir, "tools", name!, version!);
61 const entryPath = path.join(installDir, "node_modules", name!, entry!);
62 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
63 yield* fs.writeFileString(entryPath, "");
64 yield* fs.writeFileString(path.join(installDir, ".install-complete"), version!);
65 }
66 if (previousDaemon) {
67 yield* fs.makeDirectory(stateDir, { recursive: true });
68 yield* fs.writeFileString(path.join(stateDir, "daemon.json"), JSON.stringify(previousDaemon));
69 }
70 const host = yield* LocalDeviceHost.make().pipe(
71 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
72 Effect.provideService(HostProcess.Environment, environment ?? { HOME: baseDir, PATH: "" }),
73 Effect.provideService(HostProcess.IsExecutable, false),
74 Effect.provideService(HostProcess.Platform, "darwin"),
75 Effect.provideService(
76 ChildProcessSpawner.ChildProcessSpawner,
77 ChildProcessSpawner.make(() =>
78 hub.spawnFails
79 ? Effect.fail(
80 PlatformError.systemError({
81 _tag: "NotFound",
82 module: "ChildProcess",
83 method: "spawn",
84 description: "Hub entry missing",
85 }),
86 )
87 : Effect.addFinalizer(() => hub.cleanup).pipe(
88 Effect.as(
89 ChildProcessSpawner.makeHandle({
90 pid: ChildProcessSpawner.ProcessId(123),
91 stdout: Stream.empty,
92 stderr: Stream.empty,
93 all: Stream.empty,
94 exitCode: Effect.never,
95 isRunning: Effect.sync(() => hub.running),
96 kill: () => Effect.void,
97 stdin: Sink.drain,
98 getInputFd: () => Sink.drain,
99 getOutputFd: () => Stream.empty,
100 unref: Effect.succeed(Effect.void),
101 }),
102 ),
103 ),
104 ),
105 ),
106 Effect.provideService(ProcessRunner.ProcessRunner, {
107 run: (input) => {
108 runs.push(input);
109 return input.args.includes("devices")
110 ? startup(stateDir)
111 : input.args.includes("daemon")
112 ? Deferred.succeed(daemonStopRequested, input.args).pipe(Effect.as(processOutput(0)))
113 : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0));
114 },
115 }),
116 Effect.provideService(
117 HttpClient.HttpClient,
118 HttpClient.make((request) =>
119 Ref.get(daemonHealthy).pipe(
120 Effect.map((healthy) =>
121 HttpClientResponse.fromWeb(
122 request,
123 new Response("ok", {
124 status: request.url.endsWith("/health") && !healthy ? 503 : 200,
125 }),
126 ),
127 ),
128 ),
129 ),
130 ),
131 );
132 yield* host.ensureReady(() => Effect.void);
133 return { host, fs, baseDir, stateDir, hub, daemonHealthy, daemonStopRequested, runs };
134});
135​
136describe("AgentDevice startup", () => {
137 it.effect("restarts a cached daemon that no longer answers its health check", () =>
138 Effect.gen(function* () {
139 const fs = yield* FileSystem.FileSystem;
140 let attempts = 0;
141 const { host, daemonHealthy } = yield* agentFixture((stateDir) =>
142 Effect.gen(function* () {
143 attempts++;
144 yield* fs
145 .writeFileString(
146 `${stateDir}/daemon.json`,
147 JSON.stringify({ httpPort: 12345 + attempts, token: `token-${attempts}` }),
148 )
149 .pipe(Effect.orDie);
150 return processOutput(0);
151 }),
152 );
153 const first = yield* host.ensureAgentReady(() => Effect.void);
154 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
155 first.agentDevice,
156 );
157 expect(attempts).toBe(1);
158​
159 yield* Ref.set(daemonHealthy, false);
160 const restarted = yield* host.ensureAgentReady(() => Effect.void);
161 expect(attempts).toBe(2);
162 expect(restarted.agentDevice).toMatchObject({
163 baseUrl: "http://127.0.0.1:12347",
164 token: "token-2",
165 });
166 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
167 );
168​
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​
219 it.effect("reports an incompatible lock immediately and retains it for manual repair", () =>
220 Effect.gen(function* () {
221 const result = processOutput(
222 1,
223 JSON.stringify({
224 success: false,
225 error: {
226 message: "private command output",
227 details: {
228 reason: "daemon_registration_unproven",
229 inspection: { state: "unproven", reason: "non-directory" },
230 },
231 },
232 }),
233 );
234 const { host, fs, stateDir } = yield* agentFixture(() => Effect.succeed(result));
235 const lock = `${stateDir}/daemon.lock`;
236 const legacyOwner = JSON.stringify({ pid: 85669, processStartTime: "old start time" });
237 yield* fs.writeFileString(lock, legacyOwner);
238 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
239 expect(error).toMatchObject({
240 _tag: "AgentDeviceStartError",
241 reason: "daemon_lock_not_directory",
242 exitCode: 1,
243 cause: result,
244 });
245 expect(error.message).toContain("Daemon registration ownership could not be verified");
246 expect(error.message).toContain("daemon.lock is not a directory");
247 expect(error.message).toContain(stateDir);
248 expect(error.message).toContain("original CLI");
249 expect(error.message).not.toContain("private command output");
250 expect(yield* fs.readFileString(lock)).toBe(legacyOwner);
251 expect(yield* host.current).not.toBeNull();
252 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
253 );
254​
255 it.effect("reports unknown nonzero exits without exposing arbitrary command output", () =>
256 Effect.gen(function* () {
257 const result = processOutput(2, "invalid JSON", "private credentials");
258 const { host, stateDir } = yield* agentFixture(() => Effect.succeed(result));
259 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
260 expect(error).toMatchObject({
261 _tag: "AgentDeviceStartError",
262 reason: "command_failed",
263 exitCode: 2,
264 cause: result,
265 });
266 expect(error.message).toContain("exit code 2");
267 expect(error.message).toContain(stateDir);
268 expect(error.message).not.toContain("private credentials");
269 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
270 );
271​
272 it.effect("preserves process execution failures instead of waiting for a daemon file", () =>
273 Effect.gen(function* () {
274 const cause = new ProcessRunner.ProcessSpawnError({
275 command: "/missing/node",
276 argumentCount: 3,
277 cause: new Error("missing executable"),
278 });
279 const { host } = yield* agentFixture(() => Effect.fail(cause));
280 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
281 expect(error).toMatchObject({
282 _tag: "DeviceHostError",
283 step: "starting agent tools",
284 cause,
285 });
286 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
287 );
288​
289 it.effect("uses a registered daemon when reading startup command output fails", () =>
290 Effect.gen(function* () {
291 const fs = yield* FileSystem.FileSystem;
292 const cause = new ProcessRunner.ProcessReadError({
293 command: process.execPath,
294 argumentCount: 3,
295 stream: "stdout",
296 cause: new Error("output read failed after registration"),
297 });
298 let attempts = 0;
299 const { host } = yield* agentFixture((stateDir) =>
300 Effect.gen(function* () {
301 attempts++;
302 yield* fs
303 .writeFileString(
304 `${stateDir}/daemon.json`,
305 JSON.stringify({ httpPort: 12345, token: "test-token" }),
306 )
307 .pipe(Effect.orDie);
308 return yield* cause;
309 }),
310 );
311 const ready = yield* host.ensureAgentReady(() => Effect.void);
312 expect(ready.agentDevice).toMatchObject({
313 baseUrl: "http://127.0.0.1:12345",
314 token: "test-token",
315 });
316 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
317 ready.agentDevice,
318 );
319 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
320 expect(attempts).toBe(1);
321 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
322 );
323​
324 it.effect("keeps releasing agent sessions while a dead hub fails to restart and after", () =>
325 Effect.gen(function* () {
326 const fs = yield* FileSystem.FileSystem;
327 const { host, hub } = yield* agentFixture((stateDir) =>
328 fs
329 .writeFileString(
330 `${stateDir}/daemon.json`,
331 JSON.stringify({ httpPort: 12345, token: "test-token" }),
332 )
333 .pipe(Effect.orDie, Effect.as(processOutput(0))),
334 );
335 yield* host.ensureAgentReady(() => Effect.void);
336 hub.running = false;
337 hub.spawnFails = true;
338 expect((yield* host.ensureReady(() => Effect.void).pipe(Effect.result))._tag).toBe("Failure");
339 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
340 hub.spawnFails = false;
341 yield* host.ensureReady(() => Effect.void);
342 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
343 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
344 );
345​
346 it.effect("stops a previous server's daemon with the agent-device version it recorded", () =>
347 Effect.gen(function* () {
348 const path = yield* Path.Path;
349 const { host, fs, baseDir, runs } = yield* agentFixture(
350 () => Effect.die("A session that never readies agent tools must not start the daemon"),
351 processOutput(0),
352 { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" },
353 );
354 const olderInstall = path.join(baseDir, "tools", "agent-device", "0.0.1");
355 const olderEntry = path.join(
356 olderInstall,
357 "node_modules",
358 "agent-device",
359 "bin",
360 "agent-device.mjs",
361 );
362 yield* fs.makeDirectory(path.dirname(olderEntry), { recursive: true });
363 yield* fs.writeFileString(olderEntry, "");
364 yield* fs.writeFileString(path.join(olderInstall, ".install-complete"), "0.0.1");
365 yield* host.stop;
366 expect(runs.find((run) => run.args.includes("daemon"))?.args[0]).toBe(olderEntry);
367 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
368 );
369​
370 // regression: #33552 a daemon left by a previous server survived every later graceful quit
371 it.effect("stops a previous server's daemon with the current pin when its version is gone", () =>
372 Effect.gen(function* () {
373 const path = yield* Path.Path;
374 const { host, baseDir, stateDir, runs } = yield* agentFixture(
375 () => Effect.die("A session that never readies agent tools must not start the daemon"),
376 processOutput(0),
377 { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" },
378 );
379 yield* host.stop;
380 expect(runs.find((run) => run.args.includes("daemon"))?.args).toEqual([
381 path.join(
382 baseDir,
383 "tools",
384 "agent-device",
385 AGENT_DEVICE_VERSION,
386 "node_modules",
387 "agent-device",
388 "bin",
389 "agent-device.mjs",
390 ),
391 "daemon",
392 "stop",
393 "--state-dir",
394 stateDir,
395 ]);
396 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
397 );
398​
399 it.effect("drops a dead daemon's record without running agent-device when the host stops", () =>
400 Effect.gen(function* () {
401 // Above the Linux and macOS PID limits, so never a live process.
402 const deadPid = 4_194_305;
403 const path = yield* Path.Path;
404 const { host, fs, stateDir, runs } = yield* agentFixture(
405 () => Effect.die("A session that never readies agent tools must not start the daemon"),
406 processOutput(0),
407 { httpPort: 12345, token: "previous-token", pid: deadPid, version: AGENT_DEVICE_VERSION },
408 );
409 yield* host.stop;
410 expect(runs.filter((run) => run.args.includes("daemon"))).toEqual([]);
411 expect(yield* fs.exists(path.join(stateDir, "daemon.json"))).toBe(false);
412 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
413 );
414​
415 it.effect("stops the agent daemon while the hub is still shutting down", () =>
416 Effect.gen(function* () {
417 const fs = yield* FileSystem.FileSystem;
418 const { host, hub, stateDir, daemonStopRequested } = yield* agentFixture((stateDir) =>
419 fs
420 .writeFileString(
421 `${stateDir}/daemon.json`,
422 JSON.stringify({ httpPort: 12345, token: "test-token" }),
423 )
424 .pipe(Effect.orDie, Effect.as(processOutput(0))),
425 );
426 yield* host.ensureAgentReady(() => Effect.void);
427 const hubExited = yield* Deferred.make<void>();
428 hub.cleanup = Deferred.await(hubExited);
429 const stopping = yield* Effect.forkChild(host.stop);
430 expect((yield* Deferred.await(daemonStopRequested)).slice(1)).toEqual([
431 "daemon",
432 "stop",
433 "--state-dir",
434 stateDir,
435 ]);
436 yield* Deferred.succeed(hubExited, undefined);
437 yield* Fiber.join(stopping);
438 expect(yield* fs.exists(`${stateDir}/hub.json`)).toBe(false);
439 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
440 );
441});
442​
443const diagnose = (
444 files: ReadonlyArray<string>,
445 environment: NodeJS.ProcessEnv,
446 platform: NodeJS.Platform = "darwin",
447) =>
448 LocalDeviceHost.__testing.platformReason("android").pipe(
449 Effect.provideService(HostProcess.Environment, environment),
450 Effect.provideService(HostProcess.Platform, platform),
451 Effect.provideService(
452 FileSystem.FileSystem,
453 FileSystem.makeNoop({
454 exists: (file) => Effect.succeed(files.includes(file)),
455 }),
456 ),
457 Effect.provide(platform === "win32" ? NodePath.layerWin32 : NodePath.layerPosix),
458 );
459​
460describe("Android SDK availability", () => {
461 it.effect("uses the standard Windows SDK without probing PATH", () =>
462 Effect.gen(function* () {
463 const root = "C:\\Users\\test\\AppData\\Local\\Android\\Sdk";
464 const probes: string[] = [];
465 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
466 Effect.provideService(HostProcess.Environment, {
467 USERPROFILE: "C:\\Users\\test",
468 LOCALAPPDATA: "C:\\Users\\test\\AppData\\Local",
469 PATH: "\\\\slow-share\\tools;C:\\other-tools",
470 }),
471 Effect.provideService(HostProcess.Platform, "win32"),
472 Effect.provideService(
473 FileSystem.FileSystem,
474 FileSystem.makeNoop({
475 exists: (file) =>
476 Effect.sync(() => {
477 probes.push(file);
478 return file === `${root}\\platform-tools\\adb.exe`;
479 }),
480 realPath: () => Effect.die("Standard SDK must not resolve PATH executables"),
481 }),
482 ),
483 Effect.provide(NodePath.layerWin32),
484 );
485 expect(sdk).toMatchObject({ root, adb: true });
486 expect(probes.filter((file) => !file.startsWith("C:\\Users\\test\\"))).toEqual([]);
487 }),
488 );
489​
490 it.effect("falls back to adb on the Windows Path without resolving missing entries", () =>
491 Effect.gen(function* () {
492 const root = "D:\\Android\\Sdk";
493 const resolved: string[] = [];
494 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
495 Effect.provideService(HostProcess.Environment, {
496 USERPROFILE: "C:\\Users\\test",
497 Path: "C:\\missing;C:\\shims",
498 }),
499 Effect.provideService(HostProcess.Platform, "win32"),
500 Effect.provideService(
501 FileSystem.FileSystem,
502 FileSystem.makeNoop({
503 exists: (file) =>
504 Effect.succeed(
505 file === "C:\\shims\\adb.exe" || file === `${root}\\platform-tools\\adb.exe`,
506 ),
507 realPath: (file) =>
508 Effect.sync(() => {
509 resolved.push(file);
510 return `${root}\\platform-tools\\adb.exe`;
511 }),
512 }),
513 ),
514 Effect.provide(NodePath.layerWin32),
515 );
516 expect(sdk).toMatchObject({ root, adb: true });
517 expect(resolved).toEqual(["C:\\shims\\adb.exe"]);
518 }),
519 );
520​
521 // regression: #12017 detect unsupported legacy Android command-line tools
522 it.effect("explains how to upgrade legacy command-line tools in the standard macOS SDK", () =>
523 Effect.gen(function* () {
524 const root = "/test/home/Library/Android/sdk";
525 const reason = yield* diagnose(
526 [`${root}/platform-tools/adb`, `${root}/emulator/emulator`, `${root}/tools/bin/avdmanager`],
527 { HOME: "/test/home" },
528 );
529 expect(reason).toContain("older, unsupported version");
530 expect(reason).toContain(root);
531 expect(reason).toContain(
532 "Install Android SDK Command-line Tools (latest) in Android Studio's SDK Manager under SDK Tools.",
533 );
534 }),
535 );
536​
537 it.effect("accepts the latest command-line tools when legacy tools are also installed", () =>
538 Effect.gen(function* () {
539 const reason = yield* diagnose(
540 [
541 "/sdk/platform-tools/adb",
542 "/sdk/emulator/emulator",
543 "/sdk/tools/bin/avdmanager",
544 "/sdk/cmdline-tools/latest/bin/avdmanager",
545 ],
546 { ANDROID_HOME: "/sdk" },
547 );
548 expect(reason).toBeNull();
549 }),
550 );
551​
552 it.effect("discovers the standard macOS SDK without ANDROID_HOME", () =>
553 Effect.gen(function* () {
554 const root = "/test/home/Library/Android/sdk";
555 const reason = yield* diagnose(
556 [
557 `${root}/platform-tools/adb`,
558 `${root}/emulator/emulator`,
559 `${root}/cmdline-tools/latest/bin/avdmanager`,
560 ],
561 { HOME: "/test/home" },
562 );
563 expect(reason).toBeNull();
564 }),
565 );
566});
567​
568it.effect(
569 "recovers an owned Linux runtime directory without overriding explicit environments",
570 () =>
571 Effect.gen(function* () {
572 const fs = yield* FileSystem.FileSystem;
573 const directory = yield* fs.makeTempDirectoryScoped();
574 const stat = yield* fs.stat(directory);
575 for (const [platform, uid, runtimeDir, type, owner, expected] of [
576 ["linux", 1000, undefined, "Directory", 1000, "/run/user/1000"],
577 ["linux", 1000, "/custom/runtime", "Directory", 1000, "/custom/runtime"],
578 ["linux", 1000, "", "Directory", 1000, ""],
579 ["linux", 1000, undefined, "Directory", 1001, undefined],
580 ["linux", 1000, undefined, "File", 1000, undefined],
581 ["linux", undefined, undefined, "Directory", 1000, undefined],
582 ["darwin", 1000, undefined, "Directory", 1000, undefined],
583 ["win32", 1000, undefined, "Directory", 1000, undefined],
584 ] as const) {
585 const environment = { PATH: "/usr/bin", XDG_RUNTIME_DIR: runtimeDir };
586 const result = yield* LocalDeviceHost.__testing.hubEnvironment(environment).pipe(
587 Effect.provideService(HostProcess.Platform, platform),
588 Effect.provideService(HostProcess.UserId, uid),
589 Effect.provideService(
590 FileSystem.FileSystem,
591 FileSystem.makeNoop({
592 stat: (path) => {
593 expect(path).toBe("/run/user/1000");
594 return Effect.succeed({ ...stat, type, uid: Option.some(owner) });
595 },
596 }),
597 ),
598 );
599 expect(result.XDG_RUNTIME_DIR).toBe(expected);
600 expect(result.PATH).toBe("/usr/bin");
601 expect(result.FORCE_COLOR).toBe("0");
602 expect(result.NO_COLOR).toBe("1");
603 expect(environment.XDG_RUNTIME_DIR).toBe(runtimeDir);
604 }
605 const missing = yield* LocalDeviceHost.__testing
606 .hubEnvironment({})
607 .pipe(
608 Effect.provideService(HostProcess.Platform, "linux"),
609 Effect.provideService(HostProcess.UserId, 1000),
610 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
611 );
612 expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
613 }).pipe(
614 Effect.scoped,
615 Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
616 ),
617);
618​
619it.effect.each([
620 {
621 name: "old SDK",
622 front: "emulated webcam<N> none",
623 back: "emulated virtualscene none",
624 code: 0,
625 extra: undefined,
626 expected: "-camera-front emulated -camera-back emulated",
627 },
628 {
629 name: "imagefile-capable SDK",
630 front: "emulated imagefile:<path> none",
631 back: "emulated imagefile:<path> none",
632 code: 0,
633 extra: undefined,
634 expected: undefined,
635 },
636 {
637 name: "user overrides",
638 front: "emulated none",
639 back: "emulated none",
640 code: 0,
641 extra: "-memory 4096 -camera-front none",
642 expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
643 },
644 {
645 name: "different camera capabilities",
646 front: "emulated none",
647 back: "emulated imagefile:<path> none",
648 code: 0,
649 extra: undefined,
650 expected: "-camera-front emulated",
651 },
652 {
653 name: "failed help probe",
654 front: "emulated none",
655 back: "emulated none",
656 code: 1,
657 extra: undefined,
658 expected: undefined,
659 },
660])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
661 Effect.gen(function* () {
662 const result = yield* LocalDeviceHost.__testing
663 .hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
664 .pipe(
665 Effect.provideService(HostProcess.Platform, "darwin"),
666 Effect.provideService(HostProcess.UserId, 1000),
667 Effect.provideService(ProcessRunner.ProcessRunner, {
668 run: (input) => {
669 expect(input.command).toBe("/sdk/emulator/emulator");
670 expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
671 return Effect.succeed(
672 processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
673 );
674 },
675 }),
676 Effect.provide(NodeServices.layer),
677 );
678 expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
679 }),
680);
681​
682it.effect("keeps local Android and iOS available without ffmpeg", () =>
683 Effect.gen(function* () {
684 const fs = yield* FileSystem.FileSystem;
685 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-ffmpeg-" });
686 yield* fs.makeDirectory(`${baseDir}/bin`);
687 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 0\n");
688 yield* fs.chmod(`${baseDir}/bin/xcrun`, 0o755);
689 for (const [directory, tool] of [
690 ["platform-tools", "adb"],
691 ["emulator", "emulator"],
692 ["cmdline-tools/latest/bin", "avdmanager"],
693 ]) {
694 yield* fs.makeDirectory(`${baseDir}/sdk/${directory}`, { recursive: true });
695 yield* fs.writeFileString(`${baseDir}/sdk/${directory}/${tool}`, "");
696 }
697 const onTestHost = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
698 effect.pipe(
699 Effect.provideService(HostProcess.Environment, {
700 HOME: baseDir,
701 PATH: `${baseDir}/bin`,
702 ANDROID_HOME: `${baseDir}/sdk`,
703 }),
704 Effect.provideService(HostProcess.Platform, "darwin"),
705 );
706 const host = yield* LocalDeviceHost.make().pipe(
707 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
708 onTestHost,
709 Effect.provideService(
710 HttpClient.HttpClient,
711 HttpClient.make(() => Effect.die(new Error("Readiness must not make network requests"))),
712 ),
713 Effect.provideService(ProcessRunner.ProcessRunner, {
714 run: () => Effect.die("Platform availability must not probe emulator video"),
715 }),
716 );
717 expect((yield* onTestHost(host.summary)).platforms).toEqual([
718 { platform: "ios", available: true },
719 { platform: "android", available: true },
720 ]);
721 expect(yield* onTestHost(host.platformAvailability("android"))).toEqual({
722 platform: "android",
723 available: true,
724 });
725 expect(yield* onTestHost(host.platformAvailability("ios"))).toEqual({
726 platform: "ios",
727 available: true,
728 });
729 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
730);
731​
732it.effect(
733 "constructs and inspects an unconfigured host without installing or starting helpers",
734 () =>
735 Effect.gen(function* () {
736 const fs = yield* FileSystem.FileSystem;
737 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-consent-" });
738 const host = yield* LocalDeviceHost.make().pipe(
739 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
740 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
741 Effect.provideService(HostProcess.Platform, "linux"),
742 Effect.provideService(
743 ChildProcessSpawner.ChildProcessSpawner,
744 ChildProcessSpawner.make(() =>
745 Effect.die(new Error("Host construction must not spawn processes")),
746 ),
747 ),
748 Effect.provideService(ProcessRunner.ProcessRunner, {
749 run: () => Effect.die(new Error("Host construction must not run commands")),
750 }),
751 Effect.provideService(
752 HttpClient.HttpClient,
753 HttpClient.make(() =>
754 Effect.die(new Error("Host construction must not make network requests")),
755 ),
756 ),
757 );
758 expect(yield* host.current).toBeNull();
759 const error = yield* host
760 .ensureReady(() => Effect.die("Must not install without Node"))
761 .pipe(Effect.flip, Effect.provideService(HostProcess.IsExecutable, true));
762 expect(error.message).toContain("Local device support requires Node.js");
763 expect(error.message).toContain("Install Node.js");
764 yield* host.stop;
765 expect(yield* fs.exists(`${baseDir}/tools`)).toBe(false);
766 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
767);