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

LocalDeviceHost.test.ts

528 lines20.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 { 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("uses a registered daemon when reading startup command output fails", () =>
170 Effect.gen(function* () {
171 const fs = yield* FileSystem.FileSystem;
172 const cause = new ProcessRunner.ProcessReadError({
173 command: process.execPath,
174 argumentCount: 3,
175 stream: "stdout",
176 cause: new Error("output read failed after registration"),
177 });
178 let attempts = 0;
179 const { host } = yield* agentFixture((stateDir) =>
180 Effect.gen(function* () {
181 attempts++;
182 yield* fs
183 .writeFileString(
184 `${stateDir}/daemon.json`,
185 JSON.stringify({ httpPort: 12345, token: "test-token" }),
186 )
187 .pipe(Effect.orDie);
188 return yield* cause;
189 }),
190 );
191 const ready = yield* host.ensureAgentReady(() => Effect.void);
192 expect(ready.agentDevice).toMatchObject({
193 baseUrl: "http://127.0.0.1:12345",
194 token: "test-token",
195 });
196 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
197 ready.agentDevice,
198 );
199 expect(attempts).toBe(1);
200 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
201 );
202});
203​
204const diagnose = (
205 files: ReadonlyArray<string>,
206 environment: NodeJS.ProcessEnv,
207 platform: NodeJS.Platform = "darwin",
208) =>
209 LocalDeviceHost.__testing.platformReason("android").pipe(
210 Effect.provideService(HostProcess.Environment, environment),
211 Effect.provideService(HostProcess.Platform, platform),
212 Effect.provideService(
213 FileSystem.FileSystem,
214 FileSystem.makeNoop({
215 exists: (file) => Effect.succeed(files.includes(file)),
216 }),
217 ),
218 Effect.provide(platform === "win32" ? NodePath.layerWin32 : NodePath.layerPosix),
219 );
220​
221describe("Android SDK availability", () => {
222 it.effect("uses the standard Windows SDK without probing PATH", () =>
223 Effect.gen(function* () {
224 const root = "C:\\Users\\test\\AppData\\Local\\Android\\Sdk";
225 const probes: string[] = [];
226 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
227 Effect.provideService(HostProcess.Environment, {
228 USERPROFILE: "C:\\Users\\test",
229 LOCALAPPDATA: "C:\\Users\\test\\AppData\\Local",
230 PATH: "\\\\slow-share\\tools;C:\\other-tools",
231 }),
232 Effect.provideService(HostProcess.Platform, "win32"),
233 Effect.provideService(
234 FileSystem.FileSystem,
235 FileSystem.makeNoop({
236 exists: (file) =>
237 Effect.sync(() => {
238 probes.push(file);
239 return file === `${root}\\platform-tools\\adb.exe`;
240 }),
241 realPath: () => Effect.die("Standard SDK must not resolve PATH executables"),
242 }),
243 ),
244 Effect.provide(NodePath.layerWin32),
245 );
246 expect(sdk).toMatchObject({ root, adb: true });
247 expect(probes.filter((file) => !file.startsWith("C:\\Users\\test\\"))).toEqual([]);
248 }),
249 );
250​
251 it.effect("falls back to adb on the Windows Path without resolving missing entries", () =>
252 Effect.gen(function* () {
253 const root = "D:\\Android\\Sdk";
254 const resolved: string[] = [];
255 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
256 Effect.provideService(HostProcess.Environment, {
257 USERPROFILE: "C:\\Users\\test",
258 Path: "C:\\missing;C:\\shims",
259 }),
260 Effect.provideService(HostProcess.Platform, "win32"),
261 Effect.provideService(
262 FileSystem.FileSystem,
263 FileSystem.makeNoop({
264 exists: (file) =>
265 Effect.succeed(
266 file === "C:\\shims\\adb.exe" || file === `${root}\\platform-tools\\adb.exe`,
267 ),
268 realPath: (file) =>
269 Effect.sync(() => {
270 resolved.push(file);
271 return `${root}\\platform-tools\\adb.exe`;
272 }),
273 }),
274 ),
275 Effect.provide(NodePath.layerWin32),
276 );
277 expect(sdk).toMatchObject({ root, adb: true });
278 expect(resolved).toEqual(["C:\\shims\\adb.exe"]);
279 }),
280 );
281​
282 // regression: #12017 detect unsupported legacy Android command-line tools
283 it.effect("explains how to upgrade legacy command-line tools in the standard macOS SDK", () =>
284 Effect.gen(function* () {
285 const root = "/test/home/Library/Android/sdk";
286 const reason = yield* diagnose(
287 [`${root}/platform-tools/adb`, `${root}/emulator/emulator`, `${root}/tools/bin/avdmanager`],
288 { HOME: "/test/home" },
289 );
290 expect(reason).toContain("older, unsupported version");
291 expect(reason).toContain(root);
292 expect(reason).toContain(
293 "Install Android SDK Command-line Tools (latest) in Android Studio's SDK Manager under SDK Tools.",
294 );
295 }),
296 );
297​
298 it.effect("accepts the latest command-line tools when legacy tools are also installed", () =>
299 Effect.gen(function* () {
300 const reason = yield* diagnose(
301 [
302 "/sdk/platform-tools/adb",
303 "/sdk/emulator/emulator",
304 "/sdk/tools/bin/avdmanager",
305 "/sdk/cmdline-tools/latest/bin/avdmanager",
306 ],
307 { ANDROID_HOME: "/sdk" },
308 );
309 expect(reason).toBeNull();
310 }),
311 );
312​
313 it.effect("discovers the standard macOS SDK without ANDROID_HOME", () =>
314 Effect.gen(function* () {
315 const root = "/test/home/Library/Android/sdk";
316 const reason = yield* diagnose(
317 [
318 `${root}/platform-tools/adb`,
319 `${root}/emulator/emulator`,
320 `${root}/cmdline-tools/latest/bin/avdmanager`,
321 ],
322 { HOME: "/test/home" },
323 );
324 expect(reason).toBeNull();
325 }),
326 );
327});
328​
329it.effect(
330 "recovers an owned Linux runtime directory without overriding explicit environments",
331 () =>
332 Effect.gen(function* () {
333 const fs = yield* FileSystem.FileSystem;
334 const directory = yield* fs.makeTempDirectoryScoped();
335 const stat = yield* fs.stat(directory);
336 for (const [platform, uid, runtimeDir, type, owner, expected] of [
337 ["linux", 1000, undefined, "Directory", 1000, "/run/user/1000"],
338 ["linux", 1000, "/custom/runtime", "Directory", 1000, "/custom/runtime"],
339 ["linux", 1000, "", "Directory", 1000, ""],
340 ["linux", 1000, undefined, "Directory", 1001, undefined],
341 ["linux", 1000, undefined, "File", 1000, undefined],
342 ["linux", undefined, undefined, "Directory", 1000, undefined],
343 ["darwin", 1000, undefined, "Directory", 1000, undefined],
344 ["win32", 1000, undefined, "Directory", 1000, undefined],
345 ] as const) {
346 const environment = { PATH: "/usr/bin", XDG_RUNTIME_DIR: runtimeDir };
347 const result = yield* LocalDeviceHost.__testing.hubEnvironment(environment).pipe(
348 Effect.provideService(HostProcess.Platform, platform),
349 Effect.provideService(HostProcess.UserId, uid),
350 Effect.provideService(
351 FileSystem.FileSystem,
352 FileSystem.makeNoop({
353 stat: (path) => {
354 expect(path).toBe("/run/user/1000");
355 return Effect.succeed({ ...stat, type, uid: Option.some(owner) });
356 },
357 }),
358 ),
359 );
360 expect(result.XDG_RUNTIME_DIR).toBe(expected);
361 expect(result.PATH).toBe("/usr/bin");
362 expect(result.FORCE_COLOR).toBe("0");
363 expect(result.NO_COLOR).toBe("1");
364 expect(environment.XDG_RUNTIME_DIR).toBe(runtimeDir);
365 }
366 const missing = yield* LocalDeviceHost.__testing
367 .hubEnvironment({})
368 .pipe(
369 Effect.provideService(HostProcess.Platform, "linux"),
370 Effect.provideService(HostProcess.UserId, 1000),
371 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
372 );
373 expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
374 }).pipe(
375 Effect.scoped,
376 Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
377 ),
378);
379​
380it.effect.each([
381 {
382 name: "old SDK",
383 front: "emulated webcam<N> none",
384 back: "emulated virtualscene none",
385 code: 0,
386 extra: undefined,
387 expected: "-camera-front emulated -camera-back emulated",
388 },
389 {
390 name: "imagefile-capable SDK",
391 front: "emulated imagefile:<path> none",
392 back: "emulated imagefile:<path> none",
393 code: 0,
394 extra: undefined,
395 expected: undefined,
396 },
397 {
398 name: "user overrides",
399 front: "emulated none",
400 back: "emulated none",
401 code: 0,
402 extra: "-memory 4096 -camera-front none",
403 expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
404 },
405 {
406 name: "different camera capabilities",
407 front: "emulated none",
408 back: "emulated imagefile:<path> none",
409 code: 0,
410 extra: undefined,
411 expected: "-camera-front emulated",
412 },
413 {
414 name: "failed help probe",
415 front: "emulated none",
416 back: "emulated none",
417 code: 1,
418 extra: undefined,
419 expected: undefined,
420 },
421])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
422 Effect.gen(function* () {
423 const result = yield* LocalDeviceHost.__testing
424 .hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
425 .pipe(
426 Effect.provideService(HostProcess.Platform, "darwin"),
427 Effect.provideService(HostProcess.UserId, 1000),
428 Effect.provideService(ProcessRunner.ProcessRunner, {
429 run: (input) => {
430 expect(input.command).toBe("/sdk/emulator/emulator");
431 expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
432 return Effect.succeed(
433 processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
434 );
435 },
436 }),
437 Effect.provide(NodeServices.layer),
438 );
439 expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
440 }),
441);
442​
443it.effect("keeps local Android and iOS available without ffmpeg", () =>
444 Effect.gen(function* () {
445 const fs = yield* FileSystem.FileSystem;
446 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-ffmpeg-" });
447 yield* fs.makeDirectory(`${baseDir}/bin`);
448 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 0\n");
449 yield* fs.chmod(`${baseDir}/bin/xcrun`, 0o755);
450 for (const [directory, tool] of [
451 ["platform-tools", "adb"],
452 ["emulator", "emulator"],
453 ["cmdline-tools/latest/bin", "avdmanager"],
454 ]) {
455 yield* fs.makeDirectory(`${baseDir}/sdk/${directory}`, { recursive: true });
456 yield* fs.writeFileString(`${baseDir}/sdk/${directory}/${tool}`, "");
457 }
458 const onTestHost = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
459 effect.pipe(
460 Effect.provideService(HostProcess.Environment, {
461 HOME: baseDir,
462 PATH: `${baseDir}/bin`,
463 ANDROID_HOME: `${baseDir}/sdk`,
464 }),
465 Effect.provideService(HostProcess.Platform, "darwin"),
466 );
467 const host = yield* LocalDeviceHost.make().pipe(
468 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
469 onTestHost,
470 Effect.provideService(
471 HttpClient.HttpClient,
472 HttpClient.make(() => Effect.die(new Error("Readiness must not make network requests"))),
473 ),
474 Effect.provideService(ProcessRunner.ProcessRunner, {
475 run: () => Effect.die("Platform availability must not probe emulator video"),
476 }),
477 );
478 expect((yield* onTestHost(host.summary)).platforms).toEqual([
479 { platform: "ios", available: true },
480 { platform: "android", available: true },
481 ]);
482 expect(yield* onTestHost(host.platformAvailability("android"))).toEqual({
483 platform: "android",
484 available: true,
485 });
486 expect(yield* onTestHost(host.platformAvailability("ios"))).toEqual({
487 platform: "ios",
488 available: true,
489 });
490 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
491);
492​
493it.effect(
494 "constructs and inspects an unconfigured host without installing or starting helpers",
495 () =>
496 Effect.gen(function* () {
497 const fs = yield* FileSystem.FileSystem;
498 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-consent-" });
499 const host = yield* LocalDeviceHost.make().pipe(
500 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
501 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
502 Effect.provideService(HostProcess.Platform, "linux"),
503 Effect.provideService(
504 ChildProcessSpawner.ChildProcessSpawner,
505 ChildProcessSpawner.make(() =>
506 Effect.die(new Error("Host construction must not spawn processes")),
507 ),
508 ),
509 Effect.provideService(ProcessRunner.ProcessRunner, {
510 run: () => Effect.die(new Error("Host construction must not run commands")),
511 }),
512 Effect.provideService(
513 HttpClient.HttpClient,
514 HttpClient.make(() =>
515 Effect.die(new Error("Host construction must not make network requests")),
516 ),
517 ),
518 );
519 expect(yield* host.current).toBeNull();
520 const error = yield* host
521 .ensureReady(() => Effect.die("Must not install without Node"))
522 .pipe(Effect.flip, Effect.provideService(HostProcess.IsExecutable, true));
523 expect(error.message).toContain("Local device support requires Node.js");
524 expect(error.message).toContain("Install Node.js");
525 yield* host.stop;
526 expect(yield* fs.exists(`${baseDir}/tools`)).toBe(false);
527 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
528);