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

t3.ts

366 lines14.0 KB

1// `test` for web scenarios: e2e's web test plus `t3`, which seeds state and opens the signed-in
2// app. `t3-mobile.ts` is the same for the iOS app.
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as NodeWS from "@effect/platform-node/NodeWS";
6import { test as base, type Cookie } from "@e2e-dev/web";
7import {
8 CommandId,
9 EnvironmentHttpApi,
10 ORCHESTRATION_PROTOCOL_VERSION,
11 type ProjectMutation,
12 ProjectId,
13 WsRpcGroup,
14} from "@t3tools/contracts";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as Clock from "effect/Clock";
17import * as SecureRandom from "effect/crypto/SecureRandom";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as HttpApiClient from "effect/http-api/HttpApiClient";
21import * as Layer from "effect/Layer";
22import * as Path from "effect/Path";
23import * as Schedule from "effect/Schedule";
24import * as Schema from "effect/Schema";
25import {
26 Cookies,
27 FetchHttpClient,
28 HttpClient,
29 HttpClientError,
30 HttpClientRequest,
31 HttpClientResponse,
32} from "effect/http";
33import { RpcClient, RpcSerialization } from "effect/rpc";
34import { Socket } from "effect/socket";
35​
36import { APP_DIR, T3_HOME } from "../e2e.config.ts";
37import { run, ScenarioError } from "./shell.ts";
38​
39export interface T3State {
40 /** Creates a git repository holding `files` and adds it as a project. Returns its path. */
41 readonly project: (
42 title: string,
43 files?: Readonly<Record<string, string | Uint8Array>>,
44 ) => Promise<string>;
45 /**
46 * Starts a thread in a project and plays one replayed turn per message before returning.
47 * `model` is a dev replay recording: showcase, todo-list, approval, question, multi-turn,
48 * command-output.
49 */
50 readonly thread: (input: {
51 readonly project: string;
52 readonly title: string;
53 readonly messages: ReadonlyArray<string>;
54 readonly model?: string;
55 }) => Promise<T3Thread>;
57​
58export interface T3Thread {
59 readonly threadId: string;
61​
62export interface T3 extends T3State {
63 /** Registers a project created through the UI for deletion during fixture teardown. */
64 readonly trackProject: (id: string) => void;
65 /**
66 * Opens the app, signed in, at a path or on a thread `t3.thread` returned. Opening the thread
67 * by its link is the reliable way to reach it: a sidebar row covers its own title text.
68 */
69 readonly open: (target?: string | T3Thread) => Promise<void>;
71​
72/** e2e's fixtures are promise functions; this is the one place an Effect becomes a promise. */
73export const runPromise = <A, E>(effect: Effect.Effect<A, E, NodeServices.NodeServices>) =>
74 Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
75​
76const decodeLaunched = Schema.decodeUnknownEffect(
77 Schema.fromJsonString(Schema.Struct({ threadId: Schema.String })),
78);
79​
80const decodeRuntimeState = Schema.decodeUnknownEffect(
81 Schema.fromJsonString(Schema.Struct({ origin: Schema.String, startedAt: Schema.String })),
82);
83​
84type ServerApi = {
85 readonly client: HttpApiClient.ForApi<typeof EnvironmentHttpApi>;
86 readonly headers: { readonly authorization: string };
87};
88​
89/**
90 * One API client per running server, signed in once. Each CLI call starts a process that takes
91 * about 0.7 s before it does anything, so per-test state goes through the server's HTTP API. A
92 * server started again on the same home, as the second server is for each test, gets a new one.
93 */
94const serverApis = new Map<string, Promise<ServerApi>>();
95​
96const uuid = SecureRandom.SecureRandom.pipe(
97 Effect.flatMap((random) => random.uuidV4()),
98 Effect.provide(NodeCrypto.layer),
99);
100​
101/** State for the server on `home`, made through the app's own CLI and API: real events, not inserted rows. */
102export function makeState(home: string, env: NodeJS.ProcessEnv = {}) {
103 const cli = Effect.fn("scenario.cli")(function* (
104 args: ReadonlyArray<string>,
105 allowExit: ReadonlyArray<number> = [0],
106 ) {
107 const hostEnvironment = yield* HostProcess.Environment;
108 return yield* run(
109 yield* HostProcess.ExecutablePath,
110 ["apps/server/src/bin.ts", ...args, "--base-dir", home],
111 {
112 cwd: APP_DIR,
113 env: { PATH: hostEnvironment.PATH, HOME: hostEnvironment.HOME, ...env },
114 allowExit,
115 },
116 );
117 });
118​
119 // The server writes its origin beside its database once it listens. It also prints its pairing
120 // token, which can come first, so a missing file is read again.
121 const runtimeState = Effect.gen(function* () {
122 const fs = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 return yield* decodeRuntimeState(
125 yield* fs.readFileString(path.join(home, "userdata", "server-runtime.json")),
126 );
127 }).pipe(
128 Effect.retry({
129 schedule: Schedule.spaced("50 millis"),
130 times: 100,
131 while: (error) => error._tag === "PlatformError" && error.reason._tag === "NotFound",
132 }),
133 );
134 const connect = Effect.fn("scenario.connect")(function* (origin: string) {
135 const issued = yield* cli(["auth", "session", "issue", "--token-only", "--label", "scenario"]);
136 const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: origin });
137 return { client, headers: { authorization: `Bearer ${issued.stdout.trim()}` } };
138 }, Effect.provide(FetchHttpClient.layer));
139 const api = Effect.gen(function* () {
140 const { origin, startedAt } = yield* runtimeState;
141 const key = `${home}\n${origin}\n${startedAt}`;
142 return yield* Effect.tryPromise({
143 try: () => {
144 const known = serverApis.get(key);
145 if (known !== undefined) return known;
146 const connecting = runPromise(connect(origin));
147 serverApis.set(key, connecting);
148 // A failed sign-in is not kept: the next test tries again.
149 connecting.catch(() => serverApis.delete(key));
150 return connecting;
151 },
152 catch: (cause) => new ScenarioError({ message: `Could not reach the server API: ${cause}` }),
153 });
154 });
155 const mutate = Effect.fn("scenario.mutate")(function* (mutation: ProjectMutation) {
156 const { client, headers } = yield* api;
157 return yield* client.projects
158 .mutate({ headers, payload: mutation })
159 .pipe(
160 Effect.mapError((cause) => new ScenarioError({ message: `${mutation.type}: ${cause}` })),
161 );
162 });
163 const projects: Array<ProjectId> = [];
164​
165 const project = Effect.fn("scenario.project")(function* (
166 title: string,
167 files: Readonly<Record<string, string | Uint8Array>>,
168 ) {
169 const fs = yield* FileSystem.FileSystem;
170 const path = yield* Path.Path;
171 // Its own folder per test: the server and this home outlive one test.
172 yield* fs.makeDirectory(path.join(home, "workspaces"), { recursive: true });
173 const parent = yield* fs.makeTempDirectory({
174 directory: path.join(home, "workspaces"),
175 prefix: "w-",
176 });
177 const workspace = path.join(parent, title);
178 for (const [file, content] of Object.entries({ "README.md": "", ...files })) {
179 yield* fs.makeDirectory(path.dirname(path.join(workspace, file)), { recursive: true });
180 yield* typeof content === "string"
181 ? fs.writeFileString(path.join(workspace, file), content)
182 : fs.writeFile(path.join(workspace, file), content);
183 }
184 const git = (args: ReadonlyArray<string>) => run("git", args, { cwd: workspace });
185 const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];
186 yield* git(["init", "--quiet", "--initial-branch=main"]);
187 yield* git(["add", "--all"]);
188 yield* git([...author, "commit", "--quiet", "--message", "Initial commit"]);
189 const created = yield* mutate({
190 type: "project.create",
191 commandId: CommandId.make(yield* uuid),
192 projectId: ProjectId.make(yield* uuid),
193 title,
194 workspaceRoot: workspace,
195 });
196 projects.push(created.id);
197 return workspace;
198 });
199​
200 const thread = Effect.fn("scenario.thread")(function* (input: {
201 readonly project: string;
202 readonly title: string;
203 readonly messages: ReadonlyArray<string>;
204 readonly model?: string;
205 }) {
206 // Exit code 2 means the turn waits for an answer, which a scenario may want to start from.
207 const turn = (args: ReadonlyArray<string>) =>
208 cli(["thread", ...args, "--wait", "--json"], [0, 2]);
209 const [first = "Start", ...rest] = input.messages;
210 const replay = ["--provider", "devReplay", "--model", input.model ?? "multi-turn"];
211 // Until its first ACP probe finishes, the replay provider advertises only a placeholder model.
212 const started = yield* turn([
213 "start",
214 input.project,
215 first,
216 "--title",
217 input.title,
218 ...replay,
219 ]).pipe(
220 Effect.retry({
221 schedule: Schedule.spaced("250 millis"),
222 times: 40,
223 while: (error) => error.message.includes("is not advertised by provider devReplay"),
224 }),
225 );
226 const { threadId } = yield* decodeLaunched(started.stdout);
227 for (const message of rest) yield* turn(["send", threadId, message]);
228 return { threadId } satisfies T3Thread;
229 });
230​
231 return {
232 cli,
233 trackProject: (id: string) => {
234 projects.push(ProjectId.make(id));
235 },
236 state: {
237 project: (title, files = {}) => runPromise(project(title, files)),
238 thread: (input) => runPromise(thread(input)),
239 } satisfies T3State,
240 // The server outlives the test, so the next one must not see this one's projects.
241 cleanup: Effect.forEach(
242 projects,
243 (projectId) =>
244 Effect.flatMap(uuid, (commandId) =>
245 mutate({
246 type: "project.delete",
247 commandId: CommandId.make(commandId),
248 projectId,
249 force: true,
250 }),
251 ),
252 { discard: true },
253 ),
254 };
256​
257const sameSite = { lax: "Lax", strict: "Strict", none: "None" } as const;
258​
259/**
260 * Signs in the way the pairing page does and returns the session cookies. Opening the page
261 * instead races its reload after sign-in against the test's next `app.open`.
262 */
263const signIn = Effect.fn("scenario.signIn")(function* (baseUrl: string) {
264 const fs = yield* FileSystem.FileSystem;
265 const path = yield* Path.Path;
266 const credential = yield* fs.readFileString(path.join(T3_HOME, "browser-dev-token"));
267 const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl });
268 // Only the cookies are read: a proof runs this against a base server whose body may differ.
269 const response = yield* client.auth
270 .browserSession({ payload: { credential }, responseMode: "response-only" })
271 .pipe(
272 Effect.flatMap(HttpClientResponse.filterStatusOk),
273 Effect.retry({
274 schedule: Schedule.spaced("500 millis"),
275 while: (error) => {
276 if (!HttpClientError.isHttpClientError(error)) return false;
277 const status = error.response?.status;
278 return (
279 error.reason._tag === "TransportError" ||
280 status === 502 ||
281 status === 503 ||
282 status === 504
283 );
284 },
285 }),
286 Effect.timeout("15 seconds"),
287 );
288 // Drops the expired cookies that only clear an older session.
289 const cookies = Cookies.mergeIntoArray(
290 [],
291 baseUrl,
292 response.cookies,
293 yield* Clock.currentTimeMillis,
294 );
295 return cookies.map(({ name, value, options = {} }): Cookie => ({
296 name,
297 value,
298 // The server sets no Domain and `Path=/`, which is what a cookie for the origin gets.
299 url: baseUrl,
300 ...(options.expires && { expires: Math.floor(options.expires.getTime() / 1000) }),
301 ...(options.httpOnly !== undefined && { httpOnly: options.httpOnly }),
302 ...(options.secure !== undefined && { secure: options.secure }),
303 ...(options.sameSite && { sameSite: sameSite[options.sameSite] }),
304 }));
305}, Effect.provide(FetchHttpClient.layer));
306​
307/** The id every thread link starts with, asked of the server the app talks to. */
308export const environmentId = (baseUrl: string) =>
309 HttpClient.get(`${baseUrl}/.well-known/t3/environment`).pipe(
310 Effect.flatMap(HttpClientResponse.filterStatusOk),
311 Effect.flatMap(
312 HttpClientResponse.schemaBodyJson(Schema.Struct({ environmentId: Schema.String })),
313 ),
314 Effect.map((environment) => environment.environmentId),
315 Effect.provide(FetchHttpClient.layer),
316 );
317​
318/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */
319export const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
320 const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
321 const { ticket } = yield* HttpClient.execute(
322 HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
323 HttpClientRequest.bearerToken(issued.stdout.trim()),
324 ),
325 ).pipe(
326 Effect.flatMap(HttpClientResponse.filterStatusOk),
327 Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
328 Effect.provide(FetchHttpClient.layer),
329 );
330 // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
331 const protocol = yield* Layer.build(
332 RpcClient.layerProtocolSocket().pipe(
333 Layer.provide(
334 Socket.layerWebSocket(
335 `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
336 ),
337 ),
338 Layer.provide(RpcSerialization.layerJson),
339 Layer.provide(NodeWS.layerWebSocketConstructor),
340 ),
341 );
342 return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
343});
344​
345export const test = base.extend<{ t3: T3 }>({
346 t3: async ({ app, browser }, use) => {
347 const { state, cleanup, trackProject } = makeState(T3_HOME);
348 await use({
349 ...state,
350 trackProject,
351 open: async (target = "/") => {
352 const baseUrl = app.baseUrl ?? "";
353 await browser.setCookies(await runPromise(signIn(baseUrl)));
354 await app.open(
355 typeof target === "string"
356 ? target
357 : `/${await runPromise(environmentId(baseUrl))}/${target.threadId}`,
358 );
359 },
360 });
361 await runPromise(cleanup);
362 },
363});
364​
365/** Test option for a web scenario: the iOS target skips it. */
366export const WEB = { platforms: ["web"] } as const;