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

LocalDeviceHost.test.ts

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