@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 847 lines 33 KB
Raw
1 import { describe, expect, it } from "@effect/vitest";
2 import * as NodePath from "@effect/platform-node/NodePath";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Deferred from "effect/Deferred";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as Layer from "effect/Layer";
8 import * as Option from "effect/Option";
9 import * as Path from "effect/Path";
10 import * as PlatformError from "effect/PlatformError";
11 import * as Ref from "effect/Ref";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Sink from "effect/Sink";
14 import * as Stream from "effect/Stream";
15
16 import * as LocalDeviceHost from "./LocalDeviceHost.ts";
17 import * as NodeServices from "@effect/platform-node/NodeServices";
18 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19 import { HttpClient, HttpClientResponse } from "effect/http";
20 import * as NetService from "@t3tools/shared/Net";
21 import * as ServerConfig from "../config.ts";
22 import * as ProcessRunner from "../processRunner.ts";
23 import {
24 AGENT_DEVICE_VERSION,
25 DEVICE_HUB_VERSION,
26 agentDeviceStateDir,
27 } from "./DeviceToolchain.ts";
28
29 const 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
40 const agentFixture = Effect.fn("agentFixture")(function* (
41 startup: (
42 stateDir: string,
43 ) => Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
44 avdOutput: ProcessRunner.ProcessRunOutput = processOutput(0),
45 previousDaemon?: typeof LocalDeviceHost.__testing.AgentDeviceDaemonFile.Type,
46 environment?: NodeJS.ProcessEnv,
47 ) {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" });
51 const hub = {
52 running: true,
53 spawnFails: false,
54 cleanup: Effect.void,
55 cameraHelp: "",
56 cameraProbes: 0,
57 spawnedEnvironments: [] as Array<NodeJS.ProcessEnv | undefined>,
58 };
59 const daemonStopRequested = yield* Deferred.make<ReadonlyArray<string>>();
60 const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata"));
61 const daemonHealthy = yield* Ref.make(true);
62 const runs: Array<ProcessRunner.ProcessRunInput> = [];
63 for (const [name, version, entry] of [
64 ["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"],
65 ["agent-device", AGENT_DEVICE_VERSION, "bin/agent-device.mjs"],
66 ]) {
67 const installDir = path.join(baseDir, "tools", name!, version!);
68 const entryPath = path.join(installDir, "node_modules", name!, entry!);
69 yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
70 yield* fs.writeFileString(entryPath, "");
71 yield* fs.writeFileString(path.join(installDir, ".install-complete"), version!);
72 }
73 if (previousDaemon) {
74 yield* fs.makeDirectory(stateDir, { recursive: true });
75 yield* fs.writeFileString(path.join(stateDir, "daemon.json"), JSON.stringify(previousDaemon));
76 }
77 const host = yield* LocalDeviceHost.make().pipe(
78 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
79 Effect.provideService(HostProcess.Environment, environment ?? { HOME: baseDir, PATH: "" }),
80 Effect.provideService(HostProcess.IsExecutable, false),
81 Effect.provideService(HostProcess.Platform, "darwin"),
82 Effect.provideService(
83 ChildProcessSpawner.ChildProcessSpawner,
84 ChildProcessSpawner.make((command) =>
85 hub.spawnFails
86 ? Effect.fail(
87 PlatformError.systemError({
88 _tag: "NotFound",
89 module: "ChildProcess",
90 method: "spawn",
91 description: "Hub entry missing",
92 }),
93 )
94 : Effect.addFinalizer(() => hub.cleanup).pipe(
95 Effect.tap(() =>
96 Effect.sync(() =>
97 hub.spawnedEnvironments.push(
98 (
99 command as unknown as {
100 readonly options: { readonly env?: NodeJS.ProcessEnv };
101 }
102 ).options.env,
103 ),
104 ),
105 ),
106 Effect.as(
107 ChildProcessSpawner.makeHandle({
108 pid: ChildProcessSpawner.ProcessId(123),
109 stdout: Stream.empty,
110 stderr: Stream.empty,
111 all: Stream.empty,
112 exitCode: Effect.never,
113 isRunning: Effect.sync(() => hub.running),
114 kill: () => Effect.void,
115 stdin: Sink.drain,
116 getInputFd: () => Sink.drain,
117 getOutputFd: () => Stream.empty,
118 unref: Effect.succeed(Effect.void),
119 }),
120 ),
121 ),
122 ),
123 ),
124 Effect.provideService(ProcessRunner.ProcessRunner, {
125 run: (input) => {
126 runs.push(input);
127 return input.args.includes("devices")
128 ? startup(stateDir)
129 : input.args.includes("daemon")
130 ? Deferred.succeed(daemonStopRequested, input.args).pipe(Effect.as(processOutput(0)))
131 : Effect.succeed(
132 input.args.includes("-list-avds")
133 ? avdOutput
134 : input.args[0]?.startsWith("-help-camera-")
135 ? (hub.cameraProbes++, processOutput(0, hub.cameraHelp))
136 : processOutput(0),
137 );
138 },
139 }),
140 Effect.provideService(
141 HttpClient.HttpClient,
142 HttpClient.make((request) =>
143 Ref.get(daemonHealthy).pipe(
144 Effect.map((healthy) =>
145 HttpClientResponse.fromWeb(
146 request,
147 new Response("ok", {
148 status: request.url.endsWith("/health") && !healthy ? 503 : 200,
149 }),
150 ),
151 ),
152 ),
153 ),
154 ),
155 );
156 yield* host.ensureReady(() => Effect.void);
157 return { host, fs, baseDir, stateDir, hub, daemonHealthy, daemonStopRequested, runs };
158 });
159
160 describe("AgentDevice startup", () => {
161 it.effect("restarts a cached daemon that no longer answers its health check", () =>
162 Effect.gen(function* () {
163 const fs = yield* FileSystem.FileSystem;
164 let attempts = 0;
165 const { host, daemonHealthy } = yield* agentFixture((stateDir) =>
166 Effect.gen(function* () {
167 attempts++;
168 yield* fs
169 .writeFileString(
170 `${stateDir}/daemon.json`,
171 JSON.stringify({ httpPort: 12345 + attempts, token: `token-${attempts}` }),
172 )
173 .pipe(Effect.orDie);
174 return processOutput(0);
175 }),
176 );
177 const first = yield* host.ensureAgentReady(() => Effect.void);
178 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
179 first.agentDevice,
180 );
181 expect(attempts).toBe(1);
182
183 yield* Ref.set(daemonHealthy, false);
184 const restarted = yield* host.ensureAgentReady(() => Effect.void);
185 expect(attempts).toBe(2);
186 expect(restarted.agentDevice).toMatchObject({
187 baseUrl: "http://127.0.0.1:12347",
188 token: "token-2",
189 });
190 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
191 );
192
193 it.effect("uses the SDK a later shell environment selects", () =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
196 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-sdk-" });
197 const standard = `${home}/Library/Android/sdk`;
198 const profile = `${home}/profile-sdk`;
199 for (const root of [standard, profile]) {
200 for (const tool of ["platform-tools/adb", "emulator/emulator"]) {
201 yield* fs.makeDirectory(`${root}/${tool.split("/")[0]}`, { recursive: true });
202 yield* fs.writeFileString(`${root}/${tool}`, "");
203 }
204 }
205 const environment: NodeJS.ProcessEnv = { HOME: home, PATH: "" };
206 const { host, hub, runs } = yield* agentFixture(
207 (stateDir) =>
208 fs
209 .writeFileString(
210 `${stateDir}/daemon.json`,
211 JSON.stringify({ httpPort: 12345, token: "token" }),
212 )
213 .pipe(Effect.orDie, Effect.as(processOutput(0))),
214 processOutput(0),
215 undefined,
216 environment,
217 );
218 // The desktop shell snapshot updates the server's environment after the host exists.
219 environment.ANDROID_HOME = profile;
220 hub.running = false;
221 runs.length = 0;
222 const ready = yield* host.ensureAgentReady(() => Effect.void);
223 yield* ready.run("emulator", ["-list-avds"]);
224
225 const emulator = `${profile}/emulator/emulator`;
226 const sdkRuns = runs.filter(
227 (run) => run.command === emulator || run.args.includes("devices"),
228 );
229 // Two hub camera probes, the agent-device launch, and the emulator command.
230 expect(sdkRuns.map((run) => run.args[0])).toEqual([
231 "-help-camera-front",
232 "-help-camera-back",
233 expect.stringContaining("agent-device"),
234 "-list-avds",
235 ]);
236 for (const run of sdkRuns) {
237 expect(run.env?.ANDROID_HOME).toBe(profile);
238 expect(run.env?.PATH?.split(":")[0]).toBe(`${profile}/platform-tools`);
239 }
240 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
241 );
242
243 it.effect(
244 "drops emulated camera overrides once a running hub's emulator supports image files",
245 () =>
246 Effect.gen(function* () {
247 const fs = yield* FileSystem.FileSystem;
248 const sdk = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-camera-sdk-" });
249 for (const tool of ["platform-tools/adb", "emulator/emulator"]) {
250 yield* fs.makeDirectory(`${sdk}/${tool.split("/")[0]}`, { recursive: true });
251 yield* fs.writeFileString(`${sdk}/${tool}`, "");
252 }
253 const environment: NodeJS.ProcessEnv = { HOME: sdk, PATH: "", ANDROID_HOME: sdk };
254 const { host, hub } = yield* agentFixture(
255 () => Effect.succeed(processOutput(0)),
256 processOutput(0),
257 undefined,
258 environment,
259 );
260 // ensureReady is the hub's first start; the probe ran with the fixture's empty help.
261 hub.cameraHelp = "emulated none";
262 hub.running = false;
263 yield* host.ensureReady(() => Effect.void);
264 hub.running = true;
265 expect(hub.spawnedEnvironments.at(-1)?.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(
266 "-camera-front emulated -camera-back emulated",
267 );
268
269 // A live hub with an unchanged emulator answers without probing it.
270 const probes = hub.cameraProbes;
271 yield* host.ensureReady(() => Effect.void);
272 expect(hub.cameraProbes).toBe(probes);
273
274 // The SDK's emulator is updated to one that renders image files while the hub keeps running.
275 yield* fs.writeFileString(`${sdk}/emulator/emulator`, "updated");
276 hub.cameraHelp = "emulated imagefile:<filename> none";
277 yield* host.ensureReady(() => Effect.void);
278 expect(hub.spawnedEnvironments.at(-1)?.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBeUndefined();
279 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
280 );
281
282 it.effect("reports an incompatible lock immediately and retains it for manual repair", () =>
283 Effect.gen(function* () {
284 const result = processOutput(
285 1,
286 JSON.stringify({
287 success: false,
288 error: {
289 message: "private command output",
290 details: {
291 reason: "daemon_registration_unproven",
292 inspection: { state: "unproven", reason: "non-directory" },
293 },
294 },
295 }),
296 );
297 const { host, fs, stateDir } = yield* agentFixture(() => Effect.succeed(result));
298 const lock = `${stateDir}/daemon.lock`;
299 const legacyOwner = JSON.stringify({ pid: 85669, processStartTime: "old start time" });
300 yield* fs.writeFileString(lock, legacyOwner);
301 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
302 expect(error).toMatchObject({
303 _tag: "AgentDeviceStartError",
304 reason: "daemon_lock_not_directory",
305 exitCode: 1,
306 cause: result,
307 });
308 expect(error.message).toContain("Daemon registration ownership could not be verified");
309 expect(error.message).toContain("daemon.lock is not a directory");
310 expect(error.message).toContain(stateDir);
311 expect(error.message).toContain("original CLI");
312 expect(error.message).not.toContain("private command output");
313 expect(yield* fs.readFileString(lock)).toBe(legacyOwner);
314 expect(yield* host.current).not.toBeNull();
315 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
316 );
317
318 it.effect("reports unknown nonzero exits without exposing arbitrary command output", () =>
319 Effect.gen(function* () {
320 const result = processOutput(2, "invalid JSON", "private credentials");
321 const { host, stateDir } = yield* agentFixture(() => Effect.succeed(result));
322 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
323 expect(error).toMatchObject({
324 _tag: "AgentDeviceStartError",
325 reason: "command_failed",
326 exitCode: 2,
327 cause: result,
328 });
329 expect(error.message).toContain("exit code 2");
330 expect(error.message).toContain(stateDir);
331 expect(error.message).not.toContain("private credentials");
332 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
333 );
334
335 it.effect("preserves process execution failures instead of waiting for a daemon file", () =>
336 Effect.gen(function* () {
337 const cause = new ProcessRunner.ProcessSpawnError({
338 command: "/missing/node",
339 argumentCount: 3,
340 cause: new Error("missing executable"),
341 });
342 const { host } = yield* agentFixture(() => Effect.fail(cause));
343 const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip);
344 expect(error).toMatchObject({
345 _tag: "DeviceHostError",
346 step: "starting agent tools",
347 cause,
348 });
349 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
350 );
351
352 it.effect("uses a registered daemon when reading startup command output fails", () =>
353 Effect.gen(function* () {
354 const fs = yield* FileSystem.FileSystem;
355 const cause = new ProcessRunner.ProcessReadError({
356 command: process.execPath,
357 argumentCount: 3,
358 stream: "stdout",
359 cause: new Error("output read failed after registration"),
360 });
361 let attempts = 0;
362 const { host } = yield* agentFixture((stateDir) =>
363 Effect.gen(function* () {
364 attempts++;
365 yield* fs
366 .writeFileString(
367 `${stateDir}/daemon.json`,
368 JSON.stringify({ httpPort: 12345, token: "test-token" }),
369 )
370 .pipe(Effect.orDie);
371 return yield* cause;
372 }),
373 );
374 const ready = yield* host.ensureAgentReady(() => Effect.void);
375 expect(ready.agentDevice).toMatchObject({
376 baseUrl: "http://127.0.0.1:12345",
377 token: "test-token",
378 });
379 expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
380 ready.agentDevice,
381 );
382 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
383 expect(attempts).toBe(1);
384 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
385 );
386
387 it.effect("keeps releasing agent sessions while a dead hub fails to restart and after", () =>
388 Effect.gen(function* () {
389 const fs = yield* FileSystem.FileSystem;
390 const { host, hub } = yield* agentFixture((stateDir) =>
391 fs
392 .writeFileString(
393 `${stateDir}/daemon.json`,
394 JSON.stringify({ httpPort: 12345, token: "test-token" }),
395 )
396 .pipe(Effect.orDie, Effect.as(processOutput(0))),
397 );
398 yield* host.ensureAgentReady(() => Effect.void);
399 hub.running = false;
400 hub.spawnFails = true;
401 expect((yield* host.ensureReady(() => Effect.void).pipe(Effect.result))._tag).toBe("Failure");
402 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
403 hub.spawnFails = false;
404 yield* host.ensureReady(() => Effect.void);
405 expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
406 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
407 );
408
409 it.effect("stops a previous server's daemon with the agent-device version it recorded", () =>
410 Effect.gen(function* () {
411 const path = yield* Path.Path;
412 const { host, fs, baseDir, runs } = yield* agentFixture(
413 () => Effect.die("A session that never readies agent tools must not start the daemon"),
414 processOutput(0),
415 { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" },
416 );
417 const olderInstall = path.join(baseDir, "tools", "agent-device", "0.0.1");
418 const olderEntry = path.join(
419 olderInstall,
420 "node_modules",
421 "agent-device",
422 "bin",
423 "agent-device.mjs",
424 );
425 yield* fs.makeDirectory(path.dirname(olderEntry), { recursive: true });
426 yield* fs.writeFileString(olderEntry, "");
427 yield* fs.writeFileString(path.join(olderInstall, ".install-complete"), "0.0.1");
428 yield* host.stop;
429 expect(runs.find((run) => run.args.includes("daemon"))?.args[0]).toBe(olderEntry);
430 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
431 );
432
433 // regression: #33552 a daemon left by a previous server survived every later graceful quit
434 it.effect("stops a previous server's daemon with the current pin when its version is gone", () =>
435 Effect.gen(function* () {
436 const path = yield* Path.Path;
437 const { host, baseDir, stateDir, runs } = yield* agentFixture(
438 () => Effect.die("A session that never readies agent tools must not start the daemon"),
439 processOutput(0),
440 { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" },
441 );
442 yield* host.stop;
443 expect(runs.find((run) => run.args.includes("daemon"))?.args).toEqual([
444 path.join(
445 baseDir,
446 "tools",
447 "agent-device",
448 AGENT_DEVICE_VERSION,
449 "node_modules",
450 "agent-device",
451 "bin",
452 "agent-device.mjs",
453 ),
454 "daemon",
455 "stop",
456 "--state-dir",
457 stateDir,
458 ]);
459 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
460 );
461
462 it.effect("drops a dead daemon's record without running agent-device when the host stops", () =>
463 Effect.gen(function* () {
464 // Above the Linux and macOS PID limits, so never a live process.
465 const deadPid = 4_194_305;
466 const path = yield* Path.Path;
467 const { host, fs, stateDir, runs } = yield* agentFixture(
468 () => Effect.die("A session that never readies agent tools must not start the daemon"),
469 processOutput(0),
470 { httpPort: 12345, token: "previous-token", pid: deadPid, version: AGENT_DEVICE_VERSION },
471 );
472 yield* host.stop;
473 expect(runs.filter((run) => run.args.includes("daemon"))).toEqual([]);
474 expect(yield* fs.exists(path.join(stateDir, "daemon.json"))).toBe(false);
475 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
476 );
477
478 it.effect("stops the agent daemon while the hub is still shutting down", () =>
479 Effect.gen(function* () {
480 const fs = yield* FileSystem.FileSystem;
481 const { host, hub, stateDir, daemonStopRequested } = yield* agentFixture((stateDir) =>
482 fs
483 .writeFileString(
484 `${stateDir}/daemon.json`,
485 JSON.stringify({ httpPort: 12345, token: "test-token" }),
486 )
487 .pipe(Effect.orDie, Effect.as(processOutput(0))),
488 );
489 yield* host.ensureAgentReady(() => Effect.void);
490 const hubExited = yield* Deferred.make<void>();
491 hub.cleanup = Deferred.await(hubExited);
492 const stopping = yield* Effect.forkChild(host.stop);
493 expect((yield* Deferred.await(daemonStopRequested)).slice(1)).toEqual([
494 "daemon",
495 "stop",
496 "--state-dir",
497 stateDir,
498 ]);
499 yield* Deferred.succeed(hubExited, undefined);
500 yield* Fiber.join(stopping);
501 expect(yield* fs.exists(`${stateDir}/hub.json`)).toBe(false);
502 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
503 );
504 });
505
506 const diagnose = (
507 files: ReadonlyArray<string>,
508 environment: NodeJS.ProcessEnv,
509 platform: NodeJS.Platform = "darwin",
510 ) =>
511 LocalDeviceHost.__testing.platformReason("android").pipe(
512 Effect.provideService(HostProcess.Environment, environment),
513 Effect.provideService(HostProcess.Platform, platform),
514 Effect.provideService(
515 FileSystem.FileSystem,
516 FileSystem.makeNoop({
517 exists: (file) => Effect.succeed(files.includes(file)),
518 }),
519 ),
520 Effect.provide(platform === "win32" ? NodePath.layerWin32 : NodePath.layerPosix),
521 );
522
523 describe("Android SDK availability", () => {
524 it.effect("uses the standard Windows SDK without probing PATH", () =>
525 Effect.gen(function* () {
526 const root = "C:\\Users\\test\\AppData\\Local\\Android\\Sdk";
527 const probes: string[] = [];
528 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
529 Effect.provideService(HostProcess.Environment, {
530 USERPROFILE: "C:\\Users\\test",
531 LOCALAPPDATA: "C:\\Users\\test\\AppData\\Local",
532 PATH: "\\\\slow-share\\tools;C:\\other-tools",
533 }),
534 Effect.provideService(HostProcess.Platform, "win32"),
535 Effect.provideService(
536 FileSystem.FileSystem,
537 FileSystem.makeNoop({
538 exists: (file) =>
539 Effect.sync(() => {
540 probes.push(file);
541 return file === `${root}\\platform-tools\\adb.exe`;
542 }),
543 realPath: () => Effect.die("Standard SDK must not resolve PATH executables"),
544 }),
545 ),
546 Effect.provide(NodePath.layerWin32),
547 );
548 expect(sdk).toMatchObject({ root, adb: true });
549 expect(probes.filter((file) => !file.startsWith("C:\\Users\\test\\"))).toEqual([]);
550 }),
551 );
552
553 it.effect("falls back to adb on the Windows Path without resolving missing entries", () =>
554 Effect.gen(function* () {
555 const root = "D:\\Android\\Sdk";
556 const resolved: string[] = [];
557 const sdk = yield* LocalDeviceHost.__testing.androidSdk.pipe(
558 Effect.provideService(HostProcess.Environment, {
559 USERPROFILE: "C:\\Users\\test",
560 Path: "C:\\missing;C:\\shims",
561 }),
562 Effect.provideService(HostProcess.Platform, "win32"),
563 Effect.provideService(
564 FileSystem.FileSystem,
565 FileSystem.makeNoop({
566 exists: (file) =>
567 Effect.succeed(
568 file === "C:\\shims\\adb.exe" || file === `${root}\\platform-tools\\adb.exe`,
569 ),
570 realPath: (file) =>
571 Effect.sync(() => {
572 resolved.push(file);
573 return `${root}\\platform-tools\\adb.exe`;
574 }),
575 }),
576 ),
577 Effect.provide(NodePath.layerWin32),
578 );
579 expect(sdk).toMatchObject({ root, adb: true });
580 expect(resolved).toEqual(["C:\\shims\\adb.exe"]);
581 }),
582 );
583
584 // regression: #12017 detect unsupported legacy Android command-line tools
585 it.effect("explains how to upgrade legacy command-line tools in the standard macOS SDK", () =>
586 Effect.gen(function* () {
587 const root = "/test/home/Library/Android/sdk";
588 const reason = yield* diagnose(
589 [`${root}/platform-tools/adb`, `${root}/emulator/emulator`, `${root}/tools/bin/avdmanager`],
590 { HOME: "/test/home" },
591 );
592 expect(reason).toContain("older, unsupported version");
593 expect(reason).toContain(root);
594 expect(reason).toContain(
595 "Install Android SDK Command-line Tools (latest) in Android Studio's SDK Manager under SDK Tools.",
596 );
597 }),
598 );
599
600 it.effect("accepts the latest command-line tools when legacy tools are also installed", () =>
601 Effect.gen(function* () {
602 const reason = yield* diagnose(
603 [
604 "/sdk/platform-tools/adb",
605 "/sdk/emulator/emulator",
606 "/sdk/tools/bin/avdmanager",
607 "/sdk/cmdline-tools/latest/bin/avdmanager",
608 ],
609 { ANDROID_HOME: "/sdk" },
610 );
611 expect(reason).toBeNull();
612 }),
613 );
614
615 // regression: #38268 an ANDROID_HOME that is not an SDK must not stop detection
616 it.effect("falls back past an ANDROID_HOME that is not an SDK", () =>
617 Effect.gen(function* () {
618 const complete = [
619 "/parent/sdk/platform-tools/adb",
620 "/parent/sdk/emulator/emulator",
621 "/parent/sdk/cmdline-tools/latest/bin/avdmanager",
622 ];
623 for (const environment of [
624 { ANDROID_HOME: "/parent", ANDROID_SDK_ROOT: "/parent/sdk" },
625 { ANDROID_HOME: "/parent", PATH: "/parent/sdk/platform-tools" },
626 ]) {
627 expect(yield* diagnose(complete, environment)).toBeNull();
628 }
629 }),
630 );
631
632 it.effect("discovers the standard macOS SDK without ANDROID_HOME", () =>
633 Effect.gen(function* () {
634 const root = "/test/home/Library/Android/sdk";
635 const reason = yield* diagnose(
636 [
637 `${root}/platform-tools/adb`,
638 `${root}/emulator/emulator`,
639 `${root}/cmdline-tools/latest/bin/avdmanager`,
640 ],
641 { HOME: "/test/home" },
642 );
643 expect(reason).toBeNull();
644 }),
645 );
646 });
647
648 it.effect(
649 "recovers an owned Linux runtime directory without overriding explicit environments",
650 () =>
651 Effect.gen(function* () {
652 const fs = yield* FileSystem.FileSystem;
653 const directory = yield* fs.makeTempDirectoryScoped();
654 const stat = yield* fs.stat(directory);
655 for (const [platform, uid, runtimeDir, type, owner, expected] of [
656 ["linux", 1000, undefined, "Directory", 1000, "/run/user/1000"],
657 ["linux", 1000, "/custom/runtime", "Directory", 1000, "/custom/runtime"],
658 ["linux", 1000, "", "Directory", 1000, ""],
659 ["linux", 1000, undefined, "Directory", 1001, undefined],
660 ["linux", 1000, undefined, "File", 1000, undefined],
661 ["linux", undefined, undefined, "Directory", 1000, undefined],
662 ["darwin", 1000, undefined, "Directory", 1000, undefined],
663 ["win32", 1000, undefined, "Directory", 1000, undefined],
664 ] as const) {
665 const environment = { PATH: "/usr/bin", XDG_RUNTIME_DIR: runtimeDir };
666 const result = yield* LocalDeviceHost.__testing.hubEnvironment(environment).pipe(
667 Effect.provideService(HostProcess.Platform, platform),
668 Effect.provideService(HostProcess.UserId, uid),
669 Effect.provideService(
670 FileSystem.FileSystem,
671 FileSystem.makeNoop({
672 stat: (path) => {
673 expect(path).toBe("/run/user/1000");
674 return Effect.succeed({ ...stat, type, uid: Option.some(owner) });
675 },
676 }),
677 ),
678 );
679 expect(result.XDG_RUNTIME_DIR).toBe(expected);
680 expect(result.PATH).toBe("/usr/bin");
681 expect(result.FORCE_COLOR).toBe("0");
682 expect(result.NO_COLOR).toBe("1");
683 expect(environment.XDG_RUNTIME_DIR).toBe(runtimeDir);
684 }
685 const missing = yield* LocalDeviceHost.__testing
686 .hubEnvironment({})
687 .pipe(
688 Effect.provideService(HostProcess.Platform, "linux"),
689 Effect.provideService(HostProcess.UserId, 1000),
690 Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
691 );
692 expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
693 }).pipe(
694 Effect.scoped,
695 Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
696 ),
697 );
698
699 it.effect.each([
700 {
701 name: "old SDK",
702 front: "emulated webcam<N> none",
703 back: "emulated virtualscene none",
704 code: 0,
705 extra: undefined,
706 expected: "-camera-front emulated -camera-back emulated",
707 },
708 {
709 name: "imagefile-capable SDK",
710 front: "emulated imagefile:<path> none",
711 back: "emulated imagefile:<path> none",
712 code: 0,
713 extra: undefined,
714 expected: undefined,
715 },
716 {
717 name: "user overrides",
718 front: "emulated none",
719 back: "emulated none",
720 code: 0,
721 extra: "-memory 4096 -camera-front none",
722 expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
723 },
724 {
725 name: "different camera capabilities",
726 front: "emulated none",
727 back: "emulated imagefile:<path> none",
728 code: 0,
729 extra: undefined,
730 expected: "-camera-front emulated",
731 },
732 {
733 name: "failed help probe",
734 front: "emulated none",
735 back: "emulated none",
736 code: 1,
737 extra: undefined,
738 expected: undefined,
739 },
740 ])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
741 Effect.gen(function* () {
742 const result = yield* LocalDeviceHost.__testing
743 .hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
744 .pipe(
745 Effect.provideService(HostProcess.Platform, "darwin"),
746 Effect.provideService(HostProcess.UserId, 1000),
747 Effect.provideService(ProcessRunner.ProcessRunner, {
748 run: (input) => {
749 expect(input.command).toBe("/sdk/emulator/emulator");
750 expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
751 return Effect.succeed(
752 processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
753 );
754 },
755 }),
756 Effect.provide(NodeServices.layer),
757 );
758 expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
759 }),
760 );
761
762 it.effect("keeps local Android and iOS available without ffmpeg", () =>
763 Effect.gen(function* () {
764 const fs = yield* FileSystem.FileSystem;
765 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-ffmpeg-" });
766 yield* fs.makeDirectory(`${baseDir}/bin`);
767 yield* fs.writeFileString(`${baseDir}/bin/xcrun`, "#!/bin/sh\nexit 0\n");
768 yield* fs.chmod(`${baseDir}/bin/xcrun`, 0o755);
769 for (const [directory, tool] of [
770 ["platform-tools", "adb"],
771 ["emulator", "emulator"],
772 ["cmdline-tools/latest/bin", "avdmanager"],
773 ]) {
774 yield* fs.makeDirectory(`${baseDir}/sdk/${directory}`, { recursive: true });
775 yield* fs.writeFileString(`${baseDir}/sdk/${directory}/${tool}`, "");
776 }
777 const onTestHost = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
778 effect.pipe(
779 Effect.provideService(HostProcess.Environment, {
780 HOME: baseDir,
781 PATH: `${baseDir}/bin`,
782 ANDROID_HOME: `${baseDir}/sdk`,
783 }),
784 Effect.provideService(HostProcess.Platform, "darwin"),
785 );
786 const host = yield* LocalDeviceHost.make().pipe(
787 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
788 onTestHost,
789 Effect.provideService(
790 HttpClient.HttpClient,
791 HttpClient.make(() => Effect.die(new Error("Readiness must not make network requests"))),
792 ),
793 Effect.provideService(ProcessRunner.ProcessRunner, {
794 run: () => Effect.die("Platform availability must not probe emulator video"),
795 }),
796 );
797 expect((yield* onTestHost(host.summary)).platforms).toEqual([
798 { platform: "ios", available: true },
799 { platform: "android", available: true },
800 ]);
801 expect(yield* onTestHost(host.platformAvailability("android"))).toEqual({
802 platform: "android",
803 available: true,
804 });
805 expect(yield* onTestHost(host.platformAvailability("ios"))).toEqual({
806 platform: "ios",
807 available: true,
808 });
809 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
810 );
811
812 it.effect(
813 "constructs and inspects an unconfigured host without installing or starting helpers",
814 () =>
815 Effect.gen(function* () {
816 const fs = yield* FileSystem.FileSystem;
817 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-consent-" });
818 const host = yield* LocalDeviceHost.make().pipe(
819 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
820 Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }),
821 Effect.provideService(HostProcess.Platform, "linux"),
822 Effect.provideService(
823 ChildProcessSpawner.ChildProcessSpawner,
824 ChildProcessSpawner.make(() =>
825 Effect.die(new Error("Host construction must not spawn processes")),
826 ),
827 ),
828 Effect.provideService(ProcessRunner.ProcessRunner, {
829 run: () => Effect.die(new Error("Host construction must not run commands")),
830 }),
831 Effect.provideService(
832 HttpClient.HttpClient,
833 HttpClient.make(() =>
834 Effect.die(new Error("Host construction must not make network requests")),
835 ),
836 ),
837 );
838 expect(yield* host.current).toBeNull();
839 const error = yield* host
840 .ensureReady(() => Effect.die("Must not install without Node"))
841 .pipe(Effect.flip, Effect.provideService(HostProcess.IsExecutable, true));
842 expect(error.message).toContain("Local device support requires Node.js");
843 expect(error.message).toContain("Install Node.js");
844 yield* host.stop;
845 expect(yield* fs.exists(`${baseDir}/tools`)).toBe(false);
846 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
847 );