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