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

t3.ts

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