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

LocalDeviceHost.test.ts

784 lines30.5 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 // regression: #38268 an ANDROID_HOME that is not an SDK must not stop detection
553 it.effect("falls back past an ANDROID_HOME that is not an SDK", () =>
554 Effect.gen(function* () {
555 const complete = [
556 "/parent/sdk/platform-tools/adb",
557 "/parent/sdk/emulator/emulator",
558 "/parent/sdk/cmdline-tools/latest/bin/avdmanager",
559 ];
560 for (const environment of [
561 { ANDROID_HOME: "/parent", ANDROID_SDK_ROOT: "/parent/sdk" },
562 { ANDROID_HOME: "/parent", PATH: "/parent/sdk/platform-tools" },
563 ]) {
564 expect(yield* diagnose(complete, environment)).toBeNull();
565 }
566 }),
567 );
568​
569 it.effect("discovers the standard macOS SDK without ANDROID_HOME", () =>
570 Effect.gen(function* () {
571 const root = "/test/home/Library/Android/sdk";
572 const reason = yield* diagnose(
573 [
574 `${root}/platform-tools/adb`,
575 `${root}/emulator/emulator`,
576 `${root}/cmdline-tools/latest/bin/avdmanager`,
577 ],
578 { HOME: "/test/home" },
579 );
580 expect(reason).toBeNull();
581 }),
582 );
583});
584​
585it.effect(
586 "recovers an owned Linux runtime directory without overriding explicit environments",
587 () =>
588 Effect.gen(function* () {
589 const fs = yield* FileSystem.FileSystem;
590 const directory = yield* fs.makeTempDirectoryScoped();
591 const stat = yield* fs.stat(directory);
592 for (const [platform, uid, runtimeDir, type, owner, expected] of [
593 ["linux", 1000, undefined, "Directory", 1000, "/run/user/1000"],
594 ["linux", 1000, "/custom/runtime", "Directory", 1000, "/custom/runtime"],
595 ["linux", 1000, "", "Directory", 1000, ""],
596 ["linux", 1000, undefined, "Directory", 1001, undefined],
597 ["linux", 1000, undefined, "File", 1000, undefined],
598 ["linux", undefined, undefined, "Directory", 1000, undefined],
599 ["darwin", 1000, undefined, "Directory", 1000, undefined],
600 ["win32", 1000, undefined, "Directory", 1000, undefined],
601 ] as const) {
602 const environment = { PATH: "/usr/bin", XDG_RUNTIME_DIR: runtimeDir };
603 const result = yield* LocalDeviceHost.__testing.hubEnvironment(environment).pipe(
604 Effect.provideService(HostProcess.Platform, platform),
605 Effect.provideService(HostProcess.UserId, uid),
606 Effect.provideService(
607 FileSystem.FileSystem,
608 FileSystem.makeNoop({
609 stat: (path) => {
610 expect(path).toBe("/run/user/1000");
611 return Effect.succeed({ ...stat, type, uid: Option.some(owner) });
612 },
613 }),
614 ),
615 );
616 expect(result.XDG_RUNTIME_DIR).toBe(expected);
617 expect(result.PATH).toBe("/usr/bin");
618 expect(result.FORCE_COLOR).toBe("0");
619 expect(result.NO_COLOR).toBe("1");
620 expect(environment.XDG_RUNTIME_DIR).toBe(runtimeDir);
621 }
622 const missing = yield* LocalDeviceHost.__testing
623 .hubEnvironment({})
624 .pipe(
625 Effect.provideService(HostProcess.Platform, "linux"),
626 Effect.provideService(HostProcess.UserId, 1000),
627 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
628 );
629 expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
630 }).pipe(
631 Effect.scoped,
632 Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
633 ),
634);
635​
636it.effect.each([
637 {
638 name: "old SDK",
639 front: "emulated webcam<N> none",
640 back: "emulated virtualscene none",
641 code: 0,
642 extra: undefined,
643 expected: "-camera-front emulated -camera-back emulated",
644 },
645 {
646 name: "imagefile-capable SDK",
647 front: "emulated imagefile:<path> none",
648 back: "emulated imagefile:<path> none",
649 code: 0,
650 extra: undefined,
651 expected: undefined,
652 },
653 {
654 name: "user overrides",
655 front: "emulated none",
656 back: "emulated none",
657 code: 0,
658 extra: "-memory 4096 -camera-front none",
659 expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
660 },
661 {
662 name: "different camera capabilities",
663 front: "emulated none",
664 back: "emulated imagefile:<path> none",
665 code: 0,
666 extra: undefined,
667 expected: "-camera-front emulated",
668 },
669 {
670 name: "failed help probe",
671 front: "emulated none",
672 back: "emulated none",
673 code: 1,
674 extra: undefined,
675 expected: undefined,
676 },
677])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
678 Effect.gen(function* () {
679 const result = yield* LocalDeviceHost.__testing
680 .hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
681 .pipe(
682 Effect.provideService(HostProcess.Platform, "darwin"),
683 Effect.provideService(HostProcess.UserId, 1000),
684 Effect.provideService(ProcessRunner.ProcessRunner, {
685 run: (input) => {
686 expect(input.command).toBe("/sdk/emulator/emulator");
687 expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
688 return Effect.succeed(
689 processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
690 );
691 },
692 }),
693 Effect.provide(NodeServices.layer),
694 );
695 expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
696 }),
697);
698​
699it.effect("keeps local Android and iOS available without ffmpeg", () =>
700 Effect.gen(function* () {
701 const fs = yield* FileSystem.FileSystem;
702 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-ffmpeg-" });
703 yield* fs.makeDirectory(`${baseDir}/bin`);
704 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 0\n");
705 yield* fs.chmod(`${baseDir}/bin/xcrun`, 0o755);
706 for (const [directory, tool] of [
707 ["platform-tools", "adb"],
708 ["emulator", "emulator"],
709 ["cmdline-tools/latest/bin", "avdmanager"],
710 ]) {
711 yield* fs.makeDirectory(`${baseDir}/sdk/${directory}`, { recursive: true });
712 yield* fs.writeFileString(`${baseDir}/sdk/${directory}/${tool}`, "");
713 }
714 const onTestHost = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
715 effect.pipe(
716 Effect.provideService(HostProcess.Environment, {
717 HOME: baseDir,
718 PATH: `${baseDir}/bin`,
719 ANDROID_HOME: `${baseDir}/sdk`,
720 }),
721 Effect.provideService(HostProcess.Platform, "darwin"),
722 );
723 const host = yield* LocalDeviceHost.make().pipe(
724 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
725 onTestHost,
726 Effect.provideService(
727 HttpClient.HttpClient,
728 HttpClient.make(() => Effect.die(new Error("Readiness must not make network requests"))),
729 ),
730 Effect.provideService(ProcessRunner.ProcessRunner, {
731 run: () => Effect.die("Platform availability must not probe emulator video"),
732 }),
733 );
734 expect((yield* onTestHost(host.summary)).platforms).toEqual([
735 { platform: "ios", available: true },
736 { platform: "android", available: true },
737 ]);
738 expect(yield* onTestHost(host.platformAvailability("android"))).toEqual({
739 platform: "android",
740 available: true,
741 });
742 expect(yield* onTestHost(host.platformAvailability("ios"))).toEqual({
743 platform: "ios",
744 available: true,
745 });
746 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
747);
748​
749it.effect(
750 "constructs and inspects an unconfigured host without installing or starting helpers",
751 () =>
752 Effect.gen(function* () {
753 const fs = yield* FileSystem.FileSystem;
754 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-consent-" });
755 const host = yield* LocalDeviceHost.make().pipe(
756 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
757 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
758 Effect.provideService(HostProcess.Platform, "linux"),
759 Effect.provideService(
760 ChildProcessSpawner.ChildProcessSpawner,
761 ChildProcessSpawner.make(() =>
762 Effect.die(new Error("Host construction must not spawn processes")),
763 ),
764 ),
765 Effect.provideService(ProcessRunner.ProcessRunner, {
766 run: () => Effect.die(new Error("Host construction must not run commands")),
767 }),
768 Effect.provideService(
769 HttpClient.HttpClient,
770 HttpClient.make(() =>
771 Effect.die(new Error("Host construction must not make network requests")),
772 ),
773 ),
774 );
775 expect(yield* host.current).toBeNull();
776 const error = yield* host
777 .ensureReady(() => Effect.die("Must not install without Node"))
778 .pipe(Effect.flip, Effect.provideService(HostProcess.IsExecutable, true));
779 expect(error.message).toContain("Local device support requires Node.js");
780 expect(error.message).toContain("Install Node.js");
781 yield* host.stop;
782 expect(yield* fs.exists(`${baseDir}/tools`)).toBe(false);
783 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
784);