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

t3.ts

352 lines13.6 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 const started = yield* turn(["start", input.project, first, "--title", input.title, ...replay]);
212 const { threadId } = yield* decodeLaunched(started.stdout);
213 for (const message of rest) yield* turn(["send", threadId, message]);
214 return { threadId } satisfies T3Thread;
215 });
216​
217 return {
218 cli,
219 trackProject: (id: string) => {
220 projects.push(ProjectId.make(id));
221 },
222 state: {
223 project: (title, files = {}) => runPromise(project(title, files)),
224 thread: (input) => runPromise(thread(input)),
225 } satisfies T3State,
226 // The server outlives the test, so the next one must not see this one's projects.
227 cleanup: Effect.forEach(
228 projects,
229 (projectId) =>
230 Effect.flatMap(uuid, (commandId) =>
231 mutate({
232 type: "project.delete",
233 commandId: CommandId.make(commandId),
234 projectId,
235 force: true,
236 }),
237 ),
238 { discard: true },
239 ),
240 };
242​
243const sameSite = { lax: "Lax", strict: "Strict", none: "None" } as const;
244​
245/**
246 * Signs in the way the pairing page does and returns the session cookies. Opening the page
247 * instead races its reload after sign-in against the test's next `app.open`.
248 */
249const signIn = Effect.fn("scenario.signIn")(function* (baseUrl: string) {
250 const fs = yield* FileSystem.FileSystem;
251 const path = yield* Path.Path;
252 const credential = yield* fs.readFileString(path.join(T3_HOME, "browser-dev-token"));
253 const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl });
254 // Only the cookies are read: a proof runs this against a base server whose body may differ.
255 const response = yield* client.auth
256 .browserSession({ payload: { credential }, responseMode: "response-only" })
257 .pipe(
258 Effect.flatMap(HttpClientResponse.filterStatusOk),
259 Effect.retry({
260 schedule: Schedule.spaced("500 millis"),
261 while: (error) => {
262 if (!HttpClientError.isHttpClientError(error)) return false;
263 const status = error.response?.status;
264 return (
265 error.reason._tag === "TransportError" ||
266 status === 502 ||
267 status === 503 ||
268 status === 504
269 );
270 },
271 }),
272 Effect.timeout("15 seconds"),
273 );
274 // Drops the expired cookies that only clear an older session.
275 const cookies = Cookies.mergeIntoArray(
276 [],
277 baseUrl,
278 response.cookies,
279 yield* Clock.currentTimeMillis,
280 );
281 return cookies.map(({ name, value, options = {} }): Cookie => ({
282 name,
283 value,
284 // The server sets no Domain and `Path=/`, which is what a cookie for the origin gets.
285 url: baseUrl,
286 ...(options.expires && { expires: Math.floor(options.expires.getTime() / 1000) }),
287 ...(options.httpOnly !== undefined && { httpOnly: options.httpOnly }),
288 ...(options.secure !== undefined && { secure: options.secure }),
289 ...(options.sameSite && { sameSite: sameSite[options.sameSite] }),
290 }));
291}, Effect.provide(FetchHttpClient.layer));
292​
293/** The id every thread link starts with, asked of the server the app talks to. */
294export const environmentId = (baseUrl: string) =>
295 HttpClient.get(`${baseUrl}/.well-known/t3/environment`).pipe(
296 Effect.flatMap(HttpClientResponse.filterStatusOk),
297 Effect.flatMap(
298 HttpClientResponse.schemaBodyJson(Schema.Struct({ environmentId: Schema.String })),
299 ),
300 Effect.map((environment) => environment.environmentId),
301 Effect.provide(FetchHttpClient.layer),
302 );
303​
304/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */
305export const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
306 const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
307 const { ticket } = yield* HttpClient.execute(
308 HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
309 HttpClientRequest.bearerToken(issued.stdout.trim()),
310 ),
311 ).pipe(
312 Effect.flatMap(HttpClientResponse.filterStatusOk),
313 Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
314 Effect.provide(FetchHttpClient.layer),
315 );
316 // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
317 const protocol = yield* Layer.build(
318 RpcClient.layerProtocolSocket().pipe(
319 Layer.provide(
320 Socket.layerWebSocket(
321 `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
322 ),
323 ),
324 Layer.provide(RpcSerialization.layerJson),
325 Layer.provide(NodeWS.layerWebSocketConstructor),
326 ),
327 );
328 return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
329});
330​
331export const test = base.extend<{ t3: T3 }>({
332 t3: async ({ app, browser }, use) => {
333 const { state, cleanup, trackProject } = makeState(T3_HOME);
334 await use({
335 ...state,
336 trackProject,
337 open: async (target = "/") => {
338 const baseUrl = app.baseUrl ?? "";
339 await browser.setCookies(await runPromise(signIn(baseUrl)));
340 await app.open(
341 typeof target === "string"
342 ? target
343 : `/${await runPromise(environmentId(baseUrl))}/${target.threadId}`,
344 );
345 },
346 });
347 await runPromise(cleanup);
348 },
349});
350​
351/** Test option for a web scenario: the iOS target skips it. */
352export const WEB = { platforms: ["web"] } as const;