Open History to see the last commit
1#!/usr/bin/env node
2// The app command of e2e.config.ts: starts the dev stack of the checkout it runs in on a fresh
3// T3 home. e2e stops it with a signal, which ends the scope and the processes it started.
4import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as NetService from "@t3tools/shared/Net";
9import * as Console from "effect/Console";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Path from "effect/Path";
13import * as SecureRandom from "effect/crypto/SecureRandom";
14import * as Schedule from "effect/Schedule";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import { Argument, Command } from "effect/cli";
18import { ChildProcess, ChildProcessSpawner } from "effect/process";
19
20import { ScenarioError } from "./shell.ts";
21
22// The dev runner's web port is 5733 plus an offset. Mirror of BASE_WEB_PORT in dev-runner.ts.
23const BASE_WEB_PORT = 5733;
24// The replay agent `vp run dev` registers: free, recorded turns through the real adapter.
25const REPLAY = { instanceId: "devReplay", model: "showcase" };
26// Generated text (titles) cannot go to the replay agent: the server swaps an ACP agent for the
27// first enabled real provider, else its default, Codex. So every provider it could fall back to
28// is off and Codex is a command that only fails: no run reaches a paid model.
29// Mirror of TEXT_GENERATION_FALLBACK_DRIVERS in shared/serverSettings.
30const REAL_PROVIDERS = [
31 "codex",
32 "claudeAgent",
33 "cursor",
34 "grok",
35 "muse",
36 "pi",
37 "opencode",
38 "antigravity",
39];
40
41// The server labels its environment with the host's name, probed through these commands.
42// Captures must not depend on, or show, the machine that made them.
43const HOST_LABEL_SHIM = `#!/bin/sh
44case "$*" in
45 "--pretty" | "--get ComputerName") echo "Scenario" ;;
46 *) for real in /usr/bin /usr/sbin /bin; do
47 [ -x "$real/$(basename "$0")" ] && exec "$real/$(basename "$0")" "$@"
48 done
49 exit 127 ;;
50esac
51`;
52
53const encodeSettings = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
54
55export const prepareHome = Effect.fn("startApp.prepareHome")(function* (home: string) {
56 const fs = yield* FileSystem.FileSystem;
57 const path = yield* Path.Path;
58 yield* fs.remove(home, { recursive: true, force: true });
59 yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true });
60 yield* fs.makeDirectory(path.join(home, "bin"));
61 for (const command of ["hostnamectl", "scutil"]) {
62 const shim = path.join(home, "bin", command);
63 yield* fs.writeFileString(shim, HOST_LABEL_SHIM);
64 yield* fs.chmod(shim, 0o755);
65 }
66 // Editor discovery is cached, so the recording shim must exist before the server starts.
67 const editor = path.join(home, "bin", "cursor");
68 yield* fs.writeFileString(
69 editor,
70 `#!/bin/sh\nprintf '%s\\n' "$@" > "$(dirname "$0")/../editor-args.txt"\n`,
71 );
72 yield* fs.chmod(editor, 0o755);
73 const noModel = path.join(home, "bin/no-model");
74 yield* fs.writeFileString(noModel, "#!/bin/sh\necho 'scenarios run no model' >&2\nexit 1\n");
75 yield* fs.chmod(noModel, 0o755);
76 yield* fs.writeFileString(
77 path.join(home, "userdata/settings.json"),
78 yield* encodeSettings({
79 defaultModelSelection: REPLAY,
80 providerInstances: Object.fromEntries(
81 REAL_PROVIDERS.map((driver) => [
82 driver,
83 {
84 driver,
85 enabled: false,
86 ...(driver === "codex" ? { config: { binaryPath: noModel } } : {}),
87 },
88 ]),
89 ),
90 }),
91 );
92});
93
94/** Starts a process in the caller's scope and hands each line it prints to `onLine`. */
95export const start = Effect.fn("startApp.start")(function* (input: {
96 readonly cwd: string;
97 readonly command: string;
98 readonly args: ReadonlyArray<string>;
99 readonly env: NodeJS.ProcessEnv;
100 readonly onLine: (line: string) => Effect.Effect<void, never, FileSystem.FileSystem>;
101}) {
102 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
103 const child = yield* spawner.spawn(
104 ChildProcess.make(input.command, [...input.args], {
105 cwd: input.cwd,
106 env: input.env,
107 extendEnv: false,
108 stdin: "ignore",
109 stdout: "pipe",
110 stderr: "inherit",
111 forceKillAfter: "5 seconds",
112 }),
113 );
114 yield* child.stdout.pipe(
115 Stream.decodeText(),
116 Stream.splitLines,
117 Stream.runForEach(input.onLine),
118 Effect.ignore,
119 Effect.forkScoped,
120 );
121 return child;
122});
123
124const startApp = Effect.fn("startApp")(function* (input: {
125 readonly surface: "web" | "mobile";
126 readonly home: string;
127 readonly ports: ReadonlyArray<string>;
128}) {
129 const fs = yield* FileSystem.FileSystem;
130 const path = yield* Path.Path;
131 const net = yield* NetService.NetService;
132 const node = yield* HostProcess.ExecutablePath;
133 const checkout = yield* HostProcess.WorkingDirectory;
134 const hostEnvironment = yield* HostProcess.Environment;
135 yield* prepareHome(input.home);
136 const env = {
137 ...hostEnvironment,
138 PATH: `${path.join(input.home, "bin")}:${hostEnvironment.PATH ?? ""}`,
139 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
140 };
141 const devRunner = (mode: string, args: ReadonlyArray<string>) => [
142 "scripts/dev-runner.ts",
143 mode,
144 "--home-dir",
145 input.home,
146 "--no-seed",
147 ...args,
148 ];
149
150 if (input.surface === "web") {
151 // e2e opens the app at this host, so the web server is told to bind exactly it. Left to its
152 // default, `localhost`, it binds ::1 alone on machines that resolve the name to IPv6 first.
153 const [host = "", webPort = ""] = input.ports;
154 const origin = `http://${host}:${webPort}`;
155 const serverPort = String(yield* net.reserveLoopbackPort());
156 const token = yield* (yield* SecureRandom.SecureRandom).uuidV4();
157 const ports = ["--port", serverPort, "--dev-url", origin];
158 const webEnv = { ...env, T3CODE_PORT_OFFSET: String(Number(webPort) - BASE_WEB_PORT) };
159 const server = yield* start({
160 cwd: checkout,
161 command: node,
162 args: devRunner("dev:server", ports),
163 env: {
164 ...webEnv,
165 T3CODE_DEV_ALLOWED_ORIGINS: origin,
166 // Makes the startup pairing link reusable, so every test can sign in with it.
167 T3CODE_DEV_AUTH_TOKEN: `${token}${token}`.replaceAll("-", ""),
168 },
169 onLine: (line) => {
170 const url = /pairingUrl:\s*(\S+)/.exec(line)?.[1];
171 if (url === undefined) return Console.log(line);
172 // The link is a credential: it goes to a file the tests read, never to the log.
173 const { pathname, search, hash } = new URL(url);
174 return fs
175 .writeFileString(path.join(input.home, "pairing-path"), `${pathname}${search}${hash}`)
176 .pipe(Effect.ignore);
177 },
178 });
179 const web = yield* start({
180 cwd: checkout,
181 command: node,
182 args: devRunner("dev:web", [...ports, "--", "--host", host]),
183 env: webEnv,
184 onLine: Console.log,
185 });
186 // A web server that came up on another loopback address would leave e2e waiting out its
187 // whole startup timeout; say so at once instead.
188 const boundElsewhere = Effect.gen(function* () {
189 const elsewhere = host === "::1" ? "127.0.0.1" : "::1";
190 if (yield* net.hasListenerOnHost(Number(webPort), host)) return yield* Effect.never;
191 if (!(yield* net.hasListenerOnHost(Number(webPort), elsewhere))) {
192 return yield* new ScenarioError({ message: "The web server is not listening yet." });
193 }
194 yield* Console.error(
195 `The web server listens on ${elsewhere}:${webPort}, not on ${host}: it ignored --host.`,
196 );
197 return 1;
198 }).pipe(
199 Effect.retry({
200 schedule: Schedule.spaced("1 second"),
201 while: (error) => error._tag === "ScenarioError",
202 }),
203 );
204 return yield* Effect.raceAll([server.exitCode, web.exitCode, boundElsewhere]);
205 }
206
207 // The device is another machine: the server listens on every interface, and Metro serves the
208 // dev client its JavaScript. Tests mint their own pairing links, so the startup one is dropped.
209 const [serverPort = "", metroPort = "", host = ""] = input.ports;
210 const server = yield* start({
211 cwd: checkout,
212 command: node,
213 args: devRunner("dev:server", ["--host", "0.0.0.0", "--port", serverPort]),
214 env,
215 onLine: (line) => (line.includes("pairingUrl:") ? Effect.void : Console.log(line)),
216 });
217 yield* net.hasListenerOnHost(Number(serverPort), "127.0.0.1").pipe(
218 Effect.filterOrFail(
219 (listening) => listening,
220 () => new ScenarioError({ message: "The server is not listening yet." }),
221 ),
222 Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 600 }),
223 );
224 const metro = yield* start({
225 cwd: path.join(checkout, "apps/mobile"),
226 command: "npx",
227 args: ["expo", "start", "--dev-client", "--scheme", "t3code-dev", "--lan", "--port", metroPort],
228 env: {
229 ...env,
230 APP_VARIANT: "development",
231 CI: "1",
232 // Lazily fetched chunks sometimes arrive broken on pool devices.
233 EXPO_NO_METRO_LAZY: "1",
234 REACT_NATIVE_PACKAGER_HOSTNAME: host,
235 },
236 onLine: Console.log,
237 });
238 return yield* Effect.raceFirst(server.exitCode, metro.exitCode);
239});
240
241const command = Command.make(
242 "start-app",
243 {
244 surface: Argument.Literals("surface", ["web", "mobile"]).pipe(
245 Argument.withDescription(
246 "web: server and Vite. mobile: server on every interface and Metro.",
247 ),
248 ),
249 home: Argument.String("t3-home").pipe(Argument.withDescription("T3 home to recreate.")),
250 ports: Argument.String("port").pipe(
251 Argument.withDescription(
252 "web: <host> <web-port>. mobile: <server-port> <metro-port> <host>.",
253 ),
254 Argument.variadic(),
255 ),
256 },
257 (input) =>
258 startApp(input).pipe(
259 Effect.flatMap((exitCode) =>
260 Effect.sync(() => {
261 process.exitCode = Number(exitCode) || 1;
262 }),
263 ),
264 ),
265);
266
267if (import.meta.main) {
268 Command.run(command, { version: "0.0.0" }).pipe(
269 Effect.scoped,
270 Effect.provide([NodeServices.layer, NodeCrypto.layer, NetService.layer]),
271 NodeRuntime.runMain,
272 );
273}