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

LocalDeviceHost.test.ts

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