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

start-app.ts

267 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 * 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 ports = ["--port", serverPort, "--dev-url", origin];
152 const webEnv = { ...env, T3CODE_PORT_OFFSET: String(Number(webPort) - BASE_WEB_PORT) };
153 const server = yield* start({
154 cwd: checkout,
155 command: node,
156 args: devRunner("dev:server", ports),
157 env: {
158 ...webEnv,
159 T3CODE_DEV_ALLOWED_ORIGINS: origin,
160 // Makes the startup pairing link reusable, so every test can sign in with it.
161 T3CODE_DEV_AUTH_TOKEN: `${token}${token}`.replaceAll("-", ""),
162 },
163 onLine: (line) => {
164 const url = /pairingUrl:\s*(\S+)/.exec(line)?.[1];
165 if (url === undefined) return Console.log(line);
166 // The link is a credential: it goes to a file the tests read, never to the log.
167 const { pathname, search, hash } = new URL(url);
168 return fs
169 .writeFileString(path.join(input.home, "pairing-path"), `${pathname}${search}${hash}`)
170 .pipe(Effect.ignore);
171 },
172 });
173 const web = yield* start({
174 cwd: checkout,
175 command: node,
176 args: devRunner("dev:web", [...ports, "--", "--host", host]),
177 env: webEnv,
178 onLine: Console.log,
179 });
180 // A web server that came up on another loopback address would leave e2e waiting out its
181 // whole startup timeout; say so at once instead.
182 const boundElsewhere = Effect.gen(function* () {
183 const elsewhere = host === "::1" ? "127.0.0.1" : "::1";
184 if (yield* net.hasListenerOnHost(Number(webPort), host)) return yield* Effect.never;
185 if (!(yield* net.hasListenerOnHost(Number(webPort), elsewhere))) {
186 return yield* new ScenarioError({ message: "The web server is not listening yet." });
187 }
188 yield* Console.error(
189 `The web server listens on ${elsewhere}:${webPort}, not on ${host}: it ignored --host.`,
190 );
191 return 1;
192 }).pipe(
193 Effect.retry({
194 schedule: Schedule.spaced("1 second"),
195 while: (error) => error._tag === "ScenarioError",
196 }),
197 );
198 return yield* Effect.raceAll([server.exitCode, web.exitCode, boundElsewhere]);
199 }
200​
201 // The device is another machine: the server listens on every interface, and Metro serves the
202 // dev client its JavaScript. Tests mint their own pairing links, so the startup one is dropped.
203 const [serverPort = "", metroPort = "", host = ""] = input.ports;
204 const server = yield* start({
205 cwd: checkout,
206 command: node,
207 args: devRunner("dev:server", ["--host", "0.0.0.0", "--port", serverPort]),
208 env,
209 onLine: (line) => (line.includes("pairingUrl:") ? Effect.void : Console.log(line)),
210 });
211 yield* net.hasListenerOnHost(Number(serverPort), "127.0.0.1").pipe(
212 Effect.filterOrFail(
213 (listening) => listening,
214 () => new ScenarioError({ message: "The server is not listening yet." }),
215 ),
216 Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 600 }),
217 );
218 const metro = yield* start({
219 cwd: path.join(checkout, "apps/mobile"),
220 command: "npx",
221 args: ["expo", "start", "--dev-client", "--scheme", "t3code-dev", "--lan", "--port", metroPort],
222 env: {
223 ...env,
224 APP_VARIANT: "development",
225 CI: "1",
226 // Lazily fetched chunks sometimes arrive broken on pool devices.
227 EXPO_NO_METRO_LAZY: "1",
228 REACT_NATIVE_PACKAGER_HOSTNAME: host,
229 },
230 onLine: Console.log,
231 });
232 return yield* Effect.raceFirst(server.exitCode, metro.exitCode);
233});
234​
235const command = Command.make(
236 "start-app",
237 {
238 surface: Argument.Literals("surface", ["web", "mobile"]).pipe(
239 Argument.withDescription(
240 "web: server and Vite. mobile: server on every interface and Metro.",
241 ),
242 ),
243 home: Argument.String("t3-home").pipe(Argument.withDescription("T3 home to recreate.")),
244 ports: Argument.String("port").pipe(
245 Argument.withDescription(
246 "web: <host> <web-port>. mobile: <server-port> <metro-port> <host>.",
247 ),
248 Argument.variadic(),
249 ),
250 },
251 (input) =>
252 startApp(input).pipe(
253 Effect.flatMap((exitCode) =>
254 Effect.sync(() => {
255 process.exitCode = Number(exitCode) || 1;
256 }),
257 ),
258 ),
259);
260​
261if (import.meta.main) {
262 Command.run(command, { version: "0.0.0" }).pipe(
263 Effect.scoped,
264 Effect.provide([NodeServices.layer, NodeCrypto.layer, NetService.layer]),
265 NodeRuntime.runMain,
266 );