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

LocalDeviceHost.test.ts

540 lines21.4 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) {
41 const fs = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" });
44 const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata"));
45 for (const [name, version, entry] of [
46 ["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"],
47 ["agent-device", AGENT_DEVICE_VERSION, "bin/agent-device.mjs"],
48 ]) {
49 const installDir = path.join(baseDir, "tools", name!, version!);
50 const entryPath = path.join(installDir, "node_modules", name!, entry!);
51 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
52 yield* fs.writeFileString(entryPath, "");
53 yield* fs.writeFileString(path.join(installDir, ".install-complete"), version!);
54 }
55 const host = yield* LocalDeviceHost.make().pipe(
56 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
57 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
58 Effect.provideService(HostProcess.IsExecutable, false),
59 Effect.provideService(HostProcess.Platform, "darwin"),
60 Effect.provideService(
61 ChildProcessSpawner.ChildProcessSpawner,
62 ChildProcessSpawner.make(() =>
63 Effect.succeed(
64 ChildProcessSpawner.makeHandle({
65 pid: ChildProcessSpawner.ProcessId(123),
66 stdout: Stream.empty,
67 stderr: Stream.empty,
68 all: Stream.empty,
69 exitCode: Effect.never,
70 isRunning: Effect.succeed(true),
71 kill: () => Effect.void,
72 stdin: Sink.drain,
73 getInputFd: () => Sink.drain,
74 getOutputFd: () => Stream.empty,
75 unref: Effect.succeed(Effect.void),
76 }),
77 ),
78 ),
79 ),
80 Effect.provideService(ProcessRunner.ProcessRunner, {
81 run: (input) =>
82 input.args.includes("devices") ? startup(stateDir) : Effect.succeed(processOutput(0)),
83 }),
84 Effect.provideService(
85 HttpClient.HttpClient,
86 HttpClient.make((request) =>
87 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok"))),
88 ),
89 ),
90 );
91 yield* host.ensureReady(() => Effect.void);
92 return { host, fs, stateDir };
93});
94​
95describe("AgentDevice startup", () => {
96 it.effect("reports an incompatible lock immediately and retains it for manual repair", () =>
97 Effect.gen(function* () {
98 const result = processOutput(
99 1,
100 JSON.stringify({
101 success: false,
102 error: {
103 message: "private command output",
104 details: {
105 reason: "daemon_registration_unproven",
106 inspection: { state: "unproven", reason: "non-directory" },
107 },
108 },
109 }),
110 );
111 const { host, fs, stateDir } = yield* agentFixture(() => Effect.succeed(result));
112 const lock = `${stateDir}/daemon.lock`;
113 const legacyOwner = JSON.stringify({ pid: 85669, processStartTime: "old start time" });
114 yield* fs.writeFileString(lock, legacyOwner);
115 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
116 expect(error).toMatchObject({
117 _tag: "AgentDeviceStartError",
118 reason: "daemon_lock_not_directory",
119 exitCode: 1,
120 cause: result,
121 });
122 expect(error.message).toContain("Daemon registration ownership could not be verified");
123 expect(error.message).toContain("daemon.lock is not a directory");
124 expect(error.message).toContain(stateDir);
125 expect(error.message).toContain("original CLI");
126 expect(error.message).not.toContain("private command output");
127 expect(yield* fs.readFileString(lock)).toBe(legacyOwner);
128 expect(yield* host.current).not.toBeNull();
129 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
130 );
131​
132 it.effect("reports unknown nonzero exits without exposing arbitrary command output", () =>
133 Effect.gen(function* () {
134 const result = processOutput(2, "invalid JSON", "private credentials");
135 const { host, stateDir } = yield* agentFixture(() => Effect.succeed(result));
136 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
137 expect(error).toMatchObject({
138 _tag: "AgentDeviceStartError",
139 reason: "command_failed",
140 exitCode: 2,
141 cause: result,
142 });
143 expect(error.message).toContain("exit code 2");
144 expect(error.message).toContain(stateDir);
145 expect(error.message).not.toContain("private credentials");
146 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
147 );
148​
149 it.effect("preserves process execution failures instead of waiting for a daemon file", () =>
150 Effect.gen(function* () {
151 const cause = new ProcessRunner.ProcessSpawnError({
152 command: "/missing/node",
153 argumentCount: 3,
154 cause: new Error("missing executable"),
155 });
156 const { host } = yield* agentFixture(() => Effect.fail(cause));
157 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
158 expect(error).toMatchObject({
159 _tag: "DeviceHostError",
160 step: "starting agent tools",
161 cause,
162 });
163 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
164 );
165​
166 it.effect("returns a command timeout without starting another readiness wait", () =>
167 Effect.gen(function* () {
168 const { host } = yield* agentFixture(() => Effect.succeed(processOutput(124, "", "", true)));
169 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
170 expect(error).toMatchObject({ _tag: "DeviceHostTimeoutError", timeoutMs: 30_000 });
171 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
172 );
173​
174 it.effect("uses a registered daemon when reading startup command output fails", () =>
175 Effect.gen(function* () {
176 const fs = yield* FileSystem.FileSystem;
177 const cause = new ProcessRunner.ProcessReadError({
178 command: process.execPath,
179 argumentCount: 3,
180 stream: "stdout",
181 cause: new Error("output read failed after registration"),
182 });
183 let attempts = 0;
184 const { host } = yield* agentFixture((stateDir) =>
185 Effect.gen(function* () {
186 attempts++;
187 yield* fs
188 .writeFileString(
189 `${stateDir}/daemon.json`,
190 JSON.stringify({ httpPort: 12345, token: "test-token" }),
191 )
192 .pipe(Effect.orDie);
193 return yield* cause;
194 }),
195 );
196 const ready = yield* host.ensureAgentReady(() => Effect.void);
197 expect(ready.agentDevice).toMatchObject({
198 baseUrl: "http://127.0.0.1:12345",
199 token: "test-token",
200 });
201 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
202 ready.agentDevice,
203 );
204 expect(attempts).toBe(1);
205 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
206 );
207​
208 it.effect("allows retry and uses a registered daemon even when discovery exits nonzero", () =>
209 Effect.gen(function* () {
210 const fs = yield* FileSystem.FileSystem;
211 let attempts = 0;
212 const { host } = yield* agentFixture((stateDir) =>
213 Effect.gen(function* () {
214 attempts++;
215 if (attempts > 1) {
216 yield* fs
217 .writeFileString(
218 `${stateDir}/daemon.json`,
219 JSON.stringify({ httpPort: 12345, token: "test-token" }),
220 )
221 .pipe(Effect.orDie);
222 }
223 return processOutput(1);
224 }),
225 );
226 yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
227 const ready = yield* host.ensureAgentReady(() => Effect.void);
228 expect(ready.agentDevice).toMatchObject({
229 baseUrl: "http://127.0.0.1:12345",
230 token: "test-token",
231 });
232 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
233 ready.agentDevice,
234 );
235 expect(attempts).toBe(2);
236 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
237 );
238});
239​
240const diagnose = (
241 files: ReadonlyArray<string>,
242 environment: NodeJS.ProcessEnv,
243 platform: NodeJS.Platform = "darwin",
244) =>
245 LocalDeviceHost.__testing.platformReason("android").pipe(
246 Effect.provideService(HostProcess.Environment, environment),
247 Effect.provideService(HostProcess.Platform, platform),
248 Effect.provideService(
249 FileSystem.FileSystem,
250 FileSystem.makeNoop({
251 exists: (file) => Effect.succeed(files.includes(file)),
252 }),
253 ),
254 Effect.provide(platform === "win32" ? NodePath.layerWin32 : NodePath.layerPosix),
255 );
256​
257describe("Android SDK availability", () => {
258 it.effect("uses the standard Windows SDK without probing PATH", () =>
259 Effect.gen(function* () {
260 const root = "C:\\Users\\test\\AppData\\Local\\Android\\Sdk";
261 const probes: string[] = [];
262 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
263 Effect.provideService(HostProcess.Environment, {
264 USERPROFILE: "C:\\Users\\test",
265 LOCALAPPDATA: "C:\\Users\\test\\AppData\\Local",
266 PATH: "\\\\slow-share\\tools;C:\\other-tools",
267 }),
268 Effect.provideService(HostProcess.Platform, "win32"),
269 Effect.provideService(
270 FileSystem.FileSystem,
271 FileSystem.makeNoop({
272 exists: (file) =>
273 Effect.sync(() => {
274 probes.push(file);
275 return file === `${root}\\platform-tools\\adb.exe`;
276 }),
277 realPath: () => Effect.die("Standard SDK must not resolve PATH executables"),
278 }),
279 ),
280 Effect.provide(NodePath.layerWin32),
281 );
282 expect(sdk).toMatchObject({ root, adb: true });
283 expect(probes.filter((file) => !file.startsWith("C:\\Users\\test\\"))).toEqual([]);
284 }),
285 );
286​
287 it.effect("falls back to adb on the Windows Path without resolving missing entries", () =>
288 Effect.gen(function* () {
289 const root = "D:\\Android\\Sdk";
290 const resolved: string[] = [];
291 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
292 Effect.provideService(HostProcess.Environment, {
293 USERPROFILE: "C:\\Users\\test",
294 Path: "C:\\missing;C:\\shims",
295 }),
296 Effect.provideService(HostProcess.Platform, "win32"),
297 Effect.provideService(
298 FileSystem.FileSystem,
299 FileSystem.makeNoop({
300 exists: (file) =>
301 Effect.succeed(
302 file === "C:\\shims\\adb.exe" || file === `${root}\\platform-tools\\adb.exe`,
303 ),
304 realPath: (file) =>
305 Effect.sync(() => {
306 resolved.push(file);
307 return `${root}\\platform-tools\\adb.exe`;
308 }),
309 }),
310 ),
311 Effect.provide(NodePath.layerWin32),
312 );
313 expect(sdk).toMatchObject({ root, adb: true });
314 expect(resolved).toEqual(["C:\\shims\\adb.exe"]);
315 }),
316 );
317​
318 it.effect("explains that adb alone is insufficient to launch an emulator", () =>
319 Effect.gen(function* () {
320 const reason = yield* diagnose(["/sdk/platform-tools/adb"], { ANDROID_HOME: "/sdk" });
321 expect(reason).toContain("Android Emulator is missing");
322 }),
323 );
324​
325 it.effect("identifies command-line tools required by the device hub", () =>
326 Effect.gen(function* () {
327 const reason = yield* diagnose(["/sdk/platform-tools/adb", "/sdk/emulator/emulator"], {
328 ANDROID_HOME: "/sdk",
329 });
330 expect(reason).toContain("Command-line Tools (latest) are missing");
331 }),
332 );
333​
334 it.effect("explains how to upgrade legacy command-line tools in the standard macOS SDK", () =>
335 Effect.gen(function* () {
336 const root = "/test/home/Library/Android/sdk";
337 const reason = yield* diagnose(
338 [`${root}/platform-tools/adb`, `${root}/emulator/emulator`, `${root}/tools/bin/avdmanager`],
339 { HOME: "/test/home" },
340 );
341 expect(reason).toContain("older, unsupported version");
342 expect(reason).toContain(root);
343 expect(reason).toContain(
344 "Install Android SDK Command-line Tools (latest) in Android Studio's SDK Manager under SDK Tools.",
345 );
346 }),
347 );
348​
349 it.effect("recognizes legacy command-line tools on Windows", () =>
350 Effect.gen(function* () {
351 const reason = yield* diagnose(
352 [
353 "C:\\Android\\Sdk\\platform-tools\\adb.exe",
354 "C:\\Android\\Sdk\\emulator\\emulator.exe",
355 "C:\\Android\\Sdk\\tools\\bin\\avdmanager.bat",
356 ],
357 { ANDROID_HOME: "C:\\Android\\Sdk" },
358 "win32",
359 );
360 expect(reason).toContain("older, unsupported version");
361 }),
362 );
363​
364 it.effect("accepts the latest command-line tools when legacy tools are also installed", () =>
365 Effect.gen(function* () {
366 const reason = yield* diagnose(
367 [
368 "/sdk/platform-tools/adb",
369 "/sdk/emulator/emulator",
370 "/sdk/tools/bin/avdmanager",
371 "/sdk/cmdline-tools/latest/bin/avdmanager",
372 ],
373 { ANDROID_HOME: "/sdk" },
374 );
375 expect(reason).toBeNull();
376 }),
377 );
378​
379 it.effect("discovers the standard macOS SDK without ANDROID_HOME", () =>
380 Effect.gen(function* () {
381 const root = "/test/home/Library/Android/sdk";
382 const reason = yield* diagnose(
383 [
384 `${root}/platform-tools/adb`,
385 `${root}/emulator/emulator`,
386 `${root}/cmdline-tools/latest/bin/avdmanager`,
387 ],
388 { HOME: "/test/home" },
389 );
390 expect(reason).toBeNull();
391 }),
392 );
393​
394 it.effect("reports an absent SDK without running or installing tools", () =>
395 Effect.gen(function* () {
396 expect(yield* diagnose([], { HOME: "/test/home" })).toContain("Android SDK was not found");
397 }),
398 );
399});
400​
401it.effect("puts detected Android tools on the helper PATH without losing existing commands", () =>
402 Effect.gen(function* () {
403 const path = yield* Path.Path;
404 const environment = LocalDeviceHost.__testing.deviceHostEnvironment(
405 { PATH: "/usr/bin", HOME: "/test/home" },
406 "/sdk",
407 "darwin",
408 path,
409 );
410 expect(environment.PATH).toBe("/sdk/platform-tools:/sdk/emulator:/usr/bin");
411 expect(environment.ANDROID_HOME).toBe("/sdk");
412 expect(environment.HOME).toBe("/test/home");
413 }).pipe(Effect.provide(NodePath.layerPosix)),
414);
415​
416it.effect(
417 "recovers an owned Linux runtime directory without overriding explicit environments",
418 () =>
419 Effect.gen(function* () {
420 const fs = yield* FileSystem.FileSystem;
421 const directory = yield* fs.makeTempDirectoryScoped();
422 const stat = yield* fs.stat(directory);
423 for (const [platform, uid, runtimeDir, type, owner, expected] of [
424 ["linux", 1000, undefined, "Directory", 1000, "/run/user/1000"],
425 ["linux", 1000, "/custom/runtime", "Directory", 1000, "/custom/runtime"],
426 ["linux", 1000, "", "Directory", 1000, ""],
427 ["linux", 1000, undefined, "Directory", 1001, undefined],
428 ["linux", 1000, undefined, "File", 1000, undefined],
429 ["linux", undefined, undefined, "Directory", 1000, undefined],
430 ["darwin", 1000, undefined, "Directory", 1000, undefined],
431 ["win32", 1000, undefined, "Directory", 1000, undefined],
432 ] as const) {
433 const environment = { PATH: "/usr/bin", XDG_RUNTIME_DIR: runtimeDir };
434 const result = yield* LocalDeviceHost.__testing.hubEnvironment(environment).pipe(
435 Effect.provideService(HostProcess.Platform, platform),
436 Effect.provideService(HostProcess.UserId, uid),
437 Effect.provideService(
438 FileSystem.FileSystem,
439 FileSystem.makeNoop({
440 stat: (path) => {
441 expect(path).toBe("/run/user/1000");
442 return Effect.succeed({ ...stat, type, uid: Option.some(owner) });
443 },
444 }),
445 ),
446 );
447 expect(result.XDG_RUNTIME_DIR).toBe(expected);
448 expect(result.PATH).toBe("/usr/bin");
449 expect(result.FORCE_COLOR).toBe("0");
450 expect(result.NO_COLOR).toBe("1");
451 expect(environment.XDG_RUNTIME_DIR).toBe(runtimeDir);
452 }
453 const missing = yield* LocalDeviceHost.__testing
454 .hubEnvironment({})
455 .pipe(
456 Effect.provideService(HostProcess.Platform, "linux"),
457 Effect.provideService(HostProcess.UserId, 1000),
458 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
459 );
460 expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
461 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
462);
463​
464it.live("limits hub discovery to Android unless the host is a Mac", () =>
465 Effect.gen(function* () {
466 if ((yield* HostProcess.Platform) === "win32") return;
467 const fs = yield* FileSystem.FileSystem;
468 const path = yield* Path.Path;
469 const environment = yield* HostProcess.Environment;
470 const hubArguments = Effect.fn(function* (platform: NodeJS.Platform) {
471 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-hub-" });
472 const installDir = path.join(baseDir, "tools/expo-device-hub", DEVICE_HUB_VERSION);
473 const entryPath = path.join(installDir, "node_modules/expo-device-hub/dist/server/cli.mjs");
474 const argumentsPath = path.join(baseDir, "hub-args.json");
475 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
476 yield* fs.writeFileString(path.join(installDir, ".install-complete"), DEVICE_HUB_VERSION);
477 yield* fs.writeFileString(
478 entryPath,
479 `import http from 'node:http'; import fs from 'node:fs';
480const args=process.argv.slice(2); fs.writeFileSync(${JSON.stringify(argumentsPath)},JSON.stringify(args));
481http.createServer((req,res)=>res.end('ok')).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
482 );
483 const host = yield* LocalDeviceHost.make().pipe(
484 Effect.provide(
485 Layer.mergeAll(
486 ServerConfig.layerTest(baseDir, baseDir),
487 NetService.layer,
488 ProcessRunner.layer,
489 FetchHttpClient.layer,
490 ),
491 ),
492 Effect.provideService(HostProcess.Environment, { ...environment, HOME: baseDir }),
493 Effect.provideService(HostProcess.Platform, platform),
494 );
495 yield* host.ensureReady(() => Effect.void).pipe(Effect.ensuring(host.stop));
496 return (yield* fs
497 .readFileString(argumentsPath)
498 .pipe(Effect.map((contents) => JSON.parse(contents)))) as ReadonlyArray<string>;
499 });
500 expect((yield* hubArguments("linux")).slice(-2)).toEqual(["--platform", "android"]);
501 expect(yield* hubArguments("darwin")).not.toContain("--platform");
502 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
503);
504​
505it.effect(
506 "constructs and inspects an unconfigured host without installing or starting helpers",
507 () =>
508 Effect.gen(function* () {
509 const fs = yield* FileSystem.FileSystem;
510 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-consent-" });
511 const host = yield* LocalDeviceHost.make().pipe(
512 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
513 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
514 Effect.provideService(HostProcess.Platform, "linux"),
515 Effect.provideService(
516 ChildProcessSpawner.ChildProcessSpawner,
517 ChildProcessSpawner.make(() =>
518 Effect.die(new Error("Host construction must not spawn processes")),
519 ),
520 ),
521 Effect.provideService(ProcessRunner.ProcessRunner, {
522 run: () => Effect.die(new Error("Host construction must not run commands")),
523 }),
524 Effect.provideService(
525 HttpClient.HttpClient,
526 HttpClient.make(() =>
527 Effect.die(new Error("Host construction must not make network requests")),
528 ),
529 ),
530 );
531 expect(yield* host.current).toBeNull();
532 const error = yield* host
533 .ensureReady(() => Effect.die("Must not install without Node"))
534 .pipe(Effect.flip, Effect.provideService(HostProcess.IsExecutable, true));
535 expect(error.message).toContain("Local device support requires Node.js");
536 expect(error.message).toContain("Install Node.js");
537 yield* host.stop;
538 expect(yield* fs.exists(`${baseDir}/tools`)).toBe(false);
539 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
540);