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
test(e2e): isolate case accounts and preserve cleanup errors (#947)
Generd633ea70917c
diff --git a/src/web/src/test/e2e-fixture-isolation.test.ts b/src/web/src/test/e2e-fixture-isolation.test.tsindex ca7392181..fe694d363 100644--- a/src/web/src/test/e2e-fixture-isolation.test.ts+++ b/src/web/src/test/e2e-fixture-isolation.test.ts@@ -1,13 +1,46 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import type { Browser, BrowserContext, Page, TestFixture, TestInfo } from "@playwright/test"+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs"+import { resolve } from "path"+import { test as caseTest, type CaseActors } from "./e2e-ui/_fixtures/case-fixture"import { cleanupGeometryServers, seedGeometryRoutes } from "./e2e-ui/_fixtures/community-loading-geometry"import { seedChannel, seedDm, seedForumThread, seedMessage, seedServer, seedThread } from "./e2e-ui/_fixtures/seed"+import * as legacySeed from "./e2e-ui/_fixtures/seed"++type CaseFactory = (roles: readonly ("alice" | "bob" | "carol")[]) => Promise<CaseActors>+type Registration = {+ caseActors: TestFixture<CaseFactory, { browser: Browser; caseCleanupGuard: void }>+ caseCleanupGuard: [TestFixture<void, Record<string, never>>, { auto: true }]+}++const fixture = vi.hoisted(() => ({+ directory: `/tmp/alook-case-fixture-unit-${process.pid}`,+ registration: undefined as Registration | undefined,+ login: vi.fn(),+}))vi.mock("./e2e-ui/_fixtures/community-fixture", () => ({+ test: { extend: (registration: Registration) => {+ fixture.registration = registration+ return { expect: {} }+ } },expect: {},sessionCookie: (key: string) => `fixture-user=${key}`,userId: (key: string) => `user-${key}`,}))+vi.mock("./e2e-ui/_setup/auth", () => ({ loginAndSaveState: fixture.login }))+vi.mock("./e2e-ui/_setup/paths", () => ({+ AUTH_DIR: fixture.directory,+ SERVICE_STATE_PATH: `${fixture.directory}/service-state.json`,+ MANIFEST_PATH: `${fixture.directory}/manifest.json`,+ WEB_URL: "http://fixture.test",+}))+vi.mock("./e2e-ui/_fixtures/seed-retry", async (importOriginal) => ({+ ...await importOriginal<typeof import("./e2e-ui/_fixtures/seed-retry")>(),+ retrySeedRequest: (request: () => Promise<Response>) => request(),+}))+vi.mock("./e2e-ui/_fixtures/seed", async (importOriginal) => ({...await importOriginal<typeof import("./e2e-ui/_fixtures/seed")>(),seedServer: vi.fn(),@@ -39,8 +72,8 @@ describe("geometry fixture backend resource isolation", () => {const request = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))vi.stubGlobal("fetch", request)- const routes = await seedGeometryRoutes(owned)- await cleanupGeometryServers(owned)+ const routes = await seedGeometryRoutes(owned, legacySeed, (key) => `user-${key}`)+ await cleanupGeometryServers(owned, legacySeed)expect(routes).toHaveLength(9)expect(owned).toEqual(Array.from({ length: 20 }, (_, index) => `owned-${index + 1}`))@@ -60,8 +93,8 @@ describe("geometry fixture backend resource isolation", () => {const request = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))vi.stubGlobal("fetch", request)- await expect(seedGeometryRoutes(owned)).rejects.toThrow("seed failed")- await cleanupGeometryServers(owned)+ await expect(seedGeometryRoutes(owned, legacySeed, (key) => `user-${key}`)).rejects.toThrow("seed failed")+ await cleanupGeometryServers(owned, legacySeed)expect(owned).toEqual(["owned-first", "owned-second"])expect(request.mock.calls.map(([url]) => new URL(url).pathname)).toEqual([@@ -78,7 +111,7 @@ describe("geometry fixture backend resource isolation", () => {.mockResolvedValueOnce(new Response(null, { status: 204 }))vi.stubGlobal("fetch", request)- const error = await cleanupGeometryServers(["failed", "disconnected", "already-gone", "remaining"])+ const error = await cleanupGeometryServers(["failed", "disconnected", "already-gone", "remaining"], legacySeed).catch((failure: AggregateError) => failure)expect(error).toBeInstanceOf(AggregateError)@@ -91,3 +124,400 @@ describe("geometry fixture backend resource isolation", () => {])})})++describe("test-scoped case actors and cleanup", () => {+ const actors = new Map<string, { key: string; userId: string; name: string }>()+ const servers = new Map<string, { id: string; ownerId: string }>()+ const deniedDeletes = new Set<string>()+ let nextServer = 0+ let dmCursor = 0+ let dmCreated = false+ let baselineFault: "stale" | "truncated" | "error" | "malformed" | "profile" | undefined+ let loseServerResponse = false+ let closeError: Error | undefined+ const closed: Array<{ isClosed: () => boolean }> = []++ const info = (testId: string, workerIndex = 0): TestInfo => ({+ testId,+ workerIndex,+ parallelIndex: 0,+ project: { name: "chromium" },+ annotations: [],+ attach: vi.fn(async () => undefined),+ }) as unknown as TestInfo++ const browser = (): Browser => ({+ newContext: vi.fn(async () => {+ let isClosed = false+ const page = { isClosed: () => isClosed } as Page+ const context = {+ newPage: async () => page,+ close: vi.fn(async () => {+ isClosed = true+ if (closeError) throw closeError+ }),+ }+ closed.push(page)+ return context+ }),+ }) as unknown as Browser++ const run = (testInfo: TestInfo, use: (factory: CaseFactory) => Promise<void>, currentBrowser = browser()) => {+ expect(caseTest).toBeDefined()+ return fixture.registration!.caseActors({ browser: currentBrowser, caseCleanupGuard: undefined }, use, testInfo)+ }++ beforeEach(() => {+ vi.resetAllMocks()+ actors.clear()+ servers.clear()+ deniedDeletes.clear()+ closed.length = 0+ nextServer = 0+ dmCursor = 0+ dmCreated = false+ baselineFault = undefined+ loseServerResponse = false+ closeError = undefined+ rmSync(fixture.directory, { force: true, recursive: true })+ mkdirSync(fixture.directory, { recursive: true })+ writeFileSync(resolve(fixture.directory, "manifest.json"), JSON.stringify({ stamp: "case-fixture-run", users: {} }))+ writeFileSync(resolve(fixture.directory, "service-state.json"), JSON.stringify({ status: "healthy", services: [{ name: "web" }], restorePending: false }))+ fixture.login.mockImplementation(async (_browser, key: string, stamp: string, storageState: string) => {+ const token = `${key}-${stamp}`+ const value = { key, userId: token, name: `e2e-${token}` }+ actors.set(token, value)+ writeFileSync(storageState, JSON.stringify({ cookies: [{ name: "better-auth.session_token", value: token }] }))+ return { ...value, email: `${value.name}@alook.test`, storageState }+ })+ vi.stubGlobal("fetch", vi.fn(async (input: string, options?: RequestInit) => {+ const path = new URL(input).pathname+ const cookie = (options?.headers as Record<string, string>).Cookie+ const actor = actors.get(cookie.split("=")[1])!+ if (options?.method === "DELETE") {+ const id = path.split("/").at(-1)!+ if (deniedDeletes.has(id)) return new Response("{}", { status: 500 })+ const found = servers.get(id)+ if (found && found.ownerId !== actor.userId) return new Response("{}", { status: 403 })+ servers.delete(id)+ return new Response(null, { status: found ? 204 : 404 })+ }+ if (options?.method === "POST") {+ if (path === "/api/community/servers") {+ const server = { id: `owned-${++nextServer}`, ownerId: actor.userId }+ servers.set(server.id, server)+ if (loseServerResponse) return new Response("invalid server JSON")+ return Response.json({ server })+ }+ if (path === "/api/community/channels") {+ dmCreated = true+ return Response.json({ conversation: { id: "case-dm" } })+ }+ if (path.endsWith("/friends/request")) return Response.json({ id: "case-friendship" })+ return Response.json({})+ }+ if (path.endsWith("/profile")) return Response.json({ id: actor.userId, name: actor.name, aboutMe: baselineFault === "profile" ? "old account profile" : "", avatarVersion: 0, bannerColor: null, statusEmoji: null, statusText: "" })+ if (path === "/api/community/servers") return Response.json({ servers: [...servers.values()].filter((server) => server.ownerId === actor.userId) })+ if (path.endsWith("/read-state")) return Response.json({ readStates: dmCreated ? [{ channelId: "case-dm", lastReadSeq: dmCursor }] : [] })+ if (path.endsWith("/attention")) {+ if (baselineFault === "error") return Response.json({ error: "Unavailable" }, { status: 503 })+ if (baselineFault === "malformed") return Response.json({ scopes: null, items: [] })+ return Response.json({ scopes: [], items: [], stale: baselineFault === "stale", truncated: baselineFault === "truncated" })+ }+ const field = path.endsWith("/dms") ? "conversations" : path.endsWith("/server-folders") ? "folders" : path.endsWith("/marks") ? "marked" : path.endsWith("/accepted") ? "friends" : path.endsWith("/pending") ? "pending" : "blocked"+ return Response.json({ [field]: [] })+ }))+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ rmSync(fixture.directory, { force: true, recursive: true })+ })++ it("uses one private actor across devices but new identities for the next case", async () => {+ const currentBrowser = browser()+ let first = ""+ await run(info("first"), async (create) => {+ const users = await create(["alice", "bob"])+ first = users.userId("alice")+ await users.asUser("alice")+ await users.asUser("alice")+ await users.asUser("bob")+ await users.seed.seedServer("alice", "owned")+ const requests = vi.mocked(fetch).mock.calls.length+ await expect(users.seed.seedChannel("alice", "previous-case-server", "foreign")).rejects.toThrow("Foreign case resource")+ await expect(users.seed.seedMessage("alice", "previous-case-channel", "foreign")).rejects.toThrow("Foreign case resource")+ await expect(users.seed.seedDm("alice", "previous-case-user")).rejects.toThrow("unknown fixture user")+ expect(vi.mocked(fetch).mock.calls).toHaveLength(requests)+ await expect(users.asUser("carol")).rejects.toThrow("Undeclared")+ await expect(users.seed.seedServer("carol", "foreign")).rejects.toThrow("Undeclared")+ }, currentBrowser)+ const states = vi.mocked(currentBrowser.newContext).mock.calls.map(([options]) => options?.storageState)+ expect(states[0]).toBe(states[1])+ expect(states[2]).not.toBe(states[0])+ expect(closed.every((page) => page.isClosed())).toBe(true)+ expect(servers.size).toBe(0)+ await run(info("second"), async (create) => {+ const users = await create(["alice"])+ expect(users.userId("alice")).not.toBe(first)+ })+ })++ it("keeps the original body failure while retiring successful partial seeds", async () => {+ const original = new Error("first assertion failed")+ await expect(run(info("partial"), async (create) => {+ const users = await create(["alice"])+ await users.asUser("alice")+ await users.seed.seedServer("alice", "first")+ await users.seed.seedServer("alice", "second")+ throw original+ })).rejects.toBe(original)+ expect(servers.size).toBe(0)+ expect(closed.every((page) => page.isClosed())).toBe(true)+ })++ it("retains body and cleanup errors, attempts all resources and blocks a restarted successor", async () => {+ const original = new Error("first assertion failed")+ closeError = new Error("context close failed")+ const failure = await run(info("dirty"), async (create) => {+ const users = await create(["alice"])+ await users.asUser("alice")+ const failed = await users.seed.seedServer("alice", "failed")+ await users.seed.seedServer("alice", "remaining")+ deniedDeletes.add(failed)+ throw original+ }).catch((error: AggregateError) => error)+ expect(failure).toBeInstanceOf(AggregateError)+ expect((failure as AggregateError).errors[0]).toBe(original)+ expect(servers.size).toBe(1)+ const record = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(record.unresolvedServers).toHaveLength(1)+ const restarted = info("successor", 1)+ await expect(fixture.registration!.caseCleanupGuard[0]({}, async () => { throw new Error("must not start successor") }, restarted)).rejects.toThrow("blocked")+ expect(restarted.annotations).toEqual([expect.objectContaining({ type: "fixture-blocked" })])+ expect(fixture.login).toHaveBeenCalledTimes(1)+ })++ it.each([+ ["stale", "incomplete"],+ ["truncated", "incomplete"],+ ["error", "failed (503)"],+ ["malformed", "must be empty"],+ ["profile", "modified profile defaults"],+ ] as const)("rejects a %s fresh-account baseline", async (fault, message) => {+ baselineFault = fault+ await expect(run(info(fault), async (create) => { await create(["alice"]) })).rejects.toThrow(message)+ })++ it("rejects a reused unowned stack before creating an account", async () => {+ writeFileSync(resolve(fixture.directory, "service-state.json"), JSON.stringify({ status: "healthy", services: [] }))+ await expect(run(info("unowned"), async (create) => { await create(["alice"]) })).rejects.toThrow("not owned")+ expect(fixture.login).not.toHaveBeenCalled()+ })++ it("reconciles an owned server when creation succeeded but its response was lost", async () => {+ loseServerResponse = true+ await expect(run(info("lost-response"), async (create) => {+ const users = await create(["alice"])+ await users.seed.seedServer("alice", "lost")+ })).rejects.toBeInstanceOf(SyntaxError)+ expect(servers.size).toBe(0)+ expect(vi.mocked(fetch).mock.calls.some(([, options]) => options?.method === "DELETE")).toBe(true)+ })++ it("rejects a nonzero cursor created by the DM handshake without rewriting the expectation", async () => {+ await run(info("dm-conflict"), async (create) => {+ const users = await create(["alice", "bob"])+ dmCursor = 1+ await expect(users.seed.seedDm("alice", users.userId("bob"))).rejects.toThrow("zero-cursor")+ })+ })++ it("records an unclosed login context before actor assignment and blocks its successor", async () => {+ const original = new Error("login page failed")+ const closing = new Error("login context close failed")+ const context = { close: vi.fn().mockRejectedValue(closing) } as unknown as BrowserContext+ fixture.login.mockImplementation(async (_browser, _key, _stamp, _state, owner) => {+ owner.created(context)+ throw original+ })+ const failed = await run(info("login-dirty"), async (create) => { await create(["alice"]) })+ .catch((error: AggregateError) => error)+ expect(failed).toBeInstanceOf(AggregateError)+ expect((failed as AggregateError).errors).toEqual([original, closing])+ expect(context.close).toHaveBeenCalledOnce()+ const record = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(record.unresolvedServers).toEqual([])+ expect(record.unresolvedContexts).toEqual([{ role: "alice", kind: "login", ordinal: 0 }])+ const successor = info("login-successor", 1)+ await expect(fixture.registration!.caseCleanupGuard[0]({}, async () => { throw new Error("must not enter") }, successor)).rejects.toThrow("blocked")+ expect(fixture.login).toHaveBeenCalledOnce()+ })++ it("retires a recovered login context while keeping the original setup failure", async () => {+ const original = new Error("login failed after context creation")+ const context = { close: vi.fn().mockResolvedValue(undefined) } as unknown as BrowserContext+ fixture.login.mockImplementation(async (_browser, _key, _stamp, _state, owner) => {+ owner.created(context)+ throw original+ })+ const current = info("login-recovered")+ await expect(run(current, async (create) => { await create(["alice"]) })).rejects.toBe(original)+ expect(context.close).toHaveBeenCalledOnce()+ const cleanup = vi.mocked(current.attach).mock.calls.find(([name]) => name === "case-cleanup")![1]!+ const result = JSON.parse(cleanup.body!.toString())+ expect(result.outcomes.contexts).toEqual([{ role: "alice", kind: "login", ordinal: 0, closed: true }])+ await expect(fixture.registration!.caseCleanupGuard[0]({}, async () => undefined, info("clean-successor", 1))).resolves.toBeUndefined()+ })++ it("does not close a successfully retired login context again during teardown", async () => {+ const signIn = fixture.login.getMockImplementation()!+ const context = { close: vi.fn().mockResolvedValue(undefined) } as unknown as BrowserContext+ fixture.login.mockImplementation(async (currentBrowser, key, stamp, state, owner) => {+ owner.created(context)+ const result = await signIn(currentBrowser, key, stamp, state)+ await context.close()+ owner.closed(context)+ return result+ })+ await run(info("login-closed"), async (create) => { await create(["alice"]) })+ expect(context.close).toHaveBeenCalledOnce()+ })++ it("closes an actor context when its page creation fails", async () => {+ const original = new Error("actor page failed")+ const context = {+ newPage: vi.fn().mockRejectedValue(original),+ close: vi.fn().mockResolvedValue(undefined),+ } as unknown as BrowserContext+ const currentBrowser = { newContext: vi.fn().mockResolvedValue(context) } as unknown as Browser+ await expect(run(info("actor-page"), async (create) => {+ const users = await create(["alice"])+ await users.asUser("alice")+ }, currentBrowser)).rejects.toBe(original)+ expect(context.close).toHaveBeenCalledOnce()+ })+})++describe("real login helper context exit", () => {+ const login = async (...args: Parameters<typeof import("./e2e-ui/_setup/auth").loginAndSaveState>) => {+ const real = await vi.importActual<typeof import("./e2e-ui/_setup/auth")>("./e2e-ui/_setup/auth")+ return real.loginAndSaveState(...args)+ }++ const setup = () => {+ const page = {+ goto: vi.fn().mockResolvedValue(undefined),+ waitForURL: vi.fn().mockResolvedValue(undefined),+ getByRole: vi.fn(() => ({+ waitFor: vi.fn().mockResolvedValue(undefined),+ fill: vi.fn().mockResolvedValue(undefined),+ click: vi.fn().mockResolvedValue(undefined),+ })),+ }+ const context = {+ newPage: vi.fn().mockResolvedValue(page),+ close: vi.fn().mockResolvedValue(undefined),+ request: { get: vi.fn().mockResolvedValue({ ok: () => true, json: async () => ({ userId: "unit-login-user" }) }) },+ addCookies: vi.fn().mockResolvedValue(undefined),+ clearCookies: vi.fn().mockResolvedValue(undefined),+ storageState: vi.fn().mockResolvedValue(undefined),+ }+ const currentBrowser = { newContext: vi.fn().mockResolvedValue(context) } as unknown as Browser+ const actualContext = context as unknown as BrowserContext+ const owned = new Set<BrowserContext>()+ const owner = {+ created: vi.fn((value: BrowserContext) => { owned.add(value) }),+ closed: vi.fn((value: BrowserContext) => { owned.delete(value) }),+ }+ return { page, context, actualContext, currentBrowser, owned, owner }+ }++ it("registers before newPage and closes after a page creation failure", async () => {+ const s = setup()+ const original = new Error("newPage failed")+ s.context.newPage.mockImplementation(async () => {+ expect(s.owned.has(s.actualContext)).toBe(true)+ throw original+ })+ await expect(login(s.currentBrowser, "alice", "unit", "unit-state.json", s.owner)).rejects.toBe(original)+ expect(s.context.close).toHaveBeenCalledOnce()+ expect(s.owner.closed).toHaveBeenCalledWith(s.actualContext)+ expect(s.owned.size).toBe(0)+ })++ it("keeps page and close errors in order without retiring the unresolved context", async () => {+ const s = setup()+ const original = new Error("newPage failed")+ const closing = new Error("close failed")+ s.context.newPage.mockRejectedValue(original)+ s.context.close.mockRejectedValue(closing)+ const failed = await login(s.currentBrowser, "alice", "unit", "unit-state.json", s.owner)+ .catch((error: AggregateError) => error)+ expect(failed).toBeInstanceOf(AggregateError)+ expect((failed as AggregateError).errors).toEqual([original, closing])+ expect(s.context.close).toHaveBeenCalledOnce()+ expect(s.owner.closed).not.toHaveBeenCalled()+ expect(s.owned.has(s.actualContext)).toBe(true)+ })++ it("retains the original sign-in failure together with a failed close", async () => {+ const s = setup()+ const original = new Error("sign-in URL failed")+ const closing = new Error("close failed after sign-in")+ s.page.waitForURL.mockRejectedValue(original)+ s.context.close.mockRejectedValue(closing)+ const failed = await login(s.currentBrowser, "alice", "unit", "unit-state.json", s.owner)+ .catch((error: AggregateError) => error)+ expect((failed as AggregateError).errors).toEqual([original, closing])+ expect(s.page.goto.mock.calls.map(([url]) => url)).toEqual(["http://fixture.test/c", "http://fixture.test/sign-in?redirect=/c"])+ expect(s.owner.closed).not.toHaveBeenCalled()+ })++ it("keeps registration until the close promise resolves", async () => {+ const s = setup()+ let release!: () => void+ const closing = new Promise<void>((resolveValue) => { release = resolveValue })+ s.context.close.mockReturnValue(closing)+ const result = login(s.currentBrowser, "alice", "unit", "unit-state.json", s.owner)+ await vi.waitFor(() => expect(s.context.close).toHaveBeenCalledOnce())+ expect(s.owned.has(s.actualContext)).toBe(true)+ expect(s.owner.closed).not.toHaveBeenCalled()+ release()+ await expect(result).resolves.toMatchObject({ key: "alice", userId: "unit-login-user", storageState: "unit-state.json" })+ expect(s.owned.size).toBe(0)+ })++ it("rejects a successful login when close fails and leaves its context owned", async () => {+ const s = setup()+ const closing = new Error("close failed after identity capture")+ s.context.close.mockRejectedValue(closing)+ await expect(login(s.currentBrowser, "alice", "unit", "unit-state.json", s.owner)).rejects.toBe(closing)+ expect(s.context.storageState).toHaveBeenCalledWith({ path: "unit-state.json" })+ expect(s.owner.closed).not.toHaveBeenCalled()+ expect(s.owned.has(s.actualContext)).toBe(true)+ })++ it("makes no registration when context creation fails", async () => {+ const s = setup()+ const original = new Error("newContext failed")+ vi.mocked(s.currentBrowser.newContext).mockRejectedValue(original)+ await expect(login(s.currentBrowser, "alice", "unit", "unit-state.json", s.owner)).rejects.toBe(original)+ expect(s.owner.created).not.toHaveBeenCalled()+ expect(s.owner.closed).not.toHaveBeenCalled()+ expect(s.context.close).not.toHaveBeenCalled()+ })++ it("preserves the legacy four-argument authentication and storage operations", async () => {+ const s = setup()+ const result = await login(s.currentBrowser, "alice", "unit", "unit-state.json")+ expect(result).toMatchObject({ key: "alice", userId: "unit-login-user", storageState: "unit-state.json" })+ expect(result.name).toBe(result.email.split("@")[0])+ expect(s.page.goto).toHaveBeenCalledWith("http://fixture.test/c", { waitUntil: "load" })+ expect(s.context.request.get).toHaveBeenCalledWith("http://fixture.test/api/ws/token")+ expect(s.context.addCookies).toHaveBeenCalledOnce()+ expect(s.context.clearCookies).toHaveBeenCalledWith({ name: /^(?:is_new_signup|is_sign_in)$/ })+ expect(s.context.storageState).toHaveBeenCalledWith({ path: "unit-state.json" })+ expect(s.context.close).toHaveBeenCalledOnce()+ })+})diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.tsindex 39fffa3c6..0d2563450 100644--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts@@ -1,15 +1,6 @@-import { expect, test, userId } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"-import {- seedChannel,- seedDm,- seedDmMessage,- seedJoinServer,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"import {communityFrameEvents,isCommunityBatchFrame,@@ -112,10 +103,14 @@ async function watchInboxRow(page: Parameters<typeof gotoAfterUserWsAuth>[0], te}, key)}-test.describe.serial("Inbox/read refresh ownership", () => {+test.describe("Inbox/read refresh ownership", () => {test.setTimeout(180_000)- test("an Inbox click closes, publishes, and hides only its exact row before read settles", async ({ asUser }) => {+ test("an Inbox click closes, publishes, and hides only its exact row before read settles", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox projection ${stamp}`)const channelAName = `project-a-${stamp}`@@ -132,7 +127,9 @@ test.describe.serial("Inbox/read refresh ownership", () => {await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()const readGate = deferred()+ actors.onCleanup(async () => { readGate.resolve() })const readStarted = deferred()+ actors.onCleanup(async () => { readStarted.resolve() })const hrefsAtRead: string[] = []await page.route(`**/api/community/channels/${channelA}/read`, async (route) => {if (route.request().method() !== "PUT") return route.continue()@@ -167,7 +164,11 @@ test.describe.serial("Inbox/read refresh ownership", () => {await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()})- test("focused A never flashes while same-window B and DM remain unread", async ({ asUser }) => {+ test("focused A never flashes while same-window B and DM remain unread", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox race mixed ${stamp}`)const channelAName = `focused-a-${stamp}`@@ -269,7 +270,11 @@ test.describe.serial("Inbox/read refresh ownership", () => {expect(readSeq(dmId)).toBe(0)})- test("a failed focused read falls back once, then retry converges", async ({ asUser }) => {+ test("a failed focused read falls back once, then retry converges", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox race failure ${stamp}`)const channelName = `failure-${stamp}`@@ -289,6 +294,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)const retryGate = deferred()+ actors.onCleanup(async () => { retryGate.resolve() })let puts = 0await page.route(`**/api/community/channels/${channelId}/read`, async (route) => {if (route.request().method() !== "PUT") return route.continue()@@ -316,7 +322,11 @@ test.describe.serial("Inbox/read refresh ownership", () => {expect(puts).toBe(2)})- test("cold forum openers publish exact child units and read only the selected opener", async ({ asUser }) => {+ test("cold forum openers publish exact child units and read only the selected opener", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox opener handoff ${stamp}`)const forumId = await seedChannel("alice", serverId, `handoff-forum-${stamp}`, "forum")@@ -390,7 +400,11 @@ test.describe.serial("Inbox/read refresh ownership", () => {expect(snapshot.readStates.some((row) => row.channelId === firstChildId)).toBe(false)})- test("cold text-child evidence projects through the canonical parent row", async ({ asUser }) => {+ test("cold text-child evidence projects through the canonical parent row", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer, seedThread } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox text opener ${stamp}`)const parentId = await seedChannel("alice", serverId, `text-parent-${stamp}`)@@ -490,7 +504,11 @@ test.describe.serial("Inbox/read refresh ownership", () => {expect(cursor(unreadChildId)).toBe(beforeCursor(unreadChildId))})- test("a later focused intent keeps its own 500ms generation", async ({ asUser }) => {+ test("a later focused intent keeps its own 500ms generation", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox race cutoff ${stamp}`)const channelName = `cutoff-${stamp}`@@ -511,7 +529,9 @@ test.describe.serial("Inbox/read refresh ownership", () => {const stopWatching = await watchInboxRow(page, tid.inboxUnreadChannel(channelId))const firstGate = deferred()+ actors.onCleanup(async () => { firstGate.resolve() })const firstStarted = deferred()+ actors.onCleanup(async () => { firstStarted.resolve() })const putStarts: number[] = []await page.route(`**/api/community/channels/${channelId}/read`, async (route) => {if (route.request().method() !== "PUT") return route.continue()diff --git a/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts b/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.tsindex e36c77126..4c4cc6795 100644--- a/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts+++ b/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts@@ -1,11 +1,6 @@import type { Page } from "@playwright/test"-import { expect, test, userId } from "./_fixtures/community-fixture"+import { expect, test, type CaseActors } from "./_fixtures/case-fixture"import { composerEditable } from "./_fixtures/actions"-import {- seedChannel,- seedDm,- seedServer,-} from "./_fixtures/seed"import { tid } from "./_fixtures/testids"const DIRECTORY_PATH = "/api/community/users/me/channel-directory"@@ -68,24 +63,27 @@ async function closeSuggestion(page: Page) {await expect(page.getByTestId(tid.channelRefPopup)).toHaveCount(0)}-test.describe.serial("DM channel-reference directory states", () => {+async function seedDirectoryCase(actors: CaseActors) {+ const { seedServer, seedChannel, seedDm } = actors.seed+ const { userId } = actors+ const serverId = await seedServer("alice", `Channel ref states ${Date.now()}`)+ const channelId = await seedChannel("alice", serverId, "general")+ const firstDmId = await seedDm("alice", userId("bob"))+ const secondDmId = await seedDm("alice", userId("carol"))+ return { serverId, channelId, firstDmId, secondDmId }+}++test.describe("DM channel-reference directory states", () => {test.setTimeout(120_000)- let serverId: string- let channelId: string- let firstDmId: string- let secondDmId: string+ test("cold pending stays anchored through query updates and resolves without false-empty", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId, firstDmId } = await seedDirectoryCase(actors)- test.beforeAll(async () => {- serverId = await seedServer("alice", `Channel ref states ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "general")- firstDmId = await seedDm("alice", userId("bob"))- secondDmId = await seedDm("alice", userId("carol"))- })-- test("cold pending stays anchored through query updates and resolves without false-empty", async ({ asUser }) => {const { page } = await asUser("alice")const gate = deferred()+ actors.onCleanup(async () => { gate.resolve() })let directoryGets = 0await page.route(`**${DIRECTORY_PATH}`, async (route) => {directoryGets += 1@@ -116,7 +114,11 @@ test.describe.serial("DM channel-reference directory states", () => {expect(directoryGets).toBe(1)})- test("resolved empty stays anchored with explicit copy", async ({ asUser }) => {+ test("resolved empty stays anchored with explicit copy", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { firstDmId } = await seedDirectoryCase(actors)+const { page } = await asUser("alice")let directoryGets = 0await page.route(`**${DIRECTORY_PATH}`, async (route) => {@@ -136,7 +138,11 @@ test.describe.serial("DM channel-reference directory states", () => {expect(directoryGets).toBe(1)})- test("cold 500 is one attempt, same-popup input is inert, and a new session retries once", async ({ asUser }) => {+ test("cold 500 is one attempt, same-popup input is inert, and a new session retries once", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId, firstDmId } = await seedDirectoryCase(actors)+const { page } = await asUser("alice")const statuses: number[] = []await page.route(`**${DIRECTORY_PATH}`, async (route) => {@@ -169,7 +175,11 @@ test.describe.serial("DM channel-reference directory states", () => {expect(statuses).toEqual([500, 200])})- test("warm cache crosses DM routes without a duplicate request or status flash", async ({ asUser }) => {+ test("warm cache crosses DM routes without a duplicate request or status flash", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId, firstDmId, secondDmId } = await seedDirectoryCase(actors)+const { page } = await asUser("alice")let directoryGets = 0await page.route(`**${DIRECTORY_PATH}`, async (route) => {@@ -201,9 +211,14 @@ test.describe.serial("DM channel-reference directory states", () => {expect(directoryGets).toBe(1)})- test("late completion after exit and SPA route switch only warms the new DM", async ({ asUser }) => {+ test("late completion after exit and SPA route switch only warms the new DM", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId, firstDmId, secondDmId } = await seedDirectoryCase(actors)+const { page } = await asUser("alice")const gate = deferred()+ actors.onCleanup(async () => { gate.resolve() })let directoryGets = 0await page.route(`**${DIRECTORY_PATH}`, async (route) => {directoryGets += 1@@ -240,7 +255,11 @@ test.describe.serial("DM channel-reference directory states", () => {expect(directoryGets).toBe(1)})- test("server channel keeps local categories and never requests the directory", async ({ asUser }) => {+ test("server channel keeps local categories and never requests the directory", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId } = await seedDirectoryCase(actors)+const { page } = await asUser("alice")let directoryGets = 0await page.route(`**${DIRECTORY_PATH}`, async (route) => {diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.tsindex d389d51be..c53fbe02d 100644--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts@@ -1,5 +1,5 @@import type { Locator, Page, Request, Route } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import {composerEditable,expectMessageVisible,@@ -7,15 +7,6 @@ import {ignoreNextDevToolsPointerCapture,installInputCapability,} from "./_fixtures/actions"-import {- memberInfo,- seedChannel,- seedDm,- seedJoinServer,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"import {communityFrameEvents,proxyCommunityWebSockets,@@ -349,7 +340,11 @@ async function expectRetainedMountGets(expect(tracker.failures).toEqual([])}-test("same message row recovers its action menu from mouse to touch", async ({ asUser }) => {+test("same message row recovers its action menu from mouse to touch", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Pointer-modality-${stamp}`)const channelId = await seedChannel("alice", serverId, "pointer-modality")@@ -382,8 +377,12 @@ test("same message row recovers its action menu from mouse to touch", async ({ a))).toHaveLength(messageCreatesBefore)})-test("mobile reply, avatar mention, and typing rail keep exact backend and WS identity", async ({ asUser }) => {+test("mobile reply, avatar mention, and typing rail keep exact backend and WS identity", async ({ caseActors }) => {test.setTimeout(240_000)+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { memberInfo, seedChannel, seedDm, seedJoinServer, seedMessage, seedServer, seedThread } = actors.seed+const stamp = Date.now()const serverName = `Mobile-interactions-${stamp}`const serverId = await seedServer("alice", serverName)@@ -934,7 +933,11 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS idchannelReturnGets.stop()})-test("mobile thread return uses server read state instead of tab-local pixel memory", async ({ asUser }) => {+test("mobile thread return uses server read state instead of tab-local pixel memory", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedMessage, seedServer, seedThread } = actors.seed+const stamp = Date.now()const serverName = `Mobile-scroll-${stamp}`const serverId = await seedServer("alice", serverName)diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.tsindex 8b87809a7..dda518830 100644--- a/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts+++ b/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts@@ -1,36 +1,38 @@-import { test } from "./_fixtures/community-fixture"+import { test } from "./_fixtures/case-fixture"import {- cleanupGeometryServers,runDesktopPersistedPendingGeometry,runNeutralRootGeometry,runRouteLoadingGeometry,seedGeometryRoutes,} from "./_fixtures/community-loading-geometry"-test.describe.serial("community dark loading geometry", () => {- let routes!: Awaited<ReturnType<typeof seedGeometryRoutes>>- const serverIds: string[] = []+test.describe("community dark loading geometry", () => {+ test("dark: neutral root owns two viewport cold restores", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["dave", "bob"])+ const { asUser } = actors+ const serverIds: string[] = []+ await seedGeometryRoutes(serverIds, actors.seed, actors.userId)- test.beforeAll(async () => {- test.setTimeout(120_000)- routes = await seedGeometryRoutes(serverIds)+ await runNeutralRootGeometry("dark", asUser, testInfo, actors.userId, actors.onCleanup)})- test.afterAll(async () => {- await cleanupGeometryServers(serverIds)- })-- test("dark: neutral root owns two viewport cold restores", async ({ asUser }, testInfo) => {- await runNeutralRootGeometry("dark", asUser, testInfo)- })-- test("dark: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ asUser }) => {+ test("dark: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ caseActors }) => {test.setTimeout(240_000)- await runDesktopPersistedPendingGeometry("dark", asUser)+ const actors = await caseActors(["dave", "bob", "geometry"])+ const { asUser } = actors+ const serverIds: string[] = []+ await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runDesktopPersistedPendingGeometry("dark", asUser, actors.onCleanup)})- test("dark: 18 route × viewport pending→loaded pairs keep shell CLS at zero", async ({ asUser }, testInfo) => {+ test("dark: 18 route × viewport pending→loaded pairs keep shell CLS at zero", async ({ caseActors }, testInfo) => {test.setTimeout(600_000)- await runRouteLoadingGeometry("dark", routes, asUser, testInfo)+ const actors = await caseActors(["dave", "bob"])+ const { asUser } = actors+ const serverIds: string[] = []+ const routes = await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runRouteLoadingGeometry("dark", routes, asUser, testInfo, actors.onCleanup)})})diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.tsindex c099c1494..41888fe77 100644--- a/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts+++ b/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts@@ -1,36 +1,38 @@-import { test } from "./_fixtures/community-fixture"+import { test } from "./_fixtures/case-fixture"import {- cleanupGeometryServers,runDesktopPersistedPendingGeometry,runNeutralRootGeometry,runRouteLoadingGeometry,seedGeometryRoutes,} from "./_fixtures/community-loading-geometry"-test.describe.serial("community light loading geometry", () => {- let routes!: Awaited<ReturnType<typeof seedGeometryRoutes>>- const serverIds: string[] = []+test.describe("community light loading geometry", () => {+ test("light: neutral root owns two viewport cold restores", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["dave", "bob"])+ const { asUser } = actors+ const serverIds: string[] = []+ await seedGeometryRoutes(serverIds, actors.seed, actors.userId)- test.beforeAll(async () => {- test.setTimeout(120_000)- routes = await seedGeometryRoutes(serverIds)+ await runNeutralRootGeometry("light", asUser, testInfo, actors.userId, actors.onCleanup)})- test.afterAll(async () => {- await cleanupGeometryServers(serverIds)- })-- test("light: neutral root owns two viewport cold restores", async ({ asUser }, testInfo) => {- await runNeutralRootGeometry("light", asUser, testInfo)- })-- test("light: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ asUser }) => {+ test("light: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ caseActors }) => {test.setTimeout(360_000)- await runDesktopPersistedPendingGeometry("light", asUser)+ const actors = await caseActors(["dave", "bob", "geometry"])+ const { asUser } = actors+ const serverIds: string[] = []+ await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runDesktopPersistedPendingGeometry("light", asUser, actors.onCleanup)})- test("light: 18 route × viewport pending→loaded pairs keep shell CLS at zero", async ({ asUser }, testInfo) => {+ test("light: 18 route × viewport pending→loaded pairs keep shell CLS at zero", async ({ caseActors }, testInfo) => {test.setTimeout(600_000)- await runRouteLoadingGeometry("light", routes, asUser, testInfo)+ const actors = await caseActors(["dave", "bob"])+ const { asUser } = actors+ const serverIds: string[] = []+ const routes = await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runRouteLoadingGeometry("light", routes, asUser, testInfo, actors.onCleanup)})})diff --git a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.tsindex efa7c1285..eae6da9d0 100644--- a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts+++ b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts@@ -1,15 +1,8 @@import type { Page, Request } from "@playwright/test"-import { expect, sessionCookie, test } from "./_fixtures/community-fixture"+import { expect, test, type CaseActors } from "./_fixtures/case-fixture"import { GEOMETRY_EPSILON, composerEditable, gotoAfterUserWsAuth, ignoreNextDevToolsPointerCapture, waitForElementMotion } from "./_fixtures/actions"import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"import { WEB_URL } from "./_setup/paths"-import {- seedChannel,- seedJoinServer,- seedMark,- seedMessage,- seedServer,-} from "./_fixtures/seed"import { tid } from "./_fixtures/testids"type SurfaceGeometry = {@@ -40,7 +33,7 @@ type BorderGeometry = Record<"top" | "right" | "bottom" | "left", {color: string}>-async function removeServerChannels(serverId: string) {+async function removeServerChannels(serverId: string, sessionCookie: CaseActors["sessionCookie"]) {const headers = { Cookie: sessionCookie("alice"), Origin: WEB_URL }const response = await fetch(`${WEB_URL}/api/community/servers/${serverId}/channels`, { headers })if (!response.ok) throw new Error(`list server channels failed (${response.status})`)@@ -161,10 +154,14 @@ function observeWrites(page: Page) {return { writes, stop: () => page.off("request", listener) }}-test.describe.serial("mobile Inbox interactive user-bar base", () => {+test.describe("mobile Inbox interactive user-bar base", () => {test.setTimeout(180_000)- test("paints the retained Inbox digits after hidden messages and repeated detail returns", async ({ asUser }, testInfo) => {+ test("paints the retained Inbox digits after hidden messages and repeated detail returns", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox digits ${stamp}`)const landingId = await seedChannel("alice", serverId, `landing-${stamp}`)@@ -331,7 +328,11 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {}})- test("keeps the mobile shell unmasked and dismisses on outside press without writes", async ({ asUser }, testInfo) => {+ test("keeps the mobile shell unmasked and dismisses on outside press without writes", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox surface ${stamp}`)const channelId = await seedChannel("alice", serverId, `inbox-${stamp}`)@@ -536,7 +537,11 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {writes.stop()})- test("matches the mobile Composer width, height, and bottom margin", async ({ asUser }) => {+ test("matches the mobile Composer width, height, and bottom margin", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `User Bar alignment ${stamp}`)const channelId = await seedChannel("alice", serverId, `alignment-${stamp}`)@@ -588,12 +593,16 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {}})- test("preserves Marked tab, scroll, and request ownership across 639↔640", async ({ asUser }, testInfo) => {+ test("preserves Marked tab, scroll, and request ownership across 639↔640", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedMark, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Inbox continuity ${stamp}`)const channelId = await seedChannel("alice", serverId, `continuity-${stamp}`)const emptyServerId = await seedServer("alice", `Inbox continuity empty ${stamp}`)- await removeServerChannels(emptyServerId)+ await removeServerChannels(emptyServerId, actors.sessionCookie)await seedJoinServer("alice", "bob", serverId)await seedJoinServer("alice", "bob", emptyServerId)for (let index = 0; index < 14; index += 1) {diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.tsindex 9feae73f0..ab7dc9d09 100644--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts@@ -1,19 +1,10 @@import type { Locator, Page, Route, TestInfo } from "@playwright/test"-import { test, expect, sessionCookie, userId } from "./_fixtures/community-fixture"+import { test, expect, type CaseActors } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"import {communityFrameEvents,proxyCommunityWebSockets,} from "./_fixtures/community-ws-proxy"-import {- seedChannel,- seedDm,- seedDmMessage,- seedJoinServer,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"import {abortScrollTrace,attachScrollTrace,@@ -41,6 +32,7 @@ type HeldRequest = {}async function holdNextRequest(+ actors: CaseActors,page: Page,pattern: string,predicate: (url: URL) => boolean,@@ -67,15 +59,17 @@ async function holdNextRequest(await route.continue()}await page.route(pattern, handler)- return {+ const held = {matched,release,dispose: async () => {if (timeout) clearTimeout(timeout)release()- await page.unroute(pattern, handler)+ if (!page.isClosed()) await page.unroute(pattern, handler)},}+ actors.onCleanup(() => held.dispose())+ return held}function profileContent(index: number): string {@@ -95,12 +89,14 @@ function estimatePlainMessage(content: string): number {}async function seedProfile(+ actors: CaseActors,channelId: string,count: number,imageAtTail = false,authors: "rotate" | "alice" = "rotate",checkpointAt?: number,): Promise<{ ids: string[]; estimates: Record<string, number> }> {+ const { seedMessage } = actors.seedconst ids: string[] = []const estimates: Record<string, number> = {}for (let index = 0; index < count; index += 1) {@@ -116,15 +112,17 @@ async function seedProfile(const id = await seedMessage(author, channelId, content)ids.push(id)estimates[id] = estimatePlainMessage(content)- if (index === checkpointAt) await setReadCheckpoint(channelId, id)+ if (index === checkpointAt) await setReadCheckpoint(actors, channelId, id)}return { ids, estimates }}async function seedDmProfile(+ actors: CaseActors,dmId: string,count: number,): Promise<{ ids: string[]; estimates: Record<string, number> }> {+ const { seedDmMessage } = actors.seedconst ids: string[] = []const estimates: Record<string, number> = {}for (let index = 0; index < count; index += 1) {@@ -136,11 +134,11 @@ async function seedDmProfile(return { ids, estimates }}-async function setReadCheckpoint(channelId: string, messageId: string): Promise<void> {+async function setReadCheckpoint(actors: CaseActors, channelId: string, messageId: string): Promise<void> {const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {method: "PUT",headers: {- Cookie: sessionCookie("alice"),+ Cookie: actors.sessionCookie("alice"),"Content-Type": "application/json",Origin: WEB_URL,},@@ -531,46 +529,51 @@ async function expectMessageCreateIdentity(expect(created.message).toMatchObject({ id: message.id, seq: message.seq, authorId: message.authorId, clientNonce: nonce })}-test.describe.serial("message scroll characterization", () => {- let serverId: string- let coldChannelId: string- let loadingChannelId: string- let upwardChannelId: string- let composerChannelId: string- let composerDmId: string- let loadingProfile: Awaited<ReturnType<typeof seedProfile>>- let upwardProfile: Awaited<ReturnType<typeof seedProfile>>- let composerProfile: Awaited<ReturnType<typeof seedProfile>>- let composerDmProfile: Awaited<ReturnType<typeof seedDmProfile>>-- test.beforeAll(async () => {- test.setTimeout(240_000)- const stamp = Date.now()- serverId = await seedServer("alice", `Scroll characterization ${stamp}`)- await seedJoinServer("alice", "bob", serverId)- await seedJoinServer("alice", "carol", serverId)- coldChannelId = await seedChannel("alice", serverId, `scroll-cold-${stamp}`)- loadingChannelId = await seedChannel("alice", serverId, `scroll-loading-${stamp}`)- upwardChannelId = await seedChannel("alice", serverId, `scroll-upward-${stamp}`)- composerChannelId = await seedChannel("alice", serverId, `scroll-composer-${stamp}`)- composerDmId = await seedDm("alice", userId("bob"))- loadingProfile = await seedProfile(loadingChannelId, 130, false, "rotate", 64)- upwardProfile = await seedProfile(upwardChannelId, 72, false, "rotate", 23)- composerProfile = await seedProfile(composerChannelId, 36, true, "alice")- composerDmProfile = await seedDmProfile(composerDmId, 36)- })+async function seedScrollCase(actors: CaseActors) {+ const { seedServer, seedJoinServer, seedChannel, seedDm } = actors.seed+ const { userId } = actors+ const stamp = Date.now()+ const serverId = await seedServer("alice", `Scroll characterization ${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ await seedJoinServer("alice", "carol", serverId)+ const coldChannelId = await seedChannel("alice", serverId, `scroll-cold-${stamp}`)+ const loadingChannelId = await seedChannel("alice", serverId, `scroll-loading-${stamp}`)+ const upwardChannelId = await seedChannel("alice", serverId, `scroll-upward-${stamp}`)+ const composerChannelId = await seedChannel("alice", serverId, `scroll-composer-${stamp}`)+ const composerDmId = await seedDm("alice", userId("bob"))+ const loadingProfile = await seedProfile(actors, loadingChannelId, 130, false, "rotate", 64)+ const upwardProfile = await seedProfile(actors, upwardChannelId, 72, false, "rotate", 23)+ const composerProfile = await seedProfile(actors, composerChannelId, 36, true, "alice")+ const composerDmProfile = await seedDmProfile(actors, composerDmId, 36)+ return { serverId, coldChannelId, loadingChannelId, upwardChannelId, composerChannelId, composerDmId, loadingProfile, upwardProfile, composerProfile, composerDmProfile }+}++function tracedAsUser(actors: CaseActors): CaseActors["asUser"] {+ return async (key, options) => {+ const opened = await actors.asUser(key, options)+ actors.onCleanup(async () => {+ if (!opened.page.isClosed()) await abortScrollTrace(opened.page)+ })+ return opened+ }+}- test("cold and warm loading, older prepend, and jump-to-present remain observable", async ({ asUser }, testInfo) => {+test.describe("message scroll characterization", () => {+ test("cold and warm loading, older prepend, and jump-to-present remain observable", async ({ caseActors }, testInfo) => {test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { serverId, coldChannelId, loadingChannelId, loadingProfile } = await seedScrollCase(actors)+const alice = await asUser("alice")await alice.page.setViewportSize(VIEWPORT)await installScrollTrace(alice.page)- const initialMessages = await holdNextRequest(+ const initialMessages = await holdNextRequest(actors,alice.page,`**/api/community/channels/${coldChannelId}/messages**`,() => true,)- const image = await holdNextRequest(+ const image = await holdNextRequest(actors,alice.page,"**/icon-512.png?scroll-trace=1",() => true,@@ -599,7 +602,7 @@ test.describe.serial("message scroll characterization", () => {dataTransitionSource: "initial-cold",})await markScrollTrace(alice.page, "cold-request-held", { dataTransitionSource: "initial-cold" })- const coldProfile = await seedProfile(coldChannelId, 12, true, "alice")+ const coldProfile = await seedProfile(actors, coldChannelId, 12, true, "alice")initialMessages.release()await image.matchedawait expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!))).toBeVisible({ timeout: 30_000 })@@ -616,7 +619,7 @@ test.describe.serial("message scroll characterization", () => {const mobile = await asUser("alice")await mobile.page.setViewportSize({ width: 390, height: 844 })- const mobileInitialMessages = await holdNextRequest(+ const mobileInitialMessages = await holdNextRequest(actors,mobile.page,`**/api/community/channels/${coldChannelId}/messages**`,() => true,@@ -635,7 +638,7 @@ test.describe.serial("message scroll characterization", () => {await alice.page.getByTestId(tid.channelRow(loadingChannelId)).click()await alice.page.waitForURL(new RegExp(loadingChannelId), { waitUntil: "commit" })await expect(alice.page.getByTestId(tid.messageScroller)).toBeVisible()- const warmRequest = await holdNextRequest(+ const warmRequest = await holdNextRequest(actors,alice.page,`**/api/community/channels/${coldChannelId}/messages**`,() => true,@@ -666,7 +669,7 @@ test.describe.serial("message scroll characterization", () => {await installScrollTrace(anchored.page)await anchored.page.goto(`/c/channels/${serverId}/${loadingChannelId}`, { waitUntil: "commit" })await expect(anchored.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })- const older = await holdNextRequest(+ const older = await holdNextRequest(actors,anchored.page,`**/api/community/channels/${loadingChannelId}/messages**`,(url) => url.searchParams.has("cursor"),@@ -708,7 +711,7 @@ test.describe.serial("message scroll characterization", () => {&& url.search === "") newestGets += 1})- const newest = await holdNextRequest(+ const newest = await holdNextRequest(actors,anchored.page,`**/api/community/channels/${loadingChannelId}/messages**`,(url) => url.search === "",@@ -736,12 +739,17 @@ test.describe.serial("message scroll characterization", () => {await newest.dispose()})- test("peer receives follow after clamped bottom input without movement", async ({ asUser }) => {+ test("peer receives follow after clamped bottom input without movement", async ({ caseActors }) => {test.setTimeout(120_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { serverId } = await seedScrollCase(actors)+ const { seedChannel, seedMessage } = actors.seed+const channelId = await seedChannel("alice", serverId, `scroll-bottom-input-${Date.now()}`)- await seedProfile(channelId, 18)+ await seedProfile(actors, channelId, 18)let tailId = await seedMessage("bob", channelId, "bottom input start\n[keyboard target](https://example.com)")- await setReadCheckpoint(channelId, tailId)+ await setReadCheckpoint(actors, channelId, tailId)const alice = await asUser("alice")await alice.page.setViewportSize(VIEWPORT)const proxy = await proxyCommunityWebSockets(alice.context)@@ -775,10 +783,15 @@ test.describe.serial("message scroll characterization", () => {}})- test("local history submission and passive remote append use distinct owners", async ({ asUser }) => {+ test("local history submission and passive remote append use distinct owners", async ({ caseActors }) => {test.setTimeout(120_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { userId, sessionCookie } = actors+ const { serverId } = await seedScrollCase(actors)+ const { seedChannel } = actors.seedconst channelId = await seedChannel("alice", serverId, `scroll-passive-threshold-${Date.now()}`)- await seedProfile(channelId, 130, false, "rotate", 18)+ await seedProfile(actors, channelId, 130, false, "rotate", 18)const alice = await asUser("alice")await alice.page.setViewportSize(VIEWPORT)const proxy = await proxyCommunityWebSockets(alice.context)@@ -801,7 +814,7 @@ test.describe.serial("message scroll characterization", () => {const url = new URL(request.url())if (request.method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages` && url.search === "") newestGets += 1})- const newest = await holdNextRequest(alice.page, `**/api/community/channels/${channelId}/messages**`, url => url.search === "")+ const newest = await holdNextRequest(actors, alice.page, `**/api/community/channels/${channelId}/messages**`, url => url.search === "")const localContent = `local history submission ${Date.now()}`const localPost = alice.page.waitForResponse(response => response.request().method() === "POST"&& new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`@@ -866,8 +879,13 @@ test.describe.serial("message scroll characterization", () => {expect(newestGets).toBe(1)})- test("remote receive states and sustained upward input produce diagnostic traces", async ({ asUser }, testInfo) => {+ test("remote receive states and sustained upward input produce diagnostic traces", async ({ caseActors }, testInfo) => {test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { serverId, upwardChannelId, upwardProfile } = await seedScrollCase(actors)+ const { seedMessage } = actors.seed+const alice = await asUser("alice")await alice.page.setViewportSize(VIEWPORT)await installScrollTrace(alice.page)@@ -979,8 +997,12 @@ test.describe.serial("message scroll characterization", () => {.toBeGreaterThanOrEqual(7)})- test("manual draft clear and optimistic send stay distinct through viewport changes", async ({ asUser }, testInfo) => {+ test("manual draft clear and optimistic send stay distinct through viewport changes", async ({ caseActors }, testInfo) => {test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { serverId, composerChannelId, composerProfile } = await seedScrollCase(actors)+const alice = await asUser("alice")await alice.page.setViewportSize(VIEWPORT)await installScrollTrace(alice.page)@@ -1107,8 +1129,13 @@ test.describe.serial("message scroll characterization", () => {expect(messageCreateCount(proxy.frames, composerChannelId, awaySend)).toBe(1)})- test("DM composer clear preserves pinned and away viewport geometry", async ({ asUser }, testInfo) => {+ test("DM composer clear preserves pinned and away viewport geometry", async ({ caseActors }, testInfo) => {test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { userId } = actors+ const { composerDmId, composerDmProfile } = await seedScrollCase(actors)+const alice = await asUser("alice")await alice.page.setViewportSize(VIEWPORT)await installScrollTrace(alice.page)@@ -1222,14 +1249,20 @@ test.describe.serial("message scroll characterization", () => {expect(messagePosts).toBe(1)})- test("normal-flow composer resizes preserve semantic anchors and interaction boundaries", async ({ asUser }, testInfo) => {+ test("normal-flow composer resizes preserve semantic anchors and interaction boundaries", async ({ caseActors }, testInfo) => {test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { userId } = actors+ const { serverId, composerChannelId, composerProfile } = await seedScrollCase(actors)+ const { seedThread } = actors.seed+const splitThreadId = await seedThread("alice",composerProfile.ids.at(-1)!,`scroll split ${Date.now()}`,)- const splitProfile = await seedProfile(splitThreadId, 24, false, "alice")+ const splitProfile = await seedProfile(actors, splitThreadId, 24, false, "alice")const alice = await asUser("alice")const bob = await asUser("bob")await alice.page.setViewportSize(VIEWPORT)@@ -1499,8 +1532,4 @@ test.describe.serial("message scroll characterization", () => {const parentAfter = await waitForCommittedGeometry(parentScroller)expectViewportAnchorPreserved(parentBefore, parentAfter, "thread-local-submit-parent")})-- test.afterEach(async ({ page }) => {- await abortScrollTrace(page)- })})diff --git a/src/web/src/test/e2e-ui/64-billing-contact.spec.ts b/src/web/src/test/e2e-ui/64-billing-contact.spec.tsindex e11b45c0a..68db6cc21 100644--- a/src/web/src/test/e2e-ui/64-billing-contact.spec.ts+++ b/src/web/src/test/e2e-ui/64-billing-contact.spec.ts@@ -1,7 +1,10 @@-import { expect, test } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"-test("plan Contact stays usable without billing data and preserves the plan tab", async ({ asUser }, testInfo) => {+test("plan Contact stays usable without billing data and preserves the plan tab", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+for (const width of [1280, 390]) {const { page, context } = await asUser("alice", { viewport: { width, height: 844 } })const billingWrites: string[] = []@@ -10,6 +13,7 @@ test("plan Contact stays usable without billing data and preserves the plan tab"})let releaseBilling!: () => voidconst billingGate = new Promise<void>((resolve) => { releaseBilling = resolve })+ actors.onCleanup(async () => { releaseBilling() })await page.route("**/api/community/billing", async (route) => {await billingGateawait route.fulfill({ status: 503, contentType: "application/json", body: JSON.stringify({ error: "Unavailable" }) })diff --git a/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts b/src/web/src/test/e2e-ui/_fixtures/case-fixture.tsnew file mode 100644index 000000000..8c6ef0095--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts@@ -0,0 +1,227 @@+import type { BrowserContext, BrowserContextOptions, Page, TestInfo } from "@playwright/test"+import { createHash } from "crypto"+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"+import { resolve } from "path"+import { loginAndSaveState } from "../_setup/auth"+import { AUTH_DIR, SERVICE_STATE_PATH, WEB_URL } from "../_setup/paths"+import { readLifecycleState } from "../_setup/service-lifecycle"+import { USER_KEYS, type SeededUser, type UserKey } from "../_setup/users"+import { test as base } from "./community-fixture"+import { manifest } from "./manifest"+import { createSeed, type CaseSeed } from "./seed"+import { retrySeedRequest } from "./seed-retry"++export type CaseActors = {+ asUser: (key: UserKey, options?: Omit<BrowserContextOptions, "storageState">) => Promise<{ context: BrowserContext; page: Page }>+ userId: (key: UserKey) => string+ userName: (key: UserKey) => string+ sessionCookie: (key: UserKey) => string+ seed: CaseSeed+ onCleanup: (operation: () => Promise<unknown>) => void+}++type CaseIdentity = {+ stamp: string+ testId: string+ file: string+ project: string+ workerIndex: number+ parallelIndex: number+}++type CleanupFailure = {+ identity: CaseIdentity+ unresolvedServers: Array<{ owner: UserKey; id: string }>+ unresolvedContexts: ContextOwner[]+ errorCount: number+}++type ContextOwner = { role: UserKey; kind: "login" | "actor"; ordinal: number }++const failurePath = resolve(AUTH_DIR, "case-cleanup-failure.json")++async function checkCleanupFailure(testInfo: TestInfo): Promise<void> {+ if (!existsSync(failurePath)) return+ const failure = JSON.parse(readFileSync(failurePath, "utf8")) as CleanupFailure+ testInfo.annotations.push({ type: "fixture-blocked", description: `Unresolved cleanup from ${failure.identity.testId}, worker ${failure.identity.workerIndex}` })+ await testInfo.attach("case-fixture-blocked", { body: JSON.stringify(failure), contentType: "application/json" })+ throw new Error(`Case fixture blocked by unresolved cleanup: ${failure.identity.testId}, worker ${failure.identity.workerIndex}`)+}++export const test = base.extend<{ caseActors: (roles: readonly UserKey[]) => Promise<CaseActors>; caseCleanupGuard: void }>({+ serviceGuard: async ({ caseCleanupGuard, serviceGuard }, provide) => {+ void caseCleanupGuard+ await provide(serviceGuard)+ },+ caseCleanupGuard: [async ({}, provide, testInfo) => {+ await checkCleanupFailure(testInfo)+ await provide()+ }, { auto: true }],+ caseActors: async ({ browser, caseCleanupGuard }, provide, testInfo) => {+ void caseCleanupGuard+ const users: Partial<Record<UserKey, SeededUser>> = {}+ const contexts = new Map<BrowserContext, ContextOwner>()+ const contextOutcomes: Array<ContextOwner & { closed: boolean }> = []+ let contextCount = 0+ const cleanup: Array<() => Promise<unknown>> = []+ const owned = new Map<string, UserKey>()+ const resources = new Set<string>()+ let allocated = false+ const identity: CaseIdentity = {+ stamp: manifest().stamp,+ testId: testInfo.testId,+ file: testInfo.file,+ project: testInfo.project.name,+ workerIndex: testInfo.workerIndex,+ parallelIndex: testInfo.parallelIndex,+ }+ const shardPath = resolve(AUTH_DIR, "../../../../e2e-shard-manifest/shard-manifest.json")+ const shard = existsSync(shardPath) ? readFileSync(shardPath, "utf8") : "local"+ const stamp = createHash("sha256").update(JSON.stringify(identity)).update(shard).digest("hex").slice(0, 24)+ const directory = resolve(AUTH_DIR, "cases", stamp)+ const user = (key: UserKey): SeededUser => {+ const value = users[key]+ if (!value) throw new Error(`Undeclared case actor: ${key}`)+ return value+ }+ const registerContext = (role: UserKey, kind: ContextOwner["kind"], context: BrowserContext) => {+ contexts.set(context, { role, kind, ordinal: contextCount++ })+ }+ const retireContext = (context: BrowserContext) => {+ const owner = contexts.get(context)+ if (owner) contextOutcomes.push({ ...owner, closed: true })+ contexts.delete(context)+ }+ const sessionCookie = (key: UserKey): string => {+ const state = JSON.parse(readFileSync(user(key).storageState, "utf8")) as { cookies: Array<{ name: string; value: string }> }+ return state.cookies.filter((cookie) => cookie.name.startsWith("better-auth")).map((cookie) => `${cookie.name}=${cookie.value}`).join("; ")+ }+ const read = async (key: UserKey, path: string): Promise<Record<string, unknown>> => {+ const response = await retrySeedRequest(() => fetch(`${WEB_URL}${path}`, { headers: { Cookie: sessionCookie(key), Origin: WEB_URL } }))+ if (!response.ok) throw new Error(`Case baseline ${key} GET ${path} failed (${response.status})`)+ const body = await response.json() as Record<string, unknown>+ if (!body || typeof body !== "object" || body.stale === true || body.truncated === true) throw new Error(`Case baseline ${key} GET ${path} is incomplete`)+ return body+ }+ const assertEmpty = async (key: UserKey, path: string, field: string) => {+ const body = await read(key, path)+ if (!Array.isArray(body[field]) || body[field].length !== 0) throw new Error(`Case baseline ${key} ${field} must be empty`)+ }+ const seed = createSeed({+ sessionCookie,+ userId: (key) => user(key).userId,+ users: () => users,+ assertResource: (kind, id) => {+ if (kind === "user" && Object.values(users).some((value) => value?.userId === id)) return+ if (!resources.has(`${kind}:${id}`)) throw new Error(`Foreign case resource: ${kind} ${id}`)+ },+ onResourceCreated: (kind, id) => { resources.add(`${kind}:${id}`) },+ onServerCreated: (owner, id) => { owned.set(id, owner) },+ onDmCreated: async (first, second, id) => {+ for (const key of [first, second]) {+ const body = await read(key, "/api/community/users/me/read-state")+ if (!Array.isArray(body.readStates)) throw new Error(`Case DM baseline ${key} has no read-state array`)+ const row = body.readStates.find((value: { channelId: string }) => value.channelId === id) as { lastReadSeq?: number } | undefined+ if ((row?.lastReadSeq ?? 0) !== 0) throw new Error(`Case DM handshake violates the original zero-cursor premise for ${key}`)+ }+ },+ })+ let bodyError: unknown+ let bodyFailed = false+ try {+ await provide(async (roles) => {+ if (allocated) throw new Error("A test must allocate its case actors once and reuse them for all devices")+ allocated = true+ const state = readLifecycleState(SERVICE_STATE_PATH)+ if (state?.status !== "healthy" || state.services.length === 0) throw new Error("Case actors require this run's managed test database; the current stack is not owned")+ if (roles.length === 0 || new Set(roles).size !== roles.length || roles.some((key) => !USER_KEYS.includes(key))) throw new Error("Case actors require a nonempty unique role list")+ mkdirSync(directory, { recursive: true, mode: 0o700 })+ for (const key of roles) {+ users[key] = await loginAndSaveState(browser, key, stamp, resolve(directory, `${key}.json`), {+ created: (context) => registerContext(key, "login", context),+ closed: retireContext,+ })+ const profile = await read(key, "/api/community/users/me/profile")+ if (profile.id !== user(key).userId || profile.name !== user(key).name) throw new Error(`Case baseline ${key} has a different profile identity`)+ if (profile.aboutMe !== "" || profile.avatarVersion !== 0 || profile.bannerColor !== null || profile.statusEmoji !== null || profile.statusText !== "") throw new Error(`Case baseline ${key} has modified profile defaults`)+ await Promise.all([+ assertEmpty(key, "/api/community/servers", "servers"),+ assertEmpty(key, "/api/community/users/me/server-folders", "folders"),+ assertEmpty(key, "/api/community/users/me/dms", "conversations"),+ assertEmpty(key, "/api/community/users/me/read-state", "readStates"),+ assertEmpty(key, "/api/community/users/me/marks", "marked"),+ assertEmpty(key, "/api/community/friends/accepted", "friends"),+ assertEmpty(key, "/api/community/friends/pending", "pending"),+ assertEmpty(key, "/api/community/friends/blocked", "blocked"),+ assertEmpty(key, "/api/community/users/me/attention", "scopes"),+ assertEmpty(key, "/api/community/users/me/attention", "items"),+ ])+ }+ await testInfo.attach("case-actor-ownership", { body: JSON.stringify({ identity, actors: roles.map((key) => ({ key, userId: user(key).userId })) }), contentType: "application/json" })+ return {+ asUser: async (key, options) => {+ const context = await browser.newContext({ ...options, storageState: user(key).storageState })+ registerContext(key, "actor", context)+ const page = await context.newPage()+ return { context, page }+ },+ userId: (key) => user(key).userId,+ userName: (key) => user(key).name,+ sessionCookie,+ seed,+ onCleanup: (operation) => { cleanup.push(operation) },+ }+ })+ } catch (error) {+ bodyError = error+ bodyFailed = true+ } finally {+ const errors: unknown[] = []+ const outcomes = { operations: [] as boolean[], contexts: contextOutcomes, servers: [] as Array<{ owner: UserKey; id: string; retired: boolean }> }+ for (const operation of cleanup.reverse()) {+ try { await operation(); outcomes.operations.push(true) } catch (error) { outcomes.operations.push(false); errors.push(error) }+ }+ for (const [context, owner] of contexts) {+ try { await context.close(); retireContext(context) } catch (error) { outcomes.contexts.push({ ...owner, closed: false }); errors.push(error) }+ }+ for (const key of Object.keys(users) as UserKey[]) {+ try {+ const listed = await read(key, "/api/community/servers")+ if (!Array.isArray(listed.servers)) throw new Error(`Case cleanup ${key} has no server list`)+ for (const server of listed.servers as Array<{ id: string; ownerId: string }>) {+ if (server.ownerId === user(key).userId) {+ owned.set(server.id, key)+ resources.add(`server:${server.id}`)+ }+ }+ } catch (error) { errors.push(error) }+ }+ for (const [id, owner] of owned) {+ try {+ await seed.retireSeedServers(owner, [id])+ owned.delete(id)+ outcomes.servers.push({ owner, id, retired: true })+ } catch (error) { outcomes.servers.push({ owner, id, retired: false }); errors.push(error) }+ }+ for (const key of Object.keys(users) as UserKey[]) {+ try { await assertEmpty(key, "/api/community/servers", "servers") } catch (error) { errors.push(error) }+ }+ try {+ await testInfo.attach("case-cleanup", { body: JSON.stringify({ identity, requestedContexts: contextCount, requestedOperations: cleanup.length, outcomes }), contentType: "application/json" })+ } catch (error) { errors.push(error) }+ const failure: CleanupFailure = { identity, unresolvedServers: [...owned].map(([id, owner]) => ({ owner, id })), unresolvedContexts: [...contexts.values()], errorCount: errors.length }+ if (errors.length > 0) {+ try {+ if (!existsSync(failurePath)) writeFileSync(failurePath, JSON.stringify(failure), { flag: "wx", mode: 0o600 })+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") errors.push(error)+ }+ try { await testInfo.attach("case-cleanup-failure", { body: JSON.stringify(failure), contentType: "application/json" }) } catch (error) { errors.push(error) }+ throw new AggregateError(bodyFailed ? [bodyError, ...errors] : errors, "Case cleanup failed; successor fixtures are blocked")+ }+ }+ if (bodyFailed) throw bodyError+ },+})++export const expect = test.expectdiff --git a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.tsindex e23330c1d..4bcd55d6b 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts@@ -5,7 +5,7 @@ import type {Page,TestInfo,} from "@playwright/test"-import { test, expect, sessionCookie, userId } from "./community-fixture"+import { test, expect, sessionCookie } from "./community-fixture"import {COMMUNITY_RAIL_WIDTH,COMMUNITY_SEPARATOR_WIDTH,@@ -13,15 +13,7 @@ import {COMMUNITY_SIDEBAR_MIN_WIDTH,COMMUNITY_SURFACE_BORDER_WIDTH,} from "@/components/community/shell/shell-frame-geometry"-import {- retireSeedServers,- seedChannel,- seedDm,- seedForumThread,- seedMessage,- seedServer,- seedThread,-} from "./seed"+import type { CaseSeed } from "./seed"import { tid } from "./testids"import { WEB_URL } from "../_setup/paths"import { ssrGeometryErrors, type SsrLifecycleSample } from "./community-ssr-geometry"@@ -435,11 +427,16 @@ async function visibleSkeletonAnimationProperties(page: Page) {)).sort())}-export async function cleanupGeometryServers(serverIds: readonly string[]): Promise<void> {- await retireSeedServers(ISOLATED_GEOMETRY_USER, serverIds)+export async function cleanupGeometryServers(serverIds: readonly string[], seed: CaseSeed): Promise<void> {+ await seed.retireSeedServers(ISOLATED_GEOMETRY_USER, serverIds)}-export async function seedGeometryRoutes(serverIds: string[]): Promise<Omit<MatrixCase, "width">[]> {+export async function seedGeometryRoutes(+ serverIds: string[],+ seed: CaseSeed,+ userId: (key: UserKey) => string,+): Promise<Omit<MatrixCase, "width">[]> {+ const { seedChannel, seedDm, seedForumThread, seedMessage, seedServer, seedThread } = seedconst stamp = Date.now()const serverId = await seedServer(ISOLATED_GEOMETRY_USER, `Geometry ${stamp}`)serverIds.push(serverId)@@ -593,6 +590,7 @@ export async function runAndroidLoadingGeometry(asUser: CommunityAsUser, testInfexport async function runDesktopPersistedPendingGeometry(theme: Theme,asUser: CommunityAsUser,+ onCleanup: (operation: () => Promise<unknown>) => void,) {const cases = ([640, 768, 1024, 1280] as const).flatMap((viewportWidth) =>([null, 100, 160, 240, 350, 360] as const).flatMap((sidebarWidth) =>@@ -655,7 +653,9 @@ export async function runDesktopPersistedPendingGeometry(} finally {scripts?.release()communityReads?.release()- await context.close()+ try { await context.close() } catch (error) {+ onCleanup(async () => { throw error })+ }}})}@@ -693,6 +693,8 @@ export async function runNeutralRootGeometry(theme: Theme,asUser: CommunityAsUser,testInfo: TestInfo,+ userId: (key: UserKey) => string,+ onCleanup: (operation: () => Promise<unknown>) => void,) {for (const width of [390, 1280] as const) {const { context, page } = await asUser(ISOLATED_GEOMETRY_USER)@@ -702,6 +704,7 @@ export async function runNeutralRootGeometry(localStorage.removeItem(storageKey)}, `community:lastRoute:${encodeURIComponent(userId(ISOLATED_GEOMETRY_USER))}`)const scripts = await holdApplicationScripts(page)+ onCleanup(async () => { scripts.release() })await page.goto("/c", { waitUntil: "commit" })await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)expect(scripts.received).toEqual([])@@ -746,6 +749,7 @@ export async function runRouteLoadingGeometry(routes: Omit<MatrixCase, "width">[],asUser: CommunityAsUser,testInfo: TestInfo,+ onCleanup: (operation: () => Promise<unknown>) => void,) {const cases: MatrixCase[] = routes.flatMap((route) => ([{ ...route, width: 390 },@@ -759,10 +763,13 @@ export async function runRouteLoadingGeometry(await page.emulateMedia({ colorScheme: theme })await startClsObserver(page)const scripts = await holdApplicationScripts(page)+ onCleanup(async () => { scripts.release() })const communityReads = await holdCommunityReads(page)+ onCleanup(async () => { communityReads.release() })const intermediate = entry.intermediate? await holdRequest(page, entry.intermediate.requestPattern): null+ if (intermediate) onCleanup(async () => { intermediate.release() })await page.goto(entry.pathname, { waitUntil: "commit" })await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)expect(scripts.received).toEqual([])diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.tsindex 09d1e2467..37b36097c 100644--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts@@ -14,411 +14,512 @@ import { manifest } from "./manifest"// (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}`, {- method: "POST",- headers: {- Cookie: sessionCookie(key),- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: body === undefined ? undefined : JSON.stringify(body),- })+type SeedResource = "server" | "channel" | "category" | "message" | "user" | "friendship"++type SeedIdentity = {+ sessionCookie: (key: UserKey) => string+ userId: (key: UserKey) => string+ users: () => Partial<Record<UserKey, { userId: string }>>+ assertResource?: (kind: SeedResource, id: string) => void+ onResourceCreated?: (kind: SeedResource, id: string) => void+ onServerCreated?: (owner: UserKey, serverId: string) => void+ onDmCreated?: (first: UserKey, second: UserKey, dmId: string) => Promise<void>}-async function post(key: UserKey, path: string, body?: unknown): Promise<Response> {- const response = await retrySeedRequest(() => postRaw(key, path, body))- if (response.ok) return response- throw new Error(`POST ${path} failed (${response.status})`)-}+export function createSeed(identity: SeedIdentity) {+ const { sessionCookie, userId } = identity+ async function postRaw(key: UserKey, path: string, body?: unknown): Promise<Response> {+ return fetch(`${WEB_URL}${path}`, {+ method: "POST",+ headers: {+ Cookie: sessionCookie(key),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ })+ }-export async function seedServer(owner: UserKey, name: string): Promise<string> {- const res = await post(owner, "/api/community/servers", { name })- const data = (await res.json()) as { server: { id: string } }- return data.server.id-}+ async function post(key: UserKey, path: string, body?: unknown): Promise<Response> {+ const response = await retrySeedRequest(() => postRaw(key, path, body))+ if (response.ok) return response+ throw new Error(`POST ${path} failed (${response.status})`)+ }-export async function retireSeedServers(owner: UserKey, serverIds: readonly string[]): Promise<void> {- const errors: unknown[] = []- for (const serverId of serverIds) {- try {- const response = await retrySeedRequest(() => fetch(`${WEB_URL}/api/community/servers/${serverId}`, {- method: "DELETE",- headers: { Cookie: sessionCookie(owner), Origin: WEB_URL },- }))- if (response.status !== 204 && response.status !== 404) {- throw new Error(`DELETE fixture server ${serverId} failed (${response.status})`)+ async function seedServer(owner: UserKey, name: string): Promise<string> {+ const res = await post(owner, "/api/community/servers", { name })+ const data = (await res.json()) as { server: { id: string } }+ identity.onServerCreated?.(owner, data.server.id)+ identity.onResourceCreated?.("server", data.server.id)+ return data.server.id+ }++ async function retireSeedServers(owner: UserKey, serverIds: readonly string[]): Promise<void> {+ for (const id of serverIds) identity.assertResource?.("server", id)+ const errors: unknown[] = []+ for (const serverId of serverIds) {+ try {+ const response = await retrySeedRequest(() => fetch(`${WEB_URL}/api/community/servers/${serverId}`, {+ method: "DELETE",+ headers: { Cookie: sessionCookie(owner), Origin: WEB_URL },+ }))+ if (response.status !== 204 && response.status !== 404) {+ throw new Error(`DELETE fixture server ${serverId} failed (${response.status})`)+ }+ } catch (error) {+ errors.push(error)}- } catch (error) {- errors.push(error)}+ if (errors.length > 0) throw new AggregateError(errors, "Fixture server retirement failed")}- if (errors.length > 0) throw new AggregateError(errors, "Fixture server retirement failed")-}--export async function seedChannel(- owner: UserKey,- serverId: string,- name: string,- type?: "text" | "forum",- categoryId?: string,-): Promise<string> {- const res = await post(owner, "/api/community/channels", { serverId, name, type, categoryId })- const data = (await res.json()) as { channel: { id: string } }- return data.channel.id-}-// Create a category (optionally private) and return its id. A private category-// is what turns its channels' @-mention scope from server-wide to the channel-// audience — the whole point of the scope spec.-export async function seedCategory(- owner: UserKey,- serverId: string,- name: string,- opts?: { private?: boolean },-): Promise<string> {- const res = await post(owner, `/api/community/servers/${serverId}/categories`, {- name,- private: opts?.private,- })- const data = (await res.json()) as { category: { id: string } }- return data.category.id-}+ async function seedChannel(+ owner: UserKey,+ serverId: string,+ name: string,+ type?: "text" | "forum",+ categoryId?: string,+ ): Promise<string> {+ identity.assertResource?.("server", serverId)+ if (categoryId) identity.assertResource?.("category", categoryId)+ const res = await post(owner, "/api/community/channels", { serverId, name, type, categoryId })+ const data = (await res.json()) as { channel: { id: string } }+ identity.onResourceCreated?.("channel", data.channel.id)+ return data.channel.id+ }-// Server membership comes from joining via invite (channels/[id]/members is-// only for private-category channels and requires prior server membership).-// Owner mints an invite, the joiner accepts it. Idempotent-ish: an-// "Already a member" 400 is treated as success.-export async function seedJoinServer(owner: UserKey, joiner: UserKey, serverId: string): Promise<void> {- const token = await createInvite(owner, serverId)- // Retry a transient auth race (401/403) and D1/WAL contention (5xx); a 400 is- // "Already a member" and counts as success (idempotent on a Playwright retry).- let lastStatus = 0- for (let attempt = 0; attempt < 3; attempt++) {- const res = await fetch(`${WEB_URL}/api/community/invites/${token}/join`, {- method: "POST",- headers: { Cookie: sessionCookie(joiner), "Content-Type": "application/json", Origin: WEB_URL },+ // Create a category (optionally private) and return its id. A private category+ // is what turns its channels' @-mention scope from server-wide to the channel+ // audience — the whole point of the scope spec.+ async function seedCategory(+ owner: UserKey,+ serverId: string,+ name: string,+ opts?: { private?: boolean },+ ): Promise<string> {+ identity.assertResource?.("server", serverId)+ const res = await post(owner, `/api/community/servers/${serverId}/categories`, {+ name,+ private: opts?.private,})- if (res.ok || res.status === 400) return- lastStatus = res.status- if (!isRetryableSeedStatus(res.status)) break- await new Promise((r) => setTimeout(r, seedRetryDelayMs(res)))+ const data = (await res.json()) as { category: { id: string } }+ identity.onResourceCreated?.("category", data.category.id)+ return data.category.id}- throw new Error(`seedJoinServer join failed (${lastStatus})`)-}-// Add a server member to a PRIVATE-category channel's roster. Requires the-// target to already be a server member (call seedJoinServer first).-export async function seedChannelMember(owner: UserKey, channelId: string, userId: string): Promise<void> {- await post(owner, `/api/community/channels/${channelId}/members`, { userId })-}--export async function seedDm(from: UserKey, targetUserId: string): Promise<string> {- const addressee = (Object.entries(manifest().users) as Array<[- UserKey,- { userId: string },- ]>).find(([, user]) => user.userId === targetUserId)?.[0]- if (!addressee) throw new Error(`seedDm: unknown fixture user ${targetUserId}`)-- // A normal DM fixture models an accepted conversation. Tests that need- // non-friend history must create the DM/message first, then remove the- // friendship; creating a non-friend DM is no longer a valid precondition.- await seedFriendship(from, addressee, targetUserId)- const res = await post(from, "/api/community/channels", { type: "dm", userId: targetUserId })- const data = (await res.json()) as { conversation: { id: string } }- return data.conversation.id-}--// Post a DM message via API so the conversation shows in both sidebars with a-// preview. Returns the message id.-export async function seedDmMessage(author: UserKey, dmId: string, content: string): Promise<string> {- const res = await post(author, `/api/community/channels/${dmId}/messages`, { content })- const data = (await res.json()) as { message: { id: string } }- return data.message.id-}+ // Server membership comes from joining via invite (channels/[id]/members is+ // only for private-category channels and requires prior server membership).+ // Owner mints an invite, the joiner accepts it. Idempotent-ish: an+ // "Already a member" 400 is treated as success.+ async function seedJoinServer(owner: UserKey, joiner: UserKey, serverId: string): Promise<void> {+ if (identity.assertResource) identity.assertResource("user", userId(joiner))+ identity.assertResource?.("server", serverId)+ const token = await createInvite(owner, serverId)+ // Retry a transient auth race (401/403) and D1/WAL contention (5xx); a 400 is+ // "Already a member" and counts as success (idempotent on a Playwright retry).+ let lastStatus = 0+ for (let attempt = 0; attempt < 3; attempt++) {+ const res = await fetch(`${WEB_URL}/api/community/invites/${token}/join`, {+ method: "POST",+ headers: { Cookie: sessionCookie(joiner), "Content-Type": "application/json", Origin: WEB_URL },+ })+ if (res.ok || res.status === 400) return+ lastStatus = res.status+ if (!isRetryableSeedStatus(res.status)) break+ await new Promise((r) => setTimeout(r, seedRetryDelayMs(res)))+ }+ throw new Error(`seedJoinServer join failed (${lastStatus})`)+ }-export async function seedBlock(blocker: UserKey, targetUserId: string): Promise<void> {- await post(blocker, `/api/community/users/${targetUserId}/block`)-}+ // Add a server member to a PRIVATE-category channel's roster. Requires the+ // target to already be a server member (call seedJoinServer first).+ async function seedChannelMember(owner: UserKey, channelId: string, userId: string): Promise<void> {+ identity.assertResource?.("channel", channelId)+ identity.assertResource?.("user", userId)+ await post(owner, `/api/community/channels/${channelId}/members`, { userId })+ }-// Look up an existing accepted-friendship id between the requester and a target-// user, from the requester's friends list. Used to recover idempotently when a-// re-run (Playwright retry) finds the pair already friends.-async function findFriendshipId(requester: UserKey, targetUserId: string): Promise<string | undefined> {- const res = await retrySeedRequest(() => fetch(- `${WEB_URL}/api/community/friends/accepted`,- { headers: { Cookie: sessionCookie(requester), Origin: WEB_URL } },- ))- if (!res.ok) return undefined- const data = (await res.json()) as { friends: Array<{ id: string; userId: string }> }- return data.friends.find((f) => f.userId === targetUserId)?.id-}+ async function seedDm(from: UserKey, targetUserId: string): Promise<string> {+ const addressee = (Object.entries(identity.users()) as Array<[+ UserKey,+ { userId: string },+ ]>).find(([, user]) => user.userId === targetUserId)?.[0]+ if (!addressee) throw new Error(`seedDm: unknown fixture user ${targetUserId}`)++ // A normal DM fixture models an accepted conversation. Tests that need+ // non-friend history must create the DM/message first, then remove the+ // friendship; creating a non-friend DM is no longer a valid precondition.+ await seedFriendship(from, addressee, targetUserId)+ const res = await post(from, "/api/community/channels", { type: "dm", userId: targetUserId })+ const data = (await res.json()) as { conversation: { id: string } }+ identity.onResourceCreated?.("channel", data.conversation.id)+ if (identity.onDmCreated) await identity.onDmCreated(from, addressee, data.conversation.id)+ return data.conversation.id+ }-type SeedRelationship = {- id: string- userId: string- kind?: "incoming" | "outgoing"-}+ // Post a DM message via API so the conversation shows in both sidebars with a+ // preview. Returns the message id.+ async function seedDmMessage(author: UserKey, dmId: string, content: string): Promise<string> {+ identity.assertResource?.("channel", dmId)+ const res = await post(author, `/api/community/channels/${dmId}/messages`, { content })+ const data = (await res.json()) as { message: { id: string } }+ identity.onResourceCreated?.("message", data.message.id)+ return data.message.id+ }-async function listSeedRelationships(key: UserKey): Promise<{- accepted: SeedRelationship[]- pending: SeedRelationship[]-}> {- const headers = { Cookie: sessionCookie(key), Origin: WEB_URL }- const [accepted, pending] = await Promise.all([- retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/accepted`, { headers })),- retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/pending`, { headers })),- ])- if (!accepted.ok) throw new Error(`listSeedRelationships accepted failed (${accepted.status})`)- if (!pending.ok) throw new Error(`listSeedRelationships pending failed (${pending.status})`)- return {- accepted: ((await accepted.json()) as { friends: SeedRelationship[] }).friends,- pending: ((await pending.json()) as { pending: SeedRelationship[] }).pending,+ async function seedBlock(blocker: UserKey, targetUserId: string): Promise<void> {+ identity.assertResource?.("user", targetUserId)+ await post(blocker, `/api/community/users/${targetUserId}/block`)}-}-async function deleteSeedRelationship(key: UserKey, id: string): Promise<Response> {- return retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/${id}`, {- method: "DELETE",- headers: { Cookie: sessionCookie(key), Origin: WEB_URL },- }))-}+ // Look up an existing accepted-friendship id between the requester and a target+ // user, from the requester's friends list. Used to recover idempotently when a+ // re-run (Playwright retry) finds the pair already friends.+ async function findFriendshipId(requester: UserKey, targetUserId: string): Promise<string | undefined> {+ const res = await retrySeedRequest(() => fetch(+ `${WEB_URL}/api/community/friends/accepted`,+ { headers: { Cookie: sessionCookie(requester), Origin: WEB_URL } },+ ))+ if (!res.ok) return undefined+ const data = (await res.json()) as { friends: Array<{ id: string; userId: string }> }+ return data.friends.find((f) => f.userId === targetUserId)?.id+ }-// Remove an accepted friendship while preserving any existing DM and history.-// Use after seedDm/seedDmMessage when a spec needs the post-unfriend read-only-// state; creating a DM directly as non-friends is no longer a valid fixture.-export async function seedRemoveFriendship(- requester: UserKey,- targetUserId: string,-): Promise<void> {- const friendshipId = await findFriendshipId(requester, targetUserId)- if (!friendshipId) throw new Error("seedRemoveFriendship: accepted friendship not found")- const response = await deleteSeedRelationship(requester, friendshipId)- if (!response.ok) throw new Error(`seedRemoveFriendship failed (${response.status})`)-}+ type SeedRelationship = {+ id: string+ userId: string+ kind?: "incoming" | "outgoing"+ }-async function acceptSeedFriendship(- requester: UserKey,- addressee: UserKey,- targetUserId: string,- pending: SeedRelationship,-): Promise<string> {- const accepter = pending.kind === "outgoing" ? addressee : requester- const response = await retrySeedRequest(() => postRaw(- accepter,- `/api/community/friends/${pending.id}/accept`,- ))- if (response.ok) return pending.id- // Parallel fixtures may both observe the same pending row; one wins the- // accept while the other receives a terminal-state response. Confirm the- // accepted state instead of treating that harmless race as a seed failure.- if (response.status === 400 || response.status === 409) {- const existing = await findFriendshipId(requester, targetUserId)- if (existing) return existing+ async function listSeedRelationships(key: UserKey): Promise<{+ accepted: SeedRelationship[]+ pending: SeedRelationship[]+ }> {+ const headers = { Cookie: sessionCookie(key), Origin: WEB_URL }+ const [accepted, pending] = await Promise.all([+ retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/accepted`, { headers })),+ retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/pending`, { headers })),+ ])+ if (!accepted.ok) throw new Error(`listSeedRelationships accepted failed (${accepted.status})`)+ if (!pending.ok) throw new Error(`listSeedRelationships pending failed (${pending.status})`)+ return {+ accepted: ((await accepted.json()) as { friends: SeedRelationship[] }).friends,+ pending: ((await pending.json()) as { pending: SeedRelationship[] }).pending,+ }}- throw new Error(`seedFriendship accept failed (${response.status})`)-}-// Normalize a human-to-human pair to one actionable pending request. This uses-// only the public HTTP routes and is repeatable after an earlier E2E spec (or a-// Playwright retry) left the pair accepted, blocked, or pending in either-// direction.-export async function seedPendingFriendRequest(- requester: UserKey,- addressee: UserKey,- targetUserId: string,-): Promise<string> {- await Promise.all([- post(requester, `/api/community/users/${targetUserId}/unblock`),- post(addressee, `/api/community/users/${userId(requester)}/unblock`),- ])-- const relationships = await listSeedRelationships(requester)- const accepted = relationships.accepted.find((row) => row.userId === targetUserId)- if (accepted) {- const response = await deleteSeedRelationship(requester, accepted.id)- if (!response.ok) throw new Error(`seedPendingFriendRequest remove failed (${response.status})`)+ async function deleteSeedRelationship(key: UserKey, id: string): Promise<Response> {+ return retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/${id}`, {+ method: "DELETE",+ headers: { Cookie: sessionCookie(key), Origin: WEB_URL },+ }))}- const pending = relationships.pending.find((row) => row.userId === targetUserId)- if (pending) {- const response = pending.kind === "outgoing"- ? await deleteSeedRelationship(requester, pending.id)- : await post(requester, `/api/community/friends/${pending.id}/reject`)- if (!response.ok) throw new Error(`seedPendingFriendRequest clear pending failed (${response.status})`)++ // Remove an accepted friendship while preserving any existing DM and history.+ // Use after seedDm/seedDmMessage when a spec needs the post-unfriend read-only+ // state; creating a DM directly as non-friends is no longer a valid fixture.+ async function seedRemoveFriendship(+ requester: UserKey,+ targetUserId: string,+ ): Promise<void> {+ identity.assertResource?.("user", targetUserId)+ const friendshipId = await findFriendshipId(requester, targetUserId)+ if (!friendshipId) throw new Error("seedRemoveFriendship: accepted friendship not found")+ const response = await deleteSeedRelationship(requester, friendshipId)+ if (!response.ok) throw new Error(`seedRemoveFriendship failed (${response.status})`)}- const response = await retrySeedRequest(() => postRaw(- requester,- "/api/community/friends/request",- { userId: targetUserId },- ))- if (!response.ok) throw new Error(`seedPendingFriendRequest request failed (${response.status})`)- const body = (await response.json()) as { id?: string; friendship?: { id: string } | null }- const id = body.id ?? body.friendship?.id- if (!id) throw new Error("seedPendingFriendRequest: no friendship id in response")- return id-}+ async function acceptSeedFriendship(+ requester: UserKey,+ addressee: UserKey,+ targetUserId: string,+ pending: SeedRelationship,+ ): Promise<string> {+ const accepter = pending.kind === "outgoing" ? addressee : requester+ const response = await retrySeedRequest(() => postRaw(+ accepter,+ `/api/community/friends/${pending.id}/accept`,+ ))+ if (response.ok) return pending.id+ // Parallel fixtures may both observe the same pending row; one wins the+ // accept while the other receives a terminal-state response. Confirm the+ // accepted state instead of treating that harmless race as a seed failure.+ if (response.status === 400 || response.status === 409) {+ const existing = await findFriendshipId(requester, targetUserId)+ if (existing) return existing+ }+ throw new Error(`seedFriendship accept failed (${response.status})`)+ }-// Withdraw a pending request through the same route used by the product. A-// terminal/missing row is already cancelled for fixture-cleanup purposes.-export async function seedCancelFriendRequest(requester: UserKey, friendshipId: string): Promise<void> {- const response = await deleteSeedRelationship(requester, friendshipId)- if (response.ok || response.status === 400 || response.status === 404) return- throw new Error(`seedCancelFriendRequest failed (${response.status})`)-}+ // Normalize a human-to-human pair to one actionable pending request. This uses+ // only the public HTTP routes and is repeatable after an earlier E2E spec (or a+ // Playwright retry) left the pair accepted, blocked, or pending in either+ // direction.+ async function seedPendingFriendRequest(+ requester: UserKey,+ addressee: UserKey,+ targetUserId: string,+ ): Promise<string> {+ if (identity.assertResource) identity.assertResource("user", userId(addressee))+ identity.assertResource?.("user", targetUserId)+ await Promise.all([+ post(requester, `/api/community/users/${targetUserId}/unblock`),+ post(addressee, `/api/community/users/${userId(requester)}/unblock`),+ ])++ const relationships = await listSeedRelationships(requester)+ const accepted = relationships.accepted.find((row) => row.userId === targetUserId)+ if (accepted) {+ const response = await deleteSeedRelationship(requester, accepted.id)+ if (!response.ok) throw new Error(`seedPendingFriendRequest remove failed (${response.status})`)+ }+ const pending = relationships.pending.find((row) => row.userId === targetUserId)+ if (pending) {+ const response = pending.kind === "outgoing"+ ? await deleteSeedRelationship(requester, pending.id)+ : await post(requester, `/api/community/friends/${pending.id}/reject`)+ if (!response.ok) throw new Error(`seedPendingFriendRequest clear pending failed (${response.status})`)+ }-// Full friend handshake: requester sends, addressee accepts (accept is-// addressee-only, hence two keys). Returns the friendship id. Idempotent on a-// Playwright retry: if the pair is already friends the request 409s, so we-// recover the existing friendship id and skip the accept.-export async function seedFriendship(requester: UserKey, addressee: UserKey, targetUserId: string): Promise<string> {- await Promise.all([- post(requester, `/api/community/users/${targetUserId}/unblock`),- post(addressee, `/api/community/users/${userId(requester)}/unblock`),- ])-- const relationships = await listSeedRelationships(requester)- const accepted = relationships.accepted.find((row) => row.userId === targetUserId)- if (accepted) return accepted.id- const pending = relationships.pending.find((row) => row.userId === targetUserId)- if (pending) {- return acceptSeedFriendship(requester, addressee, targetUserId, pending)+ const response = await retrySeedRequest(() => postRaw(+ requester,+ "/api/community/friends/request",+ { userId: targetUserId },+ ))+ if (!response.ok) throw new Error(`seedPendingFriendRequest request failed (${response.status})`)+ const body = (await response.json()) as { id?: string; friendship?: { id: string } | null }+ const id = body.id ?? body.friendship?.id+ if (!id) throw new Error("seedPendingFriendRequest: no friendship id in response")+ identity.onResourceCreated?.("friendship", id)+ return id}- let reqRes: Response | undefined- for (let attempt = 0; attempt < 3; attempt++) {- const response = await postRaw(requester, "/api/community/friends/request", { userId: targetUserId })- reqRes = response- // 409 = already friends / request already sent — a valid idempotent state.- if (response.ok || response.status === 409 || !isRetryableSeedStatus(response.status)) break- await new Promise((r) => setTimeout(r, seedRetryDelayMs(response)))+ // Withdraw a pending request through the same route used by the product. A+ // terminal/missing row is already cancelled for fixture-cleanup purposes.+ async function seedCancelFriendRequest(requester: UserKey, friendshipId: string): Promise<void> {+ identity.assertResource?.("friendship", friendshipId)+ const response = await deleteSeedRelationship(requester, friendshipId)+ if (response.ok || response.status === 400 || response.status === 404) return+ throw new Error(`seedCancelFriendRequest failed (${response.status})`)}- if (reqRes!.status === 409) {- const existing = await findFriendshipId(requester, targetUserId)- if (existing) return existing- const refreshed = await listSeedRelationships(requester)- const pending = refreshed.pending.find((row) => row.userId === targetUserId)- if (pending) return acceptSeedFriendship(requester, addressee, targetUserId, pending)- throw new Error("seedFriendship: 409 but no accepted or pending friendship found")++ // Full friend handshake: requester sends, addressee accepts (accept is+ // addressee-only, hence two keys). Returns the friendship id. Idempotent on a+ // Playwright retry: if the pair is already friends the request 409s, so we+ // recover the existing friendship id and skip the accept.+ async function seedFriendship(requester: UserKey, addressee: UserKey, targetUserId: string): Promise<string> {+ if (identity.assertResource) identity.assertResource("user", userId(addressee))+ identity.assertResource?.("user", targetUserId)+ await Promise.all([+ post(requester, `/api/community/users/${targetUserId}/unblock`),+ post(addressee, `/api/community/users/${userId(requester)}/unblock`),+ ])++ const relationships = await listSeedRelationships(requester)+ const accepted = relationships.accepted.find((row) => row.userId === targetUserId)+ if (accepted) return accepted.id+ const pending = relationships.pending.find((row) => row.userId === targetUserId)+ if (pending) {+ return acceptSeedFriendship(requester, addressee, targetUserId, pending)+ }++ let reqRes: Response | undefined+ for (let attempt = 0; attempt < 3; attempt++) {+ const response = await postRaw(requester, "/api/community/friends/request", { userId: targetUserId })+ reqRes = response+ // 409 = already friends / request already sent — a valid idempotent state.+ 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)+ if (existing) return existing+ const refreshed = await listSeedRelationships(requester)+ const pending = refreshed.pending.find((row) => row.userId === targetUserId)+ if (pending) return acceptSeedFriendship(requester, addressee, targetUserId, pending)+ throw new Error("seedFriendship: 409 but no accepted or pending friendship found")+ }+ if (!reqRes!.ok) throw new Error(`seedFriendship request failed (${reqRes!.status})`)+ const reqData = (await reqRes!.json()) as { id?: string; friendship?: { id: string } | null }+ const friendshipId = reqData.id ?? reqData.friendship?.id+ if (!friendshipId) throw new Error("seedFriendship: no friendship id in response")+ return acceptSeedFriendship(requester, addressee, targetUserId, {+ id: friendshipId,+ userId: targetUserId,+ kind: "outgoing",+ })}- if (!reqRes!.ok) throw new Error(`seedFriendship request failed (${reqRes!.status})`)- const reqData = (await reqRes!.json()) as { id?: string; friendship?: { id: string } | null }- const friendshipId = reqData.id ?? reqData.friendship?.id- if (!friendshipId) throw new Error("seedFriendship: no friendship id in response")- return acceptSeedFriendship(requester, addressee, targetUserId, {- id: friendshipId,- userId: targetUserId,- kind: "outgoing",- })-}-// Post a message into a channel via API (persisted with a real server id).-// Use when a spec needs a pre-existing message as a precondition rather than-// exercising the send UI itself. Returns the message id.-export async function seedMessage(author: UserKey, channelId: string, content: string): Promise<string> {- const res = await post(author, `/api/community/channels/${channelId}/messages`, { content })- const data = (await res.json()) as { message: { id: string } }- return data.message.id-}+ // Post a message into a channel via API (persisted with a real server id).+ // Use when a spec needs a pre-existing message as a precondition rather than+ // exercising the send UI itself. Returns the message id.+ async function seedMessage(author: UserKey, channelId: string, content: string): Promise<string> {+ identity.assertResource?.("channel", channelId)+ const res = await post(author, `/api/community/channels/${channelId}/messages`, { content })+ const data = (await res.json()) as { message: { id: string } }+ identity.onResourceCreated?.("message", data.message.id)+ return data.message.id+ }-export async function seedReaction(author: UserKey, messageId: string, emoji: string): Promise<void> {- const response = await retrySeedRequest(() => fetch(- `${WEB_URL}/api/community/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`,- { method: "PUT", headers: { Cookie: sessionCookie(author), Origin: WEB_URL } },- ))- if (!response.ok) throw new Error(`seedReaction failed (${response.status})`)-}+ async function seedReaction(author: UserKey, messageId: string, emoji: string): Promise<void> {+ identity.assertResource?.("message", messageId)+ const response = await retrySeedRequest(() => fetch(+ `${WEB_URL}/api/community/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`,+ { method: "PUT", headers: { Cookie: sessionCookie(author), Origin: WEB_URL } },+ ))+ if (!response.ok) throw new Error(`seedReaction failed (${response.status})`)+ }-export async function seedMark(author: UserKey, channelId: string, messageId: string): Promise<void> {- const response = await retrySeedRequest(() => fetch(- `${WEB_URL}/api/community/messages/${messageId}/marks`,- {- method: "PUT",- headers: {- Cookie: sessionCookie(author),- "Content-Type": "application/json",- Origin: WEB_URL,+ async function seedMark(author: UserKey, channelId: string, messageId: string): Promise<void> {+ identity.assertResource?.("channel", channelId)+ identity.assertResource?.("message", messageId)+ const response = await retrySeedRequest(() => fetch(+ `${WEB_URL}/api/community/messages/${messageId}/marks`,+ {+ method: "PUT",+ headers: {+ Cookie: sessionCookie(author),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({ channelId }),},- body: JSON.stringify({ channelId }),- },- ))- if (!response.ok) throw new Error(`seedMark failed (${response.status})`)-}+ ))+ if (!response.ok) throw new Error(`seedMark failed (${response.status})`)+ }-// Create a forum post (a child channel of a `type:"forum"` channel) via API.-// Returns the post's own channel id. The creator is enrolled as a participant-// server-side. Use when a spec needs an existing post before driving the UI.-export async function seedForumThread(- author: UserKey,- forumChannelId: string,- name: string,- content: string,-): Promise<string> {- const nonce = `e2e:${crypto.randomUUID()}`- const structure = await post(author, `/api/community/channels/${forumChannelId}/messages`, {- content: name,- nonce: `${nonce}:opener`,- })- const data = (await structure.json()) as { threadId: string }- await post(author, `/api/community/channels/${data.threadId}/messages`, {- content,- nonce: `${nonce}:reply`,- })- return data.threadId-}+ // Create a forum post (a child channel of a `type:"forum"` channel) via API.+ // Returns the post's own channel id. The creator is enrolled as a participant+ // server-side. Use when a spec needs an existing post before driving the UI.+ async function seedForumThread(+ author: UserKey,+ forumChannelId: string,+ name: string,+ content: string,+ ): Promise<string> {+ identity.assertResource?.("channel", forumChannelId)+ const nonce = `e2e:${crypto.randomUUID()}`+ const structure = await post(author, `/api/community/channels/${forumChannelId}/messages`, {+ content: name,+ nonce: `${nonce}:opener`,+ })+ const data = (await structure.json()) as { threadId: string }+ identity.onResourceCreated?.("channel", data.threadId)+ await post(author, `/api/community/channels/${data.threadId}/messages`, {+ content,+ nonce: `${nonce}:reply`,+ })+ return data.threadId+ }-// Create a thread rooted on an existing message. Returns the thread's own-// child-channel id. A thread has NO roster of its own — its @-mention scope is-// the PARENT channel's audience — which is exactly what the scope spec probes.-export async function seedThread(author: UserKey, messageId: string, name: string): Promise<string> {- const res = await post(author, "/api/community/channels", { type: "thread", messageId, name })- const data = (await res.json()) as { id: string }- return data.id-}+ // Create a thread rooted on an existing message. Returns the thread's own+ // child-channel id. A thread has NO roster of its own — its @-mention scope is+ // the PARENT channel's audience — which is exactly what the scope spec probes.+ async function seedThread(author: UserKey, messageId: string, name: string): Promise<string> {+ identity.assertResource?.("message", messageId)+ const res = await post(author, "/api/community/channels", { type: "thread", messageId, name })+ const data = (await res.json()) as { id: string }+ identity.onResourceCreated?.("channel", data.id)+ return data.id+ }-export async function createInvite(owner: UserKey, serverId: string): Promise<string> {- const res = await post(owner, `/api/community/servers/${serverId}/invites`, {})- const data = (await res.json()) as { invite: { token: string } }- return data.invite.token-}+ async function createInvite(owner: UserKey, serverId: string): Promise<string> {+ identity.assertResource?.("server", serverId)+ const res = await post(owner, `/api/community/servers/${serverId}/invites`, {})+ const data = (await res.json()) as { invite: { token: string } }+ return data.invite.token+ }++ // Rename a user's community display name. Used by the mention specs to force+ // two members to share a name (each keeps its own auto-assigned discriminator),+ // which is the whole point of the same-name-disambiguation journey.+ async function renameUser(key: UserKey, name: string): Promise<void> {+ let lastStatus = 0+ for (let attempt = 0; attempt < 3; attempt++) {+ const res = await fetch(`${WEB_URL}/api/community/users/me/profile`, {+ method: "PATCH",+ headers: { Cookie: sessionCookie(key), "Content-Type": "application/json", Origin: WEB_URL },+ body: JSON.stringify({ name }),+ })+ if (res.ok) return+ lastStatus = res.status+ if (!isRetryableSeedStatus(res.status)) break+ await new Promise((r) => setTimeout(r, seedRetryDelayMs(res)))+ }+ throw new Error(`renameUser failed (${lastStatus})`)+ }-// Rename a user's community display name. Used by the mention specs to force-// two members to share a name (each keeps its own auto-assigned discriminator),-// which is the whole point of the same-name-disambiguation journey.-export async function renameUser(key: UserKey, name: string): Promise<void> {- let lastStatus = 0- for (let attempt = 0; attempt < 3; attempt++) {- const res = await fetch(`${WEB_URL}/api/community/users/me/profile`, {- method: "PATCH",- headers: { Cookie: sessionCookie(key), "Content-Type": "application/json", Origin: WEB_URL },- body: JSON.stringify({ name }),+ // A member's row id + display name + discriminator, read from a server's member+ // list (the same NOT NULL column the mention grammar depends on). The mention+ // popup keys its option testid off the row `id`, filters candidates by `name`+ // prefix, and the pill/profile card shows the `discriminator` — so the mention+ // specs need all three (a hardcoded query like "@bob" breaks once an earlier+ // serial spec renames the account). `viewer` must be a member of `serverId`;+ // `targetUserId` is the member being looked up.+ async function memberInfo(+ viewer: UserKey,+ serverId: string,+ targetUserId: string,+ ): Promise<{ id: string; name: string; discriminator: string }> {+ identity.assertResource?.("server", serverId)+ identity.assertResource?.("user", targetUserId)+ const res = await fetch(`${WEB_URL}/api/community/servers/${serverId}/members`, {+ headers: { Cookie: sessionCookie(viewer), Origin: WEB_URL },})- if (res.ok) return- lastStatus = res.status- if (!isRetryableSeedStatus(res.status)) break- await new Promise((r) => setTimeout(r, seedRetryDelayMs(res)))+ if (!res.ok) throw new Error(`memberInfo list failed (${res.status})`)+ const data = (await res.json()) as { members: Array<{ id: string; userId: string; name: string; discriminator?: string }> }+ const found = data.members.find((m) => m.userId === targetUserId)+ if (!found?.discriminator) throw new Error(`memberInfo: no discriminator for ${targetUserId}`)+ return { id: found.id, name: found.name, discriminator: found.discriminator }}- throw new Error(`renameUser failed (${lastStatus})`)-}-// A member's row id + display name + discriminator, read from a server's member-// list (the same NOT NULL column the mention grammar depends on). The mention-// popup keys its option testid off the row `id`, filters candidates by `name`-// prefix, and the pill/profile card shows the `discriminator` — so the mention-// specs need all three (a hardcoded query like "@bob" breaks once an earlier-// serial spec renames the account). `viewer` must be a member of `serverId`;-// `targetUserId` is the member being looked up.-export async function memberInfo(- viewer: UserKey,- serverId: string,- targetUserId: string,-): Promise<{ id: string; name: string; discriminator: string }> {- const res = await fetch(`${WEB_URL}/api/community/servers/${serverId}/members`, {- headers: { Cookie: sessionCookie(viewer), Origin: WEB_URL },- })- if (!res.ok) throw new Error(`memberInfo list failed (${res.status})`)- const data = (await res.json()) as { members: Array<{ id: string; userId: string; name: string; discriminator?: string }> }- const found = data.members.find((m) => m.userId === targetUserId)- if (!found?.discriminator) throw new Error(`memberInfo: no discriminator for ${targetUserId}`)- return { id: found.id, name: found.name, discriminator: found.discriminator }+ return {+ seedServer,+ retireSeedServers,+ seedChannel,+ seedCategory,+ seedJoinServer,+ seedChannelMember,+ seedDm,+ seedDmMessage,+ seedBlock,+ seedRemoveFriendship,+ seedPendingFriendRequest,+ seedCancelFriendRequest,+ seedFriendship,+ seedMessage,+ seedReaction,+ seedMark,+ seedForumThread,+ seedThread,+ createInvite,+ renameUser,+ memberInfo,+ }}++export const {+ seedServer,+ retireSeedServers,+ seedChannel,+ seedCategory,+ seedJoinServer,+ seedChannelMember,+ seedDm,+ seedDmMessage,+ seedBlock,+ seedRemoveFriendship,+ seedPendingFriendRequest,+ seedCancelFriendRequest,+ seedFriendship,+ seedMessage,+ seedReaction,+ seedMark,+ seedForumThread,+ seedThread,+ createInvite,+ renameUser,+ memberInfo,+} = createSeed({ sessionCookie, userId, users: () => manifest().users })++export type CaseSeed = ReturnType<typeof createSeed>diff --git a/src/web/src/test/e2e-ui/_setup/auth.ts b/src/web/src/test/e2e-ui/_setup/auth.tsindex 0688acd64..6679496c2 100644--- a/src/web/src/test/e2e-ui/_setup/auth.ts+++ b/src/web/src/test/e2e-ui/_setup/auth.ts@@ -1,4 +1,4 @@-import type { Browser, Page } from "@playwright/test"+import type { Browser, BrowserContext, Page } from "@playwright/test"import {ANALYTICS_CONSENT_COOKIE,analyticsConsentCookieValue,@@ -6,6 +6,11 @@ import {import { WEB_URL } from "./paths"import { emailFor, type SeededUser, type UserKey } from "./users"+type LoginContextOwner = {+ created: (context: BrowserContext) => void+ closed: (context: BrowserContext) => void+}+async function signIn(page: Page, email: string): Promise<void> {const attempts = [`${WEB_URL}/c`, `${WEB_URL}/sign-in?redirect=/c`]let lastError: unknown@@ -40,14 +45,17 @@ export async function loginAndSaveState(key: UserKey,stamp: string,storageStatePath: string,+ owner?: LoginContextOwner,): Promise<SeededUser> {const email = emailFor(key, stamp)// Dev sign-up derives the display name from the email local-part// (`handleDevSignIn`: `name: email.split("@")[0]`), so mirror that here.const name = email.split("@")[0]const context = await browser.newContext()- const page = await context.newPage()+ let outcome: { value: SeededUser } | { error: unknown }try {+ owner?.created(context)+ const page = await context.newPage()await signIn(page, email)// Resolve the seeded userId via the authenticated community profile API,@@ -71,8 +79,17 @@ export async function loginAndSaveState(await context.clearCookies({ name: /^(?:is_new_signup|is_sign_in)$/ })await context.storageState({ path: storageStatePath })- return { key, email, name, userId: me.userId, storageState: storageStatePath }- } finally {+ outcome = { value: { key, email, name, userId: me.userId, storageState: storageStatePath } }+ } catch (error) {+ outcome = { error }+ }+ try {await context.close()+ owner?.closed(context)+ } catch (error) {+ if ("error" in outcome) throw new AggregateError([outcome.error, error], "Login and context cleanup failed")+ throw error}+ if ("error" in outcome) throw outcome.error+ return outcome.value}