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/** Captures must not depend on, or show, the machine that made them. */
42/** Where a scenario serves a fake Linear API; nothing listens there unless one does. */
43export const SCENARIO_LINEAR_PORT = 13_997;
44
45export const SCENARIO_MACHINE_ENV = {
46 T3CODE_ENVIRONMENT_LABEL: "Scenario",
47 T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop",
48 T3CODE_LINEAR_API_URL: `http://127.0.0.1:${SCENARIO_LINEAR_PORT}/graphql`,
49};
50
51const encodeSettings = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
52
53export const prepareHome = Effect.fn("startApp.prepareHome")(function* (home: string) {
54 const fs = yield* FileSystem.FileSystem;
55 const path = yield* Path.Path;
56 yield* fs.remove(home, { recursive: true, force: true });
57 yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true });
58 yield* fs.makeDirectory(path.join(home, "bin"));
59 // Editor discovery is cached, so the recording shim must exist before the server starts.
60 const editor = path.join(home, "bin", "cursor");
61 yield* fs.writeFileString(
62 editor,
63 `#!/bin/sh\nprintf '%s\\n' "$@" > "$(dirname "$0")/../editor-args.txt"\n`,
64 );
65 yield* fs.chmod(editor, 0o755);
66 const noModel = path.join(home, "bin/no-model");
67 yield* fs.writeFileString(noModel, "#!/bin/sh\necho 'scenarios run no model' >&2\nexit 1\n");
68 yield* fs.chmod(noModel, 0o755);
69 yield* fs.writeFileString(
70 path.join(home, "userdata/settings.json"),
71 yield* encodeSettings({
72 defaultModelSelection: REPLAY,
73 providerInstances: Object.fromEntries(
74 REAL_PROVIDERS.map((driver) => [
75 driver,
76 {
77 driver,
78 enabled: false,
79 ...(driver === "codex" ? { config: { binaryPath: noModel } } : {}),
80 },
81 ]),
82 ),
83 }),
84 );
85});
86
87/** Starts a process in the caller's scope and hands each line it prints to `onLine`. */
88export const start = Effect.fn("startApp.start")(function* (input: {
89 readonly cwd: string;
90 readonly command: string;
91 readonly args: ReadonlyArray<string>;
92 readonly env: NodeJS.ProcessEnv;
93 readonly onLine: (line: string) => Effect.Effect<void, never, FileSystem.FileSystem>;
94}) {
95 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
96 const child = yield* spawner.spawn(
97 ChildProcess.make(input.command, [...input.args], {
98 cwd: input.cwd,
99 env: input.env,
100 extendEnv: false,
101 stdin: "ignore",
102 stdout: "pipe",
103 stderr: "inherit",
104 forceKillAfter: "5 seconds",
105 }),
106 );
107 yield* child.stdout.pipe(
108 Stream.decodeText(),
109 Stream.splitLines,
110 Stream.runForEach(input.onLine),
111 Effect.ignore,
112 Effect.forkScoped,
113 );
114 return child;
115});
116
117const startApp = Effect.fn("startApp")(function* (input: {
118 readonly surface: "web" | "mobile";
119 readonly home: string;
120 readonly ports: ReadonlyArray<string>;
121}) {
122 const fs = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const net = yield* NetService.NetService;
125 const node = yield* HostProcess.ExecutablePath;
126 const checkout = yield* HostProcess.WorkingDirectory;
127 const hostEnvironment = yield* HostProcess.Environment;
128 yield* prepareHome(input.home);
129 const env = {
130 ...hostEnvironment,
131 PATH: `${path.join(input.home, "bin")}:${hostEnvironment.PATH ?? ""}`,
132 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
133 ...SCENARIO_MACHINE_ENV,
134 };
135 const devRunner = (mode: string, args: ReadonlyArray<string>) => [
136 "scripts/dev-runner.ts",
137 mode,
138 "--home-dir",
139 input.home,
140 "--no-seed",
141 ...args,
142 ];
143
144 if (input.surface === "web") {
145 // e2e opens the app at this host, so the web server is told to bind exactly it. Left to its
146 // default, `localhost`, it binds ::1 alone on machines that resolve the name to IPv6 first.
147 const [host = "", webPort = ""] = input.ports;
148 const origin = `http://${host}:${webPort}`;
149 const serverPort = String(yield* net.reserveLoopbackPort());
150 const token = yield* (yield* SecureRandom.SecureRandom).uuidV4();
151 const credential = `${token}${token}`.replaceAll("-", "");
152 // The fixture can retry this credential even if a session response was lost.
153 yield* fs.writeFileString(path.join(input.home, "browser-dev-token"), credential, {
154 mode: 0o600,
155 });
156 const ports = ["--port", serverPort, "--dev-url", origin];
157 const webEnv = { ...env, T3CODE_PORT_OFFSET: String(Number(webPort) - BASE_WEB_PORT) };
158 const server = yield* start({
159 cwd: checkout,
160 command: node,
161 args: devRunner("dev:server", ports),
162 env: {
163 ...webEnv,
164 T3CODE_DEV_ALLOWED_ORIGINS: origin,
165 T3CODE_DEV_AUTH_TOKEN: credential,
166 },
167 onLine: (line) => (line.includes("pairingUrl:") ? Effect.void : Console.log(line)),
168 });
169 const web = yield* start({
170 cwd: checkout,
171 command: node,
172 args: devRunner("dev:web", [...ports, "--", "--host", host]),
173 env: webEnv,
174 onLine: Console.log,
175 });
176 // A web server that came up on another loopback address would leave e2e waiting out its
177 // whole startup timeout; say so at once instead.
178 const boundElsewhere = Effect.gen(function* () {
179 const elsewhere = host === "::1" ? "127.0.0.1" : "::1";
180 if (yield* net.hasListenerOnHost(Number(webPort), host)) return yield* Effect.never;
181 if (!(yield* net.hasListenerOnHost(Number(webPort), elsewhere))) {
182 return yield* new ScenarioError({ message: "The web server is not listening yet." });
183 }
184 yield* Console.error(
185 `The web server listens on ${elsewhere}:${webPort}, not on ${host}: it ignored --host.`,
186 );
187 return 1;
188 }).pipe(
189 Effect.retry({
190 schedule: Schedule.spaced("1 second"),
191 while: (error) => error._tag === "ScenarioError",
192 }),
193 );
194 return yield* Effect.raceAll([server.exitCode, web.exitCode, boundElsewhere]);
195 }
196
197 // The device is another machine: the server listens on every interface, and Metro serves the
198 // dev client its JavaScript. Tests mint their own pairing links, so the startup one is dropped.
199 const [serverPort = "", metroPort = "", host = ""] = input.ports;
200 const server = yield* start({
201 cwd: checkout,
202 command: node,
203 args: devRunner("dev:server", ["--host", "0.0.0.0", "--port", serverPort]),
204 env,
205 onLine: (line) => (line.includes("pairingUrl:") ? Effect.void : Console.log(line)),
206 });
207 yield* net.hasListenerOnHost(Number(serverPort), "127.0.0.1").pipe(
208 Effect.filterOrFail(
209 (listening) => listening,
210 () => new ScenarioError({ message: "The server is not listening yet." }),
211 ),
212 Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 600 }),
213 );
214 const metro = yield* start({
215 cwd: path.join(checkout, "apps/mobile"),
216 command: "npx",
217 args: ["expo", "start", "--dev-client", "--scheme", "t3code-dev", "--lan", "--port", metroPort],
218 env: {
219 ...env,
220 APP_VARIANT: "development",
221 CI: "1",
222 // Lazily fetched chunks sometimes arrive broken on pool devices.
223 EXPO_NO_METRO_LAZY: "1",
224 REACT_NATIVE_PACKAGER_HOSTNAME: host,
225 },
226 onLine: Console.log,
227 });
228 return yield* Effect.raceFirst(server.exitCode, metro.exitCode);
229});
230
231const command = Command.make(
232 "start-app",
233 {
234 surface: Argument.Literals("surface", ["web", "mobile"]).pipe(
235 Argument.withDescription(
236 "web: server and Vite. mobile: server on every interface and Metro.",
237 ),
238 ),
239 home: Argument.String("t3-home").pipe(Argument.withDescription("T3 home to recreate.")),
240 ports: Argument.String("port").pipe(
241 Argument.withDescription(
242 "web: <host> <web-port>. mobile: <server-port> <metro-port> <host>.",
243 ),
244 Argument.variadic(),
245 ),
246 },
247 (input) =>
248 startApp(input).pipe(
249 Effect.flatMap((exitCode) =>
250 Effect.sync(() => {
251 process.exitCode = Number(exitCode) || 1;
252 }),
253 ),
254 ),
255);
256
257if (import.meta.main) {
258 Command.run(command, { version: "0.0.0" }).pipe(
259 Effect.scoped,
260 Effect.provide([NodeServices.layer, NodeCrypto.layer, NetService.layer]),
261 NodeRuntime.runMain,
262 );
263}