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(web): isolate remaining UI case accounts and resources (#952)
Gener572c2a699284
diff --git a/src/web/src/test/e2e-fixture-isolation.test.ts b/src/web/src/test/e2e-fixture-isolation.test.tsindex fe694d363..bb9392549 100644--- a/src/web/src/test/e2e-fixture-isolation.test.ts+++ b/src/web/src/test/e2e-fixture-isolation.test.ts@@ -1,15 +1,18 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import type { Browser, BrowserContext, Page, TestFixture, TestInfo } from "@playwright/test"+import type { APIResponse, Browser, BrowserContext, Page, Response as PlaywrightResponse, 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 { test as caseTest, type CaseActors, type CaseResources } 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 CaseFactory = (roles: readonly ("alice" | "bob" | "carol" | "logout")[]) => Promise<CaseActors>+type ExitOwner = { allocate: CaseFactory; resources: CaseResources }type Registration = {- caseActors: TestFixture<CaseFactory, { browser: Browser; caseCleanupGuard: void }>+ caseActors: TestFixture<CaseFactory, { caseExitOwner: ExitOwner }>+ caseResources: TestFixture<CaseResources, { caseExitOwner: ExitOwner }>+ caseExitOwner: TestFixture<ExitOwner, { browser: Browser; caseCleanupGuard: void }>caseCleanupGuard: [TestFixture<void, Record<string, never>>, { auto: true }]}@@ -135,10 +138,14 @@ describe("test-scoped case actors and cleanup", () => {let baselineFault: "stale" | "truncated" | "error" | "malformed" | "profile" | undefinedlet loseServerResponse = falselet closeError: Error | undefined+ let emptySessionResponse: Response | undefined+ let missingDeleteStatus: 403 | 404 = 404+ let serverListFault: "error" | "missing" | "stale" | "truncated" | "malformed" | "empty-id" | undefinedconst closed: Array<{ isClosed: () => boolean }> = []const info = (testId: string, workerIndex = 0): TestInfo => ({testId,+ file: `${fixture.directory}/10-eject-nav-auth.spec.ts`,workerIndex,parallelIndex: 0,project: { name: "chromium" },@@ -149,8 +156,9 @@ describe("test-scoped case actors and cleanup", () => {const browser = (): Browser => ({newContext: vi.fn(async () => {let isClosed = false- const page = { isClosed: () => isClosed } as Page+ const page = { isClosed: () => isClosed, context: () => context, url: () => "http://fixture.test/sign-in" } as Pageconst context = {+ cookies: vi.fn(async () => []),newPage: async () => page,close: vi.fn(async () => {isClosed = true@@ -162,9 +170,46 @@ describe("test-scoped case actors and cleanup", () => {}),}) as unknown as Browser- const run = (testInfo: TestInfo, use: (factory: CaseFactory) => Promise<void>, currentBrowser = browser()) => {+ const run = (testInfo: TestInfo, use: (factory: CaseFactory, resources: CaseResources) => Promise<void>, currentBrowser = browser()) => {expect(caseTest).toBeDefined()- return fixture.registration!.caseActors({ browser: currentBrowser, caseCleanupGuard: undefined }, use, testInfo)+ return fixture.registration!.caseExitOwner({ browser: currentBrowser, caseCleanupGuard: undefined }, async (owner) => {+ await fixture.registration!.caseActors({ caseExitOwner: owner }, async (create) => {+ await fixture.registration!.caseResources({ caseExitOwner: owner }, (resources) => use(create, resources), testInfo)+ }, testInfo)+ }, testInfo)+ }++ const protectedRedirect = (): APIResponse => ({+ url: () => "http://fixture.test/c",+ status: () => 307,+ headers: () => ({ location: "/sign-in?redirect=%2Fc" }),+ }) as unknown as APIResponse++ const serverDeleteResponse = (page: Page, serverId: string, cookie: string, options: {+ status?: number+ method?: string+ requestUrl?: string+ responseUrl?: string+ requestPage?: Page+ cookie?: string+ completion?: null | Error+ rejectCompletion?: Error+ } = {}): PlaywrightResponse => {+ const target = `http://fixture.test/api/community/servers/${serverId}`+ return {+ url: () => options.responseUrl ?? target,+ status: () => options.status ?? 204,+ request: () => ({+ url: () => options.requestUrl ?? target,+ method: () => options.method ?? "DELETE",+ frame: () => ({ page: () => options.requestPage ?? page }),+ allHeaders: vi.fn(async () => ({ cookie: options.cookie ?? cookie })),+ }),+ finished: vi.fn(async () => {+ if (options.rejectCompletion) throw options.rejectCompletion+ return options.completion ?? null+ }),+ } as unknown as PlaywrightResponse}beforeEach(() => {@@ -179,6 +224,9 @@ describe("test-scoped case actors and cleanup", () => {baselineFault = undefinedloseServerResponse = falsecloseError = undefined+ emptySessionResponse = undefined+ missingDeleteStatus = 404+ serverListFault = undefinedrmSync(fixture.directory, { force: true, recursive: true })mkdirSync(fixture.directory, { recursive: true })writeFileSync(resolve(fixture.directory, "manifest.json"), JSON.stringify({ stamp: "case-fixture-run", users: {} }))@@ -192,6 +240,7 @@ describe("test-scoped case actors and cleanup", () => {})vi.stubGlobal("fetch", vi.fn(async (input: string, options?: RequestInit) => {const path = new URL(input).pathname+ if (path === "/api/ws/token") return emptySessionResponse ?? new Response("Unauthorized", { status: 401 })const cookie = (options?.headers as Record<string, string>).Cookieconst actor = actors.get(cookie.split("=")[1])!if (options?.method === "DELETE") {@@ -200,7 +249,7 @@ describe("test-scoped case actors and cleanup", () => {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 })+ return new Response(null, { status: found ? 204 : missingDeleteStatus })}if (options?.method === "POST") {if (path === "/api/community/servers") {@@ -217,7 +266,14 @@ describe("test-scoped case actors and cleanup", () => {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 === "/api/community/servers") {+ if (serverListFault === "error") return Response.json({ error: "Unavailable" }, { status: 503 })+ if (serverListFault === "missing") return Response.json({})+ if (serverListFault === "stale" || serverListFault === "truncated") return Response.json({ servers: [], [serverListFault]: true })+ if (serverListFault === "malformed") return Response.json({ servers: [{ id: "incomplete-server" }] })+ if (serverListFault === "empty-id") return Response.json({ servers: [{ id: "", ownerId: actor.userId }] })+ 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 })@@ -397,6 +453,305 @@ describe("test-scoped case actors and cleanup", () => {}, currentBrowser)).rejects.toBe(original)expect(context.close).toHaveBeenCalledOnce()})+ it("shares one exit owner for anonymous contexts, actor contexts and captured handles", async () => {+ const dispose = vi.fn(async () => undefined)+ const currentBrowser = browser()+ await run(info("shared-owner"), async (create, resources) => {+ const anonymous = await resources.newContext()+ const users = await create(["alice"])+ const actor = await users.asUser("alice")+ const handle = resources.own({ id: "exact-handle" }, dispose)+ users.onCleanup(async () => { await handle.close() })+ await Promise.all([resources.closeContext(anonymous), resources.closeContext(anonymous)])+ expect(vi.mocked(anonymous.close)).toHaveBeenCalledTimes(1)+ await resources.closeContext(actor.context)+ }, currentBrowser)+ expect(dispose).toHaveBeenCalledTimes(1)+ expect(dispose).toHaveBeenCalledWith({ id: "exact-handle" })+ expect(closed.every((page) => page.isClosed())).toBe(true)+ })++ it("owns an anonymous context before newPage fails without allocating an account", async () => {+ const original = new Error("newPage failed")+ const close = vi.fn(async () => undefined)+ const currentBrowser = { newContext: vi.fn(async () => ({ newPage: async () => { throw original }, close })) } as unknown as Browser+ await expect(run(info("anonymous-page-failed"), async (_create, resources) => {+ const context = await resources.newContext()+ await context.newPage()+ }, currentBrowser)).rejects.toBe(original)+ expect(close).toHaveBeenCalledTimes(1)+ expect(fixture.login).not.toHaveBeenCalled()+ expect(fetch).not.toHaveBeenCalled()+ })++ it("retains failed captured-handle cleanup and the original partial-creation error", async () => {+ const original = new Error("next resource failed")+ const disposal = new Error("handle close failed")+ const failure = await run(info("partial-owned-handle"), async (_create, resources) => {+ resources.own("already-created", async () => { throw disposal })+ throw original+ }).catch((error: AggregateError) => error)+ expect(failure).toBeInstanceOf(AggregateError)+ expect((failure as AggregateError).errors).toEqual([original, disposal])+ const record = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(record.unresolvedOperations).toBe(1)+ })++ it("rejects foreign context closes and sign-out evidence from a different actor", async () => {+ await run(info("wrong-owner"), async (create, resources) => {+ const users = await create(["alice", "logout"])+ const alice = await users.asUser("alice")+ await expect(resources.closeContext({ close: vi.fn() } as unknown as BrowserContext)).rejects.toThrow("different case owner")+ await expect(users.confirmSignedOut("logout", { ...alice, protectedResponse: protectedRedirect() })).rejects.toThrow("different case")+ await expect(users.confirmSignedOut("alice", { ...alice, protectedResponse: protectedRedirect() })).rejects.toThrow("restricted")+ })+ expect(vi.mocked(fetch).mock.calls.filter(([url]) => new URL(String(url)).pathname === "/api/ws/token")).toHaveLength(0)+ })++ it("requires both cleared original cookies and the original protected redirect", async () => {+ await run(info("missing-signout-proof"), async (create) => {+ const users = await create(["logout"])+ const logout = await users.asUser("logout")+ vi.mocked(logout.context.cookies).mockResolvedValue([{ name: "better-auth.session_token", value: "still-live" }] as Awaited<ReturnType<BrowserContext["cookies"]>>)+ await expect(users.confirmSignedOut("logout", { ...logout, protectedResponse: protectedRedirect() })).rejects.toThrow("incomplete")+ vi.mocked(logout.context.cookies).mockResolvedValue([])+ await expect(users.confirmSignedOut("logout", { ...logout, protectedResponse: { ...protectedRedirect(), status: () => 401 } as APIResponse })).rejects.toThrow("incomplete")+ })+ expect(vi.mocked(fetch).mock.calls.filter(([url]) => new URL(String(url)).pathname === "/api/ws/token")).toHaveLength(0)+ })++ it("closes all resources and Alice's full seed before proving the original logout session empty", async () => {+ const testInfo = info("normal-empty-session")+ let originalCookie = ""+ await run(testInfo, async (create, resources) => {+ const users = await create(["alice", "logout"])+ originalCookie = users.sessionCookie("logout")+ await users.seed.seedServer("alice", "complete seed")+ const dispose = vi.fn(async () => undefined)+ resources.own("gate", dispose)+ const logout = await users.asUser("logout")+ await users.confirmSignedOut("logout", { ...logout, protectedResponse: protectedRedirect() })+ expect(dispose).toHaveBeenCalledTimes(1)+ expect(servers.size).toBe(0)+ expect(closed.every((page) => page.isClosed())).toBe(true)+ })+ const requests = vi.mocked(fetch).mock.calls.filter(([url]) => new URL(String(url)).pathname === "/api/ws/token")+ expect(requests).toHaveLength(1)+ expect(String(requests[0][0])).toBe("http://fixture.test/api/ws/token?refresh=1")+ expect((requests[0][1]?.headers as Record<string, string>).Cookie).toBe(originalCookie)+ const attachments = vi.mocked(testInfo.attach).mock.calls+ const retirement = attachments.find(([name]) => name === "case-session-retirement")![1]+ expect(String(retirement!.body)).not.toContain(originalCookie)+ expect(JSON.parse(String(retirement!.body))).toMatchObject({ role: "logout", status: 401, unresolvedOperations: 0, unresolvedContexts: 0, unresolvedServers: 0 })+ })++ it.each([+ ["SDK JSON 401", () => Response.json({ code: "UNAUTHORIZED", message: "SDK failure" }, { status: 401 })],+ ["server failure", () => new Response("Unavailable", { status: 503 })],+ ["live session", () => Response.json({ userId: "still-live", token: "test-token" })],+ ] as const)("does not retire a session after %s", async (_label, response) => {+ emptySessionResponse = response()+ await expect(run(info("unproved-session"), async (create) => {+ const users = await create(["logout"])+ const logout = await users.asUser("logout")+ await users.confirmSignedOut("logout", { ...logout, protectedResponse: protectedRedirect() })+ })).rejects.toThrow("Case cleanup failed")+ const record = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(record.pendingSessionRetirement).toBe(true)+ })++ it("cannot exempt Alice's failed cleanup by retiring the logout actor", async () => {+ const failure = await run(info("other-actor-dirty"), async (create, resources) => {+ const users = await create(["alice", "logout"])+ const server = await users.seed.seedServer("alice", "failed seed retirement")+ deniedDeletes.add(server)+ resources.own("socket", async () => { throw new Error("socket close failed") })+ const logout = await users.asUser("logout")+ await users.confirmSignedOut("logout", { ...logout, protectedResponse: protectedRedirect() })+ }).catch((error: AggregateError) => error)+ expect(failure).toBeInstanceOf(AggregateError)+ expect(servers.size).toBe(1)+ expect(vi.mocked(fetch).mock.calls.filter(([url]) => new URL(String(url)).pathname === "/api/ws/token")).toHaveLength(0)+ const record = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(record.unresolvedOperations).toBe(1)+ expect(record.unresolvedServers).toHaveLength(1)+ })++ it("retires a bound product DELETE without repeating the permission-first 403 and still cleans other roles", async () => {+ const testInfo = info("product-deleted-server")+ const ids: { deleted?: string; other?: string } = {}+ await run(testInfo, async (create) => {+ const users = await create(["alice", "bob"])+ ids.deleted = await users.seed.seedServer("alice", "product deletion")+ ids.other = await users.seed.seedServer("bob", "normal cleanup")+ const { page } = await users.asUser("alice")+ servers.delete(ids.deleted)+ missingDeleteStatus = 403+ const response = serverDeleteResponse(page, ids.deleted, users.sessionCookie("alice"))+ await users.recordServerDeletion("alice", ids.deleted, { page, response })+ await expect(users.recordServerDeletion("alice", ids.deleted, { page, response })).rejects.toThrow("does not belong")+ })+ const deletedUrls = vi.mocked(fetch).mock.calls.filter(([, options]) => options?.method === "DELETE").map(([url]) => new URL(String(url)).pathname)+ expect(deletedUrls).toEqual([`/api/community/servers/${ids.other}`])+ const cleanup = vi.mocked(testInfo.attach).mock.calls.find(([name]) => name === "case-cleanup")![1]!+ expect(JSON.parse(String(cleanup.body)).outcomes.servers).toContainEqual(expect.objectContaining({ owner: "alice", id: ids.deleted, retired: true, deletion: expect.objectContaining({ status: 204 }) }))+ expect(String(cleanup.body)).not.toContain("better-auth.session_token")+ expect(servers.size).toBe(0)+ expect(closed.every((page) => page.isClosed())).toBe(true)+ const next = vi.fn(async () => undefined)+ await fixture.registration!.caseCleanupGuard[0]({}, next, info("successor-after-product-delete"))+ expect(next).toHaveBeenCalledOnce()+ })++ it("rejects server deletion proof with a foreign actor, target, page, request or session", async () => {+ await run(info("invalid-product-delete-proof"), async (create, resources) => {+ const users = await create(["alice", "bob"])+ const serverId = await users.seed.seedServer("alice", "bound target")+ const alice = await users.asUser("alice")+ const bob = await users.asUser("bob")+ const anonymous = await (await resources.newContext()).newPage()+ const cookie = users.sessionCookie("alice")+ await expect(users.recordServerDeletion("bob", serverId, { page: alice.page, response: serverDeleteResponse(alice.page, serverId, cookie) })).rejects.toThrow()+ await expect(users.recordServerDeletion("alice", "foreign-server", { page: alice.page, response: serverDeleteResponse(alice.page, "foreign-server", cookie) })).rejects.toThrow()+ for (const page of [bob.page, anonymous]) {+ await expect(users.recordServerDeletion("alice", serverId, { page, response: serverDeleteResponse(page, serverId, cookie) })).rejects.toThrow()+ }+ for (const options of [+ { requestPage: bob.page },+ { method: "GET" },+ { requestUrl: `http://other.test/api/community/servers/${serverId}` },+ { responseUrl: "http://fixture.test/api/community/servers/other-target" },+ { cookie: users.sessionCookie("bob") },+ { cookie: "" },+ ]) {+ await expect(users.recordServerDeletion("alice", serverId, { page: alice.page, response: serverDeleteResponse(alice.page, serverId, cookie, options) })).rejects.toThrow()+ }+ })+ expect(servers.size).toBe(0)+ expect(vi.mocked(fetch).mock.calls.filter(([, options]) => options?.method === "DELETE")).toHaveLength(1)+ })++ it.each([200, 401, 403, 404, 500])("does not treat product DELETE status %s as a retirement proof", async (status) => {+ await run(info(`delete-status-${status}`), async (create) => {+ const users = await create(["alice"])+ const serverId = await users.seed.seedServer("alice", "status proof")+ const { page } = await users.asUser("alice")+ const response = serverDeleteResponse(page, serverId, users.sessionCookie("alice"), { status })+ await expect(users.recordServerDeletion("alice", serverId, { page, response })).rejects.toThrow("successful DELETE")+ })+ expect(vi.mocked(fetch).mock.calls.filter(([, options]) => options?.method === "DELETE")).toHaveLength(1)+ })++ it.each(["returned Error", "rejection"] as const)("retains the original response completion failure on %s", async (kind) => {+ const original = new Error("DELETE response completion failed")+ await expect(run(info(`delete-finish-${kind}`), async (create) => {+ const users = await create(["alice"])+ const serverId = await users.seed.seedServer("alice", "unfinished response")+ const { page } = await users.asUser("alice")+ const options = kind === "returned Error" ? { completion: original } : { rejectCompletion: original }+ const response = serverDeleteResponse(page, serverId, users.sessionCookie("alice"), options)+ await users.recordServerDeletion("alice", serverId, { page, response })+ })).rejects.toBe(original)+ expect(servers.size).toBe(0)+ expect(vi.mocked(fetch).mock.calls.filter(([, options]) => options?.method === "DELETE")).toHaveLength(1)+ })++ it("keeps a product deletion unresolved when the complete owner list still contains the server", async () => {+ const testInfo = info("product-delete-still-present")+ const target: { id?: string } = {}+ await expect(run(testInfo, async (create) => {+ const users = await create(["alice"])+ target.id = await users.seed.seedServer("alice", "still present")+ const { page } = await users.asUser("alice")+ const response = serverDeleteResponse(page, target.id, users.sessionCookie("alice"))+ await users.recordServerDeletion("alice", target.id, { page, response })+ })).rejects.toThrow("Case cleanup failed")+ expect(servers.has(target.id!)).toBe(true)+ expect(vi.mocked(fetch).mock.calls.filter(([, options]) => options?.method === "DELETE")).toHaveLength(0)+ const failure = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(failure.unresolvedServers).toEqual([{ owner: "alice", id: target.id }])+ const next = vi.fn(async () => undefined)+ await expect(fixture.registration!.caseCleanupGuard[0]({}, next, info("after-live-delete-proof"))).rejects.toThrow("blocked")+ expect(next).not.toHaveBeenCalled()+ })++ it.each(["error", "missing", "stale", "truncated", "malformed", "empty-id"] as const)("cannot retire a product-deleted server when its list is %s", async (fault) => {+ await expect(run(info(`delete-list-${fault}`), async (create) => {+ const users = await create(["alice"])+ const serverId = await users.seed.seedServer("alice", "deleted with unknown list")+ const { page } = await users.asUser("alice")+ servers.delete(serverId)+ missingDeleteStatus = 403+ await users.recordServerDeletion("alice", serverId, { page, response: serverDeleteResponse(page, serverId, users.sessionCookie("alice")) })+ serverListFault = fault+ })).rejects.toThrow("Case cleanup failed")+ const failure = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(failure.unresolvedServers).toHaveLength(1)+ expect(vi.mocked(fetch).mock.calls.filter(([, options]) => options?.method === "DELETE")).toHaveLength(0)+ })++ it("preserves a later UI failure while the proved product deletion exits cleanly", async () => {+ const original = new Error("original history assertion failed")+ const testInfo = info("body-failed-after-product-delete")+ await expect(run(testInfo, async (create) => {+ const users = await create(["alice"])+ const serverId = await users.seed.seedServer("alice", "deleted before body failure")+ const { page } = await users.asUser("alice")+ servers.delete(serverId)+ missingDeleteStatus = 403+ await users.recordServerDeletion("alice", serverId, { page, response: serverDeleteResponse(page, serverId, users.sessionCookie("alice")) })+ throw original+ })).rejects.toBe(original)+ expect(vi.mocked(fetch).mock.calls.filter(([, options]) => options?.method === "DELETE")).toHaveLength(0)+ const next = vi.fn(async () => undefined)+ await fixture.registration!.caseCleanupGuard[0]({}, next, info("after-clean-body-failure"))+ expect(next).toHaveBeenCalledOnce()+ })++ it("cannot add a product deletion proof after the original case owner has exited", async () => {+ const completion: { started?: () => void; finish?: () => void } = {}+ const started = new Promise<void>((resolve) => { completion.started = resolve })+ const proof: { pending?: Promise<void>; error?: unknown } = {}+ await expect(run(info("late-product-delete-proof"), async (create) => {+ const users = await create(["alice"])+ const serverId = await users.seed.seedServer("alice", "late completion proof")+ const { page } = await users.asUser("alice")+ servers.delete(serverId)+ missingDeleteStatus = 403+ const response = serverDeleteResponse(page, serverId, users.sessionCookie("alice"))+ vi.mocked(response.finished).mockImplementation(() => new Promise<null>((resolve) => {+ completion.finish = () => resolve(null)+ completion.started!()+ }))+ proof.pending = users.recordServerDeletion("alice", serverId, { page, response }).catch((error) => { proof.error = error })+ await started+ })).rejects.toThrow("Case cleanup failed")+ completion.finish!()+ await proof.pending+ expect((proof.error as Error).message).toContain("after its case owner started exiting")+ const failure = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(failure.unresolvedServers).toHaveLength(1)+ expect(failure.unresolvedContexts).toEqual([])+ })+++ it("keeps a context creation that settles during exit with its original owner", async () => {+ let deliver!: (context: BrowserContext) => void+ const context = { close: vi.fn(async () => undefined) } as unknown as BrowserContext+ const currentBrowser = { newContext: vi.fn(() => new Promise<BrowserContext>((resolve) => { deliver = resolve })) } as unknown as Browser+ let creationFailure: unknown+ await expect(run(info("late-context"), async (_create, resources) => {+ void resources.newContext().catch((error) => { creationFailure = error })+ setTimeout(() => deliver(context), 0)+ }, currentBrowser)).rejects.toThrow("Case cleanup failed")+ expect(context.close).toHaveBeenCalledTimes(1)+ expect((creationFailure as Error).message).toContain("after its case owner started exiting")+ const record = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))+ expect(record.identity.testId).toBe("late-context")+ expect(record.unresolvedContexts).toEqual([])+ expect(fixture.login).not.toHaveBeenCalled()+ })+})describe("real login helper context exit", () => {@@ -520,4 +875,5 @@ describe("real login helper context exit", () => {expect(s.context.storageState).toHaveBeenCalledWith({ path: "unit-state.json" })expect(s.context.close).toHaveBeenCalledOnce()})+})diff --git a/src/web/src/test/e2e-ui/01-auth.spec.ts b/src/web/src/test/e2e-ui/01-auth.spec.tsindex 297397053..d2d5366ba 100644--- a/src/web/src/test/e2e-ui/01-auth.spec.ts+++ b/src/web/src/test/e2e-ui/01-auth.spec.ts@@ -1,4 +1,4 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import {test as browserTest,expect as browserExpect,@@ -83,17 +83,20 @@ async function expectCenteredNativeOauthState(// Journey 1 — login & first screen. storageState is established in// global-setup, so this journey re-verifies the redirect/auth contract with a// FRESH context (no saved session) plus an authenticated landing.-test.describe.serial("auth & first screen", () => {- test("unauthenticated /c deep-link redirects to /sign-in with redirect param", async ({ browser }) => {- const context = await browser.newContext() // no storageState — anonymous+test.describe("auth & first screen", () => {+ test("unauthenticated /c deep-link redirects to /sign-in with redirect param", async ({ browser, caseResources }) => {+ const context = await caseResources.newContext() // no storageState — anonymousconst page = await context.newPage()await page.goto("/c/channels/does-not-matter/whatever")await page.waitForURL(/\/sign-in/, { timeout: 20_000 , waitUntil: "commit" })expect(page.url()).toContain("redirect=")- await context.close()+ await caseResources.closeContext(context)})- test("authenticated user reaches the community shell", async ({ asUser }) => {+ test("authenticated user reaches the community shell", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+const { page } = await asUser("alice")await page.goto("/c")// Not bounced to sign-in.@@ -282,6 +285,7 @@ browserTest.describe("native OAuth status actions", () => {let releasePrepare!: () => voidconst prepareGate = new Promise<void>((resolve) => { releasePrepare = resolve })+ try {await page.exposeFunction("__testNativeOauthInvoke", async (command: string) => {if (command === "native_oauth_snapshot") return snapshotif (command === "native_oauth_pending_exchange") return null@@ -389,5 +393,6 @@ browserTest.describe("native OAuth status actions", () => {cancel: false,retryDisabled: false,})+ } finally { releasePrepare() }})})diff --git a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts b/src/web/src/test/e2e-ui/02-server-channel-message.spec.tsindex 02082c8b2..27a593e1e 100644--- a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts+++ b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts@@ -1,9 +1,13 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { composerEditable, createServer, sendMessage, expectMessageVisible } from "./_fixtures/actions"-test("server → channel → message", async ({ asUser }) => {+test("server → channel → message", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+const { page } = await asUser("alice")await page.goto("/c")await page.waitForURL(/\/c/, { timeout: 20_000, waitUntil: "commit" })@@ -161,6 +165,7 @@ test("server → channel → message", async ({ asUser }) => {let releaseMessages!: () => voidconst messagesGate = new Promise<void>((resolve) => { releaseMessages = resolve })+ caseResources.own(releaseMessages, async (captured) => { captured() })await page.route("**/api/community/channels/*/messages*", async (route) => {if (route.request().method() !== "GET") {await route.continue()@@ -198,6 +203,7 @@ test("server → channel → message", async ({ asUser }) => {await page.keyboard.press("Backspace")let releasePendingSend!: () => voidconst pendingSendGate = new Promise<void>((resolve) => { releasePendingSend = resolve })+ caseResources.own(releasePendingSend, async (captured) => { captured() })let pendingSendIntercepted = falselet pendingSendCompleted = falselet pendingPostCount = 0diff --git a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.tsindex 174e9d524..76f02b2ff 100644--- a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts+++ b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts@@ -1,24 +1,28 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { sendMessage, expectMessageVisible, composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"-import { seedServer, seedChannel, seedJoinServer } from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 3 — multi-user realtime. Alice and Bob are both online in the same// channel; a message/typing/reaction from one surfaces on the other WITHOUT a// reload. Requires ws-do (global-setup fails fast if it's down).-test.describe.serial("multi-user realtime", () => {- let serverId: string- let channelId: string-- test.beforeAll(async () => {+test.describe("multi-user realtime", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedServer, seedChannel, seedJoinServer } = actors.seed// Precondition (not the thing under test): Alice owns a server + channel,// Bob is a member. Seeded via API so the journey focuses on realtime UI.- serverId = await seedServer("alice", `RT ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "realtime")+ const serverId: string = await seedServer("alice", `RT ${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "realtime")await seedJoinServer("alice", "bob", serverId)- })+ return { serverId, channelId }+ }++ test("Alice's message reaches Bob live", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)- test("Alice's message reaches Bob live", async ({ asUser }) => {const alice = await asUser("alice")const bob = await asUser("bob")await alice.page.goto(`/c/channels/${serverId}/${channelId}`)@@ -50,7 +54,11 @@ test.describe.serial("multi-user realtime", () => {await expectMessageVisible(bob.page, body)})- test("Bob sees Alice's typing indicator, which clears after her message", async ({ asUser }) => {+ test("Bob sees Alice's typing indicator, which clears after her message", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const alice = await asUser("alice")const bob = await asUser("bob")await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex 1c50b972a..3f85a8320 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -1,16 +1,20 @@import type { Frame } from "@playwright/test"-import { test, expect, userId, userName } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { sendMessage } from "./_fixtures/actions"import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"-import { seedDm, seedDmMessage } from "./_fixtures/seed"+import { captureNotificationRequests, gotoAfterNotificationStartup, notificationPaths, notificationResponsesFinished } from "./_fixtures/community-notification-requests"import { lastMeLocationKey } from "@/lib/community/last-me-location"// Journey 4 — DMs. human↔human needs only not-blocked (no friendship). Covers// the new-conversation-appears-live path and the blocked-composer regression.-test.describe.serial("direct messages", () => {- test("an Inbox first-DM click commits immediately and stays on the conversation", async ({ asUser }, testInfo) => {+test.describe("direct messages", () => {+ test("an Inbox first-DM click commits immediately and stays on the conversation", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId, userName } = actors+ const { seedDm, seedDmMessage } = actors.seed+const bob = await asUser("bob")const trace = captureNotificationRequests(bob.page)const proxy = await gotoAfterNotificationStartup(bob.page, bob.context, trace)@@ -79,7 +83,11 @@ test.describe.serial("direct messages", () => {}})- test("a canonical DM keeps its title while history permission gates body and composer", async ({ asUser }) => {+ test("a canonical DM keeps its title while history permission gates body and composer", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId, userName } = actors+ const { seedDm, seedDmMessage } = actors.seed+const dmId = await seedDm("alice", userId("bob"))const body = `held DM message ${Date.now()}`const messageId = await seedDmMessage("bob", dmId, body)@@ -103,8 +111,11 @@ test.describe.serial("direct messages", () => {let metadataStarted!: () => voidlet metadataFinished!: () => voidconst metadataGate = new Promise<void>(resolve => { releaseMetadata = resolve })+ caseResources.own(releaseMetadata, async (captured) => { captured() })const metadataRequest = new Promise<void>(resolve => { metadataStarted = resolve })+ caseResources.own(metadataStarted, async (captured) => { captured() })const metadataSettled = new Promise<void>(resolve => { metadataFinished = resolve })+ caseResources.own(metadataFinished, async (captured) => { captured() })const metadataPattern = (url: URL) => url.pathname === `/api/community/channels/${dmId}`await alice.page.route(metadataPattern, async route => {if (route.request().method() !== "GET") { await route.continue(); return }@@ -121,8 +132,11 @@ test.describe.serial("direct messages", () => {let readStarted!: () => voidlet readFinished!: () => voidconst readGate = new Promise<void>((resolve) => { releaseRead = resolve })+ caseResources.own(releaseRead, async (captured) => { captured() })const readRequest = new Promise<void>((resolve) => { readStarted = resolve })+ caseResources.own(readStarted, async (captured) => { captured() })const readSettled = new Promise<void>((resolve) => { readFinished = resolve })+ caseResources.own(readFinished, async (captured) => { captured() })const readPattern = `**/api/community/channels/${dmId}/read-state`await alice.page.route(readPattern, async (route) => {readStarted()@@ -140,8 +154,11 @@ test.describe.serial("direct messages", () => {let messagesStarted!: () => voidlet messagesFinished!: () => voidconst messagesGate = new Promise<void>((resolve) => { releaseMessages = resolve })+ caseResources.own(releaseMessages, async (captured) => { captured() })const messagesRequest = new Promise<void>((resolve) => { messagesStarted = resolve })+ caseResources.own(messagesStarted, async (captured) => { captured() })const messagesSettled = new Promise<void>((resolve) => { messagesFinished = resolve })+ caseResources.own(messagesFinished, async (captured) => { captured() })let heldMessages = falseconst messagesPattern = `**/api/community/channels/${dmId}/messages*`await alice.page.route(messagesPattern, async (route) => {@@ -216,7 +233,10 @@ test.describe.serial("direct messages", () => {}})- test("an absent DM verifies once per attempt and exposes transient Retry locally", async ({ asUser }) => {+ test("an absent DM verifies once per attempt and exposes transient Retry locally", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+const alice = await asUser("alice")const wsProxy = await proxyCommunityWebSockets(alice.context, {decideConnectionFrame: (frame) => frame.type === "auth.ok" ? "hold" : "forward",@@ -264,7 +284,11 @@ test.describe.serial("direct messages", () => {}})- test("a DM message reaches the peer live and the conversation appears without reload", async ({ asUser }) => {+ test("a DM message reaches the peer live and the conversation appears without reload", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedDm } = actors.seed+// Alice opens a DM to Bob via API (precondition), then both drive the UI.const dmId = await seedDm("alice", userId("bob"))@@ -304,7 +328,11 @@ test.describe.serial("direct messages", () => {await expect(bob.page.getByTestId(tid.message(payload.message.id))).toHaveCount(1)})- test("blocking replaces the composer with a blocked notice", async ({ asUser }) => {+ test("blocking replaces the composer with a blocked notice", async ({ caseActors }) => {+ const actors = await caseActors(["bob", "carol"])+ const { asUser, userId, userName } = actors+ const { seedDm, seedDmMessage } = actors.seed+const dmId = await seedDm("carol", userId("bob"))const body = `visible before block ${Date.now()}`const messageId = await seedDmMessage("carol", dmId, body)diff --git a/src/web/src/test/e2e-ui/05-mention-bot.spec.ts b/src/web/src/test/e2e-ui/05-mention-bot.spec.tsindex a3d11297d..fe05c6ceb 100644--- a/src/web/src/test/e2e-ui/05-mention-bot.spec.ts+++ b/src/web/src/test/e2e-ui/05-mention-bot.spec.ts@@ -1,23 +1,27 @@-import { test, expect, userName } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { composerEditable } from "./_fixtures/actions"-import { seedServer, seedChannel, seedJoinServer } from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 5 — @-mentions. The mention popup shows SERVER MEMBERS (regression// a4672ca2: not the viewer's friends). Bot reply is out of scope (no daemon /// queue-worker); we assert the mention UI + that a mention produces an inbox// entry for the mentioned user.-test.describe.serial("mentions", () => {- let serverId: string- let channelId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Mention ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "mentions")+test.describe("mentions", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedServer, seedChannel, seedJoinServer } = actors.seed+ const serverId: string = await seedServer("alice", `Mention ${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "mentions")await seedJoinServer("alice", "bob", serverId)- })+ return { serverId, channelId }+ }++ test("the @-mention popup lists server members", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userName } = actors+ const { serverId, channelId } = await prepareCase1(actors)- test("the @-mention popup lists server members", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })@@ -32,7 +36,11 @@ test.describe.serial("mentions", () => {).toBeVisible({ timeout: 15_000 })})- test("@everyone is offered in a channel", async ({ asUser }) => {+ test("@everyone is offered in a channel", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })diff --git a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.tsindex 2b77b3666..36881b342 100644--- a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts+++ b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts@@ -1,20 +1,24 @@-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"-import { seedServer, seedChannel, seedJoinServer, seedCategory, seedMessage, seedThread, memberInfo } from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 6 — channel / member administration + the eject branch (needs a// second identity). Focuses on member list presence and non-member ejection.-test.describe.serial("channel & member admin", () => {- let serverId: string- let channelId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Admin ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "admin-chan")+test.describe("channel & member admin", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedServer, seedChannel, seedJoinServer } = actors.seed+ const serverId: string = await seedServer("alice", `Admin ${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "admin-chan")await seedJoinServer("alice", "bob", serverId)- })+ return { serverId, channelId }+ }++ test("a non-member is ejected when hitting the server URL directly", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)- test("a non-member is ejected when hitting the server URL directly", async ({ asUser }) => {// Carol is not a member of Alice's server.const { page } = await asUser("carol")await page.goto(`/c/channels/${serverId}/${channelId}`)@@ -22,7 +26,11 @@ test.describe.serial("channel & member admin", () => {await expect(page).not.toHaveURL(new RegExp(`/channels/${serverId}/${channelId}$`), { timeout: 20_000 })})- test("the member list shows server members", async ({ asUser }) => {+ test("the member list shows server members", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })@@ -31,7 +39,12 @@ test.describe.serial("channel & member admin", () => {await expect(page.getByTestId(tid.memberRow(userId("bob")))).toBeVisible({ timeout: 15_000 })})- test("Channels loads only on selection and lists private metadata without granting content access", async ({ asUser }) => {+ test("Channels loads only on selection and lists private metadata without granting content access", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedChannel, seedCategory, seedMessage, seedThread, memberInfo } = actors.seed+ const { serverId, channelId } = await prepareCase1(actors)+const categoryId = await seedCategory("alice", serverId, `Directory QA ${Date.now()}`, { private: true })const privateName = "bob-private-channel-with-a-very-long-name-for-mobile-review"const privateId = await seedChannel("bob", serverId, privateName, "forum", categoryId)@@ -157,7 +170,11 @@ test.describe.serial("channel & member admin", () => {await expect(page.getByTestId(tid.channelRow(privateId))).toHaveCount(0)})- test("ordinary members cannot open admin settings or access the admin list", async ({ asUser }) => {+ test("ordinary members cannot open admin settings or access the admin list", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("bob")await page.goto(`/c/channels/${serverId}/${channelId}`)await expect(page.getByTestId(tid.composerInput)).toBeVisible()diff --git a/src/web/src/test/e2e-ui/07-invite.spec.ts b/src/web/src/test/e2e-ui/07-invite.spec.tsindex 97ca66700..44a724a7a 100644--- a/src/web/src/test/e2e-ui/07-invite.spec.ts+++ b/src/web/src/test/e2e-ui/07-invite.spec.ts@@ -1,19 +1,20 @@-import { test, expect, userId, userName } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"import {communityFrameEvents,proxyCommunityWebSockets,} from "./_fixtures/community-ws-proxy"-import {- seedChannel,- seedFriendship,- seedServer,- createInvite,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"-test("an offline friend comes online through reconnect and receives the invite DM", async ({ asUser }) => {+test("an offline friend comes online through reconnect and receives the invite DM", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId, userName } = actors+ const { seedChannel, seedFriendship, seedServer } = actors.seed+const serverId = await seedServer("alice", `Friend invite ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "invite-friend")await seedFriendship("alice", "bob", userId("bob"))@@ -102,16 +103,19 @@ test("an offline friend comes online through reconnect and receives the invite D// Journey 7 — invite accept (second identity). Alice creates a server + invite// via API, Bob accepts it through the UI, and the new server appears in Bob's// rail without a manual reload (regression 1c2e2a05).-test.describe.serial("invite accept", () => {- let serverId: string- let inviteToken: string+test.describe("invite accept", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedServer, createInvite } = actors.seed+ const serverId: string = await seedServer("alice", `Invite ${Date.now()}`)+ const inviteToken: string = await createInvite("alice", serverId)+ return { serverId, inviteToken }+ }- test.beforeAll(async () => {- serverId = await seedServer("alice", `Invite ${Date.now()}`)- inviteToken = await createInvite("alice", serverId)- })+ test("Bob accepts the invite and lands in the server", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, inviteToken } = await prepareCase1(actors)- test("Bob accepts the invite and lands in the server", async ({ asUser }) => {const { page } = await asUser("bob")await page.goto(`/c/invite/${inviteToken}`)// Accept via the join CTA.diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.tsindex 68ce9dfa1..5728fd905 100644--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts@@ -1,14 +1,8 @@import type { Page } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"-import {- seedServer,- seedChannel,- seedDm,- seedMark,- seedMessage,- seedThread,-} from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 8 — adaptive list/detail routing. At <640px semantic roots render// lists and leaf paths render detail. Server and verified-parent header crumbs@@ -51,23 +45,25 @@ async function expectNoWrongMeConversationLoading(page: Page): Promise<void> {).__wrongMeConversationLoadingSeen)).toBe(false)}-test.describe.serial("mobile layout", () => {- let serverId: string- let channelId: string- let childChannelId: string- let dmId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Mobile ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "mobile-chan")+test.describe("mobile layout", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId } = actors+ const { seedServer, seedChannel, seedDm, seedMark, seedMessage, seedThread } = actors.seed+ const serverId: string = await seedServer("alice", `Mobile ${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "mobile-chan")const parentMessageId = await seedMessage("alice", channelId, "mobile seq command target")- childChannelId = await seedThread("alice", parentMessageId, "mobile-child")+ const childChannelId: string = await seedThread("alice", parentMessageId, "mobile-child")const childMessageId = await seedMessage("alice", childChannelId, "mobile child seq target")await seedMark("alice", childChannelId, childMessageId)- dmId = await seedDm("alice", userId("bob"))- })+ const dmId: string = await seedDm("alice", userId("bob"))+ return { serverId, channelId, childChannelId, dmId }+ }++ test("whole-page panels fill mobile routes and keep detail identity across 640px", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)- test("whole-page panels fill mobile routes and keep detail identity across 640px", async ({ asUser }) => {const { page } = await asUser("alice")for (const width of [375, 639]) {@@ -113,7 +109,11 @@ test.describe.serial("mobile layout", () => {}})- test("a direct channel opens detail and Back replaces to the server root", async ({ asUser }) => {+ test("a direct channel opens detail and Back replaces to the server root", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })@@ -139,7 +139,11 @@ test.describe.serial("mobile layout", () => {await expect(page.getByTestId(tid.composerInput)).toBeHidden()})- test("browser Back and Forward restore list and detail from semantic paths", async ({ asUser }) => {+ test("browser Back and Forward restore list and detail from semantic paths", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}`)const channelRow = page.getByTestId(tid.channelRow(channelId))@@ -159,7 +163,11 @@ test.describe.serial("mobile layout", () => {await expect(page.getByTestId(tid.composerInput)).toBeVisible()})- test("Friends, Machines, and Bots deep links all default to content", async ({ asUser }) => {+ test("Friends, Machines, and Bots deep links all default to content", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ await prepareCase1(actors)+const { page } = await asUser("alice")await installMeLoadingProbe(page)@@ -177,7 +185,11 @@ test.describe.serial("mobile layout", () => {}})- test("detail consumes seq without dropping other URL state", async ({ asUser }) => {+ test("detail consumes seq without dropping other URL state", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}?seq=1&keep=detail-seq`)@@ -187,7 +199,11 @@ test.describe.serial("mobile layout", () => {await expect(page.getByTestId(tid.composerInput)).toBeVisible()})- test("flat child detail consumes seq without dropping route or other URL state", async ({ asUser }) => {+ test("flat child detail consumes seq without dropping route or other URL state", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, childChannelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${childChannelId}?seq=1&keep=child-seq`,@@ -201,7 +217,11 @@ test.describe.serial("mobile layout", () => {await expect(page.getByRole("dialog").getByText("mobile child seq target")).toBeVisible()})- test("a flat child exposes its current identity and direct parent Back control", async ({ asUser }) => {+ test("a flat child exposes its current identity and direct parent Back control", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, childChannelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${childChannelId}`)const current = page.getByRole("banner").getByText("mobile-child", { exact: true })@@ -217,7 +237,11 @@ test.describe.serial("mobile layout", () => {expect(await page.evaluate(() => history.length)).toBe(historyLength)})- test("Marked opens a child message on its canonical route without losing context", async ({ asUser }) => {+ test("Marked opens a child message on its canonical route without losing context", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, childChannelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto("/c/me")await page.getByRole("button", { name: "Inbox" }).click()@@ -231,7 +255,11 @@ test.describe.serial("mobile layout", () => {await expect(page.getByRole("dialog").getByText("mobile child seq target")).toBeVisible()})- test("rejects the removed nested route and clears nested last-channel memory", async ({ asUser }) => {+ test("rejects the removed nested route and clears nested last-channel memory", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, childChannelId } = await prepareCase1(actors)+const { page } = await asUser("alice")const response = await page.goto(`/c/channels/${serverId}/${channelId}/${childChannelId}`,@@ -258,7 +286,11 @@ test.describe.serial("mobile layout", () => {)).toBe(selectedChannelId)})- test("server-root modal markers are one-shot on mobile", async ({ asUser }) => {+ test("server-root modal markers are one-shot on mobile", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId } = await prepareCase1(actors)+for (const marker of ["settings", "invite"]) {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}?${marker}=1&keep=${marker}`)@@ -293,7 +325,11 @@ test.describe.serial("mobile layout", () => {}})- test("a direct DM opens detail and Header Back replaces it with Me root", async ({ asUser }) => {+ test("a direct DM opens detail and Header Back replaces it with Me root", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { dmId } = await prepareCase1(actors)+const { page } = await asUser("alice")await installMeLoadingProbe(page)await page.goto(`/c/me/${dmId}`)@@ -307,7 +343,11 @@ test.describe.serial("mobile layout", () => {await expect(page.getByTestId(tid.composerInput)).toBeHidden()})- test("cross-layout Back and Forward restore each route-owned surface", async ({ asUser }) => {+ test("cross-layout Back and Forward restore each route-owned surface", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, dmId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}`)await expect(page.getByTestId(tid.homeButton)).toBeVisible()@@ -332,7 +372,11 @@ test.describe.serial("mobile layout", () => {await expect(page.getByTestId(tid.composerInput)).toBeVisible()})- test("resizing resolves desktop roots to detail without inventing layout URL state", async ({ asUser }) => {+ test("resizing resolves desktop roots to detail without inventing layout URL state", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)await expect(page.getByTestId(tid.composerInput)).toBeVisible()diff --git a/src/web/src/test/e2e-ui/09-forum-thread.spec.ts b/src/web/src/test/e2e-ui/09-forum-thread.spec.tsindex 059444283..0ddc68a1a 100644--- a/src/web/src/test/e2e-ui/09-forum-thread.spec.ts+++ b/src/web/src/test/e2e-ui/09-forum-thread.spec.ts@@ -1,17 +1,16 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, sendMessage } from "./_fixtures/actions"-import { seedServer, seedChannel, seedMessage } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"// Journey 9 — threads. Creating a thread from a message surfaces a thread// indicator on the parent message (regression ab572e3e).-test.describe.serial("threads", () => {- let serverId: string- let channelId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Thread ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "threads")+test.describe("threads", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedServer, seedChannel, seedMessage } = actors.seed+ const serverId: string = await seedServer("alice", `Thread ${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "threads")// Seed the parent message via API so it's already persisted with a real// id before the UI opens. Sending the FIRST message through the UI in a// cold, directly-navigated channel races the list's initial fetch (the@@ -19,9 +18,14 @@ test.describe.serial("threads", () => {// test-harness timing issue, not a product bug (spec 02/03 cover the send// UI). Seeding sidesteps the race so this journey can focus on threads.await seedMessage("alice", channelId, `thread parent ${Date.now()}`)- })+ return { serverId, channelId }+ }++ test("creating a thread from a message shows a thread indicator on the parent", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)- test("creating a thread from a message shows a thread indicator on the parent", async ({ asUser }) => {const { page } = await asUser("alice")const requests: string[] = []page.on("request", (request) => requests.push(request.url()))diff --git a/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts b/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.tsindex f516bb542..c6ce31e4d 100644--- a/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts+++ b/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts@@ -1,24 +1,32 @@-import { test, expect } from "./_fixtures/community-fixture"-import { seedServer, seedChannel } from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 10 — eject / navigation / logout safety.-test.describe.serial("eject, navigation & logout", () => {- let serverId: string- let channelId: string+test.describe("eject, navigation & logout", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedServer, seedChannel } = actors.seed+ const serverId: string = await seedServer("alice", `Eject ${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "eject-chan")+ return { serverId, channelId }+ }- test.beforeAll(async () => {- serverId = await seedServer("alice", `Eject ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "eject-chan")- })+ test("direct URL to a server you're not in redirects away", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "carol"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)- test("direct URL to a server you're not in redirects away", async ({ asUser }) => {// Carol is not a member.const { page } = await asUser("carol")await page.goto(`/c/channels/${serverId}/${channelId}`)await expect(page).not.toHaveURL(new RegExp(`/channels/${serverId}/${channelId}$`), { timeout: 20_000 })})- test("clicking a rail server lands on a channel, not the bare server root", async ({ asUser }) => {+ test("clicking a rail server lands on a channel, not the bare server root", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId } = await prepareCase1(actors)+// Alice owns the server; navigating via the rail resolves to a channel.const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}`)@@ -27,7 +35,11 @@ test.describe.serial("eject, navigation & logout", () => {expect(page.url()).toMatch(new RegExp(`/channels/${serverId}/[^/]+`))})- test("logout clears the session", async ({ asUser }) => {+ test("logout clears the session", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "logout"])+ const { asUser } = actors+ await prepareCase1(actors)+const { page } = await asUser("logout")await page.goto("/c")await page.waitForURL(/\/c/, { timeout: 20_000 , waitUntil: "commit" })@@ -48,5 +60,6 @@ test.describe.serial("eject, navigation & logout", () => {expect(redirectUrl.pathname).toBe("/sign-in")expect(redirectUrl.searchParams.get("redirect")).toBe("/c")await expect(page).toHaveURL(/\/sign-in/)+ await actors.confirmSignedOut("logout", { context: page.context(), page, protectedResponse })})})diff --git a/src/web/src/test/e2e-ui/11-profile-ui-stability.spec.ts b/src/web/src/test/e2e-ui/11-profile-ui-stability.spec.tsindex 8276b8241..0313fe491 100644--- a/src/web/src/test/e2e-ui/11-profile-ui-stability.spec.ts+++ b/src/web/src/test/e2e-ui/11-profile-ui-stability.spec.ts@@ -1,25 +1,30 @@-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"-import { seedServer, seedChannel, seedJoinServer, seedFriendship, seedRemoveFriendship } from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 11 — profile card UI stability. Opening a member's profile shows the// card; closing detaches it (regression ab873738 — assert detach, not the// transform-origin animation).-test.describe.serial("profile card stability", () => {- let serverId: string- let channelId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Profile ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "profiles")+test.describe("profile card stability", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedServer, seedChannel, seedJoinServer } = actors.seed+ const serverId: string = await seedServer("alice", `Profile ${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "profiles")await seedJoinServer("alice", "bob", serverId)- })+ return { serverId, channelId }+ }for (const isFriend of [false, true]) {const name = isFriend? "opening an accepted friend's profile focuses the textbox; closing detaches it": "opening a member profile shows the card; closing detaches it"- test(name, async ({ asUser }) => {+ test(name, async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedFriendship, seedRemoveFriendship } = actors.seed+ const { serverId, channelId } = await prepareCase1(actors)+const bobId = userId("bob")await seedFriendship("alice", "bob", bobId)if (!isFriend) await seedRemoveFriendship("alice", bobId)diff --git a/src/web/src/test/e2e-ui/12-friends.spec.ts b/src/web/src/test/e2e-ui/12-friends.spec.tsindex fefbc069f..e11feea8e 100644--- a/src/web/src/test/e2e-ui/12-friends.spec.ts+++ b/src/web/src/test/e2e-ui/12-friends.spec.ts@@ -1,21 +1,26 @@-import { test, expect, userId, userName } from "./_fixtures/community-fixture"-import { seedChannel, seedFriendship, seedServer } from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"// Journey 12 — friends. A seeded friendship (Alice↔Bob) shows on the friends// page; the row opens a DM on click. Friendship handshake uses the two-cookie// helper (accept is addressee-only).-test.describe.serial("friends", () => {- let serverId: string- let channelId: string-- test.beforeAll(async () => {+test.describe("friends", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId } = actors+ const { seedChannel, seedFriendship, seedServer } = actors.seedawait seedFriendship("alice", "bob", userId("bob"))- serverId = await seedServer("alice", `Friends Home ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "friends-home")- })+ const serverId: string = await seedServer("alice", `Friends Home ${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "friends-home")+ return { serverId, channelId }+ }++ test("a friend shows in the friends list and opens a DM", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userName } = actors+ const { serverId, channelId } = await prepareCase1(actors)- test("a friend shows in the friends list and opens a DM", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto("/c/me")await page.waitForURL(/\/c\/me\/friends$/, { timeout: 20_000 , waitUntil: "commit" })diff --git a/src/web/src/test/e2e-ui/13-mentions.spec.ts b/src/web/src/test/e2e-ui/13-mentions.spec.tsindex fc985e3c6..f404f6ae6 100644--- a/src/web/src/test/e2e-ui/13-mentions.spec.ts+++ b/src/web/src/test/e2e-ui/13-mentions.spec.ts@@ -1,14 +1,8 @@-import { test, expect, userId, userName } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { composerEditable } from "./_fixtures/actions"-import {- seedServer,- seedChannel,- seedJoinServer,- seedMessage,- renameUser,- memberInfo,-} from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 13 — mandatory mention discriminator. Every member mention serializes// as `@Name#dddd`, which lets a name with spaces render as one pill AND makes a@@ -19,46 +13,52 @@ import {// Fixture: Bob and Carol are both renamed "John Doe" (spaced name), each keeping// its own auto-assigned discriminator — so the same journey exercises the// spaced-name pill and the same-name disambiguation.-test.describe.serial("mentions — mandatory discriminator", () => {- const identityKeys = ["alice", "bob", "carol"] as const- let serverId: string- let channelId: string- let bob: { id: string; discriminator: string }- let carol: { id: string; discriminator: string }-- test.beforeAll(async () => {+test.describe("mentions — mandatory discriminator", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId, userName } = actors+ const { seedServer, seedChannel, seedJoinServer, renameUser, memberInfo } = actors.seed+ const cleanupState: { serverId?: string } = {}+ actors.onCleanup(async () => {+ const restorations = await Promise.allSettled(identityKeys.map(async (key) => {+ await renameUser(key, userName(key))+ return key+ }))+ const serverId = cleanupState.serverId!+ const verifiedMembers = await Promise.allSettled(identityKeys.map(async (key) => {+ const member = await memberInfo("alice", serverId, userId(key))+ return { key, name: member.name }+ }))+ expect(restorations).toEqual(identityKeys.map((key) => ({+ status: "fulfilled",+ value: key,+ })))+ expect(verifiedMembers).toEqual(identityKeys.map((key) => ({+ status: "fulfilled",+ value: { key, name: userName(key) },+ })))+ })await renameUser("bob", "John Doe")await renameUser("carol", "John Doe")- serverId = await seedServer("alice", `Mentions ${Date.now()}`)- channelId = await seedChannel("alice", serverId, "mentions")+ const serverId: string = await seedServer("alice", `Mentions ${Date.now()}`)+ cleanupState.serverId = serverId+ const channelId: string = await seedChannel("alice", serverId, "mentions")await seedJoinServer("alice", "bob", serverId)await seedJoinServer("alice", "carol", serverId)- bob = await memberInfo("alice", serverId, userId("bob"))- carol = await memberInfo("alice", serverId, userId("carol"))+ const bob: {+ id: string+ discriminator: string+ } = await memberInfo("alice", serverId, userId("bob"))+ const carol: {+ id: string+ discriminator: string+ } = await memberInfo("alice", serverId, userId("carol"))// Distinct discriminators are what the disambiguation hinges on — if the// two happened to collide the journey couldn't prove per-user resolution.expect(bob.discriminator).not.toBe(carol.discriminator)- })+ return { serverId, channelId, bob, carol }+ }- test.afterAll(async () => {- const restorations = await Promise.allSettled(identityKeys.map(async (key) => {- await renameUser(key, userName(key))- return key- }))- const verifiedMembers = await Promise.allSettled(identityKeys.map(async (key) => {- const member = await memberInfo("alice", serverId, userId(key))- return { key, name: member.name }- }))-- expect(restorations).toEqual(identityKeys.map((key) => ({- status: "fulfilled",- value: key,- })))- expect(verifiedMembers).toEqual(identityKeys.map((key) => ({- status: "fulfilled",- value: { key, name: userName(key) },- })))- })+ const identityKeys = ["alice", "bob", "carol"] as const// Types `@John`, waits for the popup, and picks the member whose row id is// `memberId` (the popup option testid keys off the row id — labels are@@ -89,7 +89,11 @@ test.describe.serial("mentions — mandatory discriminator", () => {await expect(editable).toHaveText("", { timeout: 10_000 })}- test("same-name mentions each resolve to the exact user on pill click (spaced name, no leaked #dddd)", async ({ asUser }) => {+ test("same-name mentions each resolve to the exact user on pill click (spaced name, no leaked #dddd)", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { serverId, channelId, bob, carol } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })@@ -151,7 +155,11 @@ test.describe.serial("mentions — mandatory discriminator", () => {await expect(card).toContainText(`#${carol.discriminator}`)})- test("a hand-typed bare @name (not picked from the popup) is inert — plain text, no pill", async ({ asUser }) => {+ test("a hand-typed bare @name (not picked from the popup) is inert — plain text, no pill", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })@@ -171,7 +179,12 @@ test.describe.serial("mentions — mandatory discriminator", () => {await expect(msg.locator("xpath=ancestor-or-self::*[1]").locator("button", { hasText: "@John" })).toHaveCount(0)})- test("@everyone renders with the distinct primary styling (its flag survives sanitize)", async ({ asUser }) => {+ test("@everyone renders with the distinct primary styling (its flag survives sanitize)", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { seedMessage } = actors.seed+ const { serverId, channelId } = await prepareCase1(actors)+const { page } = await asUser("alice")const marker = `everyoneMsg ${Date.now()}`@@ -193,7 +206,11 @@ test.describe.serial("mentions — mandatory discriminator", () => {await expect(everyonePill).toHaveClass(/text-primary/)})- test("setting a display name with # / @ / newline is rejected (400)", async ({ asUser }) => {+ test("setting a display name with # / @ / newline is rejected (400)", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ await prepareCase1(actors)+const { page } = await asUser("alice")for (const bad of ["Ann#1234", "bad@name", "line\nbreak"]) {const res = await page.request.patch("/api/community/users/me/profile", {diff --git a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.tsindex 682f1392a..64c6d9c4e 100644--- a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts+++ b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts@@ -1,16 +1,8 @@-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { gotoAfterUserWsAuth } from "./_fixtures/actions"-import {- seedServer,- seedChannel,- seedJoinServer,- seedForumThread,- seedMessage,- seedDm,- seedDmMessage,- seedRemoveFriendship,-} from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 14 — forum-post notify scope, per-post tags, post-card participant// avatars, and DM presence stability. Covers the batch that made forum posts@@ -18,20 +10,22 @@ import {// post card, showed participant AvatarGroups, and fixed the DM presence flicker// on refresh.-test.describe.serial("forum post tags + participant avatars", () => {- let serverId: string- let forumId: string- let threadId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Forum ${Date.now()}`)- forumId = await seedChannel("alice", serverId, "ideas", "forum")+test.describe("forum post tags + participant avatars", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedServer, seedChannel, seedJoinServer, seedForumThread } = actors.seed+ const serverId: string = await seedServer("alice", `Forum ${Date.now()}`)+ const forumId: string = await seedChannel("alice", serverId, "ideas", "forum")// Bob joins the server so he's a candidate participant / viewer.await seedJoinServer("alice", "bob", serverId)- threadId = await seedForumThread("alice", forumId, `Bug ${Date.now()}`, "first post body")- })+ const threadId: string = await seedForumThread("alice", forumId, `Bug ${Date.now()}`, "first post body")+ return { serverId, forumId, threadId }+ }++ test("creator edits a post's tags from the card; the filter bar derives the union", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, forumId, threadId } = await prepareCase1(actors)- test("creator edits a post's tags from the card; the filter bar derives the union", async ({ asUser }) => {const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })await page.goto(`/c/channels/${serverId}/${forumId}`)@@ -72,7 +66,11 @@ test.describe.serial("forum post tags + participant avatars", () => {await expect(page.getByTestId(tid.forumTagChip("alpha"))).toBeVisible()})- test("a non-creator non-manager sees no tag-edit icon on the post", async ({ asUser }) => {+ test("a non-creator non-manager sees no tag-edit icon on the post", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, forumId, threadId } = await prepareCase1(actors)+const { page } = await asUser("bob")await page.goto(`/c/channels/${serverId}/${forumId}`)await page.waitForURL(new RegExp(forumId), { timeout: 20_000, waitUntil: "commit" })@@ -84,7 +82,12 @@ test.describe.serial("forum post tags + participant avatars", () => {await expect(page.getByTestId(tid.forumThreadTagBtn(threadId))).toHaveCount(0)})- test("post card shows a participant AvatarGroup once a second person joins", async ({ asUser }) => {+ test("post card shows a participant AvatarGroup once a second person joins", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedMessage } = actors.seed+ const { serverId, forumId, threadId } = await prepareCase1(actors)+// Bob sends a message into the post → enrolled as a participant (source// spoke). Seeded via API (a forum post's own channel accepts messages at// the channel messages route); the enrollment path is the product code@@ -104,23 +107,27 @@ test.describe.serial("forum post tags + participant avatars", () => {// stay online after the other side refreshes — the friends-presence re-seed// used to destructively replace the online set and evict them (online→offline// flicker). Alice and Bob share a server (co-members) but are not friends.-test.describe.serial("DM presence stability on refresh", () => {- let serverId: string- let dmId: string-- test.beforeAll(async () => {+test.describe("DM presence stability on refresh", () => {+ async function prepareCase2(actors: CaseActors) {+ const { userId } = actors+ const { seedServer, seedJoinServer, seedDm, seedDmMessage, seedRemoveFriendship } = actors.seed// Server + join makes Alice and Bob co-members. Create the DM and its// history while accepted, then remove the friendship: co-members but NOT// friends is the exact shape that reproduced the flicker.- serverId = await seedServer("alice", `Presence ${Date.now()}`)+ const serverId: string = await seedServer("alice", `Presence ${Date.now()}`)await seedJoinServer("alice", "bob", serverId)- dmId = await seedDm("alice", userId("bob"))+ const dmId: string = await seedDm("alice", userId("bob"))// A message so the DM row is populated in Bob's sidebar.await seedDmMessage("alice", dmId, "hi")await seedRemoveFriendship("alice", userId("bob"))- })+ return { serverId, dmId }+ }++ test("peer stays online after the viewer refreshes the DM view", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { serverId, dmId } = await prepareCase2(actors)- test("peer stays online after the viewer refreshes the DM view", async ({ asUser }) => {// Alice stays connected (her page holds a live WS connection → she's online).const alice = await asUser("alice")await gotoAfterUserWsAuth(alice.page, "/c/me")diff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.tsindex 2188fc462..a7bfe7b33 100644--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts@@ -1,19 +1,9 @@import type { Locator, Page } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { composerEditable, openChannel } from "./_fixtures/actions"-import {- seedServer,- seedChannel,- seedCategory,- seedChannelMember,- seedJoinServer,- seedMessage,- seedThread,- seedForumThread,- seedDm,- memberInfo,-} from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"// Journey 15 — @-mention CANDIDATE SCOPE (distinct from journey 13, which pins// mention serialization/disambiguation). Scope is a 2-D cross:@@ -30,67 +20,72 @@ import {// Fixture: alice (owner) + bob + carol all join the server. The public channel// sees everyone; the private channel's audience is alice+bob ONLY — carol is// the negative probe: present in public, absent in private.-test.describe.serial("mentions — candidate scope", () => {- let serverId: string- let publicChannelId: string- let privateChannelId: string- let privateForumId: string- let privatePostId: string- let threadId: string- let alice: { id: string; name: string; discriminator: string }- let bob: { id: string; name: string; discriminator: string }- let carol: { id: string; name: string; discriminator: string }-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Scope ${Date.now()}`)+test.describe("mentions — candidate scope", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId } = actors+ const { seedServer, seedChannel, seedCategory, seedChannelMember, seedJoinServer, seedMessage, seedThread, seedForumThread, memberInfo } = actors.seed+ async function openMentionPopup(page: Page, root: Page | Locator = page) {+ const editable = composerEditable(page, root)+ await editable.click()+ await editable.pressSequentially("@")+ return {+ everyone: page.getByTestId(tid.mentionOption("everyone")),+ here: page.getByTestId(tid.mentionOption("here")),+ bob: page.getByTestId(tid.mentionOption(bob.id)),+ carol: page.getByTestId(tid.mentionOption(carol.id)),+ channelToken: page.getByTestId(tid.mentionOption("channel")),+ }+ }+ const serverId: string = await seedServer("alice", `Scope ${Date.now()}`)await seedJoinServer("alice", "bob", serverId)await seedJoinServer("alice", "carol", serverId)- alice = await memberInfo("alice", serverId, userId("alice"))- bob = await memberInfo("alice", serverId, userId("bob"))- carol = await memberInfo("alice", serverId, userId("carol"))-+ const alice: {+ id: string+ name: string+ discriminator: string+ } = await memberInfo("alice", serverId, userId("alice"))+ const bob: {+ id: string+ name: string+ discriminator: string+ } = await memberInfo("alice", serverId, userId("bob"))+ const carol: {+ id: string+ name: string+ discriminator: string+ } = await memberInfo("alice", serverId, userId("carol"))// Public/uncategorized text channel — audience is the whole server.- publicChannelId = await seedChannel("alice", serverId, "public-scope")-+ const publicChannelId: string = await seedChannel("alice", serverId, "public-scope")// Private category holding a private text channel (audience alice+bob) and// a private forum with one post (audience alice+bob). Carol is excluded from// BOTH — she stays a server member but is not in the private units.const privateCatId = await seedCategory("alice", serverId, `priv-${Date.now()}`, { private: true })- privateChannelId = await seedChannel("alice", serverId, "private-scope", "text", privateCatId)+ const privateChannelId: string = await seedChannel("alice", serverId, "private-scope", "text", privateCatId)await seedChannelMember("alice", privateChannelId, userId("bob"))-- privateForumId = await seedChannel("alice", serverId, "private-forum", "forum", privateCatId)+ const privateForumId: string = await seedChannel("alice", serverId, "private-forum", "forum", privateCatId)// A forum owns its roster; a post inherits it (the notify dimension). Add bob// to the FORUM, not the post — posts reject access-member adds and derive// their mention pool from the parent forum's audience.await seedChannelMember("alice", privateForumId, userId("bob"))- privatePostId = await seedForumThread("alice", privateForumId, `Post ${Date.now()}`, "post body")-+ const privatePostId: string = await seedForumThread("alice", privateForumId, `Post ${Date.now()}`, "post body")// A thread rooted on a message in the private channel — its scope is the// PARENT channel's audience (alice+bob), NOT its own participant set.const parentMsgId = await seedMessage("alice", privateChannelId, `thread parent ${Date.now()}`)- threadId = await seedThread("alice", parentMsgId, `Thread ${Date.now()}`)- })+ const threadId: string = await seedThread("alice", parentMsgId, `Thread ${Date.now()}`)+ return { serverId, publicChannelId, privateChannelId, privateForumId, privatePostId, threadId, alice, bob, carol, openMentionPopup }+ }// Open the @-popup in the current composer and return the option locators. The// popup keys each row (members AND @everyone) off its item id — a member// row id is the server-member row id (identical in server + channel lists), a// virtual row id is the literal "everyone". `here` is exposed here only to// assert that the removed @here row stays absent.- async function openMentionPopup(page: Page, root: Page | Locator = page) {- const editable = composerEditable(page, root)- await editable.click()- await editable.pressSequentially("@")- return {- everyone: page.getByTestId(tid.mentionOption("everyone")),- here: page.getByTestId(tid.mentionOption("here")),- bob: page.getByTestId(tid.mentionOption(bob.id)),- carol: page.getByTestId(tid.mentionOption(carol.id)),- channelToken: page.getByTestId(tid.mentionOption("channel")),- }- }- test("public top-level channel → whole server roster (bob AND carol), backed by servers/:id/members", async ({ asUser }) => {+ test("public top-level channel → whole server roster (bob AND carol), backed by servers/:id/members", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, publicChannelId, alice, bob, carol, openMentionPopup } = await prepareCase1(actors)+const { page } = await asUser("alice")// The channel-members endpoint must NOT be hit for a public channel — the// popup roster comes from the server list. Assert its absence by watching@@ -121,7 +116,11 @@ test.describe.serial("mentions — candidate scope", () => {expect(channelMembersCalls).toHaveLength(0)})- test("private channel → audience only (bob present, carol absent), backed by channels/:id/members", async ({ asUser }) => {+ test("private channel → audience only (bob present, carol absent), backed by channels/:id/members", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, privateChannelId, bob, carol, openMentionPopup } = await prepareCase1(actors)+const { page } = await asUser("alice")const channelMembersReq = page.waitForRequest((r) => new RegExp(`/api/community/channels/${privateChannelId}/members`).test(r.url()),@@ -143,7 +142,11 @@ test.describe.serial("mentions — candidate scope", () => {await expect(opt.carol).toHaveCount(0)})- test("thread in private channel → PARENT channel audience (bob mentionable though not a participant)", async ({ asUser }) => {+ test("thread in private channel → PARENT channel audience (bob mentionable though not a participant)", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, threadId, bob, carol, openMentionPopup } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${threadId}`)await page.waitForURL(new RegExp(threadId), { timeout: 20_000, waitUntil: "commit" })@@ -157,7 +160,11 @@ test.describe.serial("mentions — candidate scope", () => {await expect(opt.carol).toHaveCount(0)})- test("private local search reports a failed access read and recovers on warm channel re-entry", async ({ asUser }) => {+ test("private local search reports a failed access read and recovers on warm channel re-entry", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, publicChannelId, privateChannelId, alice, bob, carol, openMentionPopup } = await prepareCase1(actors)+const { page } = await asUser("alice")let failAccess = truelet accessReads = 0@@ -196,7 +203,11 @@ test.describe.serial("mentions — candidate scope", () => {await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)})- test("forum post reply → post audience (bob present, carol absent)", async ({ asUser }) => {+ test("forum post reply → post audience (bob present, carol absent)", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, privatePostId, bob, carol, openMentionPopup } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${privatePostId}`)await page.waitForURL(new RegExp(privatePostId), { timeout: 20_000, waitUntil: "commit" })@@ -207,7 +218,11 @@ test.describe.serial("mentions — candidate scope", () => {await expect(opt.carol).toHaveCount(0)})- test("new forum post composer supports @-mentions like the chat composer", async ({ asUser }) => {+ test("new forum post composer supports @-mentions like the chat composer", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, privateForumId, bob } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${privateForumId}`)await page.waitForURL(new RegExp(privateForumId), { timeout: 20_000, waitUntil: "commit" })@@ -230,7 +245,12 @@ test.describe.serial("mentions — candidate scope", () => {await expect(page.getByTestId(tid.mentionOption(bob.id))).toBeVisible({ timeout: 15_000 })})- test("1:1 DM keeps @abc as plain text, never starts mention suggestions, and sends with Enter", async ({ asUser }) => {+ test("1:1 DM keeps @abc as plain text, never starts mention suggestions, and sends with Enter", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { seedDm } = actors.seed+ const { bob } = await prepareCase1(actors)+const dmId = await seedDm("alice", userId("bob"))const { page } = await asUser("alice")const memberSearchRequests: string[] = []diff --git a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts b/src/web/src/test/e2e-ui/16-jump-to-present.spec.tsindex 49b266514..a5d042f12 100644--- a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts+++ b/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts@@ -1,10 +1,15 @@-import { test, expect, sessionCookie } from "./_fixtures/community-fixture"-import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"-test("anchored channel jumps to the newest tail with one request", async ({ asUser }) => {+test("anchored channel jumps to the newest tail with one request", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, sessionCookie } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const serverId = await seedServer("alice", `Jump Present ${Date.now()}`)await seedJoinServer("alice", "bob", serverId)await seedJoinServer("alice", "carol", serverId)diff --git a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.tsindex 42ca3495d..62f342a34 100644--- a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts@@ -1,16 +1,24 @@import type { Page } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { sendMessage } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"-import {- seedCategory,- seedChannel,- seedForumThread,- seedJoinServer,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { userId } = actors+ async function participantUserIds(page: Page, channelId: string): Promise<string[]> {+ const response = await page.request.get(`/api/community/channels/${channelId}/members`)+ expect(response.status()).toBe(200)+ const payload = await response.json() as {+ members: Array<{+ userId: string+ }>+ }+ return payload.members.map((member) => member.userId)+ }+ return { participantUserIds }+}function isSidebarRequest(url: string, serverId: string): boolean {const parsed = new URL(url)@@ -64,13 +72,6 @@ function childPanel(page: Page) {return page.getByTestId(tid.threadSplitPanel)}-async function participantUserIds(page: Page, channelId: string): Promise<string[]> {- const response = await page.request.get(`/api/community/channels/${channelId}/members`)- expect(response.status()).toBe(200)- const payload = await response.json() as { members: Array<{ userId: string }> }- return payload.members.map((member) => member.userId)-}-async function strictSidebar(page: Page, serverId: string, retainId?: string) {const params = new URLSearchParams({type: "thread",@@ -123,35 +124,35 @@ async function setForumPostArchived(await sidebar}-test.describe.serial("forum sidebar Stage B request shape", () => {- let serverId: string- let forumId: string- let threadId: string- let textAId: string- let textBId: string- let forumTitle: string- let ordinaryThreadId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Sidebar ${Date.now()}`)+test.describe("forum sidebar Stage B request shape", () => {+ async function prepareCase1(actors: CaseActors) {+ const { participantUserIds } = await prepareCase(actors)+ const { seedCategory, seedChannel, seedForumThread, seedJoinServer, seedMessage, seedServer, seedThread } = actors.seed+ const serverId: string = await seedServer("alice", `Sidebar ${Date.now()}`)const categoryId = await seedCategory("alice", serverId, "Grouped")- forumId = await seedChannel("alice", serverId, "forum", "forum", categoryId)- textAId = await seedChannel("alice", serverId, "text-a", undefined, categoryId)- textBId = await seedChannel("alice", serverId, "text-b", undefined, categoryId)+ const forumId: string = await seedChannel("alice", serverId, "forum", "forum", categoryId)+ const textAId: string = await seedChannel("alice", serverId, "text-a", undefined, categoryId)+ const textBId: string = await seedChannel("alice", serverId, "text-b", undefined, categoryId)await seedJoinServer("alice", "bob", serverId)await seedJoinServer("alice", "carol", serverId)- forumTitle = `Retained ${Date.now()}`- threadId = await seedForumThread("alice", forumId, forumTitle, "post body")+ const forumTitle: string = `Retained ${Date.now()}`+ const threadId: string = await seedForumThread("alice", forumId, forumTitle, "post body")const parentMessageId = await seedMessage("alice", textAId, "ordinary thread opener")- ordinaryThreadId = await seedThread("alice", parentMessageId, "ordinary thread")- })+ const ordinaryThreadId: string = await seedThread("alice", parentMessageId, "ordinary thread")+ return { participantUserIds, serverId, forumId, threadId, textAId, textBId, forumTitle, ordinaryThreadId }+ }++ test("a cold direct child and hard refresh keep exact route metadata bounded", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, threadId, forumTitle } = await prepareCase1(actors)- test("a cold direct child and hard refresh keep exact route metadata bounded", async ({ asUser }) => {const { page } = await asUser("alice")const requests: string[] = []const successfulResponses: string[] = []let releaseFirstAnchor!: () => voidconst firstAnchorGate = new Promise<void>((resolve) => { releaseFirstAnchor = resolve })+ caseResources.own(releaseFirstAnchor, async (captured) => { captured() })let anchorRouteRequests = 0await page.route("**/api/community/channels/**/messages**", async (route) => {const url = route.request().url()@@ -258,7 +259,11 @@ test.describe.serial("forum sidebar Stage B request shape", () => {.toBe(refreshSuccessfulMessageResponses.length)})- test("a flat child route preserves one settled message load", async ({ asUser }) => {+ test("a flat child route preserves one settled message load", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, threadId, forumTitle } = await prepareCase1(actors)+const { page } = await asUser("alice")const successfulResponses: string[] = []page.on("response", (response) => {@@ -285,7 +290,11 @@ test.describe.serial("forum sidebar Stage B request shape", () => {.toBeLessThanOrEqual(1)})- test("a non-participant keeps a grouped forum route after retained null arrives", async ({ asUser }) => {+ test("a non-participant keeps a grouped forum route after retained null arrives", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { participantUserIds, serverId, threadId } = await prepareCase1(actors)+const { page } = await asUser("bob")await installRouteStabilityProbe(page)const successfulResponses: string[] = []@@ -330,7 +339,11 @@ test.describe.serial("forum sidebar Stage B request shape", () => {await expect.poll(async () => participantUserIds(page, threadId)).toContain(userId("bob"))})- test("a non-participant warm forum-card click settles one negative retained request", async ({ asUser }) => {+ test("a non-participant warm forum-card click settles one negative retained request", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { participantUserIds, serverId, forumId, threadId } = await prepareCase1(actors)+const { page } = await asUser("carol")await installRouteStabilityProbe(page)const successfulResponses: string[] = []@@ -371,7 +384,11 @@ test.describe.serial("forum sidebar Stage B request shape", () => {expect(await participantUserIds(page, threadId)).not.toContain(userId("carol"))})- test("a grouped ordinary thread never asks the forum sidebar to retain it", async ({ asUser }) => {+ test("a grouped ordinary thread never asks the forum sidebar to retain it", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { participantUserIds, serverId, ordinaryThreadId } = await prepareCase1(actors)+const { page } = await asUser("bob")await installRouteStabilityProbe(page)const successfulResponses: string[] = []@@ -401,7 +418,11 @@ test.describe.serial("forum sidebar Stage B request shape", () => {expect(await participantUserIds(page, ordinaryThreadId)).not.toContain(userId("bob"))})- test("sidebar top-level and child navigation reuse the warm flat base", async ({ asUser }, testInfo) => {+ test("sidebar top-level and child navigation reuse the warm flat base", async ({ caseActors, caseResources }, testInfo) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, threadId, textAId, textBId, forumTitle } = await prepareCase1(actors)+const { page } = await asUser("alice")const requests: string[] = []const successfulResponses: string[] = []@@ -441,7 +462,9 @@ test.describe.serial("forum sidebar Stage B request shape", () => {let releaseRetained!: () => voidlet retainedStarted!: () => voidconst retainedGate = new Promise<void>((resolve) => { releaseRetained = resolve })+ caseResources.own(releaseRetained, async (captured) => { captured() })const retainedRequestStarted = new Promise<void>((resolve) => { retainedStarted = resolve })+ caseResources.own(retainedStarted, async (captured) => { captured() })await page.route("**/api/community/servers/*/channels?*", async (route) => {const url = route.request().url()if (@@ -536,9 +559,20 @@ test.describe.serial("forum sidebar Stage B request shape", () => {})})-test.describe.serial("forum sidebar archived opener projection", () => {- test("local, remote, retained, and hard-refresh paths converge on a filled top five", async ({ asUser }) => {+test.describe("forum sidebar archived opener projection", () => {+ async function prepareCase2(actors: CaseActors) {+ const { participantUserIds } = await prepareCase(actors)+ return { participantUserIds }+ }++ test("local, remote, retained, and hard-refresh paths converge on a filled top five", async ({ caseActors }) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedCategory, seedChannel, seedForumThread, seedServer } = actors.seed+ await prepareCase2(actors)+const serverId = await seedServer("alice", `Archived sidebar ${Date.now()}`)const categoryId = await seedCategory("alice", serverId, "Forum group")const forumId = await seedChannel("alice", serverId, "archive-ranking", "forum", categoryId)diff --git a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.tsindex 99649450f..efb53637e 100644--- a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts+++ b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts@@ -1,8 +1,8 @@-import { test, expect, sessionCookie } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"import { tid } from "./_fixtures/testids"-import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { WEB_URL } from "./_setup/paths"type BodySample = {@@ -10,8 +10,13 @@ type BodySample = {bodies: Array<{ id: string; top: number; bottom: number; height: number }>}-test("NEW divider does not fight upward scrolling while a peer message arrives", async ({ asUser }) => {+test("NEW divider does not fight upward scrolling while a peer message arrives", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, sessionCookie } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const serverId = await seedServer("alice", `NEW scroll ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "new-scroll")await seedJoinServer("alice", "bob", serverId)@@ -135,8 +140,13 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",expect(upwardProgress).toBeGreaterThan(600)})-test("New reading near the tail survives peer and remote-self messages until the current composer submits", async ({ asUser }) => {+test("New reading near the tail survives peer and remote-self messages until the current composer submits", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, sessionCookie } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const serverId = await seedServer("alice", `NEW near tail ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "new-near-tail")await seedJoinServer("alice", "bob", serverId)diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.tsindex 9d4573c80..51886083a 100644--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts@@ -1,5 +1,5 @@import type { Locator, Page, TestInfo } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { composerEditable, createServer } from "./_fixtures/actions"import { solidPngFixture } from "../fixtures/media"@@ -190,8 +190,12 @@ async function uploadImage(args: {}}-test("image previews keep one frame through loading, decode, failure, retry, and mobile", async ({ asUser }, testInfo) => {+test("image previews keep one frame through loading, decode, failure, retry, and mobile", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })await page.goto("/c")@@ -211,6 +215,7 @@ test("image previews keep one frame through loading, decode, failure, retry, andlet releaseColdThumbnail!: () => voidconst coldThumbnailGate = new Promise<void>((resolve) => { releaseColdThumbnail = resolve })+ caseResources.own(releaseColdThumbnail, async (captured) => { captured() })let holdColdThumbnail = truelet coldThumbnailRequests = 0let coldThumbnailPath: string | null = null@@ -258,6 +263,7 @@ test("image previews keep one frame through loading, decode, failure, retry, andlet releaseLandscape!: () => voidconst landscapeGate = new Promise<void>((resolve) => { releaseLandscape = resolve })+ caseResources.own(releaseLandscape, async (captured) => { captured() })await page.route(`**${landscape.originalPath}`, async (route) => {if (route.request().method() === "GET" && new URL(route.request().url()).pathname === landscape.originalPath) {await landscapeGate@@ -369,6 +375,7 @@ test("image previews keep one frame through loading, decode, failure, retry, and})let releasePortraitFailure!: () => voidconst portraitFailureGate = new Promise<void>((resolve) => { releasePortraitFailure = resolve })+ caseResources.own(releasePortraitFailure, async (captured) => { captured() })await page.route(`**${portrait.originalPath}`, async (route) => {if (route.request().method() !== "GET" || new URL(route.request().url()).pathname !== portrait.originalPath) {await route.continue()@@ -450,6 +457,7 @@ test("image previews keep one frame through loading, decode, failure, retry, andlet releaseMobileLandscape!: () => voidconst mobileLandscapeGate = new Promise<void>((resolve) => { releaseMobileLandscape = resolve })+ caseResources.own(releaseMobileLandscape, async (captured) => { captured() })let mobileLandscapeRequests = 0await mobilePage.route(`**${landscape.originalPath}`, async (route) => {if (route.request().method() === "GET" && new URL(route.request().url()).pathname === landscape.originalPath) {@@ -475,6 +483,7 @@ test("image previews keep one frame through loading, decode, failure, retry, andlet releaseMobilePortrait!: () => voidconst mobilePortraitGate = new Promise<void>((resolve) => { releaseMobilePortrait = resolve })+ caseResources.own(releaseMobilePortrait, async (captured) => { captured() })let mobilePortraitRequests = 0await mobilePage.route(`**${portrait.originalPath}`, async (route) => {if (route.request().method() === "GET" && new URL(route.request().url()).pathname === portrait.originalPath) {diff --git a/src/web/src/test/e2e-ui/21-mobile-message-layout.spec.ts b/src/web/src/test/e2e-ui/21-mobile-message-layout.spec.tsindex 627a9982d..b72ed2a13 100644--- a/src/web/src/test/e2e-ui/21-mobile-message-layout.spec.ts+++ b/src/web/src/test/e2e-ui/21-mobile-message-layout.spec.ts@@ -1,6 +1,6 @@import type { Page } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"-import { seedChannel, seedMessage, seedServer } from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"type RowRect = { top: number; bottom: number; height: number }@@ -54,8 +54,13 @@ async function waitForStableScrollerFrames(page: Page, messageId: string): Promi), messageId)}-test("long Markdown rows stay measured and separated at iPhone width", async ({ asUser }) => {+test("long Markdown rows stay measured and separated at iPhone width", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedMessage, seedServer } = actors.seed+const serverId = await seedServer("alice", `Mobile rows ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "mobile-rows")const otherChannelId = await seedChannel("alice", serverId, "other-mobile-rows")diff --git a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.tsindex e7a91c6df..c0524f096 100644--- a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts+++ b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts@@ -1,15 +1,6 @@-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, expectMessageVisible, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"-import {- memberInfo,- seedChannel,- seedDm,- seedDmMessage,- seedForumThread,- seedJoinServer,- seedMessage,- seedServer,-} from "./_fixtures/seed"+import {communityFrameEvents,isCommunityBatchFrame,@@ -25,8 +16,12 @@ function messageFrame(frame: CapturedCommunityFrame, channelId: string, content:&& event.message?.content?.includes(content))}-test.describe.serial("committed message delivery QA", () => {- test("Q4: a readable nonparticipant gets child content and parent projection without notifications", async ({ asUser }) => {+test.describe("committed message delivery QA", () => {+ test("Q4: a readable nonparticipant gets child content and parent projection without notifications", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { seedChannel, seedForumThread, seedJoinServer, seedServer } = actors.seed+const serverId = await seedServer("alice", `Parent projection ${Date.now()}`)const forumId = await seedChannel("alice", serverId, "parent-projection", "forum")await seedJoinServer("alice", "bob", serverId)@@ -65,7 +60,11 @@ test.describe.serial("committed message delivery QA", () => {await expect(carol.page.getByText(body, { exact: false })).toHaveCount(0)})- test("Q7 channel: a held mention bundle is repaired before late release", async ({ asUser }) => {+ test("Q7 channel: a held mention bundle is repaired before late release", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { memberInfo, seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const serverId = await seedServer("alice", `Gap channel ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "gap-channel")await seedJoinServer("alice", "bob", serverId)@@ -139,7 +138,11 @@ test.describe.serial("committed message delivery QA", () => {}, { timeout: 20_000 }).toBe(true)})- test("Q7 DM: a dropped message frame is repaired when a later seq arrives", async ({ asUser }) => {+ test("Q7 DM: a dropped message frame is repaired when a later seq arrives", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedDm, seedDmMessage } = actors.seed+const dmId = await seedDm("alice", userId("bob"))await seedDmMessage("alice", dmId, "dm gap baseline")const bob = await asUser("bob")@@ -180,7 +183,11 @@ test.describe.serial("committed message delivery QA", () => {expect(gapRequests.length).toBeGreaterThan(0)})- test("Q8: capable duplicate suppression ends safely at full reload", async ({ asUser }) => {+ test("Q8: capable duplicate suppression ends safely at full reload", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { memberInfo, seedChannel, seedJoinServer, seedServer } = actors.seed+const serverId = await seedServer("alice", `Atomic batch ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "atomic-batch")await seedJoinServer("alice", "bob", serverId)@@ -251,7 +258,11 @@ test.describe.serial("committed message delivery QA", () => {await expect(bob.page.getByTestId(tid.message(messageId!))).toHaveCount(1)})- test("Q9: every receiver gets the same batch-only channel and DM delivery", async ({ asUser }) => {+ test("Q9: every receiver gets the same batch-only channel and DM delivery", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { memberInfo, seedChannel, seedDm, seedJoinServer, seedServer } = actors.seed+const serverId = await seedServer("alice", `Batch receivers ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "batch-receivers")await seedJoinServer("alice", "bob", serverId)diff --git a/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts b/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.tsindex bc678a2ae..08834d6ba 100644--- a/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts+++ b/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts@@ -1,6 +1,6 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"-import { seedChannel, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"async function observeNextContextMenu(page: import("@playwright/test").Page) {@@ -30,7 +30,11 @@ async function contextMenuProbe(page: import("@playwright/test").Page) {).__contextMenuProbe)}-test("selected message text keeps the native context menu", async ({ asUser }) => {+test("selected message text keeps the native context menu", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedMessage, seedServer } = actors.seed+const serverId = await seedServer("alice", `Selection Menu ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "selection-menu")const body = `copy only this phrase ${Date.now()}`diff --git a/src/web/src/test/e2e-ui/24-composer-overflow.spec.ts b/src/web/src/test/e2e-ui/24-composer-overflow.spec.tsindex 0e77e509e..1be7ba09e 100644--- a/src/web/src/test/e2e-ui/24-composer-overflow.spec.ts+++ b/src/web/src/test/e2e-ui/24-composer-overflow.spec.ts@@ -1,17 +1,9 @@import { type Locator, type Page } from "@playwright/test"-import { test, expect, userId, userName } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, ignoreNextDevToolsPointerCapture } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"-import {- memberInfo,- renameUser,- seedChannel,- seedDm,- seedJoinServer,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"++import type { CaseActors } from "./_fixtures/case-fixture"const VIEWPORT_WIDTHS = [375, 639, 640] as constconst LONG_ENGLISH = "overflow".repeat(12) + "edge"@@ -192,49 +184,38 @@ function expectContainedSuggestion(}}-test.describe.serial("community composer text containment", () => {- let serverId: string- let longChannelId: string- let threadId: string- let forumChannelId: string- let dmId: string- let longMemberId: string- let longMemberDiscriminator: string- let secondaryServerName: string- let secondaryChannelSearchToken: string- let secondaryChannelName: string- let secondaryChannelId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `overflow-${Date.now()}`)- longChannelId = await seedChannel("alice", serverId, LONG_ENGLISH)- forumChannelId = await seedChannel("alice", serverId, `forum-${Date.now()}`, "forum")+test.describe("community composer text containment", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId, userName } = actors+ const { memberInfo, renameUser, seedChannel, seedDm, seedJoinServer, seedMessage, seedServer, seedThread } = actors.seed+ actors.onCleanup(async () => {+ await renameUser("bob", userName("bob"))+ })+ const serverId: string = await seedServer("alice", `overflow-${Date.now()}`)+ const longChannelId: string = await seedChannel("alice", serverId, LONG_ENGLISH)+ const forumChannelId: string = await seedChannel("alice", serverId, `forum-${Date.now()}`, "forum")const parentMessageId = await seedMessage("alice", longChannelId, "thread opener")- threadId = await seedThread("alice", parentMessageId, LONG_CJK)+ const threadId: string = await seedThread("alice", parentMessageId, LONG_CJK)await renameUser("bob", LONG_CJK)await seedJoinServer("alice", "bob", serverId)const longMember = await memberInfo("alice", serverId, userId("bob"))- longMemberId = longMember.id- longMemberDiscriminator = longMember.discriminator-- secondaryServerName = `secondary-${"s".repeat(90)}`- secondaryChannelSearchToken = `overflow-ref-${Date.now()}`+ const longMemberId: string = longMember.id+ const longMemberDiscriminator: string = longMember.discriminator+ const secondaryServerName: string = `secondary-${"s".repeat(90)}`+ const secondaryChannelSearchToken: string = `overflow-ref-${Date.now()}`await seedChannel("alice", serverId, `${secondaryChannelSearchToken}-anchor`)- secondaryChannelName = `${secondaryChannelSearchToken}-${"c".repeat(72)}`+ const secondaryChannelName: string = `${secondaryChannelSearchToken}-${"c".repeat(72)}`const secondaryServerId = await seedServer("alice", secondaryServerName)- secondaryChannelId = await seedChannel(- "alice",- secondaryServerId,- secondaryChannelName,- )- dmId = await seedDm("alice", userId("carol"))- })+ const secondaryChannelId: string = await seedChannel("alice", secondaryServerId, secondaryChannelName)+ const dmId: string = await seedDm("alice", userId("carol"))+ return { serverId, longChannelId, threadId, forumChannelId, dmId, longMemberId, longMemberDiscriminator, secondaryServerName, secondaryChannelSearchToken, secondaryChannelName, secondaryChannelId }+ }- test.afterAll(async () => {- await renameUser("bob", userName("bob"))- })+ test("default channel placeholder stays in the editable width and leaves controls clickable", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, longChannelId } = await prepareCase1(actors)- test("default channel placeholder stays in the editable width and leaves controls clickable", async ({ asUser }) => {const { page } = await asUser("alice")let messagePosts = 0page.on("request", (request) => {@@ -298,7 +279,11 @@ test.describe.serial("community composer text containment", () => {await page.keyboard.press("Escape")})- test("default CJK thread placeholder stays in the editable width", async ({ asUser }) => {+ test("default CJK thread placeholder stays in the editable width", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, threadId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${threadId}`)await page.waitForURL(new RegExp(threadId), { timeout: 20_000, waitUntil: "commit" })@@ -309,7 +294,11 @@ test.describe.serial("community composer text containment", () => {)})- test("forum custom placeholder uses the same bounded chat-only rule", async ({ asUser }) => {+ test("forum custom placeholder uses the same bounded chat-only rule", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, forumChannelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${forumChannelId}`)await page.waitForURL(new RegExp(forumChannelId), { timeout: 20_000, waitUntil: "commit" })@@ -326,7 +315,11 @@ test.describe.serial("community composer text containment", () => {}})- test("non-chat TipTap control retains the global placeholder behavior", async ({ asUser }) => {+ test("non-chat TipTap control retains the global placeholder behavior", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, longChannelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${longChannelId}`)await page.waitForURL(new RegExp(longChannelId), { timeout: 20_000, waitUntil: "commit" })@@ -355,7 +348,11 @@ test.describe.serial("community composer text containment", () => {})})- test("long mention keeps avatar and discriminator visible without horizontal crop", async ({ asUser }) => {+ test("long mention keeps avatar and discriminator visible without horizontal crop", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, longChannelId, longMemberId, longMemberDiscriminator } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 375, height: 800 })await page.goto(`/c/channels/${serverId}/${longChannelId}`)@@ -377,7 +374,11 @@ test.describe.serial("community composer text containment", () => {}})- test("long cross-server channel row truncates within the popup without hard crop", async ({ asUser }) => {+ test("long cross-server channel row truncates within the popup without hard crop", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { dmId, secondaryServerName, secondaryChannelSearchToken, secondaryChannelName, secondaryChannelId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 375, height: 800 })await page.goto(`/c/me/${dmId}`)diff --git a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.tsindex e11d53dec..e12c2a46e 100644--- a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts+++ b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts@@ -1,10 +1,10 @@import type { Page, WebSocketRoute } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import {composerEditable,gotoAfterUserWsAuth,} from "./_fixtures/actions"-import { seedChannel, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import "./community-cache-first-warm-reload.journey"@@ -32,8 +32,13 @@ async function installUserWsAuthConsumedBarrier(page: Page) {}, { attribute: USER_WS_AUTH_CONSUMED_ATTRIBUTE })}-test("slow auth and an initial retry never block a cold Community page", async ({ asUser }) => {+test("slow auth and an initial retry never block a cold Community page", async ({ caseActors, caseResources }) => {test.setTimeout(90_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Reconnect cold start ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "reconnect-cold-start")const alice = await asUser("alice")@@ -43,6 +48,7 @@ test("slow auth and an initial retry never block a cold Community page", async (const tokenGate = new Promise<void>((resolve) => {releaseTokens = resolve})+ caseResources.own(releaseTokens, async (captured) => { captured() })let socketAttempts = 0await alice.page.route("**/api/ws/token", async (route) => {@@ -78,8 +84,13 @@ test("slow auth and an initial retry never block a cold Community page", async (}})-test("a real WebSocket outage keeps cached content interactive and Retry reconnects", async ({ asUser }, testInfo) => {+test("a real WebSocket outage keeps cached content interactive and Retry reconnects", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Reconnect status ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "reconnect-status")const alice = await asUser("alice")@@ -161,6 +172,7 @@ test("a real WebSocket outage keeps cached content interactive and Retry reconnelet holdReconnectTokens = truelet releaseReconnectTokens!: () => voidconst reconnectTokenGate = new Promise<void>(resolve => { releaseReconnectTokens = resolve })+ caseResources.own(releaseReconnectTokens, async (captured) => { captured() })const gateReconnectToken: Parameters<Page["route"]>[1] = async (route) => {if (holdReconnectTokens) await reconnectTokenGateawait route.continue()@@ -237,9 +249,9 @@ test("a real WebSocket outage keeps cached content interactive and Retry reconne}})-test("an active onboarding form keeps focus priority during a reconnect", async ({ browser }) => {+test("an active onboarding form keeps focus priority during a reconnect", async ({ browser, caseResources }) => {test.setTimeout(90_000)- const context = await browser.newContext({ viewport: { width: 390, height: 844 } })+ const context = await caseResources.newContext({ viewport: { width: 390, height: 844 } })const page = await context.newPage()let userWs: WebSocketRoute | null = nulllet blockUserWs = false@@ -252,6 +264,8 @@ test("an active onboarding form keeps focus priority during a reconnect", asyncws.connectToServer()})+ let caseJourneyFailure1: unknown+let caseJourneyFailure1Present = falsetry {await installUserWsAuthConsumedBarrier(page)await page.goto("/sign-in")@@ -288,8 +302,12 @@ test("an active onboarding form keeps focus priority during a reconnect", asyncblockUserWs = falseawait expect(onboarding).toBeVisible()- } finally {- blockUserWs = false- await context.close().catch(() => {})+ } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {+ try {++ blockUserWs = false+ await caseResources.closeContext(context)++ } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }}})diff --git a/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts b/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.tsindex b6cea5bd5..fbb839000 100644--- a/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts+++ b/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts@@ -1,20 +1,25 @@import type { Page, TestInfo } from "@playwright/test"-import { test, expect, userName } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"-import { renameUser, seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { userName } = actors+ const { renameUser } = actors.seed+ actors.onCleanup(async () => {+ const restorations = await Promise.allSettled([+ renameUser("bob", userName("bob")),+ renameUser("carol", userName("carol")),+ ])+ expect(restorations.map((result) => result.status)).toEqual(["fulfilled", "fulfilled"])+ })+}const VIEWPORT_WIDTHS = [320, 390, 639, 640, 1280] as constconst LONG_TYPING_NAME = `Typing ${"occupancy ".repeat(8)}edge`-test.afterAll(async () => {- const restorations = await Promise.allSettled([- renameUser("bob", userName("bob")),- renameUser("carol", userName("carol")),- ])- expect(restorations.map((result) => result.status)).toEqual(["fulfilled", "fulfilled"])-})-async function sendExactMessage(sender: Page, receiver: Page, text: string) {const editable = composerEditable(sender)await editable.click()@@ -383,8 +388,14 @@ async function settleAwayAtTop(page: Page): Promise<void> {await expect(page.getByTestId(tid.scrollToPresent)).toBeVisible()}-test("composer accessory rail reallocates every occupied slot without overflow", async ({ asUser }, testInfo) => {+test("composer accessory rail reallocates every occupied slot without overflow", async ({ caseActors }, testInfo) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { renameUser, seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+ await prepareCase(actors)+const serverId = await seedServer("alice", `Rail occupancy ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "rail-occupancy")await seedJoinServer("alice", "bob", serverId)diff --git a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.tsindex e0e46d648..41769ef4e 100644--- a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts+++ b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts@@ -1,9 +1,37 @@import type { Locator, Page, TestInfo } from "@playwright/test"-import { test, expect, sessionCookie } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"-import { seedChannel, seedForumThread, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"+import type { CaseActors } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { sessionCookie } = actors+ async function seedTags(forumId: string, threadId: string, tags: string[]): Promise<void> {+ const listResponse = await fetch(`${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`, { headers: { Cookie: sessionCookie("bob"), Origin: WEB_URL } })+ expect(listResponse.ok).toBe(true)+ const page = await listResponse.json() as {+ threads: Array<{+ id: string+ parentMessageId: string | null+ }>+ }+ const openerMessageId = page.threads.find((thread) => thread.id === threadId)?.parentMessageId+ expect(openerMessageId).toBeTruthy()+ const tagResponse = await fetch(`${WEB_URL}/api/community/messages/${openerMessageId}/tags`, {+ method: "PUT",+ headers: {+ Cookie: sessionCookie("bob"),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({ tags }),+ })+ expect(tagResponse.status).toBe(200)+ }+ return { seedTags }+}const MOBILE_WIDTHS = [320, 390] as constconst FILTER_RAIL_WIDTHS = [320, 390, 1280] as const@@ -439,31 +467,14 @@ async function expectNoOverflowFilterRail(}}-async function seedTags(forumId: string, threadId: string, tags: string[]): Promise<void> {- const listResponse = await fetch(- `${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`,- { headers: { Cookie: sessionCookie("bob"), Origin: WEB_URL } },- )- expect(listResponse.ok).toBe(true)- const page = await listResponse.json() as {- threads: Array<{ id: string; parentMessageId: string | null }>- }- const openerMessageId = page.threads.find((thread) => thread.id === threadId)?.parentMessageId- expect(openerMessageId).toBeTruthy()- const tagResponse = await fetch(`${WEB_URL}/api/community/messages/${openerMessageId}/tags`, {- method: "PUT",- headers: {- Cookie: sessionCookie("bob"),- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: JSON.stringify({ tags }),- })- expect(tagResponse.status).toBe(200)-}--test("forum post actions stay discoverable on mobile without changing permissions", async ({ asUser }, testInfo) => {+test("forum post actions stay discoverable on mobile without changing permissions", async ({ caseActors }, testInfo) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { seedChannel, seedForumThread, seedJoinServer, seedMessage, seedServer } = actors.seed+ const { seedTags } = await prepareCase(actors)+const stamp = Date.now().toString().slice(-6)const serverId = await seedServer("alice", `Mobile forum actions ${Date.now()}`)const forumId = await seedChannel("alice", serverId, "mobile-actions", "forum")diff --git a/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts b/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.tsindex c76072ae1..e62c6f9f8 100644--- a/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts+++ b/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts@@ -1,16 +1,28 @@import type { Page, WebSocket } from "@playwright/test"-import { test, expect, sessionCookie, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"-import {- seedCategory,- seedChannel,- seedChannelMember,- seedForumThread,- seedJoinServer,- seedServer,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"+import type { CaseActors } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { sessionCookie } = actors+ async function resolveOpener(forumId: string, childId: string): Promise<string> {+ const response = await fetch(`${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`, { headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })+ expect(response.status).toBe(200)+ const body = await response.json() as {+ threads: Array<{+ id: string+ parentMessageId: string | null+ }>+ }+ const openerId = body.threads.find((thread) => thread.id === childId)?.parentMessageId+ expect(openerId).toBeTruthy()+ return openerId!+ }+ return { resolveOpener }+}type ChannelDeleteFrame = {type: "community:channel.delete"@@ -35,20 +47,6 @@ function captureChannelDeletes(page: Page) {return { frames, sockets }}-async function resolveOpener(forumId: string, childId: string): Promise<string> {- const response = await fetch(- `${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`,- { headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } },- )- expect(response.status).toBe(200)- const body = await response.json() as {- threads: Array<{ id: string; parentMessageId: string | null }>- }- const openerId = body.threads.find((thread) => thread.id === childId)?.parentMessageId- expect(openerId).toBeTruthy()- return openerId!-}-async function deletePostThroughUi(page: Page, childId: string, openerId: string) {const responsePromise = page.waitForResponse((response) => (response.request().method() === "DELETE"@@ -64,8 +62,14 @@ async function deletePostThroughUi(page: Page, childId: string, openerId: stringexpect(response.status()).toBe(204)}-test("canonical forum-post delete converges author, manager, private WS, and active routes", async ({ asUser }) => {+test("canonical forum-post delete converges author, manager, private WS, and active routes", async ({ caseActors }) => {test.setTimeout(150_000)++ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { seedCategory, seedChannel, seedChannelMember, seedForumThread, seedJoinServer, seedServer } = actors.seed+ const { resolveOpener } = await prepareCase(actors)+const serverId = await seedServer("alice", `Canonical delete ${Date.now()}`)const categoryId = await seedCategory("alice", serverId, "Private forum", { private: true })const forumId = await seedChannel("alice", serverId, "canonical-delete", "forum", categoryId)diff --git a/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts b/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.tsindex b68e6b8e8..bc5ea4669 100644--- a/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts+++ b/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts@@ -1,21 +1,32 @@-import { test, expect, sessionCookie, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { captureNotificationRequests, gotoAfterNotificationStartup } from "./_fixtures/community-notification-requests"-import { seedCategory, seedChannel, seedChannelMember, seedForumThread, seedJoinServer, seedMessage, seedServer, seedThread } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"+import type { CaseActors } from "./_fixtures/case-fixture"-async function mutate(path: string, method: string, body?: unknown) {- return fetch(`${WEB_URL}${path}`, {- method,- headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL, "Content-Type": "application/json" },- ...(body ? { body: JSON.stringify(body) } : {}),- })+async function prepareCase(actors: CaseActors) {+ const { sessionCookie } = actors+ async function mutate(path: string, method: string, body?: unknown) {+ return fetch(`${WEB_URL}${path}`, {+ method,+ headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL, "Content-Type": "application/json" },+ ...(body ? { body: JSON.stringify(body) } : {}),+ })+ }+ return { mutate }}for (const parentType of ["text", "forum"] as const) {for (const privateParent of [false, true]) {- test(`${privateParent ? "private" : "public"} ${parentType} child separates readable content from participation`, async ({ asUser }, testInfo) => {+ test(`${privateParent ? "private" : "public"} ${parentType} child separates readable content from participation`, async ({ caseActors }, testInfo) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedCategory, seedChannel, seedChannelMember, seedForumThread, seedJoinServer, seedMessage, seedServer, seedThread } = actors.seed+ const { mutate } = await prepareCase(actors)+const serverId = await seedServer("alice", `Realtime ${Date.now()}`)const categoryId = privateParent ? await seedCategory("alice", serverId, "Restricted realtime", { private: true }) : undefinedconst parentId = await seedChannel("alice", serverId, "realtime", parentType, categoryId)diff --git a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.tsindex ce747d5c2..c2e72b4a6 100644--- a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts+++ b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts@@ -1,55 +1,82 @@-import { test, expect, sessionCookie } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"import { WEB_URL } from "./_setup/paths"+import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"-const ONE_PIXEL_PNG_BASE64 =- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nL8AAAAASUVORK5CYII="--function aliceHeaders(extra?: Record<string, string>) {- return {- Cookie: sessionCookie("alice"),- Origin: WEB_URL,- ...extra,- }-}--async function pairMachine(): Promise<string> {- const pair = await fetch(`${WEB_URL}/api/community/machines/pair`, {- method: "POST",- headers: aliceHeaders(),- })- expect(pair.status).toBe(200)- const { tokenId } = await pair.json() as { tokenId: string }-- const activate = await fetch(`${WEB_URL}/api/community/daemon/activate`, {- method: "POST",- headers: {- Authorization: `Bearer ${tokenId}`,- "Content-Type": "application/json",+async function prepareCase(actors: CaseActors, caseResources: CaseResources) {+ const { sessionCookie } = actors+ function aliceHeaders(extra?: Record<string, string>) {+ return {+ Cookie: sessionCookie("alice"),Origin: WEB_URL,- },- body: JSON.stringify({- hostname: `avatar-e2e-${Date.now()}`,- platform: "darwin",- arch: "arm64",- runtimeReport: [{ id: "codex", status: "healthy" }],- }),- })- expect(activate.status).toBe(200)- const body = await activate.json() as { machineId: string }- return body.machineId+ ...extra,+ }+ }+ async function pairMachine(): Promise<string> {+ const pair = await fetch(`${WEB_URL}/api/community/machines/pair`, {+ method: "POST",+ headers: aliceHeaders(),+ })+ expect(pair.status).toBe(200)+ const { tokenId } = await pair.json() as {+ tokenId: string+ }+ const activationProof: { response?: Response; machineId?: string } = {}+ const pairingToken = caseResources.own(tokenId, async () => {+ if (!activationProof.response?.ok || !activationProof.machineId) throw new Error("Pairing token consumption is UNKNOWN; this case must stop")+ })+ const activate = await fetch(`${WEB_URL}/api/community/daemon/activate`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${tokenId}`,+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({+ hostname: `avatar-e2e-${Date.now()}`,+ platform: "darwin",+ arch: "arm64",+ runtimeReport: [{ id: "codex", status: "healthy" }],+ }),+ })+ expect(activate.status).toBe(200)+ const body = await activate.json() as {+ machineId: string+ }+ const machineId = body.machineId+ caseResources.own(machineId, async (id) => {+ const response = await fetch(`${WEB_URL}/api/community/machines/${id}`, { method: "DELETE", headers: aliceHeaders() })+ expect([204, 404]).toContain(response.status)+ })+ activationProof.response = activate+ activationProof.machineId = machineId+ await pairingToken.close()+ return machineId+ }+ async function createBot(machineId: string, name: string): Promise<string> {+ const response = await fetch(`${WEB_URL}/api/community/bots`, {+ method: "POST",+ headers: aliceHeaders({ "Content-Type": "application/json" }),+ body: JSON.stringify({ name, machineId, runtime: "codex" }),+ })+ expect(response.status).toBe(201)+ const body = await response.json() as {+ bot: {+ id: string+ }+ }+ const botId = body.bot.id+ caseResources.own(botId, async (id) => {+ const response = await fetch(`${WEB_URL}/api/community/bots/${id}`, { method: "DELETE", headers: aliceHeaders() })+ expect([204, 404]).toContain(response.status)+ })+ return botId+ }+ return { aliceHeaders, pairMachine, createBot }}-async function createBot(machineId: string, name: string): Promise<string> {- const response = await fetch(`${WEB_URL}/api/community/bots`, {- method: "POST",- headers: aliceHeaders({ "Content-Type": "application/json" }),- body: JSON.stringify({ name, machineId, runtime: "codex" }),- })- expect(response.status).toBe(201)- const body = await response.json() as { bot: { id: string } }- return body.bot.id-}+const ONE_PIXEL_PNG_BASE64 =+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nL8AAAAASUVORK5CYII="async function uploadAvatar(page: import("@playwright/test").Page,@@ -73,8 +100,13 @@ async function uploadAvatar(}, { id: botId, base64: ONE_PIXEL_PNG_BASE64 })}-test("real bot avatars become unreadable after single delete and authenticated machine cascade", async ({ asUser }) => {+test("real bot avatars become unreadable after single delete and authenticated machine cascade", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { aliceHeaders, pairMachine, createBot } = await prepareCase(actors, caseResources)+const machineId = await pairMachine()const botName = `Avatar cleanup ${Date.now()}`const botId = await createBot(machineId, botName)@@ -87,6 +119,7 @@ test("real bot avatars become unreadable after single delete and authenticated mlet releaseAvatar!: () => voidconst avatarGate = new Promise<void>((resolve) => { releaseAvatar = resolve })+ caseResources.own(releaseAvatar, async (captured) => { captured() })let failAvatar = truelet avatarRequests = 0await alice.page.route(`**${avatarPath}*`, async (route) => {diff --git a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.tsindex 1f1959e36..841667597 100644--- a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts+++ b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts@@ -1,16 +1,8 @@import type { Route } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"-import {- seedChannel,- seedDm,- seedDmMessage,- seedForumThread,- seedJoinServer,- seedMessage,- seedServer,-} from "./_fixtures/seed"+import {type CapturedCommunityFrame,communityFrameEvents,@@ -87,8 +79,13 @@ function unreadBumpsSince(.filter((event) => event.type === "community:unread.bump" && event.channelId === channelId)}-test("one human account converges read state across two browser profiles", async ({ asUser }) => {+test("one human account converges read state across two browser profiles", async ({ caseActors, caseResources }) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Multi-device ${stamp}`)const channelName = `read-sync-${stamp}`@@ -252,6 +249,7 @@ test("one human account converges read state across two browser profiles", asyncconst readAllRequestGate = new Promise<void>((resolve) => {releaseReadAllRequests = resolve})+ caseResources.own(releaseReadAllRequests, async (captured) => { captured() })const holdReadAllRequests = async (route: Route) => {if (route.request().method() !== "POST") {await route.continue()@@ -333,8 +331,13 @@ test("one human account converges read state across two browser profiles", asyncexpect(scoped.every((row) => row.lastReadSeq > 0)).toBe(true)})-test("hidden eager channel and DM mounts defer cross-device reads until visible", async ({ asUser }) => {+test("hidden eager channel and DM mounts defer cross-device reads until visible", async ({ caseActors }) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Hidden eager sync ${stamp}`)const channelId = await seedChannel("alice", serverId, `hidden-eager-${stamp}`)@@ -459,8 +462,13 @@ test("hidden eager channel and DM mounts defer cross-device reads until visible"deviceA.page.off("response", trackDmReads)})-test("a visible live tail clears both devices while an unseen tail stays unread", async ({ asUser }) => {+test("a visible live tail clears both devices while an unseen tail stays unread", async ({ caseActors }) => {test.setTimeout(180_000)++ 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", `Visible read sync ${stamp}`)const channelId = await seedChannel("alice", serverId, `visible-sync-${stamp}`)@@ -623,8 +631,13 @@ test("a visible live tail clears both devices while an unseen tail stays unread"deviceA.page.off("response", trackUnseenReads)})-test("forum cards use the ordinary parent cursor while child cursors stay independent", async ({ asUser }) => {+test("forum cards use the ordinary parent cursor while child cursors stay independent", async ({ caseActors }) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Unified forum sync ${stamp}`)const forumId = await seedChannel("alice", serverId, `unified-forum-${stamp}`, "forum")@@ -746,8 +759,13 @@ test("forum cards use the ordinary parent cursor while child cursors stay indepedeviceA.page.off("response", trackForumResponse)})-test("human author-send replaces both profiles while notification policy preserves unread", async ({ asUser }) => {+test("human author-send replaces both profiles while notification policy preserves unread", async ({ caseActors }) => {test.setTimeout(150_000)++ 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", `Writer sync ${stamp}`)const authorChannelId = await seedChannel("alice", serverId, `author-sync-${stamp}`)@@ -882,8 +900,13 @@ test("human author-send replaces both profiles while notification policy preserv.toBe(0)})-test("forum delete broadcasts replacement and removal to both active profiles", async ({ asUser }) => {+test("forum delete broadcasts replacement and removal to both active profiles", async ({ caseActors }) => {test.setTimeout(150_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedForumThread, seedJoinServer, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Forum read sync ${stamp}`)const forumId = await seedChannel("alice", serverId, `forum-read-sync-${stamp}`, "forum")diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.tsindex 84cdfd582..9de0051fb 100644--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts@@ -1,11 +1,109 @@import { createRequire } from "module"import { resolve } from "path"import type { Locator, Page, TestInfo } from "@playwright/test"-import { test, expect, sessionCookie } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"-import { seedChannel, seedForumThread, seedJoinServer, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import { MACHINE_WS_URL, REPO_ROOT, WEB_URL } from "./_setup/paths"+import type { CaseActors, CaseResources, OwnedCaseResource } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors, caseResources: CaseResources) {+ const { sessionCookie } = actors+ const createdBotIds = new Map<string, OwnedCaseResource<string>>()+ const createdMachineIds = new Map<string, OwnedCaseResource<string>>()+ async function cleanupCreatedResources(): Promise<void> {+ const errors: unknown[] = []+ for (const resource of [...createdBotIds.values(), ...createdMachineIds.values()]) {+ try {+ await resource.close()+ }+ catch (error) {+ errors.push(error)+ }+ }+ if (errors.length)+ throw new AggregateError(errors, "Bot preview resource cleanup failed")+ }+ function headersFor(key: UserKey, extra?: Record<string, string>) {+ return {+ Cookie: sessionCookie(key),+ Origin: WEB_URL,+ ...extra,+ }+ }+ async function jsonRequest<T>(key: UserKey, path: string, init?: RequestInit): Promise<T> {+ const response = await fetch(`${WEB_URL}${path}`, {+ ...init,+ headers: headersFor(key, {+ ...(init?.body ? { "Content-Type": "application/json" } : {}),+ ...(init?.headers as Record<string, string> | undefined),+ }),+ })+ expect(response.status, `${init?.method ?? "GET"} ${path}`).toBeLessThan(300)+ return response.json() as Promise<T>+ }+ async function pairMachine(): Promise<{+ credential: string+ machineId: string+ }> {+ const pair = await jsonRequest<{+ tokenId: string+ }>("alice", "/api/community/machines/pair", {+ method: "POST",+ })+ const activationProof: { response?: Response; machineId?: string } = {}+ const pairingToken = caseResources.own(pair.tokenId, async () => {+ if (!activationProof.response?.ok || !activationProof.machineId) throw new Error("Pairing token consumption is UNKNOWN; this case must stop")+ })+ const response = await fetch(`${WEB_URL}/api/community/daemon/activate`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${pair.tokenId}`,+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({+ hostname: `profile-preview-e2e-${Date.now()}`,+ platform: "darwin",+ arch: "arm64",+ runtimeReport: [{ id: "codex", status: "healthy" }],+ }),+ })+ expect(response.status).toBe(200)+ const data = await response.json() as {+ credential: string+ machineId: string+ }+ createdMachineIds.set(data.machineId, caseResources.own(data.machineId, async (machineId) => {+ const response = await fetch(`${WEB_URL}/api/community/machines/${machineId}`, { method: "DELETE", headers: headersFor("alice") })+ expect(response.status, `delete test machine ${machineId}`).toBe(204)+ createdMachineIds.delete(machineId)+ }))+ activationProof.response = response+ activationProof.machineId = data.machineId+ await pairingToken.close()+ return data+ }+ async function createBot(machineId: string, name: string): Promise<string> {+ const data = await jsonRequest<{+ bot: {+ id: string+ }+ }>("alice", "/api/community/bots", {+ method: "POST",+ body: JSON.stringify({ name, machineId, runtime: "codex" }),+ })+ createdBotIds.set(data.bot.id, caseResources.own(data.bot.id, async (botId) => {+ const response = await fetch(`${WEB_URL}/api/community/bots/${botId}`, { method: "DELETE", headers: headersFor("alice") })+ expect(response.status, `delete test bot ${botId}`).toBe(204)+ createdBotIds.delete(botId)+ }))+ return data.bot.id+ }+ actors.onCleanup(cleanupCreatedResources)+ return { createdBotIds, createdMachineIds, cleanupCreatedResources, headersFor, jsonRequest, pairMachine, createBot }+}type UserKey = "alice" | "bob"type Rect = { x: number; y: number; width: number; height: number }@@ -23,30 +121,6 @@ type PreviewFrameSample = {viewportHeight: number}-const createdBotIds: string[] = []-const createdMachineIds: string[] = []--async function cleanupCreatedResources(): Promise<void> {- for (const botId of [...createdBotIds]) {- const response = await fetch(`${WEB_URL}/api/community/bots/${botId}`, {- method: "DELETE",- headers: headersFor("alice"),- })- expect(response.status, `delete test bot ${botId}`).toBe(204)- createdBotIds.splice(createdBotIds.indexOf(botId), 1)- }- for (const machineId of [...createdMachineIds]) {- const response = await fetch(`${WEB_URL}/api/community/machines/${machineId}`, {- method: "DELETE",- headers: headersFor("alice"),- })- expect(response.status, `delete test machine ${machineId}`).toBe(204)- createdMachineIds.splice(createdMachineIds.indexOf(machineId), 1)- }-}--test.afterEach(cleanupCreatedResources)-async function rect(locator: Locator): Promise<Rect> {const value = await locator.boundingBox()expect(value).not.toBeNull()@@ -215,63 +289,6 @@ async function expectFooterGeometry(.toBe(width < 640 ? 16 : 24)}-function headersFor(key: UserKey, extra?: Record<string, string>) {- return {- Cookie: sessionCookie(key),- Origin: WEB_URL,- ...extra,- }-}--async function jsonRequest<T>(- key: UserKey,- path: string,- init?: RequestInit,-): Promise<T> {- const response = await fetch(`${WEB_URL}${path}`, {- ...init,- headers: headersFor(key, {- ...(init?.body ? { "Content-Type": "application/json" } : {}),- ...(init?.headers as Record<string, string> | undefined),- }),- })- expect(response.status, `${init?.method ?? "GET"} ${path}`).toBeLessThan(300)- return response.json() as Promise<T>-}--async function pairMachine(): Promise<{ credential: string; machineId: string }> {- const pair = await jsonRequest<{ tokenId: string }>("alice", "/api/community/machines/pair", {- method: "POST",- })- const response = await fetch(`${WEB_URL}/api/community/daemon/activate`, {- method: "POST",- headers: {- Authorization: `Bearer ${pair.tokenId}`,- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: JSON.stringify({- hostname: `profile-preview-e2e-${Date.now()}`,- platform: "darwin",- arch: "arm64",- runtimeReport: [{ id: "codex", status: "healthy" }],- }),- })- expect(response.status).toBe(200)- const data = await response.json() as { credential: string; machineId: string }- createdMachineIds.push(data.machineId)- return data-}--async function createBot(machineId: string, name: string): Promise<string> {- const data = await jsonRequest<{ bot: { id: string } }>("alice", "/api/community/bots", {- method: "POST",- body: JSON.stringify({ name, machineId, runtime: "codex" }),- })- createdBotIds.push(data.bot.id)- return data.bot.id-}-async function enrollBot(credential: string, botId: string): Promise<string> {const response = await fetch(`${WEB_URL}/api/community/daemon/enroll-agent`, {method: "POST",@@ -341,6 +358,8 @@ async function setBotMark(type MachineSocket = {send: (data: string) => voidclose: () => void+ readonly readyState: number+ once(event: "close", listener: () => void): voidonce(event: "open", listener: () => void): voidonce(event: "error", listener: (error: Error) => void): voidonce(event: "message", listener: (data: unknown) => void): void@@ -348,7 +367,7 @@ type MachineSocket = {off(event: "message", listener: (data: unknown) => void): void}-function connectMachine(credential: string) {+function connectMachine(credential: string, caseResources: CaseResources) {const requireFromDaemon = createRequire(resolve(REPO_ROOT, "src/daemon/package.json"))const Ws = requireFromDaemon("ws") as {WebSocket: new (url: string, options: { headers: Record<string, string> }) => MachineSocket@@ -356,8 +375,16 @@ function connectMachine(credential: string) {const socket = new Ws.WebSocket(MACHINE_WS_URL.replace(/^http/, "ws"), {headers: { Authorization: `Bearer ${credential}` },})+ const ownedSocket = caseResources.own(socket, async (captured) => {+ await new Promise<void>((resolve) => {+ if (captured.readyState === 3) { resolve(); return }+ captured.once("close", resolve)+ captured.close()+ })+ })return {socket,+ close: () => ownedSocket.close(),opened: new Promise<void>((resolveOpen, reject) => {socket.once("open", () => resolveOpen())socket.once("error", reject)@@ -491,16 +518,23 @@ async function probeOwnedBotProfile(return samples}-test("full audit log reveals a truncated row by hover and touch", async ({ asUser }, testInfo) => {+test("full audit log reveals a truncated row by hover and touch", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { headersFor, pairMachine, createBot } = await prepareCase(actors, caseResources)+const suffix = Date.now().toString(36)const longAuditTarget = `/Users/alice/workspace/${"deeply-nested-audit-target/".repeat(5)}result-${suffix}.md`const fullAuditText = `read · ${longAuditTarget}`const { credential, machineId } = await pairMachine()const botId = await createBot(machineId, `Tooltip bot ${suffix}`)- const machine = connectMachine(credential)+ const machine = connectMachine(credential, caseResources)await machine.opened+ let caseJourneyFailure1: unknown+let caseJourneyFailure1Present = falsetry {machine.socket.send(JSON.stringify({type: "bot_audit_event",@@ -564,13 +598,23 @@ test("full audit log reveals a truncated row by hover and touch", async ({ asUseawait attachPageScreenshot(testInfo, "bot-activity-log-tooltip-mobile-dark", page)await page.mouse.click(4, 4)await expect(tooltip).toBeHidden()- } finally {- machine.socket.close()+ } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {+ try {++ await machine.close()++ } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }}})-test("owned bot profile preview stays root-bounded from its first visible frame", async ({ asUser }, testInfo) => {+test("owned bot profile preview stays root-bounded from its first visible frame", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedForumThread, seedJoinServer, seedServer } = actors.seed+ const { jsonRequest, pairMachine, createBot } = await prepareCase(actors, caseResources)+const suffix = Date.now().toString(36)const serverId = await seedServer("alice", `preview-overflow-${suffix}`)const channelName = `regular-${suffix}`@@ -667,8 +711,14 @@ test("owned bot profile preview stays root-bounded from its first visible frame"await attachPageScreenshot(testInfo, "owned-agent-preview-non-owner", bob.page)})-test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audit modal", async ({ asUser }, testInfo) => {+test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audit modal", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedServer } = actors.seed+ const { headersFor, jsonRequest, pairMachine, createBot } = await prepareCase(actors, caseResources)+const suffix = Date.now().toString(36)const serverId = await seedServer("alice", `profile-preview-server-with-a-long-name-${suffix}`)const channelName = `bots-with-a-long-channel-name-${suffix}`@@ -741,8 +791,10 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned aud)expect(removeStaleBot.status).toBe(204)- const machine = connectMachine(credential)+ const machine = connectMachine(credential, caseResources)await machine.opened+ let caseJourneyFailure2: unknown+let caseJourneyFailure2Present = falsetry {machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "idle" }))for (let index = 0; index < 11; index += 1) {@@ -979,13 +1031,23 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audawait expect(bob.page.getByTestId(tid.botActivityModal)).toHaveCount(0)await expect.poll(() => new URL(bob.page.url()).searchParams.has("audit")).toBe(false)expect(bobMarkRequests).toEqual([])- } finally {- machine.socket.close()+ } catch (error) { caseJourneyFailure2 = error; caseJourneyFailure2Present = true; throw error } finally {+ try {++ await machine.close()++ } catch (cleanupError) { if (caseJourneyFailure2Present) throw new AggregateError([caseJourneyFailure2, cleanupError], "Journey and resource exit both failed"); throw cleanupError }}})-test("CommunitySheet footers keep four consumers horizontal and intrinsic at 390/639/640", async ({ asUser }) => {+test("CommunitySheet footers keep four consumers horizontal and intrinsic at 390/639/640", async ({ caseActors, caseResources }) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+ const { cleanupCreatedResources, jsonRequest, pairMachine, createBot } = await prepareCase(actors, caseResources)+const { machineId } = await pairMachine()const botName = `Footer bot ${Date.now().toString(36)}`await createBot(machineId, botName)diff --git a/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts b/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.tsindex 54c0503c6..4ecf603f5 100644--- a/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts+++ b/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts@@ -1,4 +1,4 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"test("first-signup mobile skips automatic onboarding and does not backfill it on desktop", async ({ page }) => {diff --git a/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts b/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.tsindex dd06a4752..23aba6b3f 100644--- a/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts+++ b/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts@@ -1,6 +1,6 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable } from "./_fixtures/actions"-import { seedChannel, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"type Candidate = {@@ -28,7 +28,11 @@ function candidate(prefix: string, index: number): Candidate {}}-test("@ candidates page to completion and shared popups stay anchored through viewport resize signals", async ({ asUser }) => {+test("@ candidates page to completion and shared popups stay anchored through viewport resize signals", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Mention pages ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "mention-pages")const { page } = await asUser("alice")@@ -69,10 +73,12 @@ test("@ candidates page to completion and shared popups stay anchored through viconst searchTailReleased = new Promise<void>((resolve) => {releaseSearchTail = resolve})+ caseResources.own(releaseSearchTail, async (captured) => { captured() })let markSearchTailRequested!: () => voidconst searchTailRequested = new Promise<void>((resolve) => {markSearchTailRequested = resolve})+ caseResources.own(markSearchTailRequested, async (captured) => { captured() })await page.route(`**/api/community/servers/${serverId}/members**`, async (route) => {const url = new URL(route.request().url())diff --git a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.tsindex 84dfd3604..8ee5be925 100644--- a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts+++ b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts@@ -1,7 +1,7 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"-import { seedChannel, seedJoinServer, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import {WS_CONNECTION_VALIDATION_TIMEOUT_MS,@@ -9,8 +9,13 @@ import {WS_FOREGROUND_SUSPENSION_GAP_MS,} from "../../lib/use-user-ws"-test("mobile foreground proof is exact, bounded, and recovers through one current generation", async ({ asUser }, testInfo) => {+test("mobile foreground proof is exact, bounded, and recovers through one current generation", async ({ caseActors }, testInfo) => {test.setTimeout(240_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Foreground validation ${stamp}`)const channelId = await seedChannel("alice", serverId, `foreground-${stamp}`)diff --git a/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts b/src/web/src/test/e2e-ui/33-picker-async-layout.spec.tsindex 076269ee7..b0d9ff385 100644--- a/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts+++ b/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts@@ -1,22 +1,15 @@import type { Locator, Page } from "@playwright/test"-import { expect, test, userId, userName } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"-import {- memberInfo,- renameUser,- seedChannel,- seedForumThread,- seedFriendship,- seedJoinServer,- seedMessage,- seedServer,-} from "./_fixtures/seed"--function deferred() {++import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"++function deferred(caseResources: CaseResources) {let resolve!: () => voidconst promise = new Promise<void>((done) => {resolve = done})+ caseResources.own(resolve, async (captured) => { captured() })return { promise, resolve }}@@ -38,78 +31,50 @@ async function openDesktopThreadMemberList(page: Page) {await threadPanel.getByRole("button", { name: "Member list" }).click()}-test.describe.serial("invite and participant picker async states", () => {- test.setTimeout(180_000)-- let inviteServerId: string- let participantServerId: string- let parentChannelId: string- let failureThreadId: string- let parentFailureThreadId: string- let emptyThreadId: string- let mutationThreadId: string- let bobName: string- let carolName: string+test.describe("invite and participant picker async states", () => {+test.setTimeout(180_000)- test.beforeAll(async () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId, userName } = actors+ const { memberInfo, renameUser, seedChannel, seedForumThread, seedFriendship, seedJoinServer, seedMessage, seedServer } = actors.seed+ actors.onCleanup(async () => {+ const restorations = await Promise.allSettled([+ renameUser("bob", userName("bob")),+ renameUser("carol", userName("carol")),+ ])+ expect(restorations.map((result) => result.status)).toEqual(["fulfilled", "fulfilled"])+ })const userStamp = Date.now().toString().slice(-6)await renameUser("bob", `PickerBob${userStamp}`)await renameUser("carol", `PickerCarol${userStamp}`)- inviteServerId = await seedServer(- "alice",- `Invite ${Date.now()} ${"unbroken-title-".repeat(5)}`,- )+ const inviteServerId: string = await seedServer("alice", `Invite ${Date.now()} ${"unbroken-title-".repeat(5)}`)await seedFriendship("alice", "bob", userId("bob"))await seedFriendship("alice", "carol", userId("carol"))-- participantServerId = await seedServer("alice", `Participants ${Date.now()}`)+ const participantServerId: string = await seedServer("alice", `Participants ${Date.now()}`)await seedJoinServer("alice", "bob", participantServerId)await seedJoinServer("alice", "carol", participantServerId)- parentChannelId = await seedChannel("alice", participantServerId, "picker-parent", "forum")- failureThreadId = await seedForumThread(- "alice",- parentChannelId,- `Failure ${"unbroken-thread-title-".repeat(4)}`,- "failure state",- )- parentFailureThreadId = await seedForumThread(- "alice",- parentChannelId,- `Parent failure ${"unbroken-thread-title-".repeat(4)}`,- "parent failure state",- )- emptyThreadId = await seedForumThread(- "alice",- parentChannelId,- `Empty ${Date.now()}`,- "resolved empty state",- )- mutationThreadId = await seedForumThread(- "alice",- parentChannelId,- `Mutation ${"unbroken-thread-title-".repeat(4)}`,- "mutation state",- )+ const parentChannelId: string = await seedChannel("alice", participantServerId, "picker-parent", "forum")+ const failureThreadId: string = await seedForumThread("alice", parentChannelId, `Failure ${"unbroken-thread-title-".repeat(4)}`, "failure state")+ const parentFailureThreadId: string = await seedForumThread("alice", parentChannelId, `Parent failure ${"unbroken-thread-title-".repeat(4)}`, "parent failure state")+ const emptyThreadId: string = await seedForumThread("alice", parentChannelId, `Empty ${Date.now()}`, "resolved empty state")+ const mutationThreadId: string = await seedForumThread("alice", parentChannelId, `Mutation ${"unbroken-thread-title-".repeat(4)}`, "mutation state")await seedMessage("bob", failureThreadId, "existing participant")await seedMessage("bob", emptyThreadId, "existing participant bob")await seedMessage("carol", emptyThreadId, "existing participant carol")- bobName = (await memberInfo("alice", participantServerId, userId("bob"))).name- carolName = (await memberInfo("alice", participantServerId, userId("carol"))).name- })+ const bobName: string = (await memberInfo("alice", participantServerId, userId("bob"))).name+ const carolName: string = (await memberInfo("alice", participantServerId, userId("carol"))).name+ return { inviteServerId, participantServerId, parentChannelId, failureThreadId, parentFailureThreadId, emptyThreadId, mutationThreadId, bobName, carolName }+ }- test.afterAll(async () => {- const restorations = await Promise.allSettled([- renameUser("bob", userName("bob")),- renameUser("carol", userName("carol")),- ])- expect(restorations.map((result) => result.status)).toEqual(["fulfilled", "fulfilled"])- })+ test("Invite friends keeps cold data provisional, search local, row pending, and title clear", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { inviteServerId, bobName, carolName } = await prepareCase1(actors)- test("Invite friends keeps cold data provisional, search local, row pending, and title clear", async ({ asUser }) => {const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 844 })- const acceptedGate = deferred()+ const acceptedGate = deferred(caseResources)let acceptedGets = 0let memberGets = 0await page.route("**/api/community/friends/accepted", async (route) => {@@ -159,7 +124,7 @@ test.describe.serial("invite and participant picker async states", () => {await expect(dialog.getByRole("button", { name: "Invite" }).first()).toBeVisible()await expect(dialog.getByRole("button", { name: "Copy" })).toBeEnabled({ timeout: 20_000 })- const dmGate = deferred()+ const dmGate = deferred(caseResources)const writes: string[] = []page.on("request", (request) => {if (request.method() === "POST") writes.push(new URL(request.url()).pathname)@@ -184,7 +149,11 @@ test.describe.serial("invite and participant picker async states", () => {expect(writes.filter((path) => /\/api\/community\/channels\/[^/]+\/messages$/.test(path))).toHaveLength(1)})- test("Invite friends exposes one recoverable first-load error chain before resolved empty", async ({ asUser }) => {+ test("Invite friends exposes one recoverable first-load error chain before resolved empty", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { inviteServerId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })@@ -217,7 +186,11 @@ test.describe.serial("invite and participant picker async states", () => {await expectTitleClearOfClose(dialog, 390)})- test("Add participants composes both sources and recovers without re-offering a participant", async ({ asUser }) => {+ test("Add participants composes both sources and recovers without re-offering a participant", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { participantServerId, parentChannelId, failureThreadId, bobName, carolName } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 844 })let failParticipants = true@@ -262,10 +235,14 @@ test.describe.serial("invite and participant picker async states", () => {expect({ participantGets, parentGets }).toEqual(beforeSearch)})- test("Add participants keeps a slow first load provisional before resolved empty", async ({ asUser }) => {+ test("Add participants keeps a slow first load provisional before resolved empty", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { participantServerId, parentChannelId, emptyThreadId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 844 })- const parentGate = deferred()+ const parentGate = deferred(caseResources)let parentGets = 0await page.route((url) => url.pathname === `/api/community/channels/${parentChannelId}/members` && url.searchParams.get("relation") === "access", async (route) => {if (route.request().method() !== "GET") return route.continue()@@ -287,7 +264,11 @@ test.describe.serial("invite and participant picker async states", () => {.toBeVisible({ timeout: 20_000 })})- test("Add participants retries an unresolved parent without refetching participants", async ({ asUser }) => {+ test("Add participants retries an unresolved parent without refetching participants", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { participantServerId, parentChannelId, parentFailureThreadId, bobName, carolName } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 844 })let failParent = true@@ -327,7 +308,11 @@ test.describe.serial("invite and participant picker async states", () => {expect(parentGets).toBeGreaterThan(failedParentGets)})- test("Add participants keeps mutation pending local to one row", async ({ asUser }) => {+ test("Add participants keeps mutation pending local to one row", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { participantServerId, mutationThreadId, bobName, carolName } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })await page.goto(`/c/channels/${participantServerId}/${mutationThreadId}`)@@ -340,7 +325,7 @@ test.describe.serial("invite and participant picker async states", () => {await expect(dialog.getByText(carolName, { exact: true })).toBeVisible()await expectTitleClearOfClose(dialog, 390)- const mutationGate = deferred()+ const mutationGate = deferred(caseResources)let participantPosts = 0await page.route(`**/api/community/channels/${mutationThreadId}/participants`, async (route) => {if (route.request().method() !== "POST") return route.continue()diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.tsindex 81541b982..e37afa035 100644--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts@@ -3,10 +3,27 @@ import { spawnSync } from "node:child_process"import { writeFileSync } from "node:fs"import type { Page, TestInfo } from "@playwright/test"import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared"-import { test, expect, sessionCookie, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"import { REPO_ROOT, WEB_URL } from "./_setup/paths"+import type { CaseActors } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { sessionCookie } = actors+ async function postAsAlice(path: string, body?: unknown): Promise<Response> {+ return fetch(`${WEB_URL}${path}`, {+ method: "POST",+ headers: {+ Cookie: sessionCookie("alice"),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ })+ }+ return { postAsAlice }+}type D1Result<Row = Record<string, unknown>> = {results: Row[]@@ -33,18 +50,6 @@ function executeLocalD1<Row = Record<string, unknown>>(sql: string): D1Result<Roreturn JSON.parse(result.stdout) as D1Result<Row>[]}-async function postAsAlice(path: string, body?: unknown): Promise<Response> {- return fetch(`${WEB_URL}${path}`, {- method: "POST",- headers: {- Cookie: sessionCookie("alice"),- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: body === undefined ? undefined : JSON.stringify(body),- })-}-const dayOverrides: Record<string, { input: number | null; output: number | null; cache: number | null }> = {"2026-08-24": { input: 0, output: 0, cache: 0 },"2026-08-25": { input: null, output: null, cache: null },@@ -267,7 +272,11 @@ async function expectDarkTheme(page: Page, expected: boolean) {.toBe(expected)}-test("My Bots restores the 30-day token heatmap across PC and mobile", async ({ asUser }, testInfo) => {+test("My Bots restores the 30-day token heatmap across PC and mobile", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ await prepareCase(actors)+const { page } = await asUser("alice", { hasTouch: true })await page.route("**/api/community/bots", async (route) => {await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(botsResponse) })@@ -495,10 +504,26 @@ test("My Bots restores the 30-day token heatmap across PC and mobile", async ({expect(writeRequests).toEqual([])})-test("My Bots renders Pi usage through real D1 and the unmocked bots API", async ({ asUser }, testInfo) => {+test("My Bots renders Pi usage through real D1 and the unmocked bots API", async ({ caseActors, caseResources }, testInfo) => {+ const actors = await caseActors(["alice"])+ const { asUser, sessionCookie, userId } = actors+ const { postAsAlice } = await prepareCase(actors)+const ownerId = userId("alice")let machineId: string | undefinedlet botId: string | undefined+ const ownedD1 = caseResources.own(ownerId, async () => {+ executeLocalD1([+ botId ? `DELETE FROM community_bot_daily_token_usage WHERE bot_id = ${sqlLiteral(botId)}` : "",+ botId ? `DELETE FROM community_bot_binding WHERE user_id = ${sqlLiteral(botId)}` : "",+ botId ? `DELETE FROM \"user\" WHERE id = ${sqlLiteral(botId)}` : "",+ machineId ? `DELETE FROM community_machine_credential WHERE machine_id = ${sqlLiteral(machineId)}` : "",+ `DELETE FROM community_machine_token WHERE user_id = ${sqlLiteral(ownerId)}`,+ machineId ? `DELETE FROM community_machine WHERE id = ${sqlLiteral(machineId)}` : "",+ ].filter(Boolean).join(";"))+ })+ let caseJourneyFailure1: unknown+let caseJourneyFailure1Present = falsetry {const pairResponse = await postAsAlice("/api/community/machines/pair")expect(pairResponse.ok).toBe(true)@@ -638,16 +663,11 @@ test("My Bots renders Pi usage through real D1 and the unmocked bots API", async}, null, 2)}\n`)await testInfo.attach("real-pi-browser-observation.json", { path: browserEvidencePath })await attachScreenshot(page, testInfo, "real-pi-d1-local-today")- } finally {- if (botId || machineId) {- executeLocalD1([- botId ? `DELETE FROM community_bot_daily_token_usage WHERE bot_id = ${sqlLiteral(botId)}` : "",- botId ? `DELETE FROM community_bot_binding WHERE user_id = ${sqlLiteral(botId)}` : "",- botId ? `DELETE FROM \"user\" WHERE id = ${sqlLiteral(botId)}` : "",- machineId ? `DELETE FROM community_machine_credential WHERE machine_id = ${sqlLiteral(machineId)}` : "",- `DELETE FROM community_machine_token WHERE user_id = ${sqlLiteral(ownerId)}`,- machineId ? `DELETE FROM community_machine WHERE id = ${sqlLiteral(machineId)}` : "",- ].filter(Boolean).join(";"))- }+ } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {+ try {++ await ownedD1.close()++ } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }}})diff --git a/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.tsindex d1afaa1c9..b059b0779 100644--- a/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts+++ b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts@@ -1,7 +1,8 @@import type { Page, Request, Response, Route } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"-import { seedChannel, seedServer } from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"+import type { CaseResources } from "./_fixtures/case-fixture"type HeldServer = {heldNavigation: () => number@@ -153,10 +154,11 @@ function expectAtomicTargetFrames(async function holdServerTransition(page: Page,- serverId: string,+ serverId: string, caseResources: CaseResources): Promise<HeldServer> {let releaseGate!: () => voidconst gate = new Promise<void>((resolve) => { releaseGate = resolve })+ caseResources.own(releaseGate, async (captured) => { captured() })let heldNavigation = 0const patterns: Array<{ pattern: string; navigation: boolean }> = [{ pattern: `**/c/channels/${serverId}**`, navigation: true },@@ -193,7 +195,7 @@ function isTargetRsc(request: Request, serverId: string): boolean {function observeTargetRsc(page: Page,serverId: string,- timeoutMs: number,+ timeoutMs: number, caseResources: CaseResources): {finished: Promise<void>requests: () => string[]@@ -242,18 +244,23 @@ function observeTargetRsc(const timeout = setTimeout(() => {settle(new Error(`Target RSC did not finish within ${timeoutMs}ms for server ${serverId}`))}, timeoutMs)+ const stop = () => {+ clearTimeout(timeout)+ page.off("request", onRequest)+ page.off("requestfailed", onRequestFailed)+ page.off("response", onResponse)+ }+ caseResources.own(stop, async (captured) => {+ captured()+ settle()+ })page.on("request", onRequest)page.on("requestfailed", onRequestFailed)page.on("response", onResponse)return {finished,requests: () => [...requests],- stop: () => {- clearTimeout(timeout)- page.off("request", onRequest)- page.off("requestfailed", onRequestFailed)- page.off("response", onResponse)- },+ stop,}}@@ -283,8 +290,13 @@ async function expectActiveServer(page: Page, activeId: string, inactiveId: striawait expect(page.getByTestId(tid.serverIcon(inactiveId))).toHaveClass(/cursor-pointer/)}-test("server switching exposes one target-scoped cold checkpoint and skips it when warm", async ({ asUser }) => {+test("server switching exposes one target-scoped cold checkpoint and skips it when warm", async ({ caseActors, caseResources }) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const stamp = Date.now()const serverA = await seedServer("alice", `Checkpoint A ${stamp}`)const serverB = await seedServer("alice", `Checkpoint B ${stamp}`)@@ -332,10 +344,10 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh// the pointer between vertically stacked icons can cross another icon and// legitimately trigger its hover prefetch; those targets must stay cold// until their explicit phase below.- const coldC = await holdServerTransition(page, serverC)- const coldD = await holdServerTransition(page, serverD)- const coldE = await holdServerTransition(page, serverE)- const coldF = await holdServerTransition(page, serverF)+ const coldC = await holdServerTransition(page, serverC, caseResources)+ const coldD = await holdServerTransition(page, serverD, caseResources)+ const coldE = await holdServerTransition(page, serverE, caseResources)+ const coldF = await holdServerTransition(page, serverF, caseResources)// Visit B once so both its route and live detail query are deterministically// memory-warm, then return to A before sampling the warm switch.@@ -411,8 +423,8 @@ test("server switching exposes one target-scoped cold checkpoint and skips it whawait page.waitForTimeout(1_000)await page.reload()await expect(page.getByRole("heading", { name: channelAName })).toBeVisible({ timeout: 30_000 })- const structuralC = await holdServerTransition(page, serverC)- const targetRsc = observeTargetRsc(page, serverC, 30_000)+ const structuralC = await holdServerTransition(page, serverC, caseResources)+ const targetRsc = observeTargetRsc(page, serverC, 30_000, caseResources)await clearSidebarFrames(page)await clearHistoryEvents(page)try {diff --git a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.tsindex 74319316f..140fa26b9 100644--- a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts+++ b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts@@ -1,6 +1,6 @@import { devices, type Locator, type Page } from "@playwright/test"-import { expect, test, userId } from "./_fixtures/community-fixture"-import { seedChannel, seedDm, seedJoinServer, seedServer } from "./_fixtures/seed"+import { expect, test } from "./_fixtures/case-fixture"+import { composerEditable, waitForElementMotion } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"@@ -379,8 +379,13 @@ async function expectFirstNativeServerTap(expect(railPatches).toHaveLength(patchesBeforeTap)}-test("first native Server tap is one root push with a stable handle and zero rail PATCH", async ({ asUser }) => {+test("first native Server tap is one root push with a stable handle and zero rail PATCH", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedChannel, seedDm, seedJoinServer, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `First tap ${stamp}`)await seedChannel("alice", serverId, `first-tap-${stamp}`)@@ -421,8 +426,13 @@ test("first native Server tap is one root push with a stable handle and zero raiawait expectFirstNativeServerTap(warm.page, serverId, warmPatches)})-test("server rail keeps scroll separate from native, touch, and keyboard drag", async ({ asUser }, testInfo) => {+test("server rail keeps scroll separate from native, touch, and keyboard drag", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(150_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const stamp = Date.now()const first = await seedServer("alice", `Rail first ${stamp}`)const second = await seedServer("alice", `Rail second ${stamp}`)@@ -694,6 +704,7 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",await expect(page.locator("html")).not.toHaveClass(/dark/)let releaseCommit!: () => voidconst commitGate = new Promise<void>((resolve) => { releaseCommit = resolve })+ caseResources.own(releaseCommit, async (captured) => { captured() })let delayed = falseawait page.route(`**${RAIL_ENDPOINT}`, async (route) => {if (route.request().method() === "PATCH" && !delayed) {@@ -729,7 +740,11 @@ test("server rail keeps scroll separate from native, touch, and keyboard drag",await page.screenshot({ path: testInfo.outputPath("server-rail-keyboard-1280.png") })})-test("short server rail keeps Add adjacent and desktop geometry stable", async ({ asUser }) => {+test("short server rail keeps Add adjacent and desktop geometry stable", async ({ caseActors }) => {+ const actors = await caseActors(["carol"])+ const { asUser } = actors+ const { seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("carol", `Rail short ${stamp}`)const { page } = await asUser("carol")diff --git a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.tsindex 2db622b61..4a8cd60c7 100644--- a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts+++ b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts@@ -1,11 +1,13 @@import type { Page, Route } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"-import { seedChannel, seedServer } from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"+import type { CaseResources } from "./_fixtures/case-fixture"-async function holdRoute(page: Page, pathname: string) {+async function holdRoute(page: Page, pathname: string, caseResources: CaseResources) {let releaseGate!: () => voidconst gate = new Promise<void>((resolve) => { releaseGate = resolve })+ caseResources.own(releaseGate, async (captured) => { captured() })let held = 0const pattern = `**${pathname}**`const handler = async (route: Route) => {@@ -125,8 +127,13 @@ function expectStationaryFrames(frames: SurfaceFrameRecord[]) {}}-test("community checkpoint shows target pending for detail and keeps list surfaces stable", async ({ asUser }) => {+test("community checkpoint shows target pending for detail and keeps list surfaces stable", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Frame Gate ${stamp}`)const channelAName = `frame-a-${stamp}`@@ -153,7 +160,7 @@ test("community checkpoint shows target pending for detail and keeps list surfac) mutations.push(`${method} ${pathname}`)})- const leafGate = await holdRoute(page, `/c/channels/${serverId}/${channelB}`)+ const leafGate = await holdRoute(page, `/c/channels/${serverId}/${channelB}`, caseResources)await page.getByTestId(tid.channelRow(channelB)).click({ noWaitAfter: true })await expect.poll(leafGate.held).toBeGreaterThan(0)const pendingMain = page.locator(@@ -182,7 +189,7 @@ test("community checkpoint shows target pending for detail and keeps list surfacawait expect(targetReady).toBeVisible()await page.setViewportSize({ width: 390, height: 844 })- const rootGate = await holdRoute(page, `/c/channels/${serverId}`)+ const rootGate = await holdRoute(page, `/c/channels/${serverId}`, caseResources)await page.getByRole("banner").getByRole("button", { name: "Back" }).click({ noWaitAfter: true })await expect.poll(rootGate.held).toBeGreaterThan(0)await page.setViewportSize({ width: 1280, height: 900 })@@ -194,7 +201,7 @@ test("community checkpoint shows target pending for detail and keeps list surfacawait rootGate.release()await expect(channelHeader(page, channelBName)).toBeVisible({ timeout: 30_000 })- const machinesGate = await holdRoute(page, "/c/me/machines")+ const machinesGate = await holdRoute(page, "/c/me/machines", caseResources)await page.goto("/c/me/friends")await expect(page.getByPlaceholder("Search friends")).toBeVisible({ timeout: 30_000 })await page.getByRole("link", { name: "Machines", exact: true }).click({ noWaitAfter: true })@@ -210,8 +217,13 @@ test("community checkpoint shows target pending for detail and keeps list surfacexpect(mutations).toEqual([])})-test("mobile route commits stay stationary while sidebar identity survives same-server history", async ({ asUser }) => {+test("mobile route commits stay stationary while sidebar identity survives same-server history", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Mobile frame ${stamp}`)const fastName = `fast-${stamp}`@@ -261,7 +273,7 @@ test("mobile route commits stay stationary while sidebar identity survives same-await clearSurfaceAnimations(page)const pendingPath = `/c/channels/${serverId}/${pendingChannel}`- const pendingGate = await holdRoute(page, pendingPath)+ const pendingGate = await holdRoute(page, pendingPath, caseResources)await page.getByTestId(tid.channelRow(pendingChannel)).click({ noWaitAfter: true })await expect.poll(pendingGate.held).toBeGreaterThan(0)const pendingMain = page.locator(diff --git a/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts b/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.tsindex ce32d2694..b2211f925 100644--- a/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts+++ b/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts@@ -1,5 +1,5 @@import type { Page, TestInfo } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import {composerEditable,gotoAfterUserWsAuth,@@ -11,14 +11,9 @@ import {proxyCommunityWebSockets,type CapturedCommunityFrame,} from "./_fixtures/community-ws-proxy"-import {- seedChannel,- seedDm,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"test.use({ viewport: { width: 390, height: 844 } })@@ -237,21 +232,23 @@ async function expectExplicitTouchSend({expect(messagePosts).toBe(1)}-test.describe.serial("composer send by input capability", () => {- let serverId: string- let channelId: string- let threadId: string- let dmId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `capability-send-${Date.now()}`)- channelId = await seedChannel("alice", serverId, "capability-send")+test.describe("composer send by input capability", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId } = actors+ const { seedChannel, seedDm, seedMessage, seedServer, seedThread } = actors.seed+ const serverId: string = await seedServer("alice", `capability-send-${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "capability-send")const openerId = await seedMessage("alice", channelId, "capability send thread opener")- threadId = await seedThread("alice", openerId, "capability-send-thread")- dmId = await seedDm("alice", userId("bob"))- })+ const threadId: string = await seedThread("alice", openerId, "capability-send-thread")+ const dmId: string = await seedDm("alice", userId("bob"))+ return { serverId, channelId, threadId, dmId }+ }++ test("narrow hover-capable PC keeps Enter send and Shift+Enter newline through resize", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)- test("narrow hover-capable PC keeps Enter send and Shift+Enter newline through resize", async ({ asUser }) => {const { page, context } = await asUser("alice")await installInputCapability(page, true)const proxy = await proxyCommunityWebSockets(context)@@ -263,7 +260,11 @@ test.describe.serial("composer send by input capability", () => {})})- test("touch channel keeps multiline Enter and the explicit button sends once", async ({ asUser }, testInfo) => {+ test("touch channel keeps multiline Enter and the explicit button sends once", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const { page, context } = await asUser("alice", { hasTouch: true })await installInputCapability(page, false)const proxy = await proxyCommunityWebSockets(context)@@ -278,7 +279,11 @@ test.describe.serial("composer send by input capability", () => {})})- test("touch child thread button targets the child", async ({ asUser }) => {+ test("touch child thread button targets the child", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, threadId } = await prepareCase1(actors)+const { page, context } = await asUser("alice", { hasTouch: true })await installInputCapability(page, false)const proxy = await proxyCommunityWebSockets(context)@@ -291,7 +296,11 @@ test.describe.serial("composer send by input capability", () => {})})- test("touch DM button targets the DM channel", async ({ asUser }) => {+ test("touch DM button targets the DM channel", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { channelId, dmId } = await prepareCase1(actors)+const { page, context } = await asUser("alice", { hasTouch: true })await installInputCapability(page, false)const proxy = await proxyCommunityWebSockets(context)diff --git a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.tsindex 763b26312..00bbff325 100644--- a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts+++ b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts@@ -1,13 +1,8 @@import type { Page, Response } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"-import {- seedChannel,- seedForumThread,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"test.use({ viewport: { width: 390, height: 844 } })@@ -19,28 +14,26 @@ async function expectMobileBack(page: Page) {return control}-test.describe.serial("mobile server header direct hierarchy", () => {- let serverId: string- let textId: string- let forumId: string- let threadId: string- let postId: string- let threadName: string- let postTitle: string-- test.beforeAll(async () => {+test.describe("mobile server header direct hierarchy", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedChannel, seedForumThread, seedMessage, seedServer, seedThread } = actors.seedconst stamp = Date.now()- serverId = await seedServer("alice", `header-hierarchy-${stamp}`)- textId = await seedChannel("alice", serverId, `text-${stamp}`)- forumId = await seedChannel("alice", serverId, `forum-${stamp}`, "forum")+ const serverId: string = await seedServer("alice", `header-hierarchy-${stamp}`)+ const textId: string = await seedChannel("alice", serverId, `text-${stamp}`)+ const forumId: string = await seedChannel("alice", serverId, `forum-${stamp}`, "forum")const openerId = await seedMessage("alice", textId, `thread opener ${stamp}`)- threadName = `thread-${stamp}`- postTitle = `post-${stamp}`- threadId = await seedThread("alice", openerId, threadName)- postId = await seedForumThread("alice", forumId, postTitle, "post body")- })+ const threadName: string = `thread-${stamp}`+ const postTitle: string = `post-${stamp}`+ const threadId: string = await seedThread("alice", openerId, threadName)+ const postId: string = await seedForumThread("alice", forumId, postTitle, "post body")+ return { serverId, textId, forumId, threadId, postId, threadName, postTitle }+ }++ test("top-level text and forum replace directly to the canonical server root", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, textId, forumId } = await prepareCase1(actors)- test("top-level text and forum replace directly to the canonical server root", async ({ asUser }) => {const { page } = await asUser("alice")for (const channelId of [textId, forumId]) {await page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })@@ -52,7 +45,11 @@ test.describe.serial("mobile server header direct hierarchy", () => {}})- test("thread and forum post expose direct parent Back and inert current labels", async ({ asUser }) => {+ test("thread and forum post expose direct parent Back and inert current labels", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, textId, forumId, threadId, postId, threadName, postTitle } = await prepareCase1(actors)+const { page } = await asUser("alice")for (const child of [{ id: threadId, parentId: textId, name: threadName },@@ -74,7 +71,11 @@ test.describe.serial("mobile server header direct hierarchy", () => {}})- test("639↔640 preserves the header and composer owners without resize requests", async ({ asUser }) => {+ test("639↔640 preserves the header and composer owners without resize requests", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, threadId } = await prepareCase1(actors)+const { page } = await asUser("alice")const startupAttentionPaths = ["/api/community/users/me/attention",diff --git a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.tsindex f212e17c2..8bc0f89b9 100644--- a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts+++ b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts@@ -1,7 +1,7 @@import type { Locator, Page, Response } from "@playwright/test"-import { expect, test, userId } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"-import { memberInfo, seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"async function indicatorHeight(indicator: Locator) {@@ -47,8 +47,13 @@ async function combineServers(page: Page, sourceId: string, targetId: string) {}}-test("server unread owns exact rail geometry, folder aggregation, read clear, and mobile parity", async ({ asUser }, testInfo) => {+test("server unread owns exact rail geometry, folder aggregation, read clear, and mobile parity", async ({ caseActors }, testInfo) => {test.setTimeout(150_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { memberInfo, seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const foregroundServer = await seedServer("alice", `Unread foreground ${stamp}`)const backgroundServer = await seedServer("alice", `Unread background ${stamp}`)diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.tsindex 4691f7522..de2d5d7fa 100644--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts@@ -1,5 +1,5 @@import type { Page, Request } from "@playwright/test"-import { expect, test, userId } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"import {communityFrameEvents,@@ -7,17 +7,9 @@ import {proxyCommunityWebSockets,type CapturedCommunityFrame,} from "./_fixtures/community-ws-proxy"-import {- memberInfo,- seedChannel,- seedDm,- seedDmMessage,- seedForumThread,- seedJoinServer,- seedMessage,- seedServer,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseResources } from "./_fixtures/case-fixture"async function installReadObserverGate(page: Page, initiallyBlocked = false) {await page.addInitScript((blockInitially) => {@@ -131,14 +123,17 @@ async function expectRailReplacementDoesNotBlockMessages({latestText: stringinboxRowTestId: stringtriggerUnread: () => Promise<string>-}) {+}, caseResources: CaseResources) {const beforeReadSeq = await readSeq(page, channelId)let releaseRailGate!: () => voidconst railRelease = new Promise<void>((resolve) => { releaseRailGate = resolve })+ caseResources.own(releaseRailGate, async (captured) => { captured() })let markRailHeld!: () => voidconst railHeld = new Promise<void>((resolve) => { markRailHeld = resolve })+ caseResources.own(markRailHeld, async (captured) => { captured() })let markRailSettled!: () => voidconst railSettled = new Promise<void>((resolve) => { markRailSettled = resolve })+ caseResources.own(markRailSettled, async (captured) => { captured() })let railRequestHeld = falseconst releaseRail = async () => {releaseRailGate()@@ -216,10 +211,14 @@ async function expectRailReplacementDoesNotBlockMessages({}}-test.describe.serial("account unread projection", () => {- test.setTimeout(180_000)+test.describe("account unread projection", () => {+test.setTimeout(180_000)++ test("one mention source disappears from Unreads, Mentions, and every dot in the same frame", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { memberInfo, seedChannel, seedJoinServer, seedServer } = actors.seed- test("one mention source disappears from Unreads, Mentions, and every dot in the same frame", async ({ asUser }) => {const stamp = Date.now()const serverId = await seedServer("alice", `Projection mention ${stamp}`)const channelName = `mention-${stamp}`@@ -307,7 +306,11 @@ test.describe.serial("account unread projection", () => {expect((await readResponse).status()).toBe(200)})- test("one committed bundle projects every surface and only a visible row clears it", async ({ asUser }, testInfo) => {+ test("one committed bundle projects every surface and only a visible row clears it", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedForumThread, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const foregroundServer = await seedServer("alice", `Projection foreground ${stamp}`)const foregroundChannel = await seedChannel("alice", foregroundServer, `foreground-${stamp}`)@@ -431,7 +434,11 @@ test.describe.serial("account unread projection", () => {expect(cursor(dmId)).toBe(beforeCursor(dmId))})- test("a held rail server-list request does not block channel or child messages", async ({ asUser }) => {+ test("a held rail server-list request does not block channel or child messages", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { memberInfo, seedChannel, seedForumThread, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const foregroundServer = await seedServer("alice", `Rail foreground ${stamp}`)const foregroundChannel = await seedChannel("alice", foregroundServer, `foreground-${stamp}`)@@ -509,7 +516,7 @@ test.describe.serial("account unread projection", () => {await sendRailMention(`channel rail ${stamp}`)return seedMessage("alice", channelId, channelText)},- })+ }, caseResources)await gotoAfterUserWsAuth(childPage, "/c/me")await expectRailReplacementDoesNotBlockMessages({@@ -523,11 +530,15 @@ test.describe.serial("account unread projection", () => {await sendRailMention(`child rail ${stamp}`)return seedMessage("alice", childId, childText)},- })+ }, caseResources)await childPage.close()})- test("mark all settles three domains and rolls back only the failed domain", async ({ asUser }) => {+ test("mark all settles three domains and rolls back only the failed domain", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverId = await seedServer("alice", `Projection mark all ${stamp}`)const channelId = await seedChannel("alice", serverId, `mark-all-${stamp}`)diff --git a/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.tsindex 96cb8b9bc..eabf08eab 100644--- a/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts+++ b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts@@ -1,7 +1,54 @@import type { BrowserContext, Page, Route } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"-import { seedChannel, seedDm, seedDmMessage, seedMessage, seedServer } from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"+import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors, caseResources: CaseResources) {+ const { userId } = actors+ const coldRootStorageKey = `community:lastRoute:${encodeURIComponent(userId("alice"))}`+ async function installColdRootProbe(page: Page, destination: string | null) {+ await page.addInitScript(({ storageKey, storedDestination, machinesPendingTestId }) => {+ const target = window as typeof window & {+ __communityColdRootProbe?: ColdRootProbe+ }+ target.__communityColdRootProbe = { machinesSeen: false }+ try {+ if (storedDestination)+ localStorage.setItem(storageKey, storedDestination)+ else+ localStorage.removeItem(storageKey)+ }+ catch { }+ const inspect = () => {+ const machines = document.querySelector(`[data-community-main-kind="machines"], [data-testid="${machinesPendingTestId}"]`)+ if (machines)+ target.__communityColdRootProbe!.machinesSeen = true+ }+ const observe = () => {+ if (!document.documentElement) {+ globalThis.setTimeout(observe, 0)+ return+ }+ new MutationObserver(inspect).observe(document.documentElement, {+ childList: true,+ subtree: true,+ })+ inspect()+ }+ observe()+ }, {+ storageKey: coldRootStorageKey,+ storedDestination: destination,+ machinesPendingTestId: tid.pendingMain("machines"),+ })+ }+ async function closeHeldContext(context: BrowserContext, gate: Awaited<ReturnType<typeof holdApplicationScripts>>) {+ gate.abort()+ await caseResources.closeContext(context)+ }+ return { coldRootStorageKey, installColdRootProbe, closeHeldContext }+}type Surface = "list" | "detail" | "neutral"type Sidebar = "me" | "server" | "none"@@ -18,52 +65,17 @@ type ColdRootProbe = {machinesSeen: boolean}-const coldRootStorageKey = `community:lastRoute:${encodeURIComponent(userId("alice"))}`--async function installColdRootProbe(page: Page, destination: string | null) {- await page.addInitScript(({ storageKey, storedDestination, machinesPendingTestId }) => {- const target = window as typeof window & { __communityColdRootProbe?: ColdRootProbe }- target.__communityColdRootProbe = { machinesSeen: false }- try {- if (storedDestination) localStorage.setItem(storageKey, storedDestination)- else localStorage.removeItem(storageKey)- } catch { }-- const inspect = () => {- const machines = document.querySelector(- `[data-community-main-kind="machines"], [data-testid="${machinesPendingTestId}"]`,- )- if (machines) target.__communityColdRootProbe!.machinesSeen = true- }- const observe = () => {- if (!document.documentElement) {- globalThis.setTimeout(observe, 0)- return- }- new MutationObserver(inspect).observe(document.documentElement, {- childList: true,- subtree: true,- })- inspect()- }- observe()- }, {- storageKey: coldRootStorageKey,- storedDestination: destination,- machinesPendingTestId: tid.pendingMain("machines"),- })-}-async function expectNoMachinesDuringColdRootRestore(page: Page) {expect(await page.evaluate(() => (window as typeof window & { __communityColdRootProbe?: ColdRootProbe }).__communityColdRootProbe)).toEqual({ machinesSeen: false })}-async function holdApplicationScripts(page: Page) {+async function holdApplicationScripts(page: Page, caseResources: CaseResources) {let releaseGate!: () => voidlet disposition: "continue" | "abort" = "continue"const gate = new Promise<void>((resolve) => { releaseGate = resolve })+ caseResources.own(releaseGate, async (captured) => { captured() })let hits = 0let sessionRequests = 0page.on("request", (request) => {@@ -182,37 +194,30 @@ async function expectServerSeededRouteSkeleton(for (const value of distinctiveStrings) await expect(frame).not.toContainText(value)}-async function closeHeldContext(- context: BrowserContext,- gate: Awaited<ReturnType<typeof holdApplicationScripts>>,-) {- gate.abort()- await context.close()-}--test.describe.serial("community initial-load module skeletons", () => {- let serverId: string- let channelId: string- let dmId: string- let serverName: string- let channelName: string- let channelMessageId: string- let privateMessage: string-- test.beforeAll(async () => {+test.describe("community initial-load module skeletons", () => {+ async function prepareCase1(actors: CaseActors, caseResources: CaseResources) {+ const { coldRootStorageKey, installColdRootProbe, closeHeldContext } = await prepareCase(actors, caseResources)+ const { userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedMessage, seedServer } = actors.seedconst stamp = Date.now()- serverName = `COLD SERVER ${stamp}`- channelName = `cold-channel-${stamp}`- privateMessage = `PRIVATE COLD MESSAGE ${stamp}`- serverId = await seedServer("alice", serverName)- channelId = await seedChannel("alice", serverId, channelName)- channelMessageId = await seedMessage("alice", channelId, privateMessage)- dmId = await seedDm("alice", userId("bob"))+ const serverName: string = `COLD SERVER ${stamp}`+ const channelName: string = `cold-channel-${stamp}`+ const privateMessage: string = `PRIVATE COLD MESSAGE ${stamp}`+ const serverId: string = await seedServer("alice", serverName)+ const channelId: string = await seedChannel("alice", serverId, channelName)+ const channelMessageId: string = await seedMessage("alice", channelId, privateMessage)+ const dmId: string = await seedDm("alice", userId("bob"))await seedDmMessage("alice", dmId, privateMessage)- })+ return { coldRootStorageKey, installColdRootProbe, closeHeldContext, serverId, channelId, dmId, serverName, channelName, channelMessageId, privateMessage }+ }- test("cold mobile paths reuse only their URL-owned skeleton modules", async ({ asUser }, testInfo) => {+ test("cold mobile paths reuse only their URL-owned skeleton modules", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { closeHeldContext, serverId, channelId, dmId, serverName, channelName, privateMessage } = await prepareCase1(actors, caseResources)+const cases: Array<[string, ExpectedFrame]> = [["/c", { route: "community-root-redirect", surface: "neutral", sidebar: "none", main: "route-resolution" }],["/c/me", { route: "me-root", surface: "list", sidebar: "me", main: "me-root" }],@@ -229,7 +234,7 @@ test.describe.serial("community initial-load module skeletons", () => {for (const [pathname, expected] of cases) {const { context, page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })- const gate = await holdApplicationScripts(page)+ const gate = await holdApplicationScripts(page, caseResources)const traffic = captureCommunityTraffic(page)await page.goto(pathname, { waitUntil: "commit" })await expect.poll(gate.hits).toBeGreaterThan(0)@@ -247,8 +252,13 @@ test.describe.serial("community initial-load module skeletons", () => {}})- test("desktop cold frames retain all route-owned shell columns", async ({ asUser }, testInfo) => {+ test("desktop cold frames retain all route-owned shell columns", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { closeHeldContext, serverId, channelId, dmId, serverName, channelName, privateMessage } = await prepareCase1(actors, caseResources)+for (const [pathname, expected] of [["/c", { route: "community-root-redirect", surface: "neutral", sidebar: "none", main: "route-resolution" }],[`/c/me/${dmId}`, { route: "dm-detail", surface: "detail", sidebar: "me", main: "dm" }],@@ -257,7 +267,7 @@ test.describe.serial("community initial-load module skeletons", () => {] satisfies Array<[string, ExpectedFrame]>) {const { context, page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })- const gate = await holdApplicationScripts(page)+ const gate = await holdApplicationScripts(page, caseResources)const traffic = captureCommunityTraffic(page)await page.goto(pathname, { waitUntil: "commit" })await expect.poll(gate.hits).toBeGreaterThan(0)@@ -275,8 +285,13 @@ test.describe.serial("community initial-load module skeletons", () => {}})- test("Android cold root restores channel, DM, and Bots without any Machines DOM", async ({ asUser }) => {+ test("Android cold root restores channel, DM, and Bots without any Machines DOM", async ({ caseActors, caseResources }) => {test.setTimeout(180_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { installColdRootProbe, serverId, channelId, dmId, serverName, channelName, privateMessage } = await prepareCase1(actors, caseResources)+const cases = [{destination: `/c/channels/${serverId}/${channelId}`,@@ -296,7 +311,7 @@ test.describe.serial("community initial-load module skeletons", () => {const { context, page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })await installColdRootProbe(page, destination)- const gate = await holdApplicationScripts(page)+ const gate = await holdApplicationScripts(page, caseResources)await page.goto("/c", { waitUntil: "commit" })await expect.poll(gate.hits).toBeGreaterThan(0)expect(gate.sessionRequests()).toBe(0)@@ -313,15 +328,19 @@ test.describe.serial("community initial-load module skeletons", () => {await expect(ready(page)).toBeVisible({ timeout: 30_000 })expect(await page.evaluate(() => history.length)).toBe(historyLength)await expectNoMachinesDuringColdRootRestore(page)- await context.close()+ await caseResources.closeContext(context)}})- test("Android cold root falls back to Machines only without valid account memory", async ({ asUser }) => {+ test("Android cold root falls back to Machines only without valid account memory", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { installColdRootProbe, serverName, channelName, privateMessage } = await prepareCase1(actors, caseResources)+const { page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })await installColdRootProbe(page, null)- const gate = await holdApplicationScripts(page)+ const gate = await holdApplicationScripts(page, caseResources)await page.goto("/c", { waitUntil: "commit" })await expect.poll(gate.hits).toBeGreaterThan(0)expect(gate.sessionRequests()).toBe(0)@@ -339,12 +358,16 @@ test.describe.serial("community initial-load module skeletons", () => {expect(await page.evaluate(() => history.length)).toBe(historyLength)})- test("a stale cold-root DM is replaced by the verified Machines fallback", async ({ asUser }) => {+ test("a stale cold-root DM is replaced by the verified Machines fallback", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { coldRootStorageKey, installColdRootProbe, serverName, channelName, privateMessage } = await prepareCase1(actors, caseResources)+const { page } = await asUser("alice")const missingDm = `/c/me/dm_missing_${Date.now()}`await page.setViewportSize({ width: 390, height: 844 })await installColdRootProbe(page, missingDm)- const gate = await holdApplicationScripts(page)+ const gate = await holdApplicationScripts(page, caseResources)await page.goto("/c", { waitUntil: "commit" })await expect.poll(gate.hits).toBeGreaterThan(0)expect(gate.sessionRequests()).toBe(0)@@ -365,15 +388,20 @@ test.describe.serial("community initial-load module skeletons", () => {.toBe("/c/me/machines")})- test("639↔640 preserves one route-owned skeleton main node with zero request or socket delta", async ({ asUser }) => {+ test("639↔640 preserves one route-owned skeleton main node with zero request or socket delta", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { closeHeldContext, serverId, channelId, dmId } = await prepareCase1(actors, caseResources)+for (const [pathname, mainKind] of [[`/c/me/${dmId}`, "dm"],[`/c/channels/${serverId}/${channelId}`, "server-conversation"],] as const) {const { context, page } = await asUser("alice")await page.setViewportSize({ width: 639, height: 844 })- const gate = await holdApplicationScripts(page)+ const gate = await holdApplicationScripts(page, caseResources)await page.goto(pathname, { waitUntil: "commit" })await expect.poll(gate.hits).toBeGreaterThan(0)expect(gate.sessionRequests()).toBe(0)@@ -398,11 +426,16 @@ test.describe.serial("community initial-load module skeletons", () => {}})- test("releasing scripts mounts one server-seeded user shell without duplicate route work", async ({ asUser }) => {+ test("releasing scripts mounts one server-seeded user shell without duplicate route work", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, serverName, channelName, channelMessageId, privateMessage } = await prepareCase1(actors, caseResources)+const { page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })- const gate = await holdApplicationScripts(page)+ const gate = await holdApplicationScripts(page, caseResources)const traffic = captureCommunityTraffic(page)await page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })await expect.poll(gate.hits).toBeGreaterThan(0)diff --git a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.tsindex b4c0541b7..f6f1cdf7c 100644--- a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts+++ b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts@@ -1,26 +1,23 @@import type { Page } from "@playwright/test"-import {- expect,- test,- userId,- userName,-} from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"-import {- seedChannel,- seedDm,- seedDmMessage,- seedFriendship,- seedJoinServer,- seedMessage,- seedServer,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import {communityFrameEvents,proxyCommunityWebSockets,type CapturedCommunityFrame,} from "./_fixtures/community-ws-proxy"+import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { userId } = actors+ function identityEvents(frames: CapturedCommunityFrame[], subjectId: string) {+ return frames.flatMap(communityFrameEvents).filter((event) => (event.type === "community:identity.update"+ && event.userId === subjectId))+ }+ return { identityEvents }+}type AvatarUpload = {status: number@@ -30,19 +27,13 @@ type AvatarUpload = {const hideDevelopmentOverlays = "nextjs-portal, .tsqd-parent-container { display: none !important; }"-function deferred() {+function deferred(caseResources: CaseResources) {let resolve!: () => voidconst promise = new Promise<void>((done) => { resolve = done })+ caseResources.own(resolve, async (captured) => { captured() })return { promise, resolve }}-function identityEvents(frames: CapturedCommunityFrame[], subjectId: string) {- return frames.flatMap(communityFrameEvents).filter((event) => (- event.type === "community:identity.update"- && event.userId === subjectId- ))-}-async function uploadSolidAvatar(page: Page, color: string): Promise<AvatarUpload> {return page.evaluate(async (fill) => {const canvas = document.createElement("canvas")@@ -83,8 +74,14 @@ async function expectPhoto(locator: ReturnType<Page["locator"]>, url: string) {)), { timeout: 20_000 }).toBe(true)}-test("versioned avatars converge across live, stale, reconnect, cold, and concurrent clients", async ({ asUser }, testInfo) => {+test("versioned avatars converge across live, stale, reconnect, cold, and concurrent clients", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)++ const actors = await caseActors(["alice", "bob", "dave"])+ const { asUser, userId, userName } = actors+ const { seedChannel, seedDm, seedDmMessage, seedFriendship, seedJoinServer, seedMessage, seedServer } = actors.seed+ const { identityEvents } = await prepareCase(actors)+const stamp = Date.now()const aliceId = userId("alice")const serverId = await seedServer("alice", `Avatar identity ${stamp}`)@@ -136,8 +133,8 @@ test("versioned avatars converge across live, stale, reconnect, cold, and concurconst warmImage = await message.locator(`img[src="${warm.url}"]`).first().elementHandle()if (!warmImage) throw new Error("Warm identity image is missing")- const profileGate = deferred()- const profileStarted = deferred()+ const profileGate = deferred(caseResources)+ const profileStarted = deferred(caseResources)const profilePattern = `**/api/community/users/${aliceId}/profile`await observer.page.route(profilePattern, async (route) => {const staleResponse = await route.fetch()@@ -154,8 +151,8 @@ test("versioned avatars converge across live, stale, reconnect, cold, and concurexpect(first.url).toBe(`/api/community/users/${aliceId}/avatar?v=${first.avatarVersion}`)await expect.poll(() => observerWs.heldCount(), { timeout: 20_000 }).toBe(1)- const avatarGate = deferred()- const avatarStarted = deferred()+ const avatarGate = deferred(caseResources)+ const avatarStarted = deferred(caseResources)const avatarPattern = `**/api/community/users/${aliceId}/avatar?v=*`await observer.page.route(avatarPattern, async (route) => {if (new URL(route.request().url()).searchParams.get("v") !== String(first.avatarVersion + 1)) {diff --git a/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts b/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.tsindex dd12d4cff..6e318cb9e 100644--- a/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts+++ b/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts@@ -1,8 +1,9 @@import type { Page } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, installInputCapability } from "./_fixtures/actions"-import { seedChannel, seedDm, seedMessage, seedServer, seedThread } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"const PNG_1X1 = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",@@ -36,25 +37,26 @@ function composerAttachments(page: Page) {return page.getByTestId(tid.composerInput).locator("../..")}-test.describe.serial("same-tab Community attachment drafts", () => {- let serverId: string- let channelAId: string- let channelBId: string- let openerId: string- let threadId: string- let dmId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `attachment-drafts-${Date.now()}`)- channelAId = await seedChannel("alice", serverId, "attachment-draft-a")- channelBId = await seedChannel("alice", serverId, "attachment-draft-b")- openerId = await seedMessage("alice", channelAId, "attachment draft thread opener")- threadId = await seedThread("alice", openerId, "attachment-draft-thread")- dmId = await seedDm("alice", userId("bob"))- })+test.describe("same-tab Community attachment drafts", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId } = actors+ const { seedChannel, seedDm, seedMessage, seedServer, seedThread } = actors.seed+ const serverId: string = await seedServer("alice", `attachment-drafts-${Date.now()}`)+ const channelAId: string = await seedChannel("alice", serverId, "attachment-draft-a")+ const channelBId: string = await seedChannel("alice", serverId, "attachment-draft-b")+ const openerId: string = await seedMessage("alice", channelAId, "attachment draft thread opener")+ const threadId: string = await seedThread("alice", openerId, "attachment-draft-thread")+ const dmId: string = await seedDm("alice", userId("bob"))+ return { serverId, channelAId, channelBId, openerId, threadId, dmId }+ }- test("desktop restores scoped real image/file drafts, rebuilds URLs, and removal never revives", async ({ asUser }) => {+ test("desktop restores scoped real image/file drafts, rebuilds URLs, and removal never revives", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelAId, channelBId, openerId, threadId, dmId } = await prepareCase1(actors)+const { page } = await asUser("alice")const channelA = `/c/channels/${serverId}/${channelAId}`await page.goto(channelA, { waitUntil: "commit" })@@ -147,8 +149,13 @@ test.describe.serial("same-tab Community attachment drafts", () => {expect(messagePosts).toBe(0)})- test("desktop restored generic file survives upload failure, retries once, and never revives", async ({ asUser }) => {+ test("desktop restored generic file survives upload failure, retries once, and never revives", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelAId, channelBId } = await prepareCase1(actors)+const { page } = await asUser("alice")const channelA = `/c/channels/${serverId}/${channelAId}`await page.goto(channelA, { waitUntil: "commit" })@@ -210,8 +217,13 @@ test.describe.serial("same-tab Community attachment drafts", () => {await expect(composerAttachments(page).getByText("retry-restored.txt", { exact: true })).toHaveCount(0)})- test("mobile restores scoped attachments, sends explicitly once, and reload restores text only", async ({ asUser }) => {+ test("mobile restores scoped attachments, sends explicitly once, and reload restores text only", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelAId, channelBId } = await prepareCase1(actors)+const { page } = await asUser("alice")await installInputCapability(page, false)await page.setViewportSize({ width: 390, height: 844 })diff --git a/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts b/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.tsindex 6cf36d64d..7214dc9b7 100644--- a/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts+++ b/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts@@ -1,17 +1,9 @@import type { Locator, Page } from "@playwright/test"-import { expect, test, userId } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"-import {- seedChannel,- seedDm,- seedDmMessage,- seedJoinServer,- seedMessage,- seedReaction,- seedServer,- seedThread,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"const HOVER_QUERY = "(hover: hover) and (pointer: fine)"const OVERFLOW_EMOJIS = ["👍", "🔥", "🎉", "✅", "🚀", "👀", "❤️", "😂", "🤔"] as const@@ -103,41 +95,39 @@ async function swipeDialogBodyWithoutStartingMessageReply(page: Page, messageId:await expect(page.getByTestId(tid.reactionDialog(messageId))).toBeVisible()}-test.describe.serial("mobile reaction details", () => {- let serverId: string- let channelId: string- let messageId: string- let messageContent: string- let emptyMessageId: string- let threadId: string- let threadOpenerId: string- let dmId: string- let dmMessageId: string-- test.beforeAll(async () => {+test.describe("mobile reaction details", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedJoinServer, seedMessage, seedReaction, seedServer, seedThread } = actors.seedconst stamp = Date.now()- serverId = await seedServer("alice", `Reaction details ${stamp}`)- channelId = await seedChannel("alice", serverId, `reactions-${stamp}`)+ const serverId: string = await seedServer("alice", `Reaction details ${stamp}`)+ const channelId: string = await seedChannel("alice", serverId, `reactions-${stamp}`)await seedJoinServer("alice", "bob", serverId)await seedJoinServer("alice", "carol", serverId)- messageContent = `Hold a reaction ${stamp} — ${"long message preview ".repeat(8).trim()}`- messageId = await seedMessage("alice", channelId, messageContent)+ const messageContent: string = `Hold a reaction ${stamp} — ${"long message preview ".repeat(8).trim()}`+ const messageId: string = await seedMessage("alice", channelId, messageContent)await seedReaction("alice", messageId, "👍")await seedReaction("bob", messageId, "👍")await seedReaction("bob", messageId, "🔥")await seedReaction("carol", messageId, "🎉")- for (const emoji of OVERFLOW_EMOJIS.slice(3)) await seedReaction("alice", messageId, emoji)- emptyMessageId = await seedMessage("alice", channelId, `Empty reactions ${stamp}`)+ for (const emoji of OVERFLOW_EMOJIS.slice(3))+ await seedReaction("alice", messageId, emoji)+ const emptyMessageId: string = await seedMessage("alice", channelId, `Empty reactions ${stamp}`)await seedReaction("alice", emptyMessageId, "✅")- threadOpenerId = await seedMessage("alice", channelId, `Thread opener reactions ${stamp}`)+ const threadOpenerId: string = await seedMessage("alice", channelId, `Thread opener reactions ${stamp}`)await seedReaction("bob", threadOpenerId, "👍")- threadId = await seedThread("alice", threadOpenerId, `Reaction thread ${stamp}`)- dmId = await seedDm("alice", userId("bob"))- dmMessageId = await seedDmMessage("alice", dmId, `DM reactions ${stamp}`)+ const threadId: string = await seedThread("alice", threadOpenerId, `Reaction thread ${stamp}`)+ const dmId: string = await seedDm("alice", userId("bob"))+ const dmMessageId: string = await seedDmMessage("alice", dmId, `DM reactions ${stamp}`)await seedReaction("bob", dmMessageId, "👍")- })+ return { serverId, channelId, messageId, messageContent, emptyMessageId, threadId, threadOpenerId, dmId, dmMessageId }+ }++ test("hold opens one authorized batch dialog while tap keeps the canonical toggle", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { serverId, channelId, messageId, messageContent } = await prepareCase1(actors)- test("hold opens one authorized batch dialog while tap keeps the canonical toggle", async ({ asUser }, testInfo) => {const alice = await asUser("alice")await alice.page.setViewportSize({ width: 390, height: 844 })await alice.page.emulateMedia({ colorScheme: "light" })@@ -201,7 +191,11 @@ test.describe.serial("mobile reaction details", () => {expect(detailsRequests).toHaveLength(1)})- test("coarse input follows the 320, 639, 640, and 1280 cross-capability geometry", async ({ asUser }) => {+ test("coarse input follows the 320, 639, 640, and 1280 cross-capability geometry", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId, messageId } = await prepareCase1(actors)+for (const width of [320, 639, 640, 1280]) {const session = await asUser("alice")await session.page.setViewportSize({ width, height: width === 320 ? 568 : 844 })@@ -214,11 +208,15 @@ test.describe.serial("mobile reaction details", () => {await expect.poll(async () => Math.min(...await tabs.evaluateAll((items) => items.map((item) => item.getBoundingClientRect().height),))).toBeGreaterThanOrEqual(44)- await session.context.close()+ await caseResources.closeContext(session.context)}})- test("the emoji rail switches displayed reactors without mutating reactions", async ({ asUser }, testInfo) => {+ test("the emoji rail switches displayed reactors without mutating reactions", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { serverId, channelId, messageId } = await prepareCase1(actors)+const alice = await asUser("alice")await alice.page.setViewportSize({ width: 320, height: 568 })await alice.page.emulateMedia({ colorScheme: "light" })@@ -325,7 +323,11 @@ test.describe.serial("mobile reaction details", () => {})})- test("hover-capable desktop keeps compact click and tooltip behavior", async ({ asUser }, testInfo) => {+ test("hover-capable desktop keeps compact click and tooltip behavior", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId, messageId } = await prepareCase1(actors)+const alice = await asUser("alice")await alice.page.setViewportSize({ width: 1280, height: 900 })await installInputCapability(alice.page, true)@@ -345,7 +347,11 @@ test.describe.serial("mobile reaction details", () => {expect(height).toBeLessThan(44)})- test("the shared thread opener opens the same mobile dialog", async ({ asUser }, testInfo) => {+ test("the shared thread opener opens the same mobile dialog", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, threadId, threadOpenerId } = await prepareCase1(actors)+const alice = await asUser("alice")await alice.page.setViewportSize({ width: 390, height: 844 })await alice.page.emulateMedia({ colorScheme: "light" })@@ -362,7 +368,11 @@ test.describe.serial("mobile reaction details", () => {})})- test("DM and message-context rows open the same authorized reaction dialog", async ({ asUser }) => {+ test("DM and message-context rows open the same authorized reaction dialog", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { serverId, channelId, messageId, dmId, dmMessageId } = await prepareCase1(actors)+const dm = await asUser("alice")await dm.page.setViewportSize({ width: 390, height: 844 })await installInputCapability(dm.page, false)@@ -372,7 +382,7 @@ test.describe.serial("mobile reaction details", () => {await clickDialogBodyWithoutOpeningMessageMenu(dm.page, dmMessageId)await expect(dm.page.getByTestId(tid.reactionMember(userId("bob")))).toBeVisible()await dm.page.getByRole("button", { name: "Close" }).click()- await dm.context.close()+ await caseResources.closeContext(dm.context)const context = await asUser("alice")await context.page.setViewportSize({ width: 390, height: 844 })@@ -385,7 +395,11 @@ test.describe.serial("mobile reaction details", () => {await clickDialogBodyWithoutOpeningMessageMenu(context.page, messageId)})- test("removing the last reaction keeps the dialog open on its empty state", async ({ asUser }, testInfo) => {+ test("removing the last reaction keeps the dialog open on its empty state", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser } = actors+ const { serverId, channelId, emptyMessageId } = await prepareCase1(actors)+const alice = await asUser("alice")await alice.page.setViewportSize({ width: 390, height: 844 })await alice.page.emulateMedia({ colorScheme: "light" })diff --git a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.tsindex 5e0a9f03d..67cae9530 100644--- a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts+++ b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts@@ -1,13 +1,8 @@-import { expect, test } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { composerEditable } from "./_fixtures/actions"-import {- seedChannel,- seedForumThread,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"const THREAD_PANEL_MIN_WIDTH = 360const THREAD_PANEL_MAX_WIDTH = 800@@ -28,31 +23,27 @@ async function resizeThreadPanel(page: import("@playwright/test").Page, targetWiawait page.mouse.up()}-test.describe.serial("desktop thread split view", () => {- let serverId: string- let textChannelId: string- let threadId: string- let forumId: string- let forumPostId: string- let parentBody: string- let threadBody: string- let forumTitle: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `Split view ${Date.now()}`)- textChannelId = await seedChannel("alice", serverId, "split-parent")- parentBody = `parent opener ${Date.now()}`+test.describe("desktop thread split view", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedChannel, seedForumThread, seedMessage, seedServer, seedThread } = actors.seed+ const serverId: string = await seedServer("alice", `Split view ${Date.now()}`)+ const textChannelId: string = await seedChannel("alice", serverId, "split-parent")+ const parentBody: string = `parent opener ${Date.now()}`const openerId = await seedMessage("alice", textChannelId, parentBody)- threadId = await seedThread("alice", openerId, "Focused thread")- threadBody = `thread reply ${Date.now()}`+ const threadId: string = await seedThread("alice", openerId, "Focused thread")+ const threadBody: string = `thread reply ${Date.now()}`await seedMessage("alice", threadId, threadBody)+ const forumId: string = await seedChannel("alice", serverId, "split-forum", "forum")+ const forumTitle: string = `Forum post ${Date.now()}`+ const forumPostId: string = await seedForumThread("alice", forumId, forumTitle, "Forum reply")+ return { serverId, textChannelId, threadId, forumId, forumPostId, parentBody, threadBody, forumTitle }+ }- forumId = await seedChannel("alice", serverId, "split-forum", "forum")- forumTitle = `Forum post ${Date.now()}`- forumPostId = await seedForumThread("alice", forumId, forumTitle, "Forum reply")- })+ test("resizes the thread panel within limits and restores the user layout", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, textChannelId, threadId, parentBody, threadBody } = await prepareCase1(actors)- test("resizes the thread panel within limits and restores the user layout", async ({ asUser }) => {const { page } = await asUser("alice")await page.setViewportSize({ width: 1600, height: 900 })await page.goto(`/c/channels/${serverId}/${threadId}`)@@ -90,8 +81,14 @@ test.describe.serial("desktop thread split view", () => {.toBe(savedWidth)})- test("keeps parent and thread live, supports fullscreen/close, and falls back below the width threshold", async ({ asUser }, testInfo) => {+ test("keeps parent and thread live, supports fullscreen/close, and falls back below the width threshold", async ({ caseActors }, testInfo) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedMessage } = actors.seed+ const { serverId, textChannelId, threadId, parentBody, threadBody } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })await page.goto(`/c/channels/${serverId}/${threadId}`)@@ -175,13 +172,18 @@ test.describe.serial("desktop thread split view", () => {await testInfo.attach("390-dark-full", { path: mobileDark, contentType: "image/png" })})- test("opens forum posts in the same desktop split contract", async ({ asUser }, testInfo) => {+ test("opens forum posts in the same desktop split contract", async ({ caseActors, caseResources }, testInfo) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, forumId, forumPostId, forumTitle } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })await page.goto(`/c/channels/${serverId}/${forumId}`)await expect(page.getByTestId(tid.forumThreadCard(forumPostId))).toBeVisible()let releaseMetadata!: () => voidconst metadataGate = new Promise<void>((resolve) => { releaseMetadata = resolve })+ caseResources.own(releaseMetadata, async (captured) => { captured() })const metadataPath = `/api/community/channels/${forumPostId}`const metadataUrl = (url: URL) => url.pathname === metadataPathconst holdMetadata = async (route: import("@playwright/test").Route) => {@@ -238,11 +240,16 @@ test.describe.serial("desktop thread split view", () => {await testInfo.attach("1280-light-forum-split", { path: forumSplit, contentType: "image/png" })})- test("keeps a cold parent placeholder until its own metadata is readable", async ({ asUser }) => {+ test("keeps a cold parent placeholder until its own metadata is readable", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, forumId, forumPostId } = await prepareCase1(actors)+const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })let releaseMetadata!: () => voidconst metadataGate = new Promise<void>((resolve) => { releaseMetadata = resolve })+ caseResources.own(releaseMetadata, async (captured) => { captured() })const metadataPath = `/api/community/channels/${forumId}`const metadataUrl = (url: URL) => url.pathname === metadataPathawait page.route(metadataUrl, async (route) => {@@ -267,8 +274,14 @@ test.describe.serial("desktop thread split view", () => {}})- test("retains the forum scroll node and resized group across a held post switch", async ({ asUser }) => {+ test("retains the forum scroll node and resized group across a held post switch", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedForumThread } = actors.seed+ const { serverId, forumId, forumPostId } = await prepareCase1(actors)+for (let index = 0; index < 12; index++) {await seedForumThread("alice", forumId, `Split filler ${index}`, `Filler reply ${index}`)}@@ -293,6 +306,7 @@ test.describe.serial("desktop thread split view", () => {if (!group || !listNode) throw new Error("Forum split nodes are unavailable")let releaseMetadata!: () => voidconst metadataGate = new Promise<void>((resolve) => { releaseMetadata = resolve })+ caseResources.own(releaseMetadata, async (captured) => { captured() })const metadataPath = `/api/community/channels/${forumPostId}`const metadataUrl = (url: URL) => url.pathname === metadataPathawait page.route(metadataUrl, async (route) => {@@ -323,8 +337,14 @@ test.describe.serial("desktop thread split view", () => {}})- test("retains the text parent draft and scroll while child drafts stay separate", async ({ asUser }) => {+ test("retains the text parent draft and scroll while child drafts stay separate", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedMessage, seedThread } = actors.seed+ const { serverId, textChannelId } = await prepareCase1(actors)+for (let index = 0; index < 35; index++) {await seedMessage("alice", textChannelId, `Parent scroll row ${index}`)}@@ -358,6 +378,7 @@ test.describe.serial("desktop thread split view", () => {if (!group || !scrollNode || !inputNode) throw new Error("Text split nodes are unavailable")let releaseMetadata!: () => voidconst metadataGate = new Promise<void>((resolve) => { releaseMetadata = resolve })+ caseResources.own(releaseMetadata, async (captured) => { captured() })const metadataPath = `/api/community/channels/${childB}`const metadataUrl = (url: URL) => url.pathname === metadataPathawait page.route(metadataUrl, async (route) => {diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-android.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-android.spec.tsindex 86f00f926..e6103ebcf 100644--- a/src/web/src/test/e2e-ui/46-community-loading-geometry-android.spec.ts+++ b/src/web/src/test/e2e-ui/46-community-loading-geometry-android.spec.ts@@ -1,4 +1,4 @@-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { expectUniqueSsrInitialFrame } from "./_fixtures/community-ssr-frame"import { tid } from "./_fixtures/testids"import {@@ -6,14 +6,19 @@ import {runSkeletonLoadingMotion,} from "./_fixtures/community-loading-geometry"-test.describe.serial("community Android loading geometry", () => {- test("Android Chrome/WebView keep parsed SSR layouts mobile before application JS and through hydration", async ({ asUser }, testInfo) => {+test.describe("community Android loading geometry", () => {+ test("Android Chrome/WebView keep parsed SSR layouts mobile before application JS and through hydration", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)- await runAndroidLoadingGeometry(asUser, testInfo)++ const actors = await caseActors(["alice"])++ await runAndroidLoadingGeometry(actors, caseResources, testInfo)})- test("community skeleton pulse changes only opacity and stops for reduced motion", async ({ asUser }) => {- await runSkeletonLoadingMotion(asUser)+ test("community skeleton pulse changes only opacity and stops for reduced motion", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice"])++ await runSkeletonLoadingMotion(actors, caseResources)})})diff --git a/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts b/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.tsindex 9506fbb2f..e46f18055 100644--- a/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts+++ b/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts@@ -1,6 +1,6 @@import { readFileSync } from "node:fs"import type { Page, Request } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"import { tid } from "./_fixtures/testids"@@ -110,7 +110,10 @@ async function expectUpdateActionGeometry(.toBeLessThanOrEqual(1)}-test("Update, Inbox, and viewer Profile share one desktop User Bar pop-up", async ({ asUser }) => {+test("Update, Inbox, and viewer Profile share one desktop User Bar pop-up", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+const { page } = await asUser("alice")const requests = await serveMachines(page)await page.emulateMedia({ reducedMotion: "reduce" })@@ -238,7 +241,10 @@ test("Update, Inbox, and viewer Profile share one desktop User Bar pop-up", asynwrites.stop()})-test("partial dispatch retries only failed eligible Machines and clears from live Machine data", async ({ asUser }) => {+test("partial dispatch retries only failed eligible Machines and clears from live Machine data", async ({ caseActors }) => {+ const actors = await caseActors(["bob"])+ const { asUser } = actors+const { context, page } = await asUser("bob")const ws = await proxyCommunityWebSockets(context)const secondMachine = {diff --git a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.tsindex e2d2b9469..e55821b42 100644--- a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts+++ b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts@@ -1,8 +1,24 @@import type { Page } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"-import { seedChannel, seedForumThread, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { seedChannel, seedForumThread, seedServer } = actors.seed+ async function seedForum(label: string) {+ const serverId = await seedServer("alice", `${label} ${Date.now()}`)+ const forumId = await seedChannel("alice", serverId, "tag-editor", "forum")+ const threadId = await seedForumThread("alice", forumId, `Post ${Date.now()}`, "tag editor body")+ return {+ route: `/c/channels/${serverId}/${forumId}`,+ forumId,+ threadId,+ }+ }+ return { seedForum }+}function observeTagPuts(page: Page): string[] {const writes: string[] = []@@ -13,15 +29,17 @@ function observeTagPuts(page: Page): string[] {return writes}-async function gateNextTagPut(page: Page) {+async function gateNextTagPut(page: Page, caseResources: CaseResources) {let release!: () => voidlet sawRequest!: () => voidconst gate = new Promise<void>((resolve) => {release = resolve})+ caseResources.own(release, async (captured) => { captured() })const requested = new Promise<void>((resolve) => {sawRequest = resolve})+ caseResources.own(sawRequest, async (captured) => { captured() })await page.route("**/api/community/messages/*/tags", async (routeRequest) => {const response = await routeRequest.fetch()sawRequest()@@ -31,19 +49,22 @@ async function gateNextTagPut(page: Page) {return { release, requested }}-async function gateNextForumFeedResponse(page: Page) {+async function gateNextForumFeedResponse(page: Page, caseResources: CaseResources) {let release!: () => voidlet sawResponse!: () => voidlet finished!: () => voidconst gate = new Promise<void>((resolve) => {release = resolve})+ caseResources.own(release, async (captured) => { captured() })const captured = new Promise<void>((resolve) => {sawResponse = resolve})+ caseResources.own(sawResponse, async (captured) => { captured() })const delivered = new Promise<void>((resolve) => {finished = resolve})+ caseResources.own(finished, async (captured) => { captured() })await page.route(/\/api\/community\/channels\/[^/]+\/threads\?/, async (routeRequest) => {const response = await routeRequest.fetch()sawResponse()@@ -54,17 +75,6 @@ async function gateNextForumFeedResponse(page: Page) {return { release, captured, delivered }}-async function seedForum(label: string) {- const serverId = await seedServer("alice", `${label} ${Date.now()}`)- const forumId = await seedChannel("alice", serverId, "tag-editor", "forum")- const threadId = await seedForumThread("alice", forumId, `Post ${Date.now()}`, "tag editor body")- return {- route: `/c/channels/${serverId}/${forumId}`,- forumId,- threadId,- }-}-async function openEditor(page: Page, threadId: string) {await page.getByTestId(tid.forumThreadCard(threadId)).hover()const trigger = page.getByTestId(tid.forumThreadTagBtn(threadId))@@ -83,8 +93,17 @@ async function addDraft(page: Page, tag: string) {)}-test.describe.serial("forum tag editor", () => {- test("keeps Archived out of the tag editor and toggles it from the row action", async ({ asUser }, testInfo) => {+test.describe("forum tag editor", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedForum } = await prepareCase(actors)+ return { seedForum }+ }++ test("keeps Archived out of the tag editor and toggles it from the row action", async ({ caseActors, caseResources }, testInfo) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedForum } = await prepareCase1(actors)+const { route, threadId } = await seedForum("Archived row action")const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })@@ -116,7 +135,7 @@ test.describe.serial("forum tag editor", () => {body: await page.screenshot(),contentType: "image/png",})- const archiveGate = await gateNextTagPut(page)+ const archiveGate = await gateNextTagPut(page, caseResources)const archivedSave = page.waitForResponse((response) => (response.request().method() === "PUT"&& new URL(response.url()).pathname.endsWith("/tags")@@ -163,7 +182,7 @@ test.describe.serial("forum tag editor", () => {contentType: "image/png",})await page.emulateMedia({ colorScheme: "light" })- const unarchiveGate = await gateNextTagPut(page)+ const unarchiveGate = await gateNextTagPut(page, caseResources)const restoredSave = page.waitForResponse((response) => (response.request().method() === "PUT"&& new URL(response.url()).pathname.endsWith("/tags")@@ -184,7 +203,11 @@ test.describe.serial("forum tag editor", () => {expect(writes).toHaveLength(4)})- test("keeps a cancelled stale feed response behind the active archive generation", async ({ asUser }) => {+ test("keeps a cancelled stale feed response behind the active archive generation", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedForum } = await prepareCase1(actors)+const { route, threadId } = await seedForum("Archive stale feed fence")const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })@@ -192,7 +215,7 @@ test.describe.serial("forum tag editor", () => {const card = page.getByTestId(tid.forumThreadCard(threadId))await expect(card).toBeVisible()- const staleFeed = await gateNextForumFeedResponse(page)+ const staleFeed = await gateNextForumFeedResponse(page, caseResources)await openEditor(page, threadId)await addDraft(page, "stale-source")const ordinarySave = page.waitForResponse((response) => (@@ -219,7 +242,11 @@ test.describe.serial("forum tag editor", () => {await expect(card).toHaveCount(0)})- test("converges Archive and Unarchive across two tabs", async ({ asUser }) => {+ test("converges Archive and Unarchive across two tabs", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedForum } = await prepareCase1(actors)+const { route, forumId, threadId } = await seedForum("Archive cross tab")const tabA = await asUser("alice")const tabB = await asUser("alice")@@ -281,7 +308,11 @@ test.describe.serial("forum tag editor", () => {}})- test("discards implicit close and commits only explicit Save", async ({ asUser }) => {+ test("discards implicit close and commits only explicit Save", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedForum } = await prepareCase1(actors)+const { route, threadId } = await seedForum("Mobile explicit save")const { page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })@@ -328,7 +359,11 @@ test.describe.serial("forum tag editor", () => {expect(writes).toHaveLength(1)})- test("keeps the row archive state after failure and retries once", async ({ asUser }) => {+ test("keeps the row archive state after failure and retries once", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedForum } = await prepareCase1(actors)+const { route, threadId } = await seedForum("Archive action retry")const { page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })@@ -340,9 +375,11 @@ test.describe.serial("forum tag editor", () => {const failureGate = new Promise<void>((resolve) => {releaseFailure = resolve})+ caseResources.own(releaseFailure, async (captured) => { captured() })const failureRequested = new Promise<void>((resolve) => {sawFailureRequest = resolve})+ caseResources.own(sawFailureRequest, async (captured) => { captured() })await page.route("**/api/community/messages/*/tags", async (routeRequest) => {if (rejectNext) {rejectNext = false@@ -392,7 +429,11 @@ test.describe.serial("forum tag editor", () => {expect(writes).toHaveLength(2)})- test("preserves one session across both breakpoint directions without transition writes", async ({ asUser }) => {+ test("preserves one session across both breakpoint directions without transition writes", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedForum } = await prepareCase1(actors)+const { route, threadId } = await seedForum("Responsive tag session")const { page } = await asUser("alice")await page.setViewportSize({ width: 639, height: 844 })@@ -456,7 +497,11 @@ test.describe.serial("forum tag editor", () => {expect(writes).toHaveLength(1)})- test("retains the draft after a failed Save and retries once", async ({ asUser }) => {+ test("retains the draft after a failed Save and retries once", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedForum } = await prepareCase1(actors)+const { route, threadId } = await seedForum("Tag save retry")const { page } = await asUser("alice")await page.setViewportSize({ width: 390, height: 844 })diff --git a/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts b/src/web/src/test/e2e-ui/51-share-image-assets.spec.tsindex fccea60e4..933ee71e4 100644--- a/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts+++ b/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts@@ -1,9 +1,9 @@import { createServer } from "node:http"import type { AddressInfo } from "node:net"-import { expect, test } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import type { Locator, Page } from "@playwright/test"import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"-import { createInvite, seedChannel, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"type CaptureKind = "clipboard" | "download"@@ -383,8 +383,13 @@ function sampleCenter(card: Locator, selector: string): Promise<SamplePoint> {}, selector)}-test("share image timestamp matches the live row and survives both exports", async ({ asUser }) => {+test("share image timestamp matches the live row and survives both exports", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Share timestamp ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "share-timestamp")const { page } = await asUser("alice")@@ -437,8 +442,13 @@ test("share image timestamp matches the live row and survives both exports", asyawait composerEditable(page).fill("")})-test("mobile routing waits for native copy and save terminal receipts", async ({ asUser }) => {+test("mobile routing waits for native copy and save terminal receipts", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Mobile share receipt ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "mobile-share-receipt")const { page } = await asUser("alice")@@ -474,8 +484,13 @@ test("mobile routing waits for native copy and save terminal receipts", async ({])})-test("a loaded two-frame GIF is frozen to a displayed frame and reused by both exports", async ({ asUser }) => {+test("a loaded two-frame GIF is frozen to a displayed frame and reused by both exports", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Animated share ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "animated-share")const { page } = await asUser("alice")@@ -521,8 +536,13 @@ test("a loaded two-frame GIF is frozen to a displayed frame and reused by both eexpect(assetRequests).toEqual([])})-test("loaded avatar and content prepare and export without requesting or decoding source assets again", async ({ asUser }, testInfo) => {+test("loaded avatar and content prepare and export without requesting or decoding source assets again", async ({ caseActors }, testInfo) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { createInvite, seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Share byte session ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "share-byte-session")const inviteToken = await createInvite("alice", serverId)@@ -655,8 +675,13 @@ test("loaded avatar and content prepare and export without requesting or decodinexpect(await frozenCard.innerHTML()).toBe(frozenMarkup)})-test("loaded cross-origin pixels without CORS require the explicit fetch fallback", async ({ asUser }) => {+test("loaded cross-origin pixels without CORS require the explicit fetch fallback", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Cross-origin share ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "cross-origin-share")const { page } = await asUser("alice")@@ -673,14 +698,20 @@ test("loaded cross-origin pixels without CORS require the explicit fetch fallbac})response.end(bytes)})+ const ownedOrigin = caseResources.own(origin, async (captured) => {+ captured.closeAllConnections()+ await new Promise<void>((resolve, reject) => captured.close((error) => error ? reject(error) : resolve()))+ })await new Promise<void>((resolve) => origin.listen(0, "127.0.0.1", resolve))+ let caseJourneyFailure1: unknown+let caseJourneyFailure1Present = falsetry {const sourceUrl = `http://127.0.0.1:${(origin.address() as AddressInfo).port}/protected.png`const message = await seedMessage(page, channelId, ``)const row = page.getByTestId(tid.message(message.id))const image = row.locator('img[alt="Protected cross-origin"]')await row.hover()- await waitForLoadedImages(row)+ await waitForLoadedImages(row)const original = await image.elementHandle()expect(original).not.toBeNull()const readability = await image.evaluate((source: HTMLImageElement) => {@@ -718,14 +749,22 @@ test("loaded cross-origin pixels without CORS require the explicit fetch fallbacexpect(copied.pixel[0]).toBeLessThan(80)await page.keyboard.press("Escape")expect(await original!.evaluate((source) => source.isConnected && (source as HTMLImageElement).complete)).toBe(true)- } finally {- origin.closeAllConnections()- await new Promise<void>((resolve, reject) => origin.close((error) => error ? reject(error) : resolve()))+ } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {+ try {++ await ownedOrigin.close()++ } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }}})-test("cold preparation disables export until the held avatar bytes are ready", async ({ asUser }) => {+test("cold preparation disables export until the held avatar bytes are ready", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Cold share ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "cold-share")const { page } = await asUser("alice")@@ -737,6 +776,7 @@ test("cold preparation disables export until the held avatar bytes are ready", alet release!: () => voidconst gate = new Promise<void>((resolve) => { release = resolve })+ caseResources.own(release, async (captured) => { captured() })let heldRequests = 0await page.route("**/api/community/users/*/avatar*", async (avatarRoute) => {if (avatarRoute.request().method() === "GET") {@@ -766,8 +806,13 @@ test("cold preparation disables export until the held avatar bytes are ready", aexpect(await captureCounts(page)).toEqual({ clipboard: 1, download: 0 })})-test("closing cold preparation suppresses output and reopening starts a fresh session", async ({ asUser }) => {+test("closing cold preparation suppresses output and reopening starts a fresh session", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Share close ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "share-close")const { page } = await asUser("alice")@@ -779,6 +824,7 @@ test("closing cold preparation suppresses output and reopening starts a fresh selet release!: () => voidconst gate = new Promise<void>((resolve) => { release = resolve })+ caseResources.own(release, async (captured) => { captured() })let heldRequests = 0const avatarPattern = "**/api/community/users/*/avatar*"await page.route(avatarPattern, async (avatarRoute) => {@@ -809,8 +855,13 @@ test("closing cold preparation suppresses output and reopening starts a fresh seawait expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 0 })})-test("loaded live avatar stays mounted through share selection and dialog close", async ({ asUser }) => {+test("loaded live avatar stays mounted through share selection and dialog close", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Share avatar identity ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "share-avatar-identity")const { page } = await asUser("alice")@@ -849,8 +900,13 @@ test("loaded live avatar stays mounted through share selection and dialog close"await page.keyboard.press("Escape")})-test("stalled avatar falls back and a single text message exports", async ({ asUser }) => {+test("stalled avatar falls back and a single text message exports", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Share avatar timeout ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "share-timeout")const { page } = await asUser("alice")@@ -860,6 +916,7 @@ test("stalled avatar falls back and a single text message exports", async ({ asUawait expect(page.getByTestId(tid.message(message.id)).locator('[data-slot="avatar-image"]')).toBeVisible()let release!: () => voidconst blocked = new Promise<void>((resolve) => { release = resolve })+ caseResources.own(release, async (captured) => { captured() })const pattern = "**/api/community/users/*/avatar*"await page.route(pattern, async (route) => {await blocked@@ -884,8 +941,13 @@ test("stalled avatar falls back and a single text message exports", async ({ asU}})-test("avatar failure is deterministic while content-image failure is atomic and retryable", async ({ asUser }) => {+test("avatar failure is deterministic while content-image failure is atomic and retryable", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Share failures ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "share-failures")const { page } = await asUser("alice")@@ -935,8 +997,13 @@ test("avatar failure is deterministic while content-image failure is atomic andawait expect(card.getByTestId(tid.messageShareImage(contentMessage.id, 0))).toHaveAttribute("src", /^data:image\//)})-test("clipboard failure releases retry and Download keeps first-winner ownership", async ({ asUser }) => {+test("clipboard failure releases retry and Download keeps first-winner ownership", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Share retry ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "share-retry")const { page } = await asUser("alice")@@ -968,8 +1035,13 @@ test("clipboard failure releases retry and Download keeps first-winner ownershipawait expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 1 })})-test("light and dark desktop and narrow previews match their frozen full PNG", async ({ asUser }) => {+test("light and dark desktop and narrow previews match their frozen full PNG", async ({ caseActors }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+const serverId = await seedServer("alice", `Share matrix ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "share-matrix")const { page } = await asUser("alice")diff --git a/src/web/src/test/e2e-ui/52-chat-composer-ordered-list.spec.ts b/src/web/src/test/e2e-ui/52-chat-composer-ordered-list.spec.tsindex 5b479b2d9..cd600c281 100644--- a/src/web/src/test/e2e-ui/52-chat-composer-ordered-list.spec.ts+++ b/src/web/src/test/e2e-ui/52-chat-composer-ordered-list.spec.ts@@ -1,5 +1,5 @@import type { Locator, Page, TestInfo } from "@playwright/test"-import { test, expect, userId } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import {composerEditable,gotoAfterUserWsAuth,@@ -11,14 +11,9 @@ import {proxyCommunityWebSockets,type CapturedCommunityFrame,} from "./_fixtures/community-ws-proxy"-import {- seedChannel,- seedDm,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors } from "./_fixtures/case-fixture"type MessageResponse = {message: { id: string; channelId: string; content: string }@@ -79,25 +74,25 @@ async function typeCanonicalMarker(return editable}-test.describe.serial("chat composer ordered-list continuation", () => {- let serverId: string- let channelAId: string- let channelBId: string- let forumId: string- let threadId: string- let dmId: string-- test.beforeAll(async () => {- serverId = await seedServer("alice", `composer-lists-${Date.now()}`)- channelAId = await seedChannel("alice", serverId, "composer-lists-a")- channelBId = await seedChannel("alice", serverId, "composer-lists-b")- forumId = await seedChannel("alice", serverId, "composer-lists-forum", "forum")+test.describe("chat composer ordered-list continuation", () => {+ async function prepareCase1(actors: CaseActors) {+ const { userId } = actors+ const { seedChannel, seedDm, seedMessage, seedServer, seedThread } = actors.seed+ const serverId: string = await seedServer("alice", `composer-lists-${Date.now()}`)+ const channelAId: string = await seedChannel("alice", serverId, "composer-lists-a")+ const channelBId: string = await seedChannel("alice", serverId, "composer-lists-b")+ const forumId: string = await seedChannel("alice", serverId, "composer-lists-forum", "forum")const openerId = await seedMessage("alice", channelAId, "ordered-list thread opener")- threadId = await seedThread("alice", openerId, "ordered-list-thread")- dmId = await seedDm("alice", userId("bob"))- })+ const threadId: string = await seedThread("alice", openerId, "ordered-list-thread")+ const dmId: string = await seedDm("alice", userId("bob"))+ return { serverId, channelAId, channelBId, forumId, threadId, dmId }+ }++ test("desktop nests with official list keys and commits exact numbered text", async ({ caseActors }, testInfo: TestInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelAId } = await prepareCase1(actors)- test("desktop nests with official list keys and commits exact numbered text", async ({ asUser }, testInfo: TestInfo) => {const { page, context } = await asUser("alice")await installInputCapability(page, true)const proxy = await proxyCommunityWebSockets(context)@@ -145,7 +140,11 @@ test.describe.serial("chat composer ordered-list continuation", () => {await expect(page.getByTestId(tid.message(messageId))).toContainText("sibling")})- test("touch Enter continues and exits while only the send button commits", async ({ asUser }, testInfo: TestInfo) => {+ test("touch Enter continues and exits while only the send button commits", async ({ caseActors }, testInfo: TestInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelAId } = await prepareCase1(actors)+const { page, context } = await asUser("alice", { viewport: { width: 390, height: 844 } })await installInputCapability(page, false)const proxy = await proxyCommunityWebSockets(context)@@ -186,7 +185,11 @@ test.describe.serial("chat composer ordered-list continuation", () => {expect(posts).toBe(1)})- test("child thread and DM commits stay in their exact channel scope", async ({ asUser }) => {+ test("child thread and DM commits stay in their exact channel scope", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, threadId, dmId } = await prepareCase1(actors)+const { page, context } = await asUser("alice")await installInputCapability(page, true)const proxy = await proxyCommunityWebSockets(context)@@ -211,7 +214,11 @@ test.describe.serial("chat composer ordered-list continuation", () => {}})- test("draft, undo, IME, plain paste, and forum-body boundaries remain stable", async ({ asUser }) => {+ test("draft, undo, IME, plain paste, and forum-body boundaries remain stable", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelAId, channelBId, forumId } = await prepareCase1(actors)+const { page } = await asUser("alice")await installInputCapability(page, true)let messagePosts = 0diff --git a/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts b/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.tsindex 00412bd8c..cfb59a0ea 100644--- a/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts+++ b/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts@@ -1,7 +1,7 @@import type { Locator, Page } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"-import { seedChannel, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"type ContextMenuProbe = {@@ -92,7 +92,11 @@ async function dismissContextMenu(page: Page) {await page.waitForTimeout(150)}-test("Community owns ordinary context menus and preserves native exceptions", async ({ asUser }) => {+test("Community owns ordinary context menus and preserves native exceptions", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedMessage, seedServer } = actors.seed+const serverId = await seedServer("alice", `Context policy ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "context-policy")const messageId = await seedMessage("alice", channelId, `Context policy row ${Date.now()}`)@@ -155,7 +159,10 @@ test("Community owns ordinary context menus and preserves native exceptions", asexpect(writes).toEqual([])})-test("public, auth, and invite routes remain browser owned", async ({ page, asUser }) => {+test("public, auth, and invite routes remain browser owned", async ({ page, caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+const invitePath = "/c/invite/not-a-real-token"let inviteDocuments = 0page.on("request", request => {diff --git a/src/web/src/test/e2e-ui/56-retired-workspace-links.spec.ts b/src/web/src/test/e2e-ui/56-retired-workspace-links.spec.tsindex 023d4c13f..caae23890 100644--- a/src/web/src/test/e2e-ui/56-retired-workspace-links.spec.ts+++ b/src/web/src/test/e2e-ui/56-retired-workspace-links.spec.ts@@ -1,5 +1,5 @@import type { Page } from "@playwright/test"-import { test, expect } from "./_fixtures/community-fixture"+import { test, expect } from "./_fixtures/case-fixture"const deletedRoutes = ["/w", "/w/sample/home", "/w/sample.name/home", "/w/sample/agents/a/chat/b", "/workspaces", "/studio/new", "/invite/not-a-community-token"]@@ -20,7 +20,10 @@ async function expectDeletedFrontend(page: Page) {expect(legacyRequests).toEqual([])}-test("authenticated deleted workspace links return ordinary 404s without legacy API calls", async ({ asUser }) => {+test("authenticated deleted workspace links return ordinary 404s without legacy API calls", async ({ caseActors }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+const { page } = await asUser("alice")await expectDeletedFrontend(page)})diff --git a/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts b/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.tsindex 643f0c5ec..114201132 100644--- a/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts+++ b/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts@@ -1,10 +1,37 @@import type { Page, WebSocket } from "@playwright/test"-import { expect, sessionCookie, test, userId } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth, openServer } from "./_fixtures/actions"-import { seedChannel, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"import type { UserKey } from "./_setup/users"+import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { sessionCookie } = actors+ const { seedChannel, seedServer } = actors.seed+ async function serverIds(key: UserKey): Promise<string[]> {+ const response = await fetch(`${WEB_URL}/api/community/servers`, {+ headers: { Cookie: sessionCookie(key), Origin: WEB_URL },+ })+ expect(response.status).toBe(200)+ const body = await response.json() as {+ servers: Array<{+ id: string+ }>+ }+ return body.servers.map((server) => server.id)+ }+ async function seedServerRoute(key: UserKey, name: string): Promise<{+ serverId: string+ channelId: string+ }> {+ const serverId = await seedServer(key, name)+ const channelId = await seedChannel(key, serverId, `${name} channel`, "text")+ return { serverId, channelId }+ }+ return { serverIds, seedServerRoute }+}type Deferred<T> = {promise: Promise<T>@@ -34,15 +61,6 @@ function deferred<T>(): Deferred<T> {return { promise, resolve }}-async function serverIds(key: UserKey): Promise<string[]> {- const response = await fetch(`${WEB_URL}/api/community/servers`, {- headers: { Cookie: sessionCookie(key), Origin: WEB_URL },- })- expect(response.status).toBe(200)- const body = await response.json() as { servers: Array<{ id: string }> }- return body.servers.map((server) => server.id)-}-async function firstTextChannelId(page: Page, serverId: string): Promise<string> {const response = await page.request.get(`/api/community/servers/${serverId}/channels`,@@ -68,15 +86,6 @@ async function openChannelRoute(await expect(page).toHaveURL(pathname)}-async function seedServerRoute(- key: UserKey,- name: string,-): Promise<{ serverId: string; channelId: string }> {- const serverId = await seedServer(key, name)- const channelId = await seedChannel(key, serverId, `${name} channel`, "text")- return { serverId, channelId }-}-async function clickDeleteServer(page: Page,serverId: string,@@ -94,9 +103,11 @@ async function clickDeleteServer(}).click()}-async function delayDelete(page: Page, serverId: string) {+async function delayDelete(page: Page, serverId: string, caseResources: CaseResources) {const release = deferred<void>()+ caseResources.own(release, async (captured) => { captured.resolve() })const intercepted = deferred<void>()+ caseResources.own(intercepted, async (captured) => { captured.resolve() })const pattern = `**/api/community/servers/${serverId}`await page.route(pattern, async (route) => {if (route.request().method() !== "DELETE") {@@ -109,7 +120,7 @@ async function delayDelete(page: Page, serverId: string) {})const response = page.waitForResponse((candidate) => (candidate.request().method() === "DELETE"- && new URL(candidate.url()).pathname === `/api/community/servers/${serverId}`+ && new URL(candidate.url()).pathname === `/api/community/servers/${serverId}`))await clickDeleteServer(page, serverId)await intercepted.promise@@ -120,9 +131,11 @@ async function delayDelete(page: Page, serverId: string) {}}-async function delayServerRsc(page: Page, serverId: string) {+async function delayServerRsc(page: Page, serverId: string, caseResources: CaseResources) {const release = deferred<void>()+ caseResources.own(release, async (captured) => { captured.resolve() })const intercepted = deferred<void>()+ caseResources.own(intercepted, async (captured) => { captured.resolve() })const pattern = "**/c/channels/**"await page.route(pattern, async (route) => {const url = new URL(route.request().url())@@ -196,9 +209,13 @@ async function expectServerLeaf(page: Page, serverId: string): Promise<string> {return new URL(page.url()).pathname}-test.describe.configure({ mode: "serial" })-test("deleting the only Server replaces once to Home", async ({ asUser }) => {++test("deleting the only Server replaces once to Home", async ({ caseActors }) => {+ const actors = await caseActors(["sole-delete"])+ const { asUser, userId } = actors+ const { serverIds, seedServerRoute } = await prepareCase(actors)+const key = "sole-delete"expect(await serverIds(key)).toEqual([])const route = await seedServerRoute(key, `delete-only-${Date.now()}`)@@ -224,6 +241,8 @@ test("deleting the only Server replaces once to Home", async ({ asUser }) => {})expect((await response).status()).toBe(204)+ const deleteResponse = await response+ await actors.recordServerDeletion(key, route.serverId, { page, response: deleteResponse })await expect(page).toHaveURL("/c/me")await expect(page.getByTestId(tid.serverIcon(route.serverId))).toHaveCount(0)await expect(page.getByText("Server deleted", { exact: true })).toBeVisible()@@ -235,7 +254,11 @@ for (const testCase of [{ key: "alice" as const, name: "computed target", chooseUserRoute: (ids: string[]) => ids[0] },{ key: "bob" as const, name: "different safe route", chooseUserRoute: (ids: string[]) => ids[1] },]) {- test(`a committed ${testCase.name} wins before DELETE success with no later history write`, async ({ asUser }) => {+ test(`a committed ${testCase.name} wins before DELETE success with no later history write`, async ({ caseActors, caseResources }) => {+ const actors = await caseActors([testCase.key])+ const { asUser } = actors+ const { serverIds, seedServerRoute } = await prepareCase(actors)+const stamp = Date.now()const survivorA = await seedServerRoute(testCase.key, `survivor-a-${stamp}`)const survivorB = await seedServerRoute(testCase.key, `survivor-b-${stamp}`)@@ -251,7 +274,7 @@ for (const testCase of [expect(survivors).toContain(survivorB.serverId)const userServerId = testCase.chooseUserRoute(survivors)expect(userServerId).toBeTruthy()- const deletion = await delayDelete(page, deleted.serverId)+ const deletion = await delayDelete(page, deleted.serverId, caseResources)await openServer(page, userServerId)const safePathname = await expectServerLeaf(page, userServerId)@@ -259,6 +282,8 @@ for (const testCase of [deletion.release()expect((await deletion.response).status()).toBe(204)+ const deleteResponse = await deletion.response+ await actors.recordServerDeletion(testCase.key, deleted.serverId, { page, response: deleteResponse })await expect(page).toHaveURL(safePathname)await expect(page.getByTestId(tid.serverIcon(deleted.serverId))).toHaveCount(0)await expect(page.getByText("Server deleted", { exact: true })).toHaveCount(0)@@ -267,7 +292,11 @@ for (const testCase of [})}-test("slow target RSC survives delete/list/WS convergence and lands on its remembered Channel", async ({ asUser }) => {+test("slow target RSC survives delete/list/WS convergence and lands on its remembered Channel", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["carol"])+ const { asUser } = actors+ const { serverIds, seedServerRoute } = await prepareCase(actors)+const stamp = Date.now()const ensuredSurvivor = await seedServerRoute("carol", `slow-target-${stamp}`)const deleted = await seedServerRoute("carol", `slow-deleted-${stamp}`)@@ -286,7 +315,7 @@ test("slow target RSC survives delete/list/WS convergence and lands on its rememconst targetPathname = await expectServerLeaf(page, targetServerId!)await expect(page.getByTestId(tid.composerInput)).toBeVisible()await openServer(page, deleted.serverId)- const targetRsc = await delayServerRsc(page, targetServerId!)+ const targetRsc = await delayServerRsc(page, targetServerId!, caseResources)const response = page.waitForResponse((candidate) => (candidate.request().method() === "DELETE"&& new URL(candidate.url()).pathname === `/api/community/servers/${deleted.serverId}`@@ -295,6 +324,8 @@ test("slow target RSC survives delete/list/WS convergence and lands on its rememawait clickDeleteServer(page, deleted.serverId)expect((await response).status()).toBe(204)+ const deleteResponse = await response+ await actors.recordServerDeletion("carol", deleted.serverId, { page, response: deleteResponse })await targetRsc.interceptedexpect(new URL(page.url()).pathname).not.toBe("/c/me")targetRsc.release()@@ -303,7 +334,11 @@ test("slow target RSC survives delete/list/WS convergence and lands on its rememawait targetRsc.cleanup()})-test("a newer user navigation wins while the delete target RSC is pending", async ({ asUser }) => {+test("a newer user navigation wins while the delete target RSC is pending", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["dave"])+ const { asUser } = actors+ const { serverIds, seedServerRoute } = await prepareCase(actors)+const stamp = Date.now()const candidateA = await seedServerRoute("dave", `queued-target-a-${stamp}`)const candidateB = await seedServerRoute("dave", `queued-target-b-${stamp}`)@@ -322,7 +357,7 @@ test("a newer user navigation wins while the delete target RSC is pending", asynawait openServer(page, targetServerId!)await expectServerLeaf(page, targetServerId!)await openServer(page, deleted.serverId)- const targetRsc = await delayServerRsc(page, targetServerId!)+ const targetRsc = await delayServerRsc(page, targetServerId!, caseResources)const response = page.waitForResponse((candidate) => (candidate.request().method() === "DELETE"&& new URL(candidate.url()).pathname === `/api/community/servers/${deleted.serverId}`@@ -331,6 +366,8 @@ test("a newer user navigation wins while the delete target RSC is pending", asynawait clickDeleteServer(page, deleted.serverId)expect((await response).status()).toBe(204)+ const deleteResponse = await response+ await actors.recordServerDeletion("dave", deleted.serverId, { page, response: deleteResponse })await targetRsc.interceptedawait page.getByTestId(tid.serverIcon(userRoute!.serverId)).click()targetRsc.release()@@ -341,7 +378,11 @@ test("a newer user navigation wins while the delete target RSC is pending", asynawait targetRsc.cleanup()})-test("a Back visit after terminal cleanup is an ordinary missing route", async ({ asUser }) => {+test("a Back visit after terminal cleanup is an ordinary missing route", async ({ caseActors, caseResources }) => {+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedServerRoute } = await prepareCase(actors)+const stamp = Date.now()const survivor = await seedServerRoute("alice", `terminal-survivor-${stamp}`)const deleted = await seedServerRoute("alice", `terminal-deleted-${stamp}`)@@ -350,12 +391,14 @@ test("a Back visit after terminal cleanup is an ordinary missing route", async (page,`/c/channels/${deleted.serverId}/${deleted.channelId}`,)- const deletion = await delayDelete(page, deleted.serverId)+ const deletion = await delayDelete(page, deleted.serverId, caseResources)await openServer(page, survivor.serverId)const safePathname = await expectServerLeaf(page, survivor.serverId)deletion.release()expect((await deletion.response).status()).toBe(204)+ const deleteResponse = await deletion.response+ await actors.recordServerDeletion("alice", deleted.serverId, { page, response: deleteResponse })await expect(page).toHaveURL(safePathname)await expect(page.getByTestId(tid.serverIcon(deleted.serverId))).toHaveCount(0)await expect(page.getByText("Server deleted", { exact: true })).toHaveCount(0)@@ -366,7 +409,11 @@ test("a Back visit after terminal cleanup is an ordinary missing route", async (await deletion.cleanup()})-test("a failed DELETE keeps the current route and emits no success frame", async ({ asUser }) => {+test("a failed DELETE keeps the current route and emits no success frame", async ({ caseActors }) => {+ const actors = await caseActors(["carol"])+ const { asUser } = actors+ const { serverIds, seedServerRoute } = await prepareCase(actors)+const route = await seedServerRoute("carol", `failed-delete-${Date.now()}`)const page = (await asUser("carol")).pageconst deletes = captureServerDeletes(page)diff --git a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts b/src/web/src/test/e2e-ui/58-system-notifications.spec.tsindex 81bcdf3a8..07d99998c 100644--- a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts+++ b/src/web/src/test/e2e-ui/58-system-notifications.spec.ts@@ -1,7 +1,7 @@import type { Page } from "@playwright/test"-import { expect, test, userName } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"-import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"type Activation = {@@ -117,8 +117,12 @@ async function retriedNotifications(page: Page) {).__desktopNotificationTest.retryActivations)}-test.describe.serial("desktop system notifications", () => {- test("a delivered message+bump bundle invokes the native command with the exact target", async ({ asUser }) => {+test.describe("desktop system notifications", () => {+ test("a delivered message+bump bundle invokes the native command with the exact target", async ({ caseActors }) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userName } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+const stamp = Date.now()const serverName = `notification-live-${stamp}`const channelName = `notification-live-${stamp}`@@ -147,8 +151,13 @@ test.describe.serial("desktop system notifications", () => {])})- test("a cold activation starts ordinary conversation navigation without a document reload", async ({ asUser }) => {+ test("a cold activation starts ordinary conversation navigation without a document reload", async ({ caseActors }) => {test.setTimeout(90_000)++ 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", `notification-cold-${stamp}`)const channelId = await seedChannel("alice", serverId, `notification-cold-${stamp}`)@@ -169,7 +178,11 @@ test.describe.serial("desktop system notifications", () => {expect(await bob.page.evaluate(() => (window as typeof window & { __desktopNotificationTest: {documentLoads:number} }).__desktopNotificationTest.documentLoads)).toBe(1)})- test("activation starts its target checkpoint before a slow permission response", async ({ asUser }) => {+ test("activation starts its target checkpoint before a slow permission response", async ({ caseActors, caseResources }) => {+ 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", `notification-delayed-${stamp}`)const channelId = await seedChannel("alice", serverId, `notification-delayed-${stamp}`)@@ -180,6 +193,7 @@ test.describe.serial("desktop system notifications", () => {await gotoAfterUserWsAuth(bob.page, "/c/me/friends")let release!: () => voidconst pending = new Promise<void>((resolve) => { release = resolve })+ caseResources.own(release, async (captured) => { captured() })let permissionHeld = falseawait bob.page.route(`**/api/community/channels/${channelId}`, async route => {permissionHeld = truediff --git a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.tsindex 6f3744a68..00eb6541b 100644--- a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts+++ b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts@@ -1,8 +1,26 @@import type { Page, Route } from "@playwright/test"-import { test, expect, sessionCookie } from "./_fixtures/community-fixture"-import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"+import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"++async function prepareCase(actors: CaseActors) {+ const { sessionCookie } = actors+ async function setReadCheckpoint(channelId: string, messageId: string): Promise<void> {+ const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {+ method: "PUT",+ headers: {+ Cookie: sessionCookie("alice"),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({ lastReadMessageId: messageId }),+ })+ expect(response.ok).toBe(true)+ }+ return { setReadCheckpoint }+}const VIEWPORT = { width: 1280, height: 800 }@@ -57,25 +75,14 @@ async function readMessageOffset(page: Page, messageId: string): Promise<number}, messageId)}-async function setReadCheckpoint(channelId: string, messageId: string): Promise<void> {- const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {- method: "PUT",- headers: {- Cookie: sessionCookie("alice"),- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: JSON.stringify({ lastReadMessageId: messageId }),- })- expect(response.ok).toBe(true)-}--async function holdNextPage(page: Page, channelId: string, param: "cursor" | "since") {+async function holdNextPage(page: Page, channelId: string, param: "cursor" | "since", caseResources: CaseResources) {let release!: () => voidlet resolveMatched!: () => voidlet consumed = falseconst gate = new Promise<void>((resolve) => { release = resolve })+ caseResources.own(release, async (captured) => { captured() })const matched = new Promise<void>((resolve) => { resolveMatched = resolve })+ caseResources.own(resolveMatched, async (captured) => { captured() })const pattern = `**/api/community/channels/${channelId}/messages**`const handler = async (route: Route) => {const url = new URL(route.request().url())@@ -112,8 +119,14 @@ function expectAnchorPreserved(before: Geometry, retainedOffset: number | null,).toBeLessThanOrEqual(1)}-test("older and newer pages preserve a real-message anchor and do not replay", async ({ asUser }, testInfo) => {+test("older and newer pages preserve a real-message anchor and do not replay", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedMessage, seedServer } = actors.seed+ const { setReadCheckpoint } = await prepareCase(actors)+const stamp = Date.now()const serverId = await seedServer("alice", `Pagination anchor ${stamp}`)await seedJoinServer("alice", "bob", serverId)@@ -138,7 +151,7 @@ test("older and newer pages preserve a real-message anchor and do not replay", a})await olderUser.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })await expect(olderUser.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })- const olderPage = await holdNextPage(olderUser.page, channelId, "cursor")+ const olderPage = await holdNextPage(olderUser.page, channelId, "cursor", caseResources)await moveToEdge(olderUser.page, "start")await olderPage.matchedconst olderBefore = await waitForStableGeometry(olderUser.page)@@ -160,7 +173,7 @@ test("older and newer pages preserve a real-message anchor and do not replay", a})await newerUser.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })await expect(newerUser.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })- const newerPage = await holdNextPage(newerUser.page, channelId, "since")+ const newerPage = await holdNextPage(newerUser.page, channelId, "since", caseResources)await moveToEdge(newerUser.page, "end")await newerPage.matchedconst newerBefore = await waitForStableGeometry(newerUser.page)diff --git a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.tsindex ccf0b7112..813d1e07f 100644--- a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts+++ b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts@@ -1,18 +1,10 @@import type { Page, Request, Route, TestInfo } from "@playwright/test"-import { expect, test, userId } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth, waitForElementMotion } from "./_fixtures/actions"import { COMMUNITY_LAYOUT_STORAGE_KEY } from "@/components/community/shell/shell-frame-geometry"-import {- memberInfo,- seedCancelFriendRequest,- seedChannel,- seedJoinServer,- seedMark,- seedMessage,- seedPendingFriendRequest,- seedServer,-} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"const layoutStorageKey = COMMUNITY_LAYOUT_STORAGE_KEYconst expectedDefaultSidebarWidth = 317@@ -137,9 +129,10 @@ async function installLayoutState(})}-async function holdApplicationScripts(page: Page) {+async function holdApplicationScripts(page: Page, caseResources: CaseResources) {let release!: () => voidconst gate = new Promise<void>((resolve) => { release = resolve })+ caseResources.own(release, async (captured) => { captured() })let hits = 0let sessionRequests = 0page.on("request", (request) => {@@ -158,9 +151,10 @@ async function holdApplicationScripts(page: Page) {return { hits: () => hits, sessionRequests: () => sessionRequests, release }}-async function holdCommunityReads(page: Page) {+async function holdCommunityReads(page: Page, caseResources: CaseResources) {let release!: () => voidconst gate = new Promise<void>((resolve) => { release = resolve })+ caseResources.own(release, async (captured) => { captured() })let hits = 0await page.route("**/api/community/**", async (route) => {if (route.request().method() !== "GET") {@@ -379,20 +373,22 @@ async function attachJson(testInfo: TestInfo, name: string, value: unknown) {})}-test.describe.serial("desktop default User Bar width", () => {- let serverId: string- let channelId: string-- test.beforeAll(async () => {+test.describe("desktop default User Bar width", () => {+ async function prepareCase1(actors: CaseActors) {+ const { seedChannel, seedServer } = actors.seedconst stamp = Date.now()- serverId = await seedServer("alice", `Desktop width ${stamp}`)- channelId = await seedChannel("alice", serverId, `desktop-width-${stamp}`)- })+ const serverId: string = await seedServer("alice", `Desktop width ${stamp}`)+ const channelId: string = await seedChannel("alice", serverId, `desktop-width-${stamp}`)+ return { serverId, channelId }+ }- test("prepaints saved pending-shell widths and preserves the loaded handoff", async ({- asUser,- }, testInfo) => {+ test("prepaints saved pending-shell widths and preserves the loaded handoff", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const evidence: Array<{targetWidth: numbersavedLayout: { sidebar: number; main: number }@@ -411,8 +407,8 @@ test.describe.serial("desktop default User Bar width", () => {: targetWidth / availablePanelWidth * 100const savedLayout = { sidebar, main: 100 - sidebar }await installLayoutState(page, savedLayout, 2_000)- const scripts = await holdApplicationScripts(page)- const communityReads = await holdCommunityReads(page)+ const scripts = await holdApplicationScripts(page, caseResources)+ const communityReads = await holdCommunityReads(page, caseResources)await page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })await expect.poll(scripts.hits).toBeGreaterThan(0)@@ -433,7 +429,7 @@ test.describe.serial("desktop default User Bar width", () => {Reflect.get(window, "__desktopWidthSamples") as LayoutSample[])))evidence.push({ targetWidth, savedLayout, sequence })- await session.context.close()+ await caseResources.closeContext(session.context)}await attachJson(testInfo, "saved-pending-shell-frame-sequences", evidence)@@ -447,11 +443,13 @@ test.describe.serial("desktop default User Bar width", () => {}})- test("keeps unsaved, saved, and user-resized layouts pixel-stable", async ({- asUser,- }, testInfo) => {+ test("keeps unsaved, saved, and user-resized layouts pixel-stable", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(180_000)+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const fresh = await asUser("alice")await fresh.page.setViewportSize({ width: 1280, height: 900 })await installLayoutState(fresh.page, null)@@ -507,7 +505,7 @@ test.describe.serial("desktop default User Bar width", () => {await expectDesktopGeometry(fresh.page, expectedDefaultSidebarWidth)expect(await fresh.page.evaluate((key) => localStorage.getItem(key), layoutStorageKey)).toBeNull()- await fresh.context.close()+ await caseResources.closeContext(fresh.context)const mobileGeometry: Array<Record<string, unknown>> = []for (const viewport of [@@ -556,7 +554,7 @@ test.describe.serial("desktop default User Bar width", () => {layoutStorageKey,)).toBeNull()mobileGeometry.push({ viewport, ...geometry })- await mobile.context.close()+ await caseResources.closeContext(mobile.context)}const seededLayout = { sidebar: 25, main: 75 }@@ -659,10 +657,14 @@ test.describe.serial("desktop default User Bar width", () => {})})- test("keeps a populated Inbox free of horizontal overflow at the 100px floor", async ({- asUser,- }, testInfo) => {+ test("keeps a populated Inbox free of horizontal overflow at the 100px floor", async ({ caseActors }, testInfo) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob", "carol"])+ const { asUser, userId } = actors+ const { memberInfo, seedCancelFriendRequest, seedChannel, seedJoinServer, seedMark, seedMessage, seedPendingFriendRequest, seedServer } = actors.seed+ await prepareCase1(actors)+const stamp = Date.now()const longServerName = `Inbox width with a deliberately long server title ${stamp}`const longChannelName = `inbox-width-with-a-deliberately-long-channel-name-${stamp}`@@ -785,11 +787,13 @@ test.describe.serial("desktop default User Bar width", () => {}})- test("restores fresh and saved mobile-first desktop entries before paint", async ({- asUser,- }, testInfo) => {+ test("restores fresh and saved mobile-first desktop entries before paint", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)+ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId, channelId } = await prepareCase1(actors)+const runFreshSequence = async (widths: number[]) => {const session = await asUser("alice")const page = session.page@@ -840,7 +844,7 @@ test.describe.serial("desktop default User Bar width", () => {previousWidth = width}- await session.context.close()+ await caseResources.closeContext(session.context)return { widths, desktopPoints }}@@ -927,13 +931,16 @@ test.describe.serial("desktop default User Bar width", () => {storageWrites: savedStorageWrites,},})- await saved.context.close()+ await caseResources.closeContext(saved.context)})- test("captures closed, Inbox, Profile, update, and cold restore parity", async ({- asUser,- }, testInfo) => {+ test("captures closed, Inbox, Profile, update, and cold restore parity", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { serverId } = await prepareCase1(actors)+const focusRecords: Array<Record<string, unknown>> = []for (const width of [1024, 1280] as const) {@@ -1043,14 +1050,14 @@ test.describe.serial("desktop default User Bar width", () => {})expect(writes.writes).toEqual([])writes.stop()- await authenticated.context.close()+ await caseResources.closeContext(authenticated.context)const pending = await asUser("alice")await pending.page.setViewportSize({ width, height: width === 1024 ? 768 : 900 })await pending.page.emulateMedia({ colorScheme: theme })await installLayoutState(pending.page, null)- const scripts = await holdApplicationScripts(pending.page)- const communityReads = await holdCommunityReads(pending.page)+ const scripts = await holdApplicationScripts(pending.page, caseResources)+ const communityReads = await holdCommunityReads(pending.page, caseResources)await pending.page.goto(`/c/channels/${serverId}`, { waitUntil: "commit" })await expect.poll(scripts.hits).toBeGreaterThan(0)expect(scripts.sessionRequests()).toBe(0)@@ -1083,7 +1090,7 @@ test.describe.serial("desktop default User Bar width", () => {expect(await pending.page.evaluate((key) => localStorage.getItem(key), layoutStorageKey)).toBeNull()communityReads.release()- await pending.context.close()+ await caseResources.closeContext(pending.context)}}await attachJson(testInfo, "user-bar-focus-records", focusRecords)diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.tsindex 6653b4357..8db988ab3 100644--- a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts+++ b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts@@ -1,9 +1,10 @@import { devices, type Page } from "@playwright/test"-import { expect, test, sessionCookie, userId } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { composerEditable } from "./_fixtures/actions"-import { seedCategory, seedChannel, seedChannelMember, seedDm, seedDmMessage, seedFriendship, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"+import type { CaseActors } from "./_fixtures/case-fixture"type Activation = { notificationId: string; messageId: string; targetId: string }type Bridge = { pending: Activation | null; listener: unknown; takes: number; dismissed: string[]; visibility: DocumentVisibilityState; documentLoads: number }@@ -65,64 +66,67 @@ type MessageDoorEvidence = {payload: { id?: string; channelId?: string }}-async function captureMessageDoor(page: Page, targetId: string, messageId: string) {- let capture!: (evidence: MessageDoorEvidence) => void- let fail!: (error: unknown) => void- const result = new Promise<MessageDoorEvidence>((resolve, reject) => {- capture = resolve- fail = reject- })- await page.route((url) => url.pathname === `/api/community/messages/${messageId}`, async (route) => {- try {- const response = await route.fetch()- const payload = await response.json()- const evidence = { status: response.status(), payload }- if (response.ok()) expect(payload.channelId).toBe(targetId)- await route.fulfill({ response })- capture(evidence)- } catch (error) {- fail(error)- await route.abort()- }- })- return { result }-}--async function deleteAsAlice(path: string) {- const response = await fetch(`${WEB_URL}${path}`, { method: "DELETE", headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })- expect(response.ok, `${path}: ${response.status}`).toBeTruthy()-}--let serverId: string-let channelId: string-let channelMessageId: string-let dmId: string-let dmMessageId: string-let dmSeq: number-let channelSeq: number-test.describe("mobile notification chat routes (native bridge simulation)", () => {- test.beforeAll(async () => {- test.setTimeout(120_000)- serverId = await seedServer("alice", `mobile-route-${Date.now()}`)- channelId = await seedChannel("alice", serverId, "notification-chat")+ async function prepareCase1(actors: CaseActors) {+ async function deleteAsAlice(path: string) {+ const response = await fetch(`${WEB_URL}${path}`, { method: "DELETE", headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })+ expect(response.ok, `${path}: ${response.status}`).toBeTruthy()+ }+ async function captureMessageDoor(page: Page, targetId: string, messageId: string) {+ let capture!: (evidence: MessageDoorEvidence) => void+ let fail!: (error: unknown) => void+ const result = new Promise<MessageDoorEvidence>((resolve, reject) => {+ capture = resolve+ fail = reject+ })+ await page.route((url) => url.pathname === `/api/community/messages/${messageId}`, async (route) => {+ try {+ const response = await route.fetch()+ const payload = await response.json()+ const evidence = { status: response.status(), payload }+ if (response.ok())+ expect(payload.channelId).toBe(targetId)+ await route.fulfill({ response })+ capture(evidence)+ }+ catch (error) {+ fail(error)+ await route.abort()+ }+ })+ return { result }+ }+ const { sessionCookie, userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedFriendship, seedJoinServer, seedMessage, seedServer } = actors.seed+ const serverId: string = await seedServer("alice", `mobile-route-${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "notification-chat")await seedJoinServer("alice", "bob", serverId)- channelMessageId = await seedMessage("alice", channelId, "Channel notification route evidence")+ const channelMessageId: string = await seedMessage("alice", channelId, "Channel notification route evidence")await seedFriendship("alice", "bob", userId("bob"))- dmId = await seedDm("alice", userId("bob"))- dmMessageId = await seedDmMessage("alice", dmId, "DM notification route evidence")+ const dmId: string = await seedDm("alice", userId("bob"))+ const dmMessageId: string = await seedDmMessage("alice", dmId, "DM notification route evidence")const seqs = await Promise.all([[dmId, dmMessageId], [channelId, channelMessageId]].map(async ([targetId, messageId]) => {const response = await fetch(`${WEB_URL}/api/community/channels/${targetId}/messages?anchor=${messageId}&limit=1`, { headers: { Cookie: sessionCookie("bob") } })expect(response.status).toBe(200)- const payload = await response.json() as { messages: Array<{ id: string; seq: number }> }+ const payload = await response.json() as {+ messages: Array<{+ id: string+ seq: number+ }>+ }return payload.messages.find((message) => message.id === messageId)!.seq- }))- ;[dmSeq, channelSeq] = seqs- })+ }));+ const [dmSeq, channelSeq] = seqs+ return { deleteAsAlice, serverId, channelId, channelMessageId, dmId, dmMessageId, dmSeq, channelSeq, captureMessageDoor }+ }for (const mode of ["cold", "resume"] as const) {for (const surface of ["dm", "channel"] as const) {- test(`${mode} ${surface} opens chat without a context sheet`, async ({ asUser }, testInfo) => {+ test(`${mode} ${surface} opens chat without a context sheet`, async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, channelMessageId, dmId, dmMessageId, captureMessageDoor } = await prepareCase1(actors)+const { page } = await asUser("bob", devices["iPhone 13"])const targetId = surface === "dm" ? dmId : channelIdconst messageId = surface === "dm" ? dmMessageId : channelMessageId@@ -151,7 +155,12 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =}for (const kind of ["deleted", "revoked"] as const) {- test(`${kind} target shows an unavailable message page with the normal Inbox action`, async ({ asUser }, testInfo) => {+ test(`${kind} target shows an unavailable message page with the normal Inbox action`, async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedCategory, seedChannel, seedChannelMember, seedMessage } = actors.seed+ const { deleteAsAlice, serverId, captureMessageDoor } = await prepareCase1(actors)+const categoryId = kind === "revoked" ? await seedCategory("alice", serverId, `private-${Date.now()}`, { private: true }) : undefinedconst targetId = await seedChannel("alice", serverId, `${kind}-${Date.now()}`, "text", categoryId)if (kind === "revoked") await seedChannelMember("alice", targetId, userId("bob"))@@ -196,7 +205,11 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =}for (const surface of ["dm", "channel"] as const) {- test(`ordinary ${surface} seq permalink retains message context`, async ({ asUser }, testInfo) => {+ test(`ordinary ${surface} seq permalink retains message context`, async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, channelMessageId, dmId, dmMessageId, dmSeq, channelSeq } = await prepareCase1(actors)+const { page } = await asUser("bob", devices["iPhone 13"])const targetId = surface === "dm" ? dmId : channelIdconst messageId = surface === "dm" ? dmMessageId : channelMessageId@@ -221,7 +234,11 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =})}- test("ordinary channel msg permalink retains its message anchor", async ({ asUser }, testInfo) => {+ test("ordinary channel msg permalink retains its message anchor", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, channelMessageId } = await prepareCase1(actors)+const { page } = await asUser("bob", devices["iPhone 13"])const responsePromise = page.waitForResponse((response) => {const url = new URL(response.url())diff --git a/src/web/src/test/e2e-ui/65-analytics-document-boundary.spec.ts b/src/web/src/test/e2e-ui/65-analytics-document-boundary.spec.tsindex b6205a796..5bdad2fc2 100644--- a/src/web/src/test/e2e-ui/65-analytics-document-boundary.spec.ts+++ b/src/web/src/test/e2e-ui/65-analytics-document-boundary.spec.ts@@ -1,5 +1,5 @@import type { APIResponse, Locator, Page, Request, Route } from "@playwright/test"-import { expect, test } from "./_fixtures/community-fixture"+import { expect, test } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"async function expectDefaultAnalytics(page: Page) {@@ -125,9 +125,13 @@ test("a saved withdrawal replaces the public document once with the actual denie})for (const signedIn of [false, true]) {- test(`Home private entries replace the public document for signed-in=${signedIn}`, async ({ page: guest, asUser }) => {+ test(`Home private entries replace the public document for signed-in=${signedIn}`, async ({ page: guest, caseActors }) => {test.slow()- const page = signedIn ? (await asUser("alice")).page : guest++ const actors = signedIn ? await caseActors(["alice"]) : undefined+ const asUser = actors?.asUser++ const page = signedIn ? (await asUser!("alice")).page : guestif (signedIn) {await page.goto("/privacy?qa=entry#analytics-choices")await savePrivacyChoice(page, "granted", "denied")@@ -148,9 +152,13 @@ for (const signedIn of [false, true]) {}})- test(`Templates and Pricing private entries use document navigation for signed-in=${signedIn}`, async ({ page: guest, asUser }) => {+ test(`Templates and Pricing private entries use document navigation for signed-in=${signedIn}`, async ({ page: guest, caseActors }) => {test.slow()- const page = signedIn ? (await asUser("alice")).page : guest++ const actors = signedIn ? await caseActors(["alice"]) : undefined+ const asUser = actors?.asUser++ const page = signedIn ? (await asUser!("alice")).page : guestconst destination = signedIn ? "/c/me" : "/sign-in"if (signedIn) {await page.goto("/privacy?qa=entry#analytics-choices")diff --git a/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts b/src/web/src/test/e2e-ui/_fixtures/case-fixture.tsindex 8c6ef0095..e67f11f52 100644--- a/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts+++ b/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts@@ -1,4 +1,4 @@-import type { BrowserContext, BrowserContextOptions, Page, TestInfo } from "@playwright/test"+import type { APIResponse, BrowserContext, BrowserContextOptions, Page, Response as PlaywrightResponse, TestInfo } from "@playwright/test"import { createHash } from "crypto"import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"import { resolve } from "path"@@ -18,6 +18,21 @@ export type CaseActors = {sessionCookie: (key: UserKey) => stringseed: CaseSeedonCleanup: (operation: () => Promise<unknown>) => void+ confirmSignedOut: (role: UserKey, evidence: SignedOutEvidence) => Promise<void>+ recordServerDeletion: (role: UserKey, serverId: string, evidence: ServerDeletionEvidence) => Promise<void>+}++export type SignedOutEvidence = { context: BrowserContext; page: Page; protectedResponse: APIResponse }+export type ServerDeletionEvidence = { page: Page; response: PlaywrightResponse }+export type OwnedCaseResource<T> = { readonly value: T; close: () => Promise<void> }+export type CaseResources = {+ newContext: (options?: BrowserContextOptions) => Promise<BrowserContext>+ closeContext: (context: BrowserContext) => Promise<void>+ own: <T>(value: T, dispose: (value: T) => Promise<void>) => OwnedCaseResource<T>+}+type CaseExitOwner = {+ allocate: (roles: readonly UserKey[]) => Promise<CaseActors>+ resources: CaseResources}type CaseIdentity = {@@ -33,10 +48,14 @@ type CleanupFailure = {identity: CaseIdentityunresolvedServers: Array<{ owner: UserKey; id: string }>unresolvedContexts: ContextOwner[]+ unresolvedOperations: number+ pendingSessionRetirement: booleanerrorCount: number}-type ContextOwner = { role: UserKey; kind: "login" | "actor"; ordinal: number }+type ContextOwner = { role: UserKey | null; kind: "login" | "actor" | "anonymous"; ordinal: number }+type ServerDeletionProof = { request: string; status: 204; contextOrdinal: number; sessionFingerprint: string }+type OwnedServer = { owner: UserKey; deletion?: ServerDeletionProof }const failurePath = resolve(AUTH_DIR, "case-cleanup-failure.json")@@ -48,23 +67,35 @@ async function checkCleanupFailure(testInfo: TestInfo): Promise<void> {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 }>({+export const test = base.extend<{ caseActors: CaseExitOwner["allocate"]; caseResources: CaseResources; caseExitOwner: CaseExitOwner; caseCleanupGuard: void }>({serviceGuard: async ({ caseCleanupGuard, serviceGuard }, provide) => {void caseCleanupGuardawait provide(serviceGuard)},- caseCleanupGuard: [async ({}, provide, testInfo) => {+ caseCleanupGuard: [async ({ }, provide, testInfo) => {await checkCleanupFailure(testInfo)await provide()}, { auto: true }],- caseActors: async ({ browser, caseCleanupGuard }, provide, testInfo) => {+ caseActors: async ({ caseExitOwner }, provide) => { await provide(caseExitOwner.allocate) },+ caseResources: async ({ caseExitOwner }, provide) => { await provide(caseExitOwner.resources) },+ caseExitOwner: async ({ browser, caseCleanupGuard }, provide, testInfo) => {void caseCleanupGuardconst 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 operations = new Set<OwnedCaseResource<unknown>>()+ let operationCount = 0+ const operationOutcomes: boolean[] = []+ const closingContexts = new Map<BrowserContext, Promise<void>>()+ const creatingContexts = new Set<Promise<BrowserContext>>()+ const closedContexts = new WeakSet<BrowserContext>()+ let exiting = false+ let pendingSessionRetirement = false+ const retiredSessions = new Map<UserKey, { fingerprint: string }>()+ const originalSessions = new Map<UserKey, string>()+ const businessRoles = new Set<UserKey>()+ const owned = new Map<string, OwnedServer>()const resources = new Set<string>()let allocated = falseconst identity: CaseIdentity = {@@ -84,14 +115,61 @@ export const test = base.extend<{ caseActors: (roles: readonly UserKey[]) => Proif (!value) throw new Error(`Undeclared case actor: ${key}`)return value}- const registerContext = (role: UserKey, kind: ContextOwner["kind"], context: BrowserContext) => {+ const registerContext = (role: UserKey | null, 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)+ closedContexts.add(context)+ }+ const closeContext = async (context: BrowserContext): Promise<void> => {+ if (closedContexts.has(context)) return+ if (!contexts.has(context)) throw new Error("Context belongs to a different case owner")+ const pending = closingContexts.get(context)+ if (pending) return pending+ const closing = (async () => { await context.close(); retireContext(context) })()+ closingContexts.set(context, closing)+ try { await closing } finally { closingContexts.delete(context) }+ }+ const newContext = async (options: BrowserContextOptions | undefined, role: UserKey | null): Promise<BrowserContext> => {+ if (exiting) throw new Error("Case owner is exiting")+ const creation = (async () => {+ const context = await browser.newContext(options)+ registerContext(role, role === null ? "anonymous" : "actor", context)+ if (exiting) {+ await closeContext(context)+ throw new Error("Context creation completed after its case owner started exiting")+ }+ return context+ })()+ creatingContexts.add(creation)+ try { return await creation } finally { creatingContexts.delete(creation) }+ }+ const own = <T>(value: T, dispose: (value: T) => Promise<void>): OwnedCaseResource<T> => {+ if (exiting) throw new Error("Case owner is exiting")+ let closed = false+ let pending: Promise<void> | undefined+ const resource: OwnedCaseResource<T> = {+ value,+ close: async () => {+ if (closed) return+ if (pending) return pending+ pending = (async () => {+ await dispose(value)+ closed = true+ operations.delete(resource as OwnedCaseResource<unknown>)+ operationOutcomes.push(true)+ })()+ try { await pending } finally { pending = undefined }+ },+ }+ operations.add(resource as OwnedCaseResource<unknown>)+ operationCount += 1+ return resource}+ const caseResources: CaseResources = { newContext: (options) => newContext(options, null), closeContext, own }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("; ")@@ -107,7 +185,7 @@ export const test = base.extend<{ caseActors: (roles: readonly UserKey[]) => Proconst 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({+ const originalSeed = createSeed({sessionCookie,userId: (key) => user(key).userId,users: () => users,@@ -116,7 +194,7 @@ export const test = base.extend<{ caseActors: (roles: readonly UserKey[]) => Proif (!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) },+ 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")@@ -126,10 +204,101 @@ export const test = base.extend<{ caseActors: (roles: readonly UserKey[]) => Pro}},})+ const seed = Object.fromEntries(Object.entries(originalSeed).map(([name, operation]) => [name, (...args: unknown[]) => {+ if (typeof args[0] === "string" && USER_KEYS.includes(args[0] as UserKey)) businessRoles.add(args[0] as UserKey)+ return (operation as (...values: unknown[]) => unknown)(...args)+ }])) as CaseSeed+ const recordServerDeletion = async (role: UserKey, serverId: string, evidence: ServerDeletionEvidence): Promise<void> => {+ user(role)+ const registration = owned.get(serverId)+ const contextOwner = contexts.get(evidence.page.context())+ if (exiting || !registration || registration.owner !== role || registration.deletion || contextOwner?.role !== role || contextOwner.kind !== "actor") throw new Error("Server deletion proof does not belong to this case actor and resource")+ const request = evidence.response.request()+ const target = `${WEB_URL}/api/community/servers/${serverId}`+ if (request.frame().page() !== evidence.page || request.method() !== "DELETE" || request.url() !== target || evidence.response.url() !== target || evidence.response.status() !== 204) throw new Error("Original server deletion request is not a matching successful DELETE")+ const headers = await request.allHeaders()+ const originalCookie = originalSessions.get(role)+ const sessionTokens = originalCookie?.split(";").map((value) => value.trim()).filter((value) => value.slice(0, value.indexOf("=")).endsWith(".session_token")) ?? []+ const requestCookies = headers.cookie?.split(";").map((value) => value.trim()) ?? []+ if (sessionTokens.length === 0 || !sessionTokens.every((token) => requestCookies.includes(token))) throw new Error("Original server deletion session proof is incomplete")+ const completion = await evidence.response.finished()+ if (completion !== null) throw completion+ if (exiting || owned.get(serverId) !== registration) throw new Error("Server deletion proof completed after its case owner started exiting")+ registration.deletion = { request: target, status: 204, contextOrdinal: contextOwner.ordinal, sessionFingerprint: createHash("sha256").update(sessionTokens.join(";")).digest("hex") }+ }+ const cleanupOwned = async (excluded: ReadonlySet<UserKey>): Promise<unknown[]> => {+ const errors: unknown[] = []+ const serverInventories = new Map<UserKey, Set<string>>()+ const creations = await Promise.allSettled([...creatingContexts])+ for (const result of creations) if (result.status === "rejected") errors.push(result.reason)+ for (const operation of [...operations].reverse()) {+ try { await operation.close() } catch (error) { operationOutcomes.push(false); errors.push(error) }+ }+ for (const [context, owner] of contexts) {+ try { await closeContext(context) } catch (error) { contextOutcomes.push({ ...owner, closed: false }); errors.push(error) }+ }+ for (const key of Object.keys(users) as UserKey[]) {+ if (excluded.has(key)) continue+ try {+ const listed = await read(key, "/api/community/servers")+ if (!Array.isArray(listed.servers) || listed.servers.some((value) => !value || typeof value.id !== "string" || value.id.length === 0 || typeof value.ownerId !== "string" || value.ownerId.length === 0)) throw new Error(`Case cleanup ${key} has no complete server list`)+ serverInventories.set(key, new Set((listed.servers as Array<{ id: string }>).map((server) => server.id)))+ for (const server of listed.servers as Array<{ id: string; ownerId: string }>) {+ if (server.ownerId === user(key).userId) {+ if (!owned.get(server.id)?.deletion) owned.set(server.id, { owner: key })+ resources.add(`server:${server.id}`)+ }+ }+ } catch (error) { errors.push(error) }+ }+ for (const [id, registration] of owned) {+ const { owner, deletion } = registration+ try {+ if (deletion) {+ const inventory = serverInventories.get(owner)+ if (!inventory || inventory.has(id)) throw new Error(`Product-deleted fixture server ${id} has no complete absence proof`)+ } else {+ await originalSeed.retireSeedServers(owner, [id])+ }+ owned.delete(id)+ serverOutcomes.push({ owner, id, retired: true, ...(deletion ? { deletion } : {}) })+ } catch (error) { serverOutcomes.push({ owner, id, retired: false }); errors.push(error) }+ }+ for (const key of Object.keys(users) as UserKey[]) {+ if (excluded.has(key)) continue+ try { await assertEmpty(key, "/api/community/servers", "servers") } catch (error) { errors.push(error) }+ }+ return errors+ }+ const serverOutcomes: Array<{ owner: UserKey; id: string; retired: boolean; deletion?: ServerDeletionProof }> = []+ const confirmSignedOut = async (role: UserKey, evidence: SignedOutEvidence): Promise<void> => {+ if (role !== "logout" || !testInfo.file.endsWith("10-eject-nav-auth.spec.ts")) throw new Error("Session retirement is restricted to the original logout journey")+ const actor = user(role)+ const cookie = originalSessions.get(role)+ const contextOwner = contexts.get(evidence.context)+ if (!cookie || contextOwner?.role !== role || contextOwner.kind !== "actor" || evidence.page.context() !== evidence.context) throw new Error("Sign-out evidence has a different case, role, context or original session")+ if (retiredSessions.has(role)) throw new Error("Original session retirement was already confirmed")+ const responseUrl = new URL(evidence.protectedResponse.url())+ const location = evidence.protectedResponse.headers().location+ const redirect = location ? new URL(location, WEB_URL) : undefined+ const pageUrl = new URL(evidence.page.url())+ if (responseUrl.origin !== WEB_URL || responseUrl.pathname !== "/c" || evidence.protectedResponse.status() !== 307 || redirect?.origin !== WEB_URL || redirect.pathname !== "/sign-in" || redirect.searchParams.get("redirect") !== "/c" || pageUrl.origin !== WEB_URL || pageUrl.pathname !== "/sign-in" || (await evidence.context.cookies()).some((value) => value.name.startsWith("better-auth"))) throw new Error("Original cookie and protected redirect sign-out proof is incomplete")+ if (businessRoles.has(role) || [...owned.values()].some((value) => value.owner === role)) throw new Error("Logout role has unresolved or unknown business resources")+ pendingSessionRetirement = true+ exiting = true+ const errors = await cleanupOwned(new Set([role]))+ if (errors.length || operations.size || contexts.size || owned.size) throw new AggregateError(errors, "Sign-out cannot retire a session with unresolved case resources")+ const response = await fetch(`${WEB_URL}/api/ws/token?refresh=1`, { headers: { Cookie: cookie, Origin: WEB_URL } })+ if (response.status !== 401 || response.headers.get("content-type") !== "text/plain;charset=UTF-8" || await response.text() !== "Unauthorized") throw new Error("Original session did not produce the authoritative normal empty-session response")+ const fingerprint = createHash("sha256").update(cookie).digest("hex")+ await testInfo.attach("case-session-retirement", { body: JSON.stringify({ identity, role, userId: actor.userId, fingerprint, request: "/api/ws/token?refresh=1", status: 401, normalEmptySession: true, unresolvedOperations: operations.size, unresolvedContexts: contexts.size, unresolvedServers: owned.size }), contentType: "application/json" })+ retiredSessions.set(role, { fingerprint })+ pendingSessionRetirement = false+ }let bodyError: unknownlet bodyFailed = falsetry {- await provide(async (roles) => {+ const allocate: CaseExitOwner["allocate"] = async (roles) => {if (allocated) throw new Error("A test must allocate its case actors once and reuse them for all devices")allocated = trueconst state = readLifecycleState(SERVICE_STATE_PATH)@@ -141,6 +310,7 @@ export const test = base.extend<{ caseActors: (roles: readonly UserKey[]) => Procreated: (context) => registerContext(key, "login", context),closed: retireContext,})+ originalSessions.set(key, sessionCookie(key))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`)@@ -160,8 +330,7 @@ export const test = base.extend<{ caseActors: (roles: readonly UserKey[]) => Proawait 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 context = await newContext({ ...options, storageState: user(key).storageState }, key)const page = await context.newPage()return { context, page }},@@ -169,47 +338,24 @@ export const test = base.extend<{ caseActors: (roles: readonly UserKey[]) => ProuserName: (key) => user(key).name,sessionCookie,seed,- onCleanup: (operation) => { cleanup.push(operation) },+ onCleanup: (operation) => { own(operation, async (captured) => { await captured() }) },+ confirmSignedOut,+ recordServerDeletion,}- })+ }+ await provide({ allocate, resources: caseResources })} catch (error) {bodyError = errorbodyFailed = 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) }- }+ exiting = true+ const errors = await cleanupOwned(new Set(retiredSessions.keys()))+ if (pendingSessionRetirement) errors.push(new Error("Original session retirement remains unresolved"))+ const outcomes = { operations: operationOutcomes, contexts: contextOutcomes, servers: serverOutcomes }try {- await testInfo.attach("case-cleanup", { body: JSON.stringify({ identity, requestedContexts: contextCount, requestedOperations: cleanup.length, outcomes }), contentType: "application/json" })+ await testInfo.attach("case-cleanup", { body: JSON.stringify({ identity, requestedContexts: contextCount, requestedOperations: operationCount, 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 }+ const failure: CleanupFailure = { identity, unresolvedServers: [...owned].map(([id, value]) => ({ owner: value.owner, id })), unresolvedContexts: [...contexts.values()], unresolvedOperations: operations.size, pendingSessionRetirement, errorCount: errors.length }if (errors.length > 0) {try {if (!existsSync(failurePath)) writeFileSync(failurePath, JSON.stringify(failure), { flag: "wx", mode: 0o600 })diff --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 4bcd55d6b..e15399263 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 } from "./community-fixture"+import { test, expect } from "./community-fixture"import {COMMUNITY_RAIL_WIDTH,COMMUNITY_SEPARATOR_WIDTH,@@ -14,6 +14,7 @@ import {COMMUNITY_SURFACE_BORDER_WIDTH,} from "@/components/community/shell/shell-frame-geometry"import type { CaseSeed } from "./seed"+import type { CaseActors, CaseResources } from "./case-fixture"import { tid } from "./testids"import { WEB_URL } from "../_setup/paths"import { ssrGeometryErrors, type SsrLifecycleSample } from "./community-ssr-geometry"@@ -49,9 +50,10 @@ type MatrixCase = {}}-async function holdApplicationScripts(page: Page) {+async function holdApplicationScripts(page: Page, resources?: CaseResources) {let release!: () => voidconst gate = new Promise<void>((resolve) => { release = resolve })+ resources?.own(release, async (captured) => { captured() })const blocked: string[] = []const received: string[] = []let sessionRequests = 0@@ -72,9 +74,10 @@ async function holdApplicationScripts(page: Page) {return { blocked, received, sessionRequests: () => sessionRequests, release }}-async function holdCommunityReads(page: Page) {+async function holdCommunityReads(page: Page, resources?: CaseResources) {let release!: () => voidconst gate = new Promise<void>((resolve) => { release = resolve })+ resources?.own(release, async (captured) => { captured() })let hits = 0await page.route("**/api/community/**", async (route) => {if (route.request().method() !== "GET") {@@ -133,13 +136,17 @@ async function holdRequest(page: Page, pattern: string) {return { hits: () => hits, release }}-async function pairMachine() {+async function pairMachine(actors: CaseActors, resources: CaseResources) {const pair = await fetch(`${WEB_URL}/api/community/machines/pair`, {method: "POST",- headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL },+ headers: { Cookie: actors.sessionCookie("alice"), Origin: WEB_URL },})expect(pair.status).toBe(200)const { tokenId } = await pair.json() as { tokenId: string }+ const activationProof: { response?: Response; machineId?: string } = {}+ const pairingToken = resources.own(tokenId, async () => {+ if (!activationProof.response?.ok || !activationProof.machineId) throw new Error("Pairing token consumption is UNKNOWN; this case must stop")+ })const activate = await fetch(`${WEB_URL}/api/community/daemon/activate`, {method: "POST",headers: {@@ -155,6 +162,14 @@ async function pairMachine() {}),})expect(activate.status).toBe(200)+ const { machineId } = await activate.json() as { machineId: string }+ resources.own(machineId, async (id) => {+ const response = await fetch(`${WEB_URL}/api/community/machines/${id}`, { method: "DELETE", headers: { Cookie: actors.sessionCookie("alice"), Origin: WEB_URL } })+ expect([204, 404]).toContain(response.status)+ })+ activationProof.response = activate+ activationProof.machineId = machineId+ await pairingToken.close()}const shellPanel = (page: Page, id: "sidebar" | "main") => (@@ -514,60 +529,65 @@ export async function seedGeometryRoutes(]}-export async function runAndroidLoadingGeometry(asUser: CommunityAsUser, testInfo: TestInfo) {- await pairMachine()- for (const userAgent of Object.values(ANDROID_USER_AGENTS)) {- for (const width of [320, 390, 639] as const) {- for (const [pathname, surface] of [- ["/c/me", "list"],- ["/c/me/machines", "detail"],- ] as const) {- const { context, page } = await asUser("alice", { userAgent })- await page.setViewportSize({ width, height: width === 320 ? 720 : 900 })- await installSsrLifecycleProbe(page, surface)- const scripts = await holdApplicationScripts(page)- const communityReads = await holdCommunityReads(page)- let ssrEvidence: unknown+export async function runAndroidLoadingGeometry(actors: CaseActors, resources: CaseResources, testInfo: TestInfo) {+ const { asUser } = actors+ await pairMachine(actors, resources)+ for (const userAgent of Object.values(ANDROID_USER_AGENTS)) {+ for (const width of [320, 390, 639] as const) {+ for (const [pathname, surface] of [+ ["/c/me", "list"],+ ["/c/me/machines", "detail"],+ ] as const) {+ const { context, page } = await asUser("alice", { userAgent })+ await page.setViewportSize({ width, height: width === 320 ? 720 : 900 })+ await installSsrLifecycleProbe(page, surface)+ const scripts = await holdApplicationScripts(page, resources)+ const communityReads = await holdCommunityReads(page, resources)+ let ssrEvidence: unknown+ let caseJourneyFailure1: unknown+ let caseJourneyFailure1Present = false+ try {+ await page.goto(pathname, { waitUntil: "commit" })+ await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)+ expect(scripts.received).toEqual([])+ await expectServerSeededRouteFrame(page, width, width === 320 ? 720 : 900)+ await page.waitForTimeout(250)+ ssrEvidence = {+ blockedScripts: [...scripts.blocked],+ receivedScripts: [...scripts.received],+ sessionRequests: scripts.sessionRequests(),+ }+ expect(scripts.received, "application JS must remain blocked during SSR measurement").toEqual([])+ expect(+ scripts.sessionRequests(),+ "server-seeded identity must not issue a browser session request",+ ).toBe(0)+ await page.evaluate(() => Reflect.set(window, "__communityApplicationScriptsReleased", true))+ scripts.release()+ await expect.poll(communityReads.hits).toBeGreaterThan(0)+ await expect(page.locator('[data-slot="community-shell-root"]')).toBeVisible()+ await page.waitForTimeout(250)+ const pendingSamples = await ssrLifecycleSamples(page)+ expectMobileGeometry(pendingSamples, width, surface)+ const pendingHeading = pathname === "/c/me/machines"+ ? await expectMachinesHeadingSpacing(page)+ : null++ communityReads.release()+ await expect(+ pathname === "/c/me"+ ? page.getByRole("link", { name: "Friends", exact: true })+ : page.getByTestId(tid.machinePairOpen),+ ).toBeVisible({ timeout: 30_000 })+ if (pendingHeading) {+ const loadedHeading = await expectMachinesHeadingSpacing(page)+ expectSameGeometry({ heading: pendingHeading }, { heading: loadedHeading })+ }+ await page.waitForTimeout(250)+ expectMobileGeometry(await ssrLifecycleSamples(page), width, surface)+ } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {try {- await page.goto(pathname, { waitUntil: "commit" })- await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)- expect(scripts.received).toEqual([])- await expectServerSeededRouteFrame(page, width, width === 320 ? 720 : 900)- await page.waitForTimeout(250)- ssrEvidence = {- blockedScripts: [...scripts.blocked],- receivedScripts: [...scripts.received],- sessionRequests: scripts.sessionRequests(),- }- expect(scripts.received, "application JS must remain blocked during SSR measurement").toEqual([])- expect(- scripts.sessionRequests(),- "server-seeded identity must not issue a browser session request",- ).toBe(0)- await page.evaluate(() => Reflect.set(window, "__communityApplicationScriptsReleased", true))- scripts.release()- await expect.poll(communityReads.hits).toBeGreaterThan(0)- await expect(page.locator('[data-slot="community-shell-root"]')).toBeVisible()- await page.waitForTimeout(250)- const pendingSamples = await ssrLifecycleSamples(page)- expectMobileGeometry(pendingSamples, width, surface)- const pendingHeading = pathname === "/c/me/machines"- ? await expectMachinesHeadingSpacing(page)- : null- communityReads.release()- await expect(- pathname === "/c/me"- ? page.getByRole("link", { name: "Friends", exact: true })- : page.getByTestId(tid.machinePairOpen),- ).toBeVisible({ timeout: 30_000 })- if (pendingHeading) {- const loadedHeading = await expectMachinesHeadingSpacing(page)- expectSameGeometry({ heading: pendingHeading }, { heading: loadedHeading })- }- await page.waitForTimeout(250)- expectMobileGeometry(await ssrLifecycleSamples(page), width, surface)- } finally {await page.evaluate(() => Reflect.set(window, "__communitySsrProbeStopped", true))await testInfo.attach(`ssr-lifecycle-${width}-${surface}-${userAgent.includes("; wv") ? "webview" : "chrome"}`, {body: Buffer.from(JSON.stringify({@@ -580,11 +600,13 @@ export async function runAndroidLoadingGeometry(asUser: CommunityAsUser, testInf})scripts.release()communityReads.release()- await context.close()- }+ await resources.closeContext(context)++ } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }}}}+ }}export async function runDesktopPersistedPendingGeometry(@@ -619,7 +641,7 @@ export async function runDesktopPersistedPendingGeometry(await expect.poll(communityReads.hits).toBeGreaterThan(0)await expect(page.locator('[data-slot="community-shell-root"]')).toBeVisible()await page.waitForTimeout(250)-+const samples = await desktopPendingFrameSamples(page)await page.evaluate(() => Reflect.set(window,@@ -663,30 +685,31 @@ export async function runDesktopPersistedPendingGeometry(for (const result of results) if (result.status === "rejected") throw result.reason}-export async function runSkeletonLoadingMotion(asUser: CommunityAsUser) {- for (const reducedMotion of ["no-preference", "reduce"] as const) {- const { context, page } = await asUser("alice", {- userAgent: ANDROID_USER_AGENTS.webview,- })- await page.setViewportSize({ width: 320, height: 720 })- await page.emulateMedia({ reducedMotion })- const scripts = await holdApplicationScripts(page)- const communityReads = await holdCommunityReads(page)- await page.goto("/c/me/machines", { waitUntil: "commit" })- await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)- expect(scripts.received).toEqual([])- expect(scripts.sessionRequests()).toBe(0)- await expectServerSeededRouteFrame(page, 320, 720)- scripts.release()- await expect.poll(communityReads.hits).toBeGreaterThan(0)- await expect(page.locator('[data-slot="skeleton"]:visible').first()).toBeVisible()-- const animationProperties = await visibleSkeletonAnimationProperties(page)- expect(animationProperties).toEqual(reducedMotion === "reduce" ? [] : ["opacity"])-- communityReads.release()- await context.close()- }+export async function runSkeletonLoadingMotion(actors: CaseActors, resources: CaseResources) {+ const { asUser } = actors+ for (const reducedMotion of ["no-preference", "reduce"] as const) {+ const { context, page } = await asUser("alice", {+ userAgent: ANDROID_USER_AGENTS.webview,+ })+ await page.setViewportSize({ width: 320, height: 720 })+ await page.emulateMedia({ reducedMotion })+ const scripts = await holdApplicationScripts(page, resources)+ const communityReads = await holdCommunityReads(page, resources)+ await page.goto("/c/me/machines", { waitUntil: "commit" })+ await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)+ expect(scripts.received).toEqual([])+ expect(scripts.sessionRequests()).toBe(0)+ await expectServerSeededRouteFrame(page, 320, 720)+ scripts.release()+ await expect.poll(communityReads.hits).toBeGreaterThan(0)+ await expect(page.locator('[data-slot="skeleton"]:visible').first()).toBeVisible()++ const animationProperties = await visibleSkeletonAnimationProperties(page)+ expect(animationProperties).toEqual(reducedMotion === "reduce" ? [] : ["opacity"])++ communityReads.release()+ await resources.closeContext(context)+ }}export async function runNeutralRootGeometry(diff --git a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.tsindex 09e82101f..0cb035b17 100644--- a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts+++ b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts@@ -1,15 +1,9 @@import type { Page } from "@playwright/test"import { PERSIST_CACHE_PREFIX } from "@/lib/query-persister"-import { expect, test, userId, userName } from "./_fixtures/community-fixture"-import {- seedChannel,- seedDm,- seedDmMessage,- seedMessage,- seedServer,- seedThread,-} from "./_fixtures/seed"+import { expect, test } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"+import type { CaseResources } from "./_fixtures/case-fixture"type ReloadCapture = {customBootstrapSeen: boolean@@ -149,7 +143,7 @@ async function expectCacheFirstReload(page: Page,assertUnqualifiedShell: () => Promise<void>,assertCachedContent: () => Promise<void>,- assertReconciledContent: () => Promise<void>,+ assertReconciledContent: () => Promise<void>, caseResources: CaseResources): Promise<ReloadCapture> {await page.addInitScript((loadingSelectors) => {const state = {@@ -185,8 +179,10 @@ async function expectCacheFirstReload(let releaseReads!: () => voidconst readsGate = new Promise<void>((resolve) => { releaseReads = resolve })+ caseResources.own(releaseReads, async (captured) => { captured() })let releaseMessages!: () => voidconst messagesGate = new Promise<void>((resolve) => { releaseMessages = resolve })+ caseResources.own(releaseMessages, async (captured) => { captured() })let heldReads = 0let heldMessages = 0let forwardedMessages = 0@@ -204,7 +200,7 @@ async function expectCacheFirstReload(heldReads += 1await readsGate}- await route.continue().catch(() => {})+ await route.continue().catch(() => { })})let wsAttempts = 0await page.routeWebSocket((url) => url.pathname.endsWith("/user"), (socket) => {@@ -264,8 +260,13 @@ async function expectCacheFirstReload(}}-test("a warm channel reload qualifies its cached shell before showing persisted messages", async ({ asUser }) => {+test("a warm channel reload qualifies its cached shell before showing persisted messages", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser, userId } = actors+ const { seedChannel, seedMessage, seedServer } = actors.seed+const suffix = Date.now().toString(36)const serverId = await seedServer("alice", `Warm channel ${suffix}`)const channelId = await seedChannel("alice", serverId, `warm-${suffix}`)@@ -297,11 +298,16 @@ test("a warm channel reload qualifies its cached shell before showing persisted}, async () => {await expect(page.getByTestId(tid.message(messageId))).toBeVisible()await expect(page.getByTestId(tid.composerInput)).toBeVisible()- })+ }, caseResources)})-test("a warm DM reload qualifies cached identity and history before showing persisted messages", async ({ asUser }) => {+test("a warm DM reload qualifies cached identity and history before showing persisted messages", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId, userName } = actors+ const { seedDm, seedDmMessage } = actors.seed+const dmId = await seedDm("alice", userId("bob"))const body = `cached dm ${Date.now()}`const messageId = await seedDmMessage("bob", dmId, body)@@ -332,11 +338,16 @@ test("a warm DM reload qualifies cached identity and history before showing pers}, async () => {await expect(page.getByTestId(tid.message(messageId))).toBeVisible()await expect(page.getByTestId(tid.composerInput)).toBeVisible()- })+ }, caseResources)})-test("a warm desktop thread reload qualifies its type before restoring cached split panes", async ({ asUser }) => {+test("a warm desktop thread reload qualifies its type before restoring cached split panes", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser, userId } = actors+ const { seedChannel, seedMessage, seedServer, seedThread } = actors.seed+const suffix = Date.now().toString(36)const serverId = await seedServer("alice", `Warm split ${suffix}`)const channelId = await seedChannel("alice", serverId, `split-${suffix}`)@@ -387,11 +398,16 @@ test("a warm desktop thread reload qualifies its type before restoring cached sp.toBeVisible()await expect(page.getByTestId(tid.threadSplitParent).getByTestId(tid.composerInput)).toBeVisible()await expect(page.getByTestId(tid.threadSplitPanel).getByTestId(tid.composerInput)).toBeVisible()- })+ }, caseResources)})-test("a true-cold channel load reuses localized skeletons without a custom bootstrap", async ({ asUser }) => {+test("a true-cold channel load reuses localized skeletons without a custom bootstrap", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedMessage, seedServer } = actors.seed+const suffix = Date.now().toString(36)const serverId = await seedServer("alice", `Cold control ${suffix}`)const channelId = await seedChannel("alice", serverId, `cold-${suffix}`)@@ -437,6 +453,7 @@ test("a true-cold channel load reuses localized skeletons without a custom bootslet releaseReads!: () => voidconst readsGate = new Promise<void>((resolve) => { releaseReads = resolve })+ caseResources.own(releaseReads, async (captured) => { captured() })let heldReads = 0await page.route("**/api/community/**", async (route) => {if (route.request().method() !== "GET") {