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