diff --git a/docs/internals/15_testing.md b/docs/internals/15_testing.md index 569a8b6f2f767..9408797a09834 100644 --- a/docs/internals/15_testing.md +++ b/docs/internals/15_testing.md @@ -53,7 +53,7 @@ vp run scenarios:prove scripts/scenarios/.e2e.ts --base main --upload-comm ``` - One test per file (`WEB` from `./t3.ts` or `IOS` from `./t3-mobile.ts`). Seed projects and threads via `t3.project` / `t3.thread` before calling `t3.open(...)` so the app does not land on first-run setup. -- Navigate directly with `t3.open(thread)` or `t3.open("/settings/...")` rather than clicking sidebar text; let `t3.open` complete pairing before other navigation. +- In web scenarios, navigate directly with `t3.open(thread)` or `t3.open("/settings/...")` unless the scenario exercises sidebar navigation. - Put `expect` assertions only on the behavior the bug breaks, and take `app.screenshot("label")` where the bug shows so `scenarios:prove` pairs base and head captures. Never call `agent.act` or `agent.assert` (no model is configured). - The app starts with a minimal env (`PATH`, `HOME`, temp dir); pass extra env vars via `T3_SCENARIO_INHERIT_ENV='VAR,PREFIX_*'`. Run one scenario run at a time per checkout. - `scenarios:prove` exits `0` only when the test fails on base and passes on head (`1` = did not prove, `2` = app failed to start, `3` = scenario failed before its assertion). iOS scenarios lease a Simlock simulator and require `SIMLOCK_AGENT_DEVICE_URL` and `AGENT_DEVICE_DAEMON_AUTH_TOKEN`. diff --git a/scripts/scenarios/start-app.ts b/scripts/scenarios/start-app.ts index d635f1ba0fd64..59d0715ffc4c6 100644 --- a/scripts/scenarios/start-app.ts +++ b/scripts/scenarios/start-app.ts @@ -148,6 +148,11 @@ const startApp = Effect.fn("startApp")(function* (input: { const origin = `http://${host}:${webPort}`; const serverPort = String(yield* net.reserveLoopbackPort()); const token = yield* (yield* SecureRandom.SecureRandom).uuidV4(); + const credential = `${token}${token}`.replaceAll("-", ""); + // The fixture can retry this credential even if a session response was lost. + yield* fs.writeFileString(path.join(input.home, "browser-dev-token"), credential, { + mode: 0o600, + }); const ports = ["--port", serverPort, "--dev-url", origin]; const webEnv = { ...env, T3CODE_PORT_OFFSET: String(Number(webPort) - BASE_WEB_PORT) }; const server = yield* start({ @@ -157,18 +162,9 @@ const startApp = Effect.fn("startApp")(function* (input: { env: { ...webEnv, T3CODE_DEV_ALLOWED_ORIGINS: origin, - // Makes the startup pairing link reusable, so every test can sign in with it. - T3CODE_DEV_AUTH_TOKEN: `${token}${token}`.replaceAll("-", ""), - }, - onLine: (line) => { - const url = /pairingUrl:\s*(\S+)/.exec(line)?.[1]; - if (url === undefined) return Console.log(line); - // The link is a credential: it goes to a file the tests read, never to the log. - const { pathname, search, hash } = new URL(url); - return fs - .writeFileString(path.join(input.home, "pairing-path"), `${pathname}${search}${hash}`) - .pipe(Effect.ignore); + T3CODE_DEV_AUTH_TOKEN: credential, }, + onLine: (line) => (line.includes("pairingUrl:") ? Effect.void : Console.log(line)), }); const web = yield* start({ cwd: checkout, diff --git a/scripts/scenarios/t3.ts b/scripts/scenarios/t3.ts index fab377de1028b..b511bbe680a2f 100644 --- a/scripts/scenarios/t3.ts +++ b/scripts/scenarios/t3.ts @@ -3,8 +3,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeWS from "@effect/platform-node/NodeWS"; -import { test as base } from "@e2e-dev/web"; -import { expect } from "e2e"; +import { test as base, type Cookie } from "@e2e-dev/web"; import { CommandId, EnvironmentHttpApi, @@ -14,6 +13,7 @@ import { WsRpcGroup, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Clock from "effect/Clock"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -22,7 +22,14 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { + Cookies, + FetchHttpClient, + HttpClient, + HttpClientError, + HttpClientRequest, + HttpClientResponse, +} from "effect/http"; import { RpcClient, RpcSerialization } from "effect/rpc"; import { Socket } from "effect/socket"; @@ -228,11 +235,55 @@ export function makeState(home: string, env: NodeJS.ProcessEnv = {}) { }; } -const readPairingPath = Effect.gen(function* () { +const sameSite = { lax: "Lax", strict: "Strict", none: "None" } as const; + +/** + * Signs in the way the pairing page does and returns the session cookies. Opening the page + * instead races its reload after sign-in against the test's next `app.open`. + */ +const signIn = Effect.fn("scenario.signIn")(function* (baseUrl: string) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - return yield* fs.readFileString(path.join(T3_HOME, "pairing-path")); -}); + const credential = yield* fs.readFileString(path.join(T3_HOME, "browser-dev-token")); + const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl }); + // Only the cookies are read: a proof runs this against a base server whose body may differ. + const response = yield* client.auth + .browserSession({ payload: { credential }, responseMode: "response-only" }) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.retry({ + schedule: Schedule.spaced("500 millis"), + while: (error) => { + if (!HttpClientError.isHttpClientError(error)) return false; + const status = error.response?.status; + return ( + error.reason._tag === "TransportError" || + status === 502 || + status === 503 || + status === 504 + ); + }, + }), + Effect.timeout("15 seconds"), + ); + // Drops the expired cookies that only clear an older session. + const cookies = Cookies.mergeIntoArray( + [], + baseUrl, + response.cookies, + yield* Clock.currentTimeMillis, + ); + return cookies.map(({ name, value, options = {} }): Cookie => ({ + name, + value, + // The server sets no Domain and `Path=/`, which is what a cookie for the origin gets. + url: baseUrl, + ...(options.expires && { expires: Math.floor(options.expires.getTime() / 1000) }), + ...(options.httpOnly !== undefined && { httpOnly: options.httpOnly }), + ...(options.secure !== undefined && { secure: options.secure }), + ...(options.sameSite && { sameSite: sameSite[options.sameSite] }), + })); +}, Effect.provide(FetchHttpClient.layer)); /** The id every thread link starts with, asked of the server the app talks to. */ export const environmentId = (baseUrl: string) => @@ -278,14 +329,13 @@ export const test = base.extend<{ t3: T3 }>({ await use({ ...state, open: async (target = "/") => { - await app.open(await runPromise(readPairingPath)); - // The pairing page signs in and then leaves itself. Going anywhere before it has done - // so cancels the sign-in, and the next page is the pairing page again. - await expect(browser).not.toHaveURL(/\/pair(?:[?#]|$)/, { timeout: 60_000 }); - if (typeof target !== "string") { - const environment = await runPromise(environmentId(app.baseUrl ?? "")); - await app.open(`/${environment}/${target.threadId}`); - } else if (target !== "/") await app.open(target); + const baseUrl = app.baseUrl ?? ""; + await browser.setCookies(await runPromise(signIn(baseUrl))); + await app.open( + typeof target === "string" + ? target + : `/${await runPromise(environmentId(baseUrl))}/${target.threadId}`, + ); }, }); await runPromise(cleanup);