Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as NodePath from "@effect/platform-node/NodePath";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as PlatformError from "effect/PlatformError";
10import * as Ref from "effect/Ref";
11import * as FileSystem from "effect/FileSystem";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14
15import * as LocalDeviceHost from "./LocalDeviceHost.ts";
16import * as NodeServices from "@effect/platform-node/NodeServices";
17import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18import { HttpClient, HttpClientResponse } from "effect/http";
19import * as NetService from "@t3tools/shared/Net";
20import * as ServerConfig from "../config.ts";
21import * as ServerSettings from "../serverSettings.ts";
22import * as ProcessRunner from "../processRunner.ts";
23import {
24 AGENT_DEVICE_VERSION,
25 DEVICE_HUB_VERSION,
26 agentDeviceStateDir,
27} from "./DeviceToolchain.ts";
28
29const processOutput = (code: number, stdout = "", stderr = "", timedOut = false) => ({
30 code: ChildProcessSpawner.ExitCode(code),
31 stdout,
32 stderr,
33 timedOut,
34 stdoutTruncated: false,
35 stderrTruncated: false,
36 stdoutInvalidUtf8: false,
37 stderrInvalidUtf8: false,
38});
39
40const agentFixture = Effect.fn("agentFixture")(function* (
41 startup: (
42 stateDir: string,
43 ) => Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
44 avdOutput: ProcessRunner.ProcessRunOutput = processOutput(0),
45 previousDaemon?: typeof LocalDeviceHost.__testing.AgentDeviceDaemonFile.Type,
46) {
47 const fs = yield* FileSystem.FileSystem;
48 const path = yield* Path.Path;
49 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" });
50 const hub = { running: true, spawnFails: false };
51 const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata"));
52 const daemonHealthy = yield* Ref.make(true);
53 const runs: Array<ProcessRunner.ProcessRunInput> = [];
54 for (const [name, version, entry] of [
55 ["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"],
56 ["agent-device", AGENT_DEVICE_VERSION, "bin/agent-device.mjs"],
57 ]) {
58 const installDir = path.join(baseDir, "tools", name!, version!);
59 const entryPath = path.join(installDir, "node_modules", name!, entry!);
60 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
61 yield* fs.writeFileString(entryPath, "");
62 yield* fs.writeFileString(path.join(installDir, ".install-complete"), version!);
63 }
64 if (previousDaemon) {
65 yield* fs.makeDirectory(stateDir, { recursive: true });
66 yield* fs.writeFileString(path.join(stateDir, "daemon.json"), JSON.stringify(previousDaemon));
67 }
68 const host = yield* LocalDeviceHost.make().pipe(
69 Effect.provide(
70 Layer.mergeAll(
71 ServerConfig.layerTest(baseDir, baseDir),
72 NetService.layer,
73 ServerSettings.layerTest(),
74 ),
75 ),
76 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
77 Effect.provideService(HostProcess.IsExecutable, false),
78 Effect.provideService(HostProcess.Platform, "darwin"),
79 Effect.provideService(
80 ChildProcessSpawner.ChildProcessSpawner,
81 ChildProcessSpawner.make(() =>
82 hub.spawnFails
83 ? Effect.fail(
84 PlatformError.systemError({
85 _tag: "NotFound",
86 module: "ChildProcess",
87 method: "spawn",
88 description: "Hub entry missing",
89 }),
90 )
91 : Effect.succeed(
92 ChildProcessSpawner.makeHandle({
93 pid: ChildProcessSpawner.ProcessId(123),
94 stdout: Stream.empty,
95 stderr: Stream.empty,
96 all: Stream.empty,
97 exitCode: Effect.never,
98 isRunning: Effect.sync(() => hub.running),
99 kill: () => Effect.void,
100 stdin: Sink.drain,
101 getInputFd: () => Sink.drain,
102 getOutputFd: () => Stream.empty,
103 unref: Effect.succeed(Effect.void),
104 }),
105 ),
106 ),
107 ),
108 Effect.provideService(ProcessRunner.ProcessRunner, {
109 run: (input) => {
110 runs.push(input);
111 return input.args.includes("devices")
112 ? startup(stateDir)
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, 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("reports an incompatible lock immediately and retains it for manual repair", () =>
170 Effect.gen(function* () {
171 const result = processOutput(
172 1,
173 JSON.stringify({
174 success: false,
175 error: {
176 message: "private command output",
177 details: {
178 reason: "daemon_registration_unproven",
179 inspection: { state: "unproven", reason: "non-directory" },
180 },
181 },
182 }),
183 );
184 const { host, fs, stateDir } = yield* agentFixture(() => Effect.succeed(result));
185 const lock = `${stateDir}/daemon.lock`;
186 const legacyOwner = JSON.stringify({ pid: 85669, processStartTime: "old start time" });
187 yield* fs.writeFileString(lock, legacyOwner);
188 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
189 expect(error).toMatchObject({
190 _tag: "AgentDeviceStartError",
191 reason: "daemon_lock_not_directory",
192 exitCode: 1,
193 cause: result,
194 });
195 expect(error.message).toContain("Daemon registration ownership could not be verified");
196 expect(error.message).toContain("daemon.lock is not a directory");
197 expect(error.message).toContain(stateDir);
198 expect(error.message).toContain("original CLI");
199 expect(error.message).not.toContain("private command output");
200 expect(yield* fs.readFileString(lock)).toBe(legacyOwner);
201 expect(yield* host.current).not.toBeNull();
202 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
203 );
204
205 it.effect("reports unknown nonzero exits without exposing arbitrary command output", () =>
206 Effect.gen(function* () {
207 const result = processOutput(2, "invalid JSON", "private credentials");
208 const { host, stateDir } = yield* agentFixture(() => Effect.succeed(result));
209 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
210 expect(error).toMatchObject({
211 _tag: "AgentDeviceStartError",
212 reason: "command_failed",
213 exitCode: 2,
214 cause: result,
215 });
216 expect(error.message).toContain("exit code 2");
217 expect(error.message).toContain(stateDir);
218 expect(error.message).not.toContain("private credentials");
219 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
220 );
221
222 it.effect("preserves process execution failures instead of waiting for a daemon file", () =>
223 Effect.gen(function* () {
224 const cause = new ProcessRunner.ProcessSpawnError({
225 command: "/missing/node",
226 argumentCount: 3,
227 cause: new Error("missing executable"),
228 });
229 const { host } = yield* agentFixture(() => Effect.fail(cause));
230 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
231 expect(error).toMatchObject({
232 _tag: "DeviceHostError",
233 step: "starting agent tools",
234 cause,
235 });
236 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
237 );
238
239 it.effect("uses a registered daemon when reading startup command output fails", () =>
240 Effect.gen(function* () {
241 const fs = yield* FileSystem.FileSystem;
242 const cause = new ProcessRunner.ProcessReadError({
243 command: process.execPath,
244 argumentCount: 3,
245 stream: "stdout",
246 cause: new Error("output read failed after registration"),
247 });
248 let attempts = 0;
249 const { host } = yield* agentFixture((stateDir) =>
250 Effect.gen(function* () {
251 attempts++;
252 yield* fs
253 .writeFileString(
254 `${stateDir}/daemon.json`,
255 JSON.stringify({ httpPort: 12345, token: "test-token" }),
256 )
257 .pipe(Effect.orDie);
258 return yield* cause;
259 }),
260 );
261 const ready = yield* host.ensureAgentReady(() => Effect.void);
262 expect(ready.agentDevice).toMatchObject({
263 baseUrl: "http://127.0.0.1:12345",
264 token: "test-token",
265 });
266 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
267 ready.agentDevice,
268 );
269 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
270 expect(attempts).toBe(1);
271 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
272 );
273
274 it.effect("keeps releasing agent sessions while a dead hub fails to restart and after", () =>
275 Effect.gen(function* () {
276 const fs = yield* FileSystem.FileSystem;
277 const { host, hub } = yield* agentFixture((stateDir) =>
278 fs
279 .writeFileString(
280 `${stateDir}/daemon.json`,
281 JSON.stringify({ httpPort: 12345, token: "test-token" }),
282 )
283 .pipe(Effect.orDie, Effect.as(processOutput(0))),
284 );
285 yield* host.ensureAgentReady(() => Effect.void);
286 hub.running = false;
287 hub.spawnFails = true;
288 expect((yield* host.ensureReady(() => Effect.void).pipe(Effect.result))._tag).toBe("Failure");
289 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
290 hub.spawnFails = false;
291 yield* host.ensureReady(() => Effect.void);
292 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
293 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
294 );
295
296 it.effect("stops a previous server's daemon with the agent-device version it recorded", () =>
297 Effect.gen(function* () {
298 const path = yield* Path.Path;
299 const { host, fs, baseDir, runs } = yield* agentFixture(
300 () => Effect.die("A session that never readies agent tools must not start the daemon"),
301 processOutput(0),
302 { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" },
303 );
304 const olderInstall = path.join(baseDir, "tools", "agent-device", "0.0.1");
305 const olderEntry = path.join(
306 olderInstall,
307 "node_modules",
308 "agent-device",
309 "bin",
310 "agent-device.mjs",
311 );
312 yield* fs.makeDirectory(path.dirname(olderEntry), { recursive: true });
313 yield* fs.writeFileString(olderEntry, "");
314 yield* fs.writeFileString(path.join(olderInstall, ".install-complete"), "0.0.1");
315 yield* host.stop;
316 expect(runs.find((run) => run.args.includes("daemon"))?.args[0]).toBe(olderEntry);
317 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
318 );
319
320 // regression: #33552 a daemon left by a previous server survived every later graceful quit
321 it.effect("stops a previous server's daemon with the current pin when its version is gone", () =>
322 Effect.gen(function* () {
323 const path = yield* Path.Path;
324 const { host, baseDir, stateDir, runs } = yield* agentFixture(
325 () => Effect.die("A session that never readies agent tools must not start the daemon"),
326 processOutput(0),
327 { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" },
328 );
329 yield* host.stop;
330 expect(runs.find((run) => run.args.includes("daemon"))?.args).toEqual([
331 path.join(
332 baseDir,
333 "tools",
334 "agent-device",
335 AGENT_DEVICE_VERSION,
336 "node_modules",
337 "agent-device",
338 "bin",
339 "agent-device.mjs",
340 ),
341 "daemon",
342 "stop",
343 "--state-dir",
344 stateDir,
345 ]);
346 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
347 );
348
349 it.effect("drops a dead daemon's record without running agent-device when the host stops", () =>
350 Effect.gen(function* () {
351 // Above the Linux and macOS PID limits, so never a live process.
352 const deadPid = 4_194_305;
353 const path = yield* Path.Path;
354 const { host, fs, stateDir, runs } = yield* agentFixture(
355 () => Effect.die("A session that never readies agent tools must not start the daemon"),
356 processOutput(0),
357 { httpPort: 12345, token: "previous-token", pid: deadPid, version: AGENT_DEVICE_VERSION },
358 );
359 yield* host.stop;
360 expect(runs.filter((run) => run.args.includes("daemon"))).toEqual([]);
361 expect(yield* fs.exists(path.join(stateDir, "daemon.json"))).toBe(false);
362 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
363 );
364});
365
366const diagnose = (
367 files: ReadonlyArray<string>,
368 environment: NodeJS.ProcessEnv,
369 platform: NodeJS.Platform = "darwin",
370) =>
371 LocalDeviceHost.__testing.platformReason("android").pipe(
372 Effect.provideService(HostProcess.Environment, environment),
373 Effect.provideService(HostProcess.Platform, platform),
374 Effect.provideService(ProcessRunner.ProcessRunner, {
375 run: () => Effect.die("Android diagnostics must not run commands"),
376 }),
377 Effect.provideService(
378 FileSystem.FileSystem,
379 FileSystem.makeNoop({
380 exists: (file) => Effect.succeed(files.includes(file)),
381 }),
382 ),
383 Effect.provide(platform === "win32" ? NodePath.layerWin32 : NodePath.layerPosix),
384 );
385
386const diagnoseIos = (
387 outcome: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
388 applications: ReadonlyArray<string> = ["Xcode.app"],
389 platform: NodeJS.Platform = "darwin",
390 {
391 environment = {},
392 selectedDeveloperDirectory = "/Applications/Xcode.app/Contents/Developer",
393 developerDirectoryExists = true,
394 }: {
395 environment?: NodeJS.ProcessEnv;
396 selectedDeveloperDirectory?: string | null;
397 developerDirectoryExists?: boolean;
398 } = {},
399) => {
400 const developerDirectory = environment.DEVELOPER_DIR ?? selectedDeveloperDirectory;
401 return LocalDeviceHost.__testing.platformReason("ios").pipe(
402 Effect.provideService(HostProcess.Environment, { PATH: "", ...environment }),
403 Effect.provideService(HostProcess.Platform, platform),
404 Effect.provideService(ProcessRunner.ProcessRunner, {
405 run: (input) => {
406 expect(platform).toBe("darwin");
407 const timeoutMs = Duration.toMillis(input.timeout ?? Infinity);
408 expect(Number.isFinite(timeoutMs)).toBe(true);
409 expect(timeoutMs).toBeGreaterThan(0);
410 if (input.command === "xcode-select") {
411 expect(input.args).toEqual(["--print-path"]);
412 return Effect.succeed(
413 developerDirectory === null
414 ? processOutput(
415 2,
416 "",
417 "xcode-select: error: unable to get active developer directory",
418 )
419 : processOutput(0, `${developerDirectory}\n`),
420 );
421 }
422 expect([input.command, ...input.args]).toEqual(["xcrun", "simctl", "help"]);
423 return outcome;
424 },
425 }),
426 Effect.provideService(
427 FileSystem.FileSystem,
428 FileSystem.makeNoop({
429 readDirectory: (path) => {
430 expect(path).toBe("/Applications");
431 return Effect.succeed([...applications]);
432 },
433 exists: (path) =>
434 Effect.succeed(
435 path === developerDirectory
436 ? developerDirectoryExists
437 : applications.some(
438 (bundle) => path === `/Applications/${bundle}/Contents/Developer`,
439 ),
440 ),
441 }),
442 ),
443 Effect.provide(NodePath.layerPosix),
444 );
445};
446
447describe("iOS Simulator availability", () => {
448 it.effect("accepts working simctl on macOS and rejects other platforms without probing", () =>
449 Effect.gen(function* () {
450 for (const options of [
451 {},
452 { selectedDeveloperDirectory: "/Volumes/Tools/Xcode.app/Contents/Developer" },
453 { environment: { DEVELOPER_DIR: "/Volumes/Tools/Xcode-beta.app/Contents/Developer" } },
454 ]) {
455 expect(
456 yield* diagnoseIos(Effect.succeed(processOutput(0)), [], "darwin", options),
457 ).toBeNull();
458 }
459 for (const platform of ["linux", "win32"] as const) {
460 expect(yield* diagnoseIos(Effect.die("Only macOS can probe simctl"), [], platform)).toMatch(
461 /macOS.*Xcode/,
462 );
463 }
464 }),
465 );
466
467 it.effect("does not invoke the xcrun installer stub without a valid developer directory", () =>
468 Effect.gen(function* () {
469 let xcrunCalls = 0;
470 const stub = Effect.sync(() => {
471 xcrunCalls++;
472 return processOutput(
473 1,
474 "",
475 "xcode-select: note: No developer tools were found, requesting install.",
476 );
477 });
478 for (const options of [
479 { selectedDeveloperDirectory: null },
480 { selectedDeveloperDirectory: "/missing/Xcode.app/Contents/Developer" },
481 { environment: { DEVELOPER_DIR: "/missing/Developer" } },
482 ]) {
483 const reason = yield* diagnoseIos(stub, [], "darwin", {
484 ...options,
485 developerDirectoryExists: false,
486 });
487 expect(xcrunCalls).toBe(0);
488 expect(reason).toMatch(
489 /install.*Xcode|select.*developer|developer.*(missing|not found|invalid)/i,
490 );
491 }
492 }),
493 );
494
495 it.effect("offers usable Xcode selection guidance, including a DEVELOPER_DIR override", () =>
496 Effect.gen(function* () {
497 for (const bundle of ["Xcode.app", "Xcode-beta.app", "Xcode 26.app"]) {
498 for (const environment of [{}, { DEVELOPER_DIR: "/Library/Developer/CommandLineTools" }]) {
499 const reason = yield* diagnoseIos(
500 Effect.succeed(processOutput(72, "", 'xcrun: error: unable to find utility "simctl"')),
501 ["Safari.app", bundle],
502 "darwin",
503 { environment, selectedDeveloperDirectory: "/Library/Developer/CommandLineTools" },
504 );
505 const developerPath = `/Applications/${bundle}/Contents/Developer`;
506 expect(reason).toContain(developerPath);
507 if (environment.DEVELOPER_DIR) {
508 expect(reason).toContain("DEVELOPER_DIR");
509 expect(reason).toMatch(/unset|change|update|set .*DEVELOPER_DIR/i);
510 expect(reason).toMatch(/restart/i);
511 } else {
512 const command = reason?.match(/sudo xcode-select (?:-s|--switch) (.+)/)?.[1];
513 expect(command).toBeDefined();
514 const quoted =
515 command?.startsWith(`"${developerPath}"`) ||
516 command?.startsWith(`'${developerPath}'`);
517 expect(quoted || (!bundle.includes(" ") && command?.startsWith(developerPath))).toBe(
518 true,
519 );
520 }
521 }
522 }
523 }),
524 );
525
526 it.effect("offers installation or selection outside Applications when no Xcode is found", () =>
527 Effect.gen(function* () {
528 const reason = yield* diagnoseIos(
529 Effect.succeed(processOutput(72, "", 'xcrun: error: unable to find utility "simctl"')),
530 ["Safari.app"],
531 );
532 expect(reason).toMatch(/install Xcode/i);
533 expect(reason).toContain("outside /Applications");
534 expect(reason).toContain("xcode-select");
535 expect(reason).not.toContain("/Applications/Xcode.app");
536 }),
537 );
538
539 it.effect("reports missing tools only for a not-found spawn failure", () =>
540 Effect.gen(function* () {
541 for (const [cause, missing] of [
542 [
543 PlatformError.systemError({
544 _tag: "NotFound",
545 module: "ChildProcess",
546 method: "spawn",
547 pathOrDescriptor: "xcrun",
548 }),
549 true,
550 ],
551 [
552 PlatformError.systemError({
553 _tag: "PermissionDenied",
554 module: "ChildProcess",
555 method: "spawn",
556 pathOrDescriptor: "xcrun",
557 }),
558 false,
559 ],
560 [new Error("unknown spawn failure"), false],
561 ] as const) {
562 const reason = yield* diagnoseIos(
563 Effect.fail(
564 new ProcessRunner.ProcessSpawnError({ command: "xcrun", argumentCount: 2, cause }),
565 ),
566 );
567 if (missing) {
568 expect(reason).toMatch(/command line tools.*not found/i);
569 } else {
570 expect(reason).toMatch(/could not run xcrun simctl/i);
571 expect(reason).not.toMatch(/not found|install Xcode|xcode-select/i);
572 }
573 }
574 }),
575 );
576
577 it.effect("preserves license and timeout diagnostics without suggesting missing tools", () =>
578 Effect.gen(function* () {
579 for (const [outcome, diagnostic] of [
580 [
581 Effect.succeed(
582 processOutput(69, "", "You have not agreed to the Xcode license agreements."),
583 ),
584 /license agreements/,
585 ],
586 [
587 Effect.fail(
588 new ProcessRunner.ProcessTimeoutError({
589 command: "xcrun",
590 argumentCount: 2,
591 timeoutMs: 15_000,
592 }),
593 ),
594 /timed out/i,
595 ],
596 ] as const) {
597 const reason = yield* diagnoseIos(outcome);
598 expect(reason).toMatch(diagnostic);
599 expect(reason).not.toMatch(/not found|install Xcode|xcode-select/i);
600 }
601 }),
602 );
603});
604
605describe("Android SDK availability", () => {
606 it.effect("uses the standard Windows SDK without probing PATH", () =>
607 Effect.gen(function* () {
608 const root = "C:\\Users\\test\\AppData\\Local\\Android\\Sdk";
609 const probes: string[] = [];
610 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
611 Effect.provideService(HostProcess.Environment, {
612 USERPROFILE: "C:\\Users\\test",
613 LOCALAPPDATA: "C:\\Users\\test\\AppData\\Local",
614 PATH: "\\\\slow-share\\tools;C:\\other-tools",
615 }),
616 Effect.provideService(HostProcess.Platform, "win32"),
617 Effect.provideService(
618 FileSystem.FileSystem,
619 FileSystem.makeNoop({
620 exists: (file) =>
621 Effect.sync(() => {
622 probes.push(file);
623 return file === `${root}\\platform-tools\\adb.exe`;
624 }),
625 realPath: () => Effect.die("Standard SDK must not resolve PATH executables"),
626 }),
627 ),
628 Effect.provide(NodePath.layerWin32),
629 );
630 expect(sdk).toMatchObject({ root, adb: true });
631 expect(probes.filter((file) => !file.startsWith("C:\\Users\\test\\"))).toEqual([]);
632 }),
633 );
634
635 it.effect("falls back to adb on the Windows Path without resolving missing entries", () =>
636 Effect.gen(function* () {
637 const root = "D:\\Android\\Sdk";
638 const resolved: string[] = [];
639 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
640 Effect.provideService(HostProcess.Environment, {
641 USERPROFILE: "C:\\Users\\test",
642 Path: "C:\\missing;C:\\shims",
643 }),
644 Effect.provideService(HostProcess.Platform, "win32"),
645 Effect.provideService(
646 FileSystem.FileSystem,
647 FileSystem.makeNoop({
648 exists: (file) =>
649 Effect.succeed(
650 file === "C:\\shims\\adb.exe" || file === `${root}\\platform-tools\\adb.exe`,
651 ),
652 realPath: (file) =>
653 Effect.sync(() => {
654 resolved.push(file);
655 return `${root}\\platform-tools\\adb.exe`;
656 }),
657 }),
658 ),
659 Effect.provide(NodePath.layerWin32),
660 );
661 expect(sdk).toMatchObject({ root, adb: true });
662 expect(resolved).toEqual(["C:\\shims\\adb.exe"]);
663 }),
664 );
665
666 // regression: #12017 detect unsupported legacy Android command-line tools
667 it.effect("explains how to upgrade legacy command-line tools in the standard macOS SDK", () =>
668 Effect.gen(function* () {
669 const root = "/test/home/Library/Android/sdk";
670 const reason = yield* diagnose(
671 [`${root}/platform-tools/adb`, `${root}/emulator/emulator`, `${root}/tools/bin/avdmanager`],
672 { HOME: "/test/home" },
673 );
674 expect(reason).toContain("older, unsupported version");
675 expect(reason).toContain(root);
676 expect(reason).toContain(
677 "Install Android SDK Command-line Tools (latest) in Android Studio's SDK Manager under SDK Tools.",
678 );
679 }),
680 );
681
682 it.effect("accepts the latest command-line tools when legacy tools are also installed", () =>
683 Effect.gen(function* () {
684 const reason = yield* diagnose(
685 [
686 "/sdk/platform-tools/adb",
687 "/sdk/emulator/emulator",
688 "/sdk/tools/bin/avdmanager",
689 "/sdk/cmdline-tools/latest/bin/avdmanager",
690 ],
691 { ANDROID_HOME: "/sdk" },
692 );
693 expect(reason).toBeNull();
694 }),
695 );
696
697 it.effect("discovers the standard macOS SDK without ANDROID_HOME", () =>
698 Effect.gen(function* () {
699 const root = "/test/home/Library/Android/sdk";
700 const reason = yield* diagnose(
701 [
702 `${root}/platform-tools/adb`,
703 `${root}/emulator/emulator`,
704 `${root}/cmdline-tools/latest/bin/avdmanager`,
705 ],
706 { HOME: "/test/home" },
707 );
708 expect(reason).toBeNull();
709 }),
710 );
711});
712
713it.effect(
714 "recovers an owned Linux runtime directory without overriding explicit environments",
715 () =>
716 Effect.gen(function* () {
717 const fs = yield* FileSystem.FileSystem;
718 const directory = yield* fs.makeTempDirectoryScoped();
719 const stat = yield* fs.stat(directory);
720 for (const [platform, uid, runtimeDir, type, owner, expected] of [
721 ["linux", 1000, undefined, "Directory", 1000, "/run/user/1000"],
722 ["linux", 1000, "/custom/runtime", "Directory", 1000, "/custom/runtime"],
723 ["linux", 1000, "", "Directory", 1000, ""],
724 ["linux", 1000, undefined, "Directory", 1001, undefined],
725 ["linux", 1000, undefined, "File", 1000, undefined],
726 ["linux", undefined, undefined, "Directory", 1000, undefined],
727 ["darwin", 1000, undefined, "Directory", 1000, undefined],
728 ["win32", 1000, undefined, "Directory", 1000, undefined],
729 ] as const) {
730 const environment = { PATH: "/usr/bin", XDG_RUNTIME_DIR: runtimeDir };
731 const result = yield* LocalDeviceHost.__testing.hubEnvironment(environment).pipe(
732 Effect.provideService(HostProcess.Platform, platform),
733 Effect.provideService(HostProcess.UserId, uid),
734 Effect.provideService(
735 FileSystem.FileSystem,
736 FileSystem.makeNoop({
737 stat: (path) => {
738 expect(path).toBe("/run/user/1000");
739 return Effect.succeed({ ...stat, type, uid: Option.some(owner) });
740 },
741 }),
742 ),
743 );
744 expect(result.XDG_RUNTIME_DIR).toBe(expected);
745 expect(result.PATH).toBe("/usr/bin");
746 expect(result.FORCE_COLOR).toBe("0");
747 expect(result.NO_COLOR).toBe("1");
748 expect(environment.XDG_RUNTIME_DIR).toBe(runtimeDir);
749 }
750 const missing = yield* LocalDeviceHost.__testing
751 .hubEnvironment({})
752 .pipe(
753 Effect.provideService(HostProcess.Platform, "linux"),
754 Effect.provideService(HostProcess.UserId, 1000),
755 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
756 );
757 expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
758 }).pipe(
759 Effect.scoped,
760 Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
761 ),
762);
763
764it.effect.each([
765 {
766 name: "old SDK",
767 front: "emulated webcam<N> none",
768 back: "emulated virtualscene none",
769 code: 0,
770 extra: undefined,
771 expected: "-camera-front emulated -camera-back emulated",
772 },
773 {
774 name: "imagefile-capable SDK",
775 front: "emulated imagefile:<path> none",
776 back: "emulated imagefile:<path> none",
777 code: 0,
778 extra: undefined,
779 expected: undefined,
780 },
781 {
782 name: "user overrides",
783 front: "emulated none",
784 back: "emulated none",
785 code: 0,
786 extra: "-memory 4096 -camera-front none",
787 expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
788 },
789 {
790 name: "different camera capabilities",
791 front: "emulated none",
792 back: "emulated imagefile:<path> none",
793 code: 0,
794 extra: undefined,
795 expected: "-camera-front emulated",
796 },
797 {
798 name: "failed help probe",
799 front: "emulated none",
800 back: "emulated none",
801 code: 1,
802 extra: undefined,
803 expected: undefined,
804 },
805])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
806 Effect.gen(function* () {
807 const result = yield* LocalDeviceHost.__testing
808 .hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
809 .pipe(
810 Effect.provideService(HostProcess.Platform, "darwin"),
811 Effect.provideService(HostProcess.UserId, 1000),
812 Effect.provideService(ProcessRunner.ProcessRunner, {
813 run: (input) => {
814 expect(input.command).toBe("/sdk/emulator/emulator");
815 expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
816 return Effect.succeed(
817 processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
818 );
819 },
820 }),
821 Effect.provide(NodeServices.layer),
822 );
823 expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
824 }),
825);
826
827it.effect("keeps local Android and iOS available without ffmpeg", () =>
828 Effect.gen(function* () {
829 const fs = yield* FileSystem.FileSystem;
830 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-ffmpeg-" });
831 yield* fs.makeDirectory(`${baseDir}/bin`);
832 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 0\n");
833 yield* fs.chmod(`${baseDir}/bin/xcrun`, 0o755);
834 for (const [directory, tool] of [
835 ["platform-tools", "adb"],
836 ["emulator", "emulator"],
837 ["cmdline-tools/latest/bin", "avdmanager"],
838 ]) {
839 yield* fs.makeDirectory(`${baseDir}/sdk/${directory}`, { recursive: true });
840 yield* fs.writeFileString(`${baseDir}/sdk/${directory}/${tool}`, "");
841 }
842 const onTestHost = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
843 effect.pipe(
844 Effect.provideService(HostProcess.Environment, {
845 HOME: baseDir,
846 PATH: `${baseDir}/bin`,
847 ANDROID_HOME: `${baseDir}/sdk`,
848 }),
849 Effect.provideService(HostProcess.Platform, "darwin"),
850 );
851 const host = yield* LocalDeviceHost.make().pipe(
852 Effect.provide(
853 Layer.mergeAll(
854 ServerConfig.layerTest(baseDir, baseDir),
855 NetService.layer,
856 ServerSettings.layerTest({ enableDeviceSupport: true }),
857 ),
858 ),
859 onTestHost,
860 Effect.provideService(
861 HttpClient.HttpClient,
862 HttpClient.make(() => Effect.die(new Error("Readiness must not make network requests"))),
863 ),
864 Effect.provideService(ProcessRunner.ProcessRunner, {
865 // Only the Xcode preflight may run; anything else would be an emulator video probe.
866 run: (input) =>
867 input.command === "xcode-select"
868 ? Effect.succeed(processOutput(0, `${baseDir}\n`))
869 : input.command === "xcrun"
870 ? Effect.succeed(processOutput(0))
871 : Effect.die("Platform availability must not probe emulator video"),
872 }),
873 );
874 expect((yield* onTestHost(host.summary)).platforms).toEqual([
875 { platform: "ios", available: true },
876 { platform: "android", available: true },
877 ]);
878 expect(yield* onTestHost(host.platformAvailability("android"))).toEqual({
879 platform: "android",
880 available: true,
881 });
882 expect(yield* onTestHost(host.platformAvailability("ios"))).toEqual({
883 platform: "ios",
884 available: true,
885 });
886 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
887);
888
889it.effect(
890 "constructs and inspects an unconfigured host without installing or starting helpers",
891 () =>
892 Effect.gen(function* () {
893 const fs = yield* FileSystem.FileSystem;
894 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-consent-" });
895 const host = yield* LocalDeviceHost.make().pipe(
896 Effect.provide(
897 Layer.mergeAll(
898 ServerConfig.layerTest(baseDir, baseDir),
899 NetService.layer,
900 ServerSettings.layerTest(),
901 ),
902 ),
903 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
904 Effect.provideService(HostProcess.Platform, "linux"),
905 Effect.provideService(
906 ChildProcessSpawner.ChildProcessSpawner,
907 ChildProcessSpawner.make(() =>
908 Effect.die(new Error("Host construction must not spawn processes")),
909 ),
910 ),
911 Effect.provideService(ProcessRunner.ProcessRunner, {
912 run: () => Effect.die(new Error("Host construction must not run commands")),
913 }),
914 Effect.provideService(
915 HttpClient.HttpClient,
916 HttpClient.make(() =>
917 Effect.die(new Error("Host construction must not make network requests")),
918 ),
919 ),
920 );
921 expect(yield* host.current).toBeNull();
922 const error = yield* host
923 .ensureReady(() => Effect.die("Must not install without Node"))
924 .pipe(Effect.flip, Effect.provideService(HostProcess.IsExecutable, true));
925 expect(error.message).toContain("Local device support requires Node.js");
926 expect(error.message).toContain("Install Node.js");
927 yield* host.stop;
928 expect(yield* fs.exists(`${baseDir}/tools`)).toBe(false);
929 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
930);
931
932it.effect("reads a macOS summary without Xcode probes while device support is off", () =>
933 Effect.gen(function* () {
934 const fs = yield* FileSystem.FileSystem;
935 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-disabled-" });
936 const summary = yield* LocalDeviceHost.make().pipe(
937 Effect.flatMap((host) => host.summary),
938 Effect.provide(
939 Layer.mergeAll(
940 ServerConfig.layerTest(baseDir, baseDir),
941 NetService.layer,
942 ServerSettings.layerTest(),
943 ),
944 ),
945 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
946 Effect.provideService(HostProcess.Platform, "darwin"),
947 Effect.provideService(ProcessRunner.ProcessRunner, {
948 run: () => Effect.die(new Error("Startup must not probe Xcode while devices are off")),
949 }),
950 Effect.provideService(
951 HttpClient.HttpClient,
952 HttpClient.make(() => Effect.die(new Error("Summary must not make network requests"))),
953 ),
954 );
955 expect(summary.platforms[0]).toEqual({
956 platform: "ios",
957 available: false,
958 reason: "Xcode command line tools were not found.",
959 });
960 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
961);