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) {
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(ProcessRunner.ProcessRunner, {
399 run: () => Effect.die("Android SDK availability must not run commands"),
400 }),
401 Effect.provideService(HostProcess.Environment, environment),
402 Effect.provideService(HostProcess.Platform, platform),
403 Effect.provideService(
404 FileSystem.FileSystem,
405 FileSystem.makeNoop({
406 exists: (file) => Effect.succeed(files.includes(file)),
407 }),
408 ),
409 Effect.provide(platform === "win32" ? NodePath.layerWin32 : NodePath.layerPosix),
410 );
411
412describe("Android SDK availability", () => {
413 it.effect("uses the standard Windows SDK without probing PATH", () =>
414 Effect.gen(function* () {
415 const root = "C:\\Users\\test\\AppData\\Local\\Android\\Sdk";
416 const probes: string[] = [];
417 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
418 Effect.provideService(HostProcess.Environment, {
419 USERPROFILE: "C:\\Users\\test",
420 LOCALAPPDATA: "C:\\Users\\test\\AppData\\Local",
421 PATH: "\\\\slow-share\\tools;C:\\other-tools",
422 }),
423 Effect.provideService(HostProcess.Platform, "win32"),
424 Effect.provideService(
425 FileSystem.FileSystem,
426 FileSystem.makeNoop({
427 exists: (file) =>
428 Effect.sync(() => {
429 probes.push(file);
430 return file === `${root}\\platform-tools\\adb.exe`;
431 }),
432 realPath: () => Effect.die("Standard SDK must not resolve PATH executables"),
433 }),
434 ),
435 Effect.provide(NodePath.layerWin32),
436 );
437 expect(sdk).toMatchObject({ root, adb: true });
438 expect(probes.filter((file) => !file.startsWith("C:\\Users\\test\\"))).toEqual([]);
439 }),
440 );
441
442 it.effect("falls back to adb on the Windows Path without resolving missing entries", () =>
443 Effect.gen(function* () {
444 const root = "D:\\Android\\Sdk";
445 const resolved: string[] = [];
446 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
447 Effect.provideService(HostProcess.Environment, {
448 USERPROFILE: "C:\\Users\\test",
449 Path: "C:\\missing;C:\\shims",
450 }),
451 Effect.provideService(HostProcess.Platform, "win32"),
452 Effect.provideService(
453 FileSystem.FileSystem,
454 FileSystem.makeNoop({
455 exists: (file) =>
456 Effect.succeed(
457 file === "C:\\shims\\adb.exe" || file === `${root}\\platform-tools\\adb.exe`,
458 ),
459 realPath: (file) =>
460 Effect.sync(() => {
461 resolved.push(file);
462 return `${root}\\platform-tools\\adb.exe`;
463 }),
464 }),
465 ),
466 Effect.provide(NodePath.layerWin32),
467 );
468 expect(sdk).toMatchObject({ root, adb: true });
469 expect(resolved).toEqual(["C:\\shims\\adb.exe"]);
470 }),
471 );
472
473 // regression: #12017 detect unsupported legacy Android command-line tools
474 it.effect("explains how to upgrade legacy command-line tools in the standard macOS SDK", () =>
475 Effect.gen(function* () {
476 const root = "/test/home/Library/Android/sdk";
477 const reason = yield* diagnose(
478 [`${root}/platform-tools/adb`, `${root}/emulator/emulator`, `${root}/tools/bin/avdmanager`],
479 { HOME: "/test/home" },
480 );
481 expect(reason).toContain("older, unsupported version");
482 expect(reason).toContain(root);
483 expect(reason).toContain(
484 "Install Android SDK Command-line Tools (latest) in Android Studio's SDK Manager under SDK Tools.",
485 );
486 }),
487 );
488
489 it.effect("accepts the latest command-line tools when legacy tools are also installed", () =>
490 Effect.gen(function* () {
491 const reason = yield* diagnose(
492 [
493 "/sdk/platform-tools/adb",
494 "/sdk/emulator/emulator",
495 "/sdk/tools/bin/avdmanager",
496 "/sdk/cmdline-tools/latest/bin/avdmanager",
497 ],
498 { ANDROID_HOME: "/sdk" },
499 );
500 expect(reason).toBeNull();
501 }),
502 );
503
504 it.effect("discovers the standard macOS SDK without ANDROID_HOME", () =>
505 Effect.gen(function* () {
506 const root = "/test/home/Library/Android/sdk";
507 const reason = yield* diagnose(
508 [
509 `${root}/platform-tools/adb`,
510 `${root}/emulator/emulator`,
511 `${root}/cmdline-tools/latest/bin/avdmanager`,
512 ],
513 { HOME: "/test/home" },
514 );
515 expect(reason).toBeNull();
516 }),
517 );
518});
519
520it.effect(
521 "recovers an owned Linux runtime directory without overriding explicit environments",
522 () =>
523 Effect.gen(function* () {
524 const fs = yield* FileSystem.FileSystem;
525 const directory = yield* fs.makeTempDirectoryScoped();
526 const stat = yield* fs.stat(directory);
527 for (const [platform, uid, runtimeDir, type, owner, expected] of [
528 ["linux", 1000, undefined, "Directory", 1000, "/run/user/1000"],
529 ["linux", 1000, "/custom/runtime", "Directory", 1000, "/custom/runtime"],
530 ["linux", 1000, "", "Directory", 1000, ""],
531 ["linux", 1000, undefined, "Directory", 1001, undefined],
532 ["linux", 1000, undefined, "File", 1000, undefined],
533 ["linux", undefined, undefined, "Directory", 1000, undefined],
534 ["darwin", 1000, undefined, "Directory", 1000, undefined],
535 ["win32", 1000, undefined, "Directory", 1000, undefined],
536 ] as const) {
537 const environment = { PATH: "/usr/bin", XDG_RUNTIME_DIR: runtimeDir };
538 const result = yield* LocalDeviceHost.__testing.hubEnvironment(environment).pipe(
539 Effect.provideService(HostProcess.Platform, platform),
540 Effect.provideService(HostProcess.UserId, uid),
541 Effect.provideService(
542 FileSystem.FileSystem,
543 FileSystem.makeNoop({
544 stat: (path) => {
545 expect(path).toBe("/run/user/1000");
546 return Effect.succeed({ ...stat, type, uid: Option.some(owner) });
547 },
548 }),
549 ),
550 );
551 expect(result.XDG_RUNTIME_DIR).toBe(expected);
552 expect(result.PATH).toBe("/usr/bin");
553 expect(result.FORCE_COLOR).toBe("0");
554 expect(result.NO_COLOR).toBe("1");
555 expect(environment.XDG_RUNTIME_DIR).toBe(runtimeDir);
556 }
557 const missing = yield* LocalDeviceHost.__testing
558 .hubEnvironment({})
559 .pipe(
560 Effect.provideService(HostProcess.Platform, "linux"),
561 Effect.provideService(HostProcess.UserId, 1000),
562 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
563 );
564 expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
565 }).pipe(
566 Effect.scoped,
567 Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
568 ),
569);
570
571it.effect.each([
572 {
573 name: "old SDK",
574 front: "emulated webcam<N> none",
575 back: "emulated virtualscene none",
576 code: 0,
577 extra: undefined,
578 expected: "-camera-front emulated -camera-back emulated",
579 },
580 {
581 name: "imagefile-capable SDK",
582 front: "emulated imagefile:<path> none",
583 back: "emulated imagefile:<path> none",
584 code: 0,
585 extra: undefined,
586 expected: undefined,
587 },
588 {
589 name: "user overrides",
590 front: "emulated none",
591 back: "emulated none",
592 code: 0,
593 extra: "-memory 4096 -camera-front none",
594 expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
595 },
596 {
597 name: "different camera capabilities",
598 front: "emulated none",
599 back: "emulated imagefile:<path> none",
600 code: 0,
601 extra: undefined,
602 expected: "-camera-front emulated",
603 },
604 {
605 name: "failed help probe",
606 front: "emulated none",
607 back: "emulated none",
608 code: 1,
609 extra: undefined,
610 expected: undefined,
611 },
612])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
613 Effect.gen(function* () {
614 const result = yield* LocalDeviceHost.__testing
615 .hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
616 .pipe(
617 Effect.provideService(HostProcess.Platform, "darwin"),
618 Effect.provideService(HostProcess.UserId, 1000),
619 Effect.provideService(ProcessRunner.ProcessRunner, {
620 run: (input) => {
621 expect(input.command).toBe("/sdk/emulator/emulator");
622 expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
623 return Effect.succeed(
624 processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
625 );
626 },
627 }),
628 Effect.provide(NodeServices.layer),
629 );
630 expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
631 }),
632);
633
634it.live("requires usable iOS tools while keeping Android available without ffmpeg", () =>
635 Effect.gen(function* () {
636 const fs = yield* FileSystem.FileSystem;
637 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-ffmpeg-" });
638 yield* fs.makeDirectory(`${baseDir}/bin`);
639 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 0\n");
640 yield* fs.chmod(`${baseDir}/bin/xcrun`, 0o755);
641 for (const [directory, tool] of [
642 ["platform-tools", "adb"],
643 ["emulator", "emulator"],
644 ["cmdline-tools/latest/bin", "avdmanager"],
645 ]) {
646 yield* fs.makeDirectory(`${baseDir}/sdk/${directory}`, { recursive: true });
647 yield* fs.writeFileString(`${baseDir}/sdk/${directory}/${tool}`, "");
648 }
649 const onTestHost = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
650 effect.pipe(
651 Effect.provideService(HostProcess.Environment, {
652 HOME: baseDir,
653 PATH: `${baseDir}/bin`,
654 ANDROID_HOME: `${baseDir}/sdk`,
655 }),
656 Effect.provideService(HostProcess.Platform, "darwin"),
657 );
658 const host = yield* LocalDeviceHost.make().pipe(
659 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
660 onTestHost,
661 Effect.provideService(
662 HttpClient.HttpClient,
663 HttpClient.make(() => Effect.die(new Error("Readiness must not make network requests"))),
664 ),
665 Effect.provide(ProcessRunner.layer),
666 );
667 expect((yield* onTestHost(host.summary)).platforms).toEqual([
668 { platform: "ios", available: true },
669 { platform: "android", available: true },
670 ]);
671 expect(yield* onTestHost(host.platformAvailability("android"))).toEqual({
672 platform: "android",
673 available: true,
674 });
675 expect(yield* onTestHost(host.platformAvailability("ios"))).toEqual({
676 platform: "ios",
677 available: true,
678 });
679 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 1\n");
680 expect((yield* onTestHost(host.summary)).platforms).toEqual([
681 {
682 platform: "ios",
683 available: false,
684 reason:
685 "iOS Simulator tools were not found. Install Xcode and select it with xcode-select.",
686 },
687 { platform: "android", available: true },
688 ]);
689 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 0\n");
690 expect(yield* onTestHost(host.platformAvailability("ios"))).toEqual({
691 platform: "ios",
692 available: true,
693 });
694 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
695);
696
697it.effect(
698 "constructs and inspects an unconfigured host without installing or starting helpers",
699 () =>
700 Effect.gen(function* () {
701 const fs = yield* FileSystem.FileSystem;
702 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-consent-" });
703 const host = yield* LocalDeviceHost.make().pipe(
704 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
705 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
706 Effect.provideService(HostProcess.Platform, "linux"),
707 Effect.provideService(
708 ChildProcessSpawner.ChildProcessSpawner,
709 ChildProcessSpawner.make(() =>
710 Effect.die(new Error("Host construction must not spawn processes")),
711 ),
712 ),
713 Effect.provideService(ProcessRunner.ProcessRunner, {
714 run: () => Effect.die(new Error("Host construction must not run commands")),
715 }),
716 Effect.provideService(
717 HttpClient.HttpClient,
718 HttpClient.make(() =>
719 Effect.die(new Error("Host construction must not make network requests")),
720 ),
721 ),
722 );
723 expect(yield* host.current).toBeNull();
724 const error = yield* host
725 .ensureReady(() => Effect.die("Must not install without Node"))
726 .pipe(Effect.flip, Effect.provideService(HostProcess.IsExecutable, true));
727 expect(error.message).toContain("Local device support requires Node.js");
728 expect(error.message).toContain("Install Node.js");
729 yield* host.stop;
730 expect(yield* fs.exists(`${baseDir}/tools`)).toBe(false);
731 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
732);