Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(ci): isolate UI E2E D1 runtime (#487)
Gustavo Ye66a9fd135393
diff --git a/.github/workflows/e2e-ui.yml b/.github/workflows/e2e-ui.ymlindex 825b676df..15dc33cf7 100644--- a/.github/workflows/e2e-ui.yml+++ b/.github/workflows/e2e-ui.yml@@ -59,7 +59,7 @@ jobs:node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile- - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\n' > src/web/.dev.vars+ - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars- id: playwright-versionworking-directory: src/webrun: |diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsxindex d2058dfda..e993c3edb 100644--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx@@ -18,6 +18,7 @@ import { Button } from "@/components/ui/button"import { apiFetch, toastApiError } from "@/lib/api/client"import { tid } from "@/lib/community/testids"import { isLocalMode, WS_DO_PORT_DEFAULT } from "@/lib/utils"+import { websocketUrl } from "@/lib/websocket-url"// Community daemon HTTP/WS endpoints live on the same worker + ws-do as the// rest of the app — see use-user-ws.ts, which connects to the identical@@ -37,8 +38,8 @@ function buildPairCommand(machineKey: string): string {function pairEndpoints(): { serverUrl: string; wsUrl: string } {const wsUrl = isLocal- ? `ws://localhost:${WS_DO_PORT_DEFAULT}`- : `${location.origin.replace("http", "ws")}/api/ws/community-daemon`+ ? websocketUrl("community-daemon", { local: true, port: WS_DO_PORT_DEFAULT })+ : websocketUrl("community-daemon", { local: false, origin: location.origin })return { serverUrl: location.origin, wsUrl }}diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.tsindex ef87a190f..0e21f4e9a 100644--- a/src/web/src/lib/use-user-ws.test.ts+++ b/src/web/src/lib/use-user-ws.test.ts@@ -247,6 +247,17 @@ describe("useUserWs", () => {expect(onMsg).not.toHaveBeenCalled()})+ it("uses the web websocket route with the token response's local port", async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ userId: "user-1", token: "tok-123", wsPort: 3000 }),+ } as Response)++ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })++ expect(MockWebSocket.instances[0]?.url).toBe("ws://localhost:3000/api/ws/user?userId=user-1")+ })+it("opens the access gate only after auth.ok", async () => {setupTokenFetch()diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex 3e4278b42..b6604d0b5 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -11,6 +11,7 @@ import {type CommunityWsFrameDropReason,} from "@/lib/analytics"import { isLocalMode, WS_DO_PORT_DEFAULT } from "@/lib/utils"+import { websocketUrl } from "@/lib/websocket-url"const isLocal = isLocalMode()const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000@@ -199,9 +200,10 @@ export function useUserWs(}}- const url = isLocal- ? `ws://localhost:${wsPort}/?userId=${userId}`- : `${location.origin.replace("http", "ws")}/api/ws/user?userId=${userId}`+ const wsBaseUrl = isLocal+ ? websocketUrl("user", { local: true, port: wsPort })+ : websocketUrl("user", { local: false, origin: location.origin })+ const url = `${wsBaseUrl}?userId=${userId}`let ws: WebSockettry {diff --git a/src/web/src/lib/websocket-url.test.ts b/src/web/src/lib/websocket-url.test.tsnew file mode 100644index 000000000..adc0061dc--- /dev/null+++ b/src/web/src/lib/websocket-url.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from "vitest"+import { websocketUrl } from "./websocket-url"++describe("websocketUrl", () => {+ it("routes local users and machines through the web worker", () => {+ const options = { local: true, port: 3000 } as const++ expect(websocketUrl("user", options)).toBe("ws://localhost:3000/api/ws/user")+ expect(websocketUrl("community-daemon", options)).toBe("ws://localhost:3000/api/ws/community-daemon")+ })++ it("uses the public secure websocket origin in production", () => {+ expect(websocketUrl("user", {+ local: false,+ origin: "https://alook.ai",+ })).toBe("wss://alook.ai/api/ws/user")+ })+})diff --git a/src/web/src/lib/websocket-url.ts b/src/web/src/lib/websocket-url.tsnew file mode 100644index 000000000..6e75c9eca--- /dev/null+++ b/src/web/src/lib/websocket-url.ts@@ -0,0 +1,11 @@+export type WebSocketTarget = "user" | "community-daemon"++export function websocketUrl(+ target: WebSocketTarget,+ options: { local: true; port: number } | { local: false; origin: string },+): string {+ const base = options.local+ ? `ws://localhost:${options.port}`+ : options.origin.replace("http", "ws")+ return `${base}/api/ws/${target}`+}diff --git a/src/web/src/test/e2e-seed-retry.test.ts b/src/web/src/test/e2e-seed-retry.test.tsnew file mode 100644index 000000000..3665366ec--- /dev/null+++ b/src/web/src/test/e2e-seed-retry.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it, vi } from "vitest"+import {+ isRetryableSeedStatus,+ retrySeedRequest,+ seedRetryDelayMs,+} from "./e2e-ui/_fixtures/seed-retry"++describe("UI E2E seed retry", () => {+ it("retries transient auth, rate-limit, and server failures", () => {+ expect(isRetryableSeedStatus(401)).toBe(true)+ expect(isRetryableSeedStatus(403)).toBe(true)+ expect(isRetryableSeedStatus(429)).toBe(true)+ expect(isRetryableSeedStatus(503)).toBe(true)+ expect(isRetryableSeedStatus(400)).toBe(false)+ expect(isRetryableSeedStatus(404)).toBe(false)+ })++ it("honors Retry-After for rate-limited fixture writes", () => {+ expect(seedRetryDelayMs({ status: 429, headers: new Headers({ "Retry-After": "7" }) })).toBe(7000)+ expect(seedRetryDelayMs({ status: 429, headers: new Headers() })).toBe(400)+ expect(seedRetryDelayMs({ status: 503, headers: new Headers({ "Retry-After": "7" }) })).toBe(400)+ })++ it("waits the advertised delay and retries a rate-limited request", async () => {+ const request = vi.fn()+ .mockResolvedValueOnce(new Response(null, {+ status: 429,+ headers: { "Retry-After": "7" },+ }))+ .mockResolvedValueOnce(new Response(null, { status: 201 }))+ const wait = vi.fn().mockResolvedValue(undefined)++ const response = await retrySeedRequest(request, wait)++ expect(response.status).toBe(201)+ expect(request).toHaveBeenCalledTimes(2)+ expect(wait).toHaveBeenCalledOnce()+ expect(wait).toHaveBeenCalledWith(7000)+ })++ it("does not retry an ordinary client error", async () => {+ const request = vi.fn()+ .mockResolvedValueOnce(new Response(null, { status: 400 }))+ .mockResolvedValueOnce(new Response(null, { status: 201 }))+ const wait = vi.fn().mockResolvedValue(undefined)++ const response = await retrySeedRequest(request, wait)++ expect(response.status).toBe(400)+ expect(request).toHaveBeenCalledOnce()+ expect(wait).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/test/e2e-service-definitions.test.ts b/src/web/src/test/e2e-service-definitions.test.tsnew file mode 100644index 000000000..b82cecb8f--- /dev/null+++ b/src/web/src/test/e2e-service-definitions.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vitest"+import { serviceDefinitions } from "./e2e-ui/_setup/services"++describe("UI E2E service definitions", () => {+ it("uses one Wrangler runtime for web and ws-do in CI", () => {+ const definitions = serviceDefinitions(true)++ expect(definitions).toHaveLength(1)+ expect(definitions[0]).toMatchObject({ name: "web-ws-do" })+ expect(definitions[0]?.args).toEqual(expect.arrayContaining([+ "src/web/wrangler.toml",+ "src/ws-do/wrangler.toml",+ "--persist-to",+ "src/web/.wrangler/state",+ ]))+ })++ it("keeps the fast two-process topology for local iteration", () => {+ expect(serviceDefinitions(false).map((definition) => definition.name)).toEqual(["web", "ws-do"])+ })+})diff --git a/src/web/src/test/e2e-ui/_fixtures/seed-retry.ts b/src/web/src/test/e2e-ui/_fixtures/seed-retry.tsnew file mode 100644index 000000000..95c232f7f--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/seed-retry.ts@@ -0,0 +1,30 @@+import { parseRetryAfterSeconds } from "@/lib/retry-after"++const DEFAULT_RETRY_DELAY_MS = 400++export function isRetryableSeedStatus(status: number): boolean {+ return status === 401 || status === 403 || status === 429 || status >= 500+}++export function seedRetryDelayMs(response: Pick<Response, "status" | "headers">): number {+ if (response.status !== 429) return DEFAULT_RETRY_DELAY_MS+ const retryAfterSeconds = parseRetryAfterSeconds(response.headers)+ return retryAfterSeconds === null+ ? DEFAULT_RETRY_DELAY_MS+ : retryAfterSeconds * 1000+}++export async function retrySeedRequest(+ request: () => Promise<Response>,+ wait: (delayMs: number) => Promise<void> = (delayMs) => (+ new Promise((resolve) => setTimeout(resolve, delayMs))+ ),+): Promise<Response> {+ let response: Response | undefined+ for (let attempt = 0; attempt < 3; attempt++) {+ response = await request()+ if (response.ok || !isRetryableSeedStatus(response.status)) return response+ if (attempt < 2) await wait(seedRetryDelayMs(response))+ }+ return response!+}diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.tsindex 53b9cefc5..ec3287af1 100644--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts@@ -1,6 +1,7 @@import { WEB_URL } from "../_setup/paths"import { sessionCookie } from "./community-fixture"import type { UserKey } from "../_setup/users"+import { isRetryableSeedStatus, retrySeedRequest, seedRetryDelayMs } from "./seed-retry"// API-driven precondition seeding for the Playwright specs. Deliberately does// NOT import @alook/test-utils (that barrel pulls in better-sqlite3 +@@ -8,11 +9,9 @@ import type { UserKey } from "../_setup/users"// the same community routes over HTTP with a user's session cookie — the// operations under test are still exercised through the UI in the specs.// Statuses worth retrying: a transient auth race (401/403 before the session-// cookie is fully established on a cold worker) and D1/WAL contention (5xx).-// A 4xx that isn't auth is a real precondition failure — don't mask it.-function isRetryableStatus(status: number): boolean {- return status === 401 || status === 403 || status >= 500-}+// cookie is fully established on a cold worker), fixture-burst rate limiting+// (429), and transient service failures (5xx). Other 4xx responses are real+// precondition failures and must not be masked.async function postRaw(key: UserKey, path: string, body?: unknown): Promise<Response> {return fetch(`${WEB_URL}${path}`, {@@ -27,15 +26,9 @@ async function postRaw(key: UserKey, path: string, body?: unknown): Promise<Resp}async function post(key: UserKey, path: string, body?: unknown): Promise<Response> {- let lastStatus = 0- for (let attempt = 0; attempt < 3; attempt++) {- const res = await postRaw(key, path, body)- if (res.ok) return res- lastStatus = res.status- if (!isRetryableStatus(res.status)) break- await new Promise((r) => setTimeout(r, 400))- }- throw new Error(`POST ${path} failed (${lastStatus})`)+ const response = await retrySeedRequest(() => postRaw(key, path, body))+ if (response.ok) return response+ throw new Error(`POST ${path} failed (${response.status})`)}export async function seedServer(owner: UserKey, name: string): Promise<string> {@@ -89,8 +82,8 @@ export async function seedJoinServer(owner: UserKey, joiner: UserKey, serverId:})if (res.ok || res.status === 400) returnlastStatus = res.status- if (!isRetryableStatus(res.status)) break- await new Promise((r) => setTimeout(r, 500))+ if (!isRetryableSeedStatus(res.status)) break+ await new Promise((r) => setTimeout(r, seedRetryDelayMs(res)))}throw new Error(`seedJoinServer join failed (${lastStatus})`)}@@ -138,10 +131,11 @@ async function findFriendshipId(requester: UserKey, targetUserId: string): Promiexport async function seedFriendship(requester: UserKey, addressee: UserKey, targetUserId: string): Promise<string> {let reqRes: Response | undefinedfor (let attempt = 0; attempt < 3; attempt++) {- reqRes = await postRaw(requester, "/api/community/friends/request", { userId: targetUserId })+ const response = await postRaw(requester, "/api/community/friends/request", { userId: targetUserId })+ reqRes = response// 409 = already friends / request already sent — a valid idempotent state.- if (reqRes.ok || reqRes.status === 409 || !isRetryableStatus(reqRes.status)) break- await new Promise((r) => setTimeout(r, 400))+ if (response.ok || response.status === 409 || !isRetryableSeedStatus(response.status)) break+ await new Promise((r) => setTimeout(r, seedRetryDelayMs(response)))}if (reqRes!.status === 409) {const existing = await findFriendshipId(requester, targetUserId)@@ -215,8 +209,8 @@ export async function renameUser(key: UserKey, name: string): Promise<void> {})if (res.ok) returnlastStatus = res.status- if (!isRetryableStatus(res.status)) break- await new Promise((r) => setTimeout(r, 400))+ if (!isRetryableSeedStatus(res.status)) break+ await new Promise((r) => setTimeout(r, seedRetryDelayMs(res)))}throw new Error(`renameUser failed (${lastStatus})`)}diff --git a/src/web/src/test/e2e-ui/_setup/global-setup.ts b/src/web/src/test/e2e-ui/_setup/global-setup.tsindex 58afb9201..08f846a87 100644--- a/src/web/src/test/e2e-ui/_setup/global-setup.ts+++ b/src/web/src/test/e2e-ui/_setup/global-setup.ts@@ -3,13 +3,15 @@ import { resolve } from "path"import { chromium } from "@playwright/test"import { AUTH_DIR, MANIFEST_PATH } from "./paths"import { loginAndSaveState } from "./auth"-import { resetDb, startServices, backupState, REUSE_EXISTING } from "./services"+import { prepareServices, resetDb, startServices, backupState, REUSE_EXISTING } from "./services"import { USER_KEYS, type RunManifest, type SeededUser, type UserKey } from "./users"export default async function globalSetup(): Promise<void> {rmSync(AUTH_DIR, { recursive: true, force: true })mkdirSync(AUTH_DIR, { recursive: true })+ prepareServices()+// Local runs: back up the developer's D1/DO state, wipe to a clean DB, and// restore it on teardown (see global-teardown). CI has no prior state.let backedUp = falsediff --git a/src/web/src/test/e2e-ui/_setup/services.ts b/src/web/src/test/e2e-ui/_setup/services.tsindex cd37b3135..936b43073 100644--- a/src/web/src/test/e2e-ui/_setup/services.ts+++ b/src/web/src/test/e2e-ui/_setup/services.ts@@ -9,9 +9,16 @@ export interface ManagedService {healthUrl: string}+export interface ServiceDefinition {+ name: string+ args: string[]+ healthUrl: string+}+// Reuse a server the developer already has running (local iteration). CI// always starts fresh, so REUSE is off there.export const REUSE_EXISTING = !process.env.CI+export const SINGLE_RUNTIME = !!process.env.CI// Local D1/DO state that `db:reset` wipes. Backing it up to a sibling path// (outside `.wrangler/state`, so `rm -rf .wrangler/state` can't touch it)@@ -55,6 +62,25 @@ async function waitForHealth(url: string, name: string, timeoutMs = 90_000): Prothrow new Error(`${name} not ready after ${timeoutMs}ms (${url})`)}+export function prepareServices(): void {+ if (!SINGLE_RUNTIME) return+ const res = spawnSync(+ "pnpm",+ ["--filter", "@alook/web", "exec", "opennextjs-cloudflare", "build"],+ {+ cwd: REPO_ROOT,+ stdio: "inherit",+ env: {+ ...process.env,+ NEXT_PUBLIC_WS_DO_PORT: String(portOf(WEB_URL) ?? 3000),+ },+ },+ )+ if (res.status !== 0) {+ throw new Error(`web worker build failed (exit ${res.status}, signal ${res.signal})`)+ }+}+export function resetDb(): void {// `wrangler d1 migrations apply` prints the full migrations table (twice) on// every run — noise in CI when it succeeds. DROP stdout entirely (that table@@ -103,15 +129,46 @@ function killPortOrphans(ports: number[]): void {}}-function startService(name: string, filter: string, healthUrl: string): ManagedService {- const logFd = openSync(resolve(SERVICE_LOG_DIR, `${name}.log`), "a")+export function serviceDefinitions(singleRuntime: boolean): ServiceDefinition[] {+ const webHealth = `${WEB_URL}/api/health`+ const wsHealth = `${WS_URL}/health`+ if (!singleRuntime) {+ return [+ { name: "web", args: ["--filter", "@alook/web", "dev"], healthUrl: webHealth },+ { name: "ws-do", args: ["--filter", "@alook/ws-do", "dev"], healthUrl: wsHealth },+ ]+ }++ return [{+ name: "web-ws-do",+ args: [+ "exec",+ "wrangler",+ "dev",+ "-c",+ "src/web/wrangler.toml",+ "-c",+ "src/ws-do/wrangler.toml",+ "--persist-to",+ "src/web/.wrangler/state",+ "--port",+ String(portOf(WEB_URL) ?? 3000),+ "--local",+ "--show-interactive-dev-session=false",+ ],+ healthUrl: webHealth,+ }]+}++function startService(definition: ServiceDefinition): ManagedService {+ const logFd = openSync(resolve(SERVICE_LOG_DIR, `${definition.name}.log`), "a")try {- const proc = spawn("pnpm", ["--filter", filter, "dev"], {+ const proc = spawn("pnpm", definition.args, {cwd: REPO_ROOT,stdio: ["ignore", logFd, logFd],detached: true,})- return { name, proc, healthUrl }+ return { name: definition.name, proc, healthUrl: definition.healthUrl }} finally {closeSync(logFd)}@@ -152,17 +209,15 @@ export async function startServices(): Promise<ManagedService[]> {// Starting fresh — clear any orphaned dev servers on our ports first so a// prior crashed run doesn't leave 3000/8789 occupied (or get reused).- const ports = [portOf(WEB_URL), portOf(WS_URL)].filter((p): p is number => p != null)+ const ports = (SINGLE_RUNTIME ? [portOf(WEB_URL)] : [portOf(WEB_URL), portOf(WS_URL)])+ .filter((p): p is number => p != null)killPortOrphans(ports)// Give the OS a moment to release the sockets before we bind them.await new Promise((r) => setTimeout(r, 1000))rmSync(SERVICE_LOG_DIR, { recursive: true, force: true })mkdirSync(SERVICE_LOG_DIR, { recursive: true })- const services = [- startService("web", "@alook/web", webHealth),- startService("ws-do", "@alook/ws-do", wsHealth),- ]+ const services = serviceDefinitions(SINGLE_RUNTIME).map(startService)await Promise.all(services.map((s) => waitForHealth(s.healthUrl, s.name)))await warmUpRoutes()