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

t3.ts

172 lines6.9 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 NodeServices from "@effect/platform-node/NodeServices";
4import { test as base } from "@e2e-dev/web";
5import { expect } from "e2e";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
12​
13import { APP_DIR, T3_HOME } from "../e2e.config.ts";
14import { run } from "./shell.ts";
15​
16export interface T3State {
17 /** Creates a git repository holding `files` and adds it as a project. Returns its path. */
18 readonly project: (
19 title: string,
20 files?: Readonly<Record<string, string | Uint8Array>>,
21 ) => Promise<string>;
22 /**
23 * Starts a thread in a project and plays one replayed turn per message before returning.
24 * `model` is a dev replay recording: showcase, todo-list, approval, question, multi-turn.
25 */
26 readonly thread: (input: {
27 readonly project: string;
28 readonly title: string;
29 readonly messages: ReadonlyArray<string>;
30 readonly model?: string;
31 }) => Promise<T3Thread>;
33​
34export interface T3Thread {
35 readonly threadId: string;
37​
38export interface T3 extends T3State {
39 /**
40 * Opens the app, signed in, at a path or on a thread `t3.thread` returned. Opening the thread
41 * by its link is the reliable way to reach it: a sidebar row covers its own title text.
42 */
43 readonly open: (target?: string | T3Thread) => Promise<void>;
45​
46/** e2e's fixtures are promise functions; this is the one place an Effect becomes a promise. */
47export const runPromise = <A, E>(effect: Effect.Effect<A, E, NodeServices.NodeServices>) =>
48 Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
49​
50const decodeLaunched = Schema.decodeUnknownEffect(
51 Schema.fromJsonString(Schema.Struct({ threadId: Schema.String })),
52);
53​
54/** State for the server on `home`, made through the app's own CLI: real events, not inserted rows. */
55export function makeState(home: string, env: NodeJS.ProcessEnv = {}) {
56 const cli = Effect.fn("scenario.cli")(function* (
57 args: ReadonlyArray<string>,
58 allowExit: ReadonlyArray<number> = [0],
59 ) {
60 const hostEnvironment = yield* HostProcess.Environment;
61 return yield* run(
62 yield* HostProcess.ExecutablePath,
63 ["apps/server/src/bin.ts", ...args, "--base-dir", home],
64 {
65 cwd: APP_DIR,
66 env: { PATH: hostEnvironment.PATH, HOME: hostEnvironment.HOME, ...env },
67 allowExit,
68 },
69 );
70 });
71 const projects: Array<string> = [];
72​
73 const project = Effect.fn("scenario.project")(function* (
74 title: string,
75 files: Readonly<Record<string, string | Uint8Array>>,
76 ) {
77 const fs = yield* FileSystem.FileSystem;
78 const path = yield* Path.Path;
79 // Its own folder per test: the server and this home outlive one test.
80 yield* fs.makeDirectory(path.join(home, "workspaces"), { recursive: true });
81 const parent = yield* fs.makeTempDirectory({
82 directory: path.join(home, "workspaces"),
83 prefix: "w-",
84 });
85 const workspace = path.join(parent, title);
86 for (const [file, content] of Object.entries({ "README.md": "", ...files })) {
87 yield* fs.makeDirectory(path.dirname(path.join(workspace, file)), { recursive: true });
88 yield* typeof content === "string"
89 ? fs.writeFileString(path.join(workspace, file), content)
90 : fs.writeFile(path.join(workspace, file), content);
91 }
92 const git = (args: ReadonlyArray<string>) => run("git", args, { cwd: workspace });
93 const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];
94 yield* git(["init", "--quiet", "--initial-branch=main"]);
95 yield* git(["add", "--all"]);
96 yield* git([...author, "commit", "--quiet", "--message", "Initial commit"]);
97 yield* cli(["project", "add", workspace, "--title", title]);
98 projects.push(workspace);
99 return workspace;
100 });
101​
102 const thread = Effect.fn("scenario.thread")(function* (input: {
103 readonly project: string;
104 readonly title: string;
105 readonly messages: ReadonlyArray<string>;
106 readonly model?: string;
107 }) {
108 // Exit code 2 means the turn waits for an answer, which a scenario may want to start from.
109 const turn = (args: ReadonlyArray<string>) =>
110 cli(["thread", ...args, "--wait", "--json"], [0, 2]);
111 const [first = "Start", ...rest] = input.messages;
112 const replay = ["--provider", "devReplay", "--model", input.model ?? "multi-turn"];
113 const started = yield* turn(["start", input.project, first, "--title", input.title, ...replay]);
114 const { threadId } = yield* decodeLaunched(started.stdout);
115 for (const message of rest) yield* turn(["send", threadId, message]);
116 return { threadId } satisfies T3Thread;
117 });
118​
119 return {
120 cli,
121 state: {
122 project: (title, files = {}) => runPromise(project(title, files)),
123 thread: (input) => runPromise(thread(input)),
124 } satisfies T3State,
125 // The server outlives the test, so the next one must not see this one's projects.
126 cleanup: Effect.forEach(
127 projects,
128 (workspace) => cli(["project", "remove", workspace, "--force"]),
129 { discard: true },
130 ),
131 };
133​
134const readPairingPath = Effect.gen(function* () {
135 const fs = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
137 return yield* fs.readFileString(path.join(T3_HOME, "pairing-path"));
138});
139​
140/** The id every thread link starts with, asked of the server the app talks to. */
141const environmentId = (baseUrl: string) =>
142 HttpClient.get(`${baseUrl}/.well-known/t3/environment`).pipe(
143 Effect.flatMap(HttpClientResponse.filterStatusOk),
144 Effect.flatMap(
145 HttpClientResponse.schemaBodyJson(Schema.Struct({ environmentId: Schema.String })),
146 ),
147 Effect.map((environment) => environment.environmentId),
148 Effect.provide(FetchHttpClient.layer),
149 );
150​
151export const test = base.extend<{ t3: T3 }>({
152 t3: async ({ app, browser }, use) => {
153 const { state, cleanup } = makeState(T3_HOME);
154 await use({
155 ...state,
156 open: async (target = "/") => {
157 await app.open(await runPromise(readPairingPath));
158 // The pairing page signs in and then leaves itself. Going anywhere before it has done
159 // so cancels the sign-in, and the next page is the pairing page again.
160 await expect(browser).not.toHaveURL(/\/pair(?:[?#]|$)/, { timeout: 60_000 });
161 if (typeof target !== "string") {
162 const environment = await runPromise(environmentId(app.baseUrl ?? ""));
163 await app.open(`/${environment}/${target.threadId}`);
164 } else if (target !== "/") await app.open(target);
165 },
166 });
167 await runPromise(cleanup);
168 },
169});
170​
171/** Test option for a web scenario: the iOS target skips it. */
172export const WEB = { platforms: ["web"] } as const;