Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

start-app.ts

271 lines9.9 KB

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