Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - owns Metro.
2/**
3 * One device's run state, shared by mobile:behavior and mobile:metrics: an isolated server with a
4 * long settled thread, a Metro serving a checkout with the behavior probe, and the dev client opened
5 * on it and paired with the server. Everything stops when the caller's scope closes.
6 */
7import * as NodeChildProcess from "node:child_process";
8import * as NodeOS from "node:os";
9import * as NodePath from "node:path";
10import type { ThreadId } from "@t3tools/contracts";
11import * as Console from "effect/Console";
12import * as Effect from "effect/Effect";
13import { FetchHttpClient, HttpClient } from "effect/http";
14import { ChildProcess } from "effect/process";
15
16import { APP_ID, DeviceError, makeDevice, SCHEME, type ProbeState } from "./device.ts";
17import {
18 freePort,
19 spawnLogged,
20 startEnvironment,
21 uuid,
22 type EnvironmentOptions,
23} from "./environment.ts";
24import { serveReleaseBytecode } from "./release-bytecode.ts";
25
26const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../..");
27
28/** This machine's address as the simulator sees it: the tailnet address, else the first LAN IPv4. */
29export function reachableHost(): string {
30 const tailnet = NodeChildProcess.spawnSync("tailscale", ["ip", "-4"], { encoding: "utf8" });
31 const ip = tailnet.status === 0 ? tailnet.stdout.trim().split("\n")[0] : undefined;
32 if (ip) return ip;
33 const lan = Object.values(NodeOS.networkInterfaces())
34 .flatMap((entries) => entries ?? [])
35 .find((entry) => entry.family === "IPv4" && !entry.internal);
36 return lan?.address ?? "127.0.0.1";
37}
38
39/**
40 * `dev` serves the development bundle; `release` serves the production bundle as Hermes bytecode
41 * (see release-bytecode.ts) to the same dev client.
42 */
43export type Build = "dev" | "release";
44
45/** Metro with the behavior probe compiled in, stopped with its process group when the scope ends. */
46export const startMetro = Effect.fn("session.startMetro")(function* (input: {
47 readonly host: string;
48 readonly out: string;
49 /** The checkout whose app Metro serves; defaults to this one. */
50 readonly checkout?: string;
51 readonly env?: Readonly<Record<string, string>>;
52 readonly build?: Build;
53}) {
54 const checkout = input.checkout ?? REPO_ROOT;
55 const release = input.build === "release";
56 const port = yield* freePort();
57 // In release mode the app opens the bytecode proxy on `port`, which fronts Metro.
58 const metroPort = release ? yield* freePort() : port;
59 // Its own process group, so stopping it reaches the Expo and Metro processes under npx.
60 yield* spawnLogged(
61 ChildProcess.make(
62 "npx",
63 [
64 "expo",
65 "start",
66 "--dev-client",
67 "--scheme",
68 SCHEME,
69 "--lan",
70 "--port",
71 String(metroPort),
72 ...(release ? ["--no-dev", "--minify"] : []),
73 ],
74 {
75 cwd: NodePath.join(checkout, "apps/mobile"),
76 detached: true,
77 stdin: "ignore",
78 extendEnv: true,
79 env: {
80 APP_VARIANT: "development",
81 CI: "1",
82 // Lazily fetched chunks sometimes arrive broken on pool emulators and throw SyntaxErrors.
83 EXPO_NO_METRO_LAZY: "1",
84 EXPO_PUBLIC_T3_BEHAVIOR_PROBE: "1",
85 REACT_NATIVE_PACKAGER_HOSTNAME: input.host,
86 ...input.env,
87 },
88 forceKillAfter: "10 seconds",
89 },
90 ),
91 NodePath.join(input.out, "metro.log"),
92 ).pipe(Effect.mapError((cause) => new DeviceError({ message: "Starting Metro failed.", cause })));
93 const metro = `http://${input.host}:${port}`;
94 for (let attempt = 0; ; attempt++) {
95 const ready = yield* HttpClient.get(`http://${input.host}:${metroPort}/status`).pipe(
96 Effect.flatMap((response) => response.text),
97 Effect.provide(FetchHttpClient.layer),
98 Effect.orElseSucceed(() => ""),
99 );
100 if (ready.includes("running")) break;
101 if (attempt >= 120)
102 return yield* new DeviceError({
103 message: `Metro never started; see ${input.out}/metro.log.`,
104 });
105 yield* Effect.sleep("1 second");
106 }
107 if (!release) return metro;
108 yield* Console.error("Compiling the production bundle to Hermes bytecode (a few minutes)...");
109 const bytes = yield* serveReleaseBytecode({ port, metroPort, checkout, out: input.out });
110 yield* Console.error(`Serving ${Math.round(bytes / 1024)} KB of release bytecode on ${metro}.`);
111 return metro;
112});
113
114export interface SessionOptions {
115 readonly out: string;
116 readonly host: string;
117 readonly agentDevice: string;
118 readonly targetArgs: ReadonlyArray<string>;
119 readonly deviceName: string;
120 readonly platform?: "ios" | "android";
121 readonly fold?: "closed" | "open";
122 readonly forgetOtherEnvironments: boolean;
123 /** Turns in the long settled thread every run seeds. */
124 readonly longTurns: number;
125 readonly homeThreads?: number;
126 readonly checkout?: string;
127 readonly metroEnv?: Readonly<Record<string, string>>;
128 readonly build?: Build;
129 readonly environment?: EnvironmentOptions;
130}
131
132export const startSession = Effect.fn("session.start")(function* (options: SessionOptions) {
133 const env = yield* startEnvironment({
134 baseDir: NodePath.join(options.out, "env"),
135 deviceHost: options.host,
136 ...options.environment,
137 });
138 for (let index = 0; index < (options.homeThreads ?? 0); index++) {
139 yield* env.createEmptyThread(`Bench inbox thread ${index + 1}`);
140 }
141 const tag = (yield* uuid).slice(0, 4);
142 yield* Console.error(`Seeding a ${options.longTurns}-turn thread on ${env.origin}...`);
143 const longTitle = `Long settled thread ${tag}`;
144 const longThread: ThreadId = yield* env.longThread(longTitle, options.longTurns);
145
146 const metro = yield* startMetro({
147 host: options.host,
148 out: options.out,
149 ...(options.checkout ? { checkout: options.checkout } : {}),
150 ...(options.metroEnv ? { env: options.metroEnv } : {}),
151 ...(options.build ? { build: options.build } : {}),
152 });
153 const device = makeDevice({
154 agentDevice: options.agentDevice,
155 targetArgs: options.targetArgs,
156 metro,
157 deviceName: options.deviceName,
158 });
159 yield* Console.error(`Opening the dev client against ${metro}...`);
160 // agent-device answers iOS's "Open in" prompt; the flags keep dev-menu chrome off the app.
161 const metroUrl = new URL(metro);
162 const launchUrl = `${SCHEME}://expo-development-client/?url=${encodeURIComponent(metro)}&disableOnboarding=1&__expo_disable_fab=1&__expo_disable_auto_launch=1`;
163 yield* device
164 .run(
165 [
166 "open",
167 APP_ID,
168 "--relaunch",
169 "--metro-host",
170 metroUrl.hostname,
171 "--metro-port",
172 metroUrl.port,
173 "--launch-url",
174 launchUrl,
175 ],
176 240_000,
177 )
178 .pipe(Effect.retry({ times: 2 }));
179 for (let attempt = 0; ; attempt++) {
180 const loaded = yield* device
181 .evaluate("typeof __t3Behavior")
182 .pipe(Effect.orElseSucceed(() => ""));
183 if (loaded === "object") break;
184 // iOS asks before a URL opens another app; busy hosts can miss the first accept.
185 if (options.platform !== "android" && attempt % 5 === 0) {
186 yield* device.acceptOpenPrompt.pipe(Effect.ignore);
187 }
188 if (attempt > 120)
189 return yield* new DeviceError({
190 message:
191 "The probe never loaded. Is this a dev client built from this checkout's native fingerprint?",
192 });
193 yield* Effect.sleep("2 seconds");
194 }
195 if (options.fold) yield* device.fold(options.fold);
196 const forget = (ids: ReadonlyArray<string>) =>
197 device
198 .evaluate(`__t3Behavior.forgetEnvironments(${JSON.stringify(ids)})`)
199 .pipe(Effect.andThen(Effect.sleep("3 seconds")));
200 const pair = Effect.gen(function* () {
201 const pairing = yield* env.pairingUrl();
202 yield* device.openUrl(
203 `${SCHEME}://connections/new?pairingUrl=${encodeURIComponent(pairing)}&autoConnect=1`,
204 );
205 });
206 yield* pair;
207 // Registered once pairing starts, so a stopped run never leaves its environment in the app.
208 yield* Effect.addFinalizer(() => forget([env.environmentId]).pipe(Effect.ignore));
209 const seeded = (state: ProbeState) => state.homeList !== null && longThread in state.threads;
210 // A busy pool simulator sometimes drops the first pairing link; a fresh credential retries it.
211 yield* device
212 .waitFor("the paired environment's threads on Home", seeded, 60_000)
213 .pipe(
214 Effect.catch(() =>
215 pair.pipe(
216 Effect.andThen(
217 device.waitFor("the paired environment's threads on Home", seeded, 60_000),
218 ),
219 ),
220 ),
221 );
222 // Other saved environments keep cached threads (some stuck working) that skew status cases.
223 const others = (yield* device.state).environments.filter((id) => id !== env.environmentId);
224 if (others.length > 0 && !options.forgetOtherEnvironments)
225 return yield* new DeviceError({
226 message: `The app has ${others.length} other saved environment(s). Use a device with no other connections, or pass --forget-other-environments on a disposable device.`,
227 });
228 if (others.length > 0) yield* forget(others);
229 return { env, device, metro, longThread, longTitle, seeded };
230});
231
232export type Session = Effect.Success<ReturnType<typeof startSession>>;