The best way to control Claude Code, Codex and more from any computer or phone

main
ts 263 lines 9.69 KB
Raw
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.
4 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6 import * as NodeServices from "@effect/platform-node/NodeServices";
7 import * as HostProcess from "@t3tools/shared/HostProcess";
8 import * as NetService from "@t3tools/shared/Net";
9 import * as Console from "effect/Console";
10 import * as Effect from "effect/Effect";
11 import * as FileSystem from "effect/FileSystem";
12 import * as Path from "effect/Path";
13 import * as SecureRandom from "effect/crypto/SecureRandom";
14 import * as Schedule from "effect/Schedule";
15 import * as Schema from "effect/Schema";
16 import * as Stream from "effect/Stream";
17 import { Argument, Command } from "effect/cli";
18 import { ChildProcess, ChildProcessSpawner } from "effect/process";
19
20 import { 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.
23 const BASE_WEB_PORT = 5733;
24 // The replay agent `vp run dev` registers: free, recorded turns through the real adapter.
25 const 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.
30 const 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 export const SCENARIO_MACHINE_ENV = {
43 T3CODE_ENVIRONMENT_LABEL: "Scenario",
44 T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop",
45 };
46
47 const encodeSettings = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
48
49 export const prepareHome = Effect.fn("startApp.prepareHome")(function* (home: string) {
50 const fs = yield* FileSystem.FileSystem;
51 const path = yield* Path.Path;
52 yield* fs.remove(home, { recursive: true, force: true });
53 yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true });
54 yield* fs.makeDirectory(path.join(home, "bin"));
55 // Editor discovery is cached, so the recording shim must exist before the server starts.
56 const editor = path.join(home, "bin", "cursor");
57 yield* fs.writeFileString(
58 editor,
59 `#!/bin/sh\nprintf '%s\\n' "$@" > "$(dirname "$0")/../editor-args.txt"\n`,
60 );
61 yield* fs.chmod(editor, 0o755);
62 const noModel = path.join(home, "bin/no-model");
63 yield* fs.writeFileString(noModel, "#!/bin/sh\necho 'scenarios run no model' >&2\nexit 1\n");
64 yield* fs.chmod(noModel, 0o755);
65 yield* fs.writeFileString(
66 path.join(home, "userdata/settings.json"),
67 yield* encodeSettings({
68 defaultModelSelection: REPLAY,
69 providerInstances: Object.fromEntries(
70 REAL_PROVIDERS.map((driver) => [
71 driver,
72 {
73 driver,
74 enabled: false,
75 ...(driver === "codex" ? { config: { binaryPath: noModel } } : {}),
76 },
77 ]),
78 ),
79 }),
80 );
81 });
82
83 /** Starts a process in the caller's scope and hands each line it prints to `onLine`. */
84 export const start = Effect.fn("startApp.start")(function* (input: {
85 readonly cwd: string;
86 readonly command: string;
87 readonly args: ReadonlyArray<string>;
88 readonly env: NodeJS.ProcessEnv;
89 readonly onLine: (line: string) => Effect.Effect<void, never, FileSystem.FileSystem>;
90 }) {
91 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
92 const child = yield* spawner.spawn(
93 ChildProcess.make(input.command, [...input.args], {
94 cwd: input.cwd,
95 env: input.env,
96 extendEnv: false,
97 stdin: "ignore",
98 stdout: "pipe",
99 stderr: "inherit",
100 forceKillAfter: "5 seconds",
101 }),
102 );
103 yield* child.stdout.pipe(
104 Stream.decodeText(),
105 Stream.splitLines,
106 Stream.runForEach(input.onLine),
107 Effect.ignore,
108 Effect.forkScoped,
109 );
110 return child;
111 });
112
113 const startApp = Effect.fn("startApp")(function* (input: {
114 readonly surface: "web" | "mobile";
115 readonly home: string;
116 readonly ports: ReadonlyArray<string>;
117 }) {
118 const fs = yield* FileSystem.FileSystem;
119 const path = yield* Path.Path;
120 const net = yield* NetService.NetService;
121 const node = yield* HostProcess.ExecutablePath;
122 const checkout = yield* HostProcess.WorkingDirectory;
123 const hostEnvironment = yield* HostProcess.Environment;
124 yield* prepareHome(input.home);
125 const env = {
126 ...hostEnvironment,
127 PATH: `${path.join(input.home, "bin")}:${hostEnvironment.PATH ?? ""}`,
128 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
129 ...SCENARIO_MACHINE_ENV,
130 };
131 const devRunner = (mode: string, args: ReadonlyArray<string>) => [
132 "scripts/dev-runner.ts",
133 mode,
134 "--home-dir",
135 input.home,
136 "--no-seed",
137 ...args,
138 ];
139
140 if (input.surface === "web") {
141 // e2e opens the app at this host, so the web server is told to bind exactly it. Left to its
142 // default, `localhost`, it binds ::1 alone on machines that resolve the name to IPv6 first.
143 const [host = "", webPort = ""] = input.ports;
144 const origin = `http://${host}:${webPort}`;
145 const serverPort = String(yield* net.reserveLoopbackPort());
146 const token = yield* (yield* SecureRandom.SecureRandom).uuidV4();
147 const ports = ["--port", serverPort, "--dev-url", origin];
148 const webEnv = { ...env, T3CODE_PORT_OFFSET: String(Number(webPort) - BASE_WEB_PORT) };
149 const server = yield* start({
150 cwd: checkout,
151 command: node,
152 args: devRunner("dev:server", ports),
153 env: {
154 ...webEnv,
155 T3CODE_DEV_ALLOWED_ORIGINS: origin,
156 // Makes the startup pairing link reusable, so every test can sign in with it.
157 T3CODE_DEV_AUTH_TOKEN: `${token}${token}`.replaceAll("-", ""),
158 },
159 onLine: (line) => {
160 const url = /pairingUrl:\s*(\S+)/.exec(line)?.[1];
161 if (url === undefined) return Console.log(line);
162 // The link is a credential: it goes to a file the tests read, never to the log.
163 const { pathname, search, hash } = new URL(url);
164 return fs
165 .writeFileString(path.join(input.home, "pairing-path"), `${pathname}${search}${hash}`)
166 .pipe(Effect.ignore);
167 },
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
231 const 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
257 if (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 }