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): distinguish parsing from pre-hydration SSR geometry (#792)
Gustavo Ye4f66d9274ca4
diff --git a/src/web/src/test/community-ssr-geometry.test.ts b/src/web/src/test/community-ssr-geometry.test.tsnew file mode 100644index 000000000..ce32ecfe9--- /dev/null+++ b/src/web/src/test/community-ssr-geometry.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from "vitest"+import { ssrGeometryErrors, type SsrLifecycleSample } from "./e2e-ui/_fixtures/community-ssr-geometry"++const rect = (width: number) => ({ x: 0, y: 0, width, height: 900 })+const sample = (overrides: Partial<SsrLifecycleSample> = {}): SsrLifecycleSample => ({+ timestamp: 100,+ phase: "ssr",+ readyState: "interactive",+ shellChildCount: 3,+ overflow: 0,+ geometry: { shell: rect(390), main: rect(390), surface: rect(390) },+ ...overrides,+})++describe("SSR lifecycle geometry boundary", () => {+ it("retains a parsing prefix and validates the complete pre-JS and hydrated document", () => {+ const samples = [+ sample({ phase: "parsing", readyState: "loading", shellChildCount: 0, geometry: { shell: rect(390) } }),+ sample(),+ sample({ phase: "hydrating" }),+ ]+ expect(ssrGeometryErrors(samples, 390, "detail")).toEqual([])+ expect(samples).toHaveLength(3)+ })++ it.each(["ssr", "hydrating"] as const)("rejects missing modules in a %s sample even when later frames recover", (phase) => {+ const errors = ssrGeometryErrors([+ sample(),+ sample({ phase, geometry: { shell: rect(390) } }),+ sample({ phase: "hydrating" }),+ ], 390, "detail")+ expect(errors).toContain(`sample 1 (${phase}): incomplete modules shell`)+ })++ it("rejects a parsed frame where the entire shell disappears", () => {+ expect(ssrGeometryErrors([+ sample(), sample({ geometry: {} }), sample(),+ ], 390, "detail")).toContain("sample 1 (ssr): incomplete modules ")+ })++ it("rejects desktop width and overflow during parsing", () => {+ const errors = ssrGeometryErrors([+ sample({ phase: "parsing", overflow: 250, geometry: { shell: rect(640) } }),+ sample(),+ ], 390, "detail")+ expect(errors).toContain("sample 0 (parsing): horizontal overflow 250")+ expect(errors).toContain("sample 0 (parsing): shell width 640, expected 390")+ })++ it("validates every present list module during parsing and requires all modules after parsing", () => {+ const geometry = { shell: rect(390), rail: rect(56), sidebar: rect(333), surface: rect(334), userBar: rect(390) }+ expect(ssrGeometryErrors([+ sample({ phase: "parsing", geometry: { shell: rect(390), rail: rect(56) } }),+ sample({ geometry }),+ ], 390, "list")).toEqual([])+ expect(ssrGeometryErrors([+ sample({ phase: "parsing", geometry: { userBar: rect(640) } }),+ sample({ geometry: { shell: rect(390) } }),+ sample({ geometry }),+ ], 390, "list")).toEqual([+ "sample 0 (parsing): userBar width 640, expected 390",+ "sample 1 (ssr): incomplete modules shell",+ ])+ })++ it("rejects an empty recording", () => {+ expect(ssrGeometryErrors([], 390, "detail")).toEqual([+ "no lifecycle samples", "no complete parsed-document sample",+ ])+ })++ it("cannot pass with only parsing samples", () => {+ expect(ssrGeometryErrors([sample({ phase: "parsing" })], 390, "detail"))+ .toContain("no complete parsed-document sample")+ })++ it("rejects extra desktop modules and later geometry drift", () => {+ expect(ssrGeometryErrors([+ sample({ phase: "parsing", geometry: { shell: rect(390), sidebar: rect(240) } }),+ sample(),+ sample({ phase: "hydrating", geometry: { shell: rect(390), main: { ...rect(390), y: 22 }, surface: rect(390) } }),+ ], 390, "detail")).toEqual([+ "sample 0 (parsing): unexpected module sidebar",+ "sample 2 (hydrating): main.y drift",+ ])+ })+})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 2a21ebfda..ad18d7185 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@@ -5,9 +5,9 @@ import {} from "./_fixtures/community-loading-geometry"test.describe.serial("community Android loading geometry", () => {- test("Android Chrome/WebView keep 320/390/639 cold frames mobile before breakpoint hydration", async ({ asUser }) => {+ test("Android Chrome/WebView keep parsed SSR layouts mobile before application JS and through hydration", async ({ asUser }, testInfo) => {test.setTimeout(240_000)- await runAndroidLoadingGeometry(asUser)+ await runAndroidLoadingGeometry(asUser, testInfo)})test("community skeleton pulse changes only opacity and stops for reduced motion", async ({ asUser }) => {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 857689573..125a62159 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@@ -22,6 +22,7 @@ import {} from "./seed"import { tid } from "./testids"import { WEB_URL } from "../_setup/paths"+import { ssrGeometryErrors, type SsrLifecycleSample } from "./community-ssr-geometry"import type { UserKey } from "../_setup/users"type Theme = "light" | "dark"@@ -65,6 +66,25 @@ async function holdSession(page: Page) {return { hits: () => hits, release }}+async function holdApplicationScripts(page: Page) {+ let release!: () => void+ const gate = new Promise<void>((resolve) => { release = resolve })+ const blocked: string[] = []+ const received: string[] = []+ const isApplicationScript = (url: string) => /\/_next\/.*\.js(?:\?|$)/.test(url)+ page.on("response", (response) => {+ if (isApplicationScript(response.url())) received.push(response.url())+ })+ await page.route("**/_next/**", async (route) => {+ if (isApplicationScript(route.request().url())) {+ blocked.push(route.request().url())+ await gate+ }+ await route.continue()+ })+ return { blocked, received, release }+}+async function holdRequest(page: Page, pattern: string) {let release!: () => voidconst gate = new Promise<void>((resolve) => { release = resolve })@@ -188,11 +208,6 @@ async function readCls(page: Page) {}))}-type FirstFrameSample = {- overflow: number- geometry: Geometry-}-type DesktopPendingFrameSample = {overflow: numbersidebarWidth: number@@ -201,10 +216,12 @@ type DesktopPendingFrameSample = {userBarRight: number}-async function installFirstFrameProbe(page: Page, surface: "list" | "detail") {+async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail") {await page.addInitScript((expectedSurface) => {- const samples: FirstFrameSample[] = []- Reflect.set(window, "__communityFirstFrameSamples", samples)+ const samples: SsrLifecycleSample[] = []+ Reflect.set(window, "__communitySsrLifecycleSamples", samples)+ let parsed = document.readyState !== "loading"+ document.addEventListener("DOMContentLoaded", () => { parsed = true }, { once: true })const rect = (selector: string) => {const element = document.querySelector<HTMLElement>(selector)@@ -214,7 +231,8 @@ async function installFirstFrameProbe(page: Page, surface: "list" | "detail") {return { x: box.x, y: box.y, width: box.width, height: box.height }}const sample = () => {- if (document.querySelector('[data-slot="community-shell-root"]')) {+ const shell = document.querySelector('[data-slot="community-shell-root"]')+ if (shell || parsed) {const activePanel = '[data-slot="resizable-panel"][data-mobile-active="true"]'const hiddenPanel = '[data-slot="resizable-panel"][data-mobile-hidden="true"]'const geometry = Object.fromEntries(Object.entries({@@ -226,19 +244,25 @@ async function installFirstFrameProbe(page: Page, surface: "list" | "detail") {userBar: rect('[data-slot="community-user-bar-overlay"]'),}).filter((entry): entry is [string, NonNullable<typeof entry[1]>] => entry[1] !== null))samples.push({+ timestamp: performance.now(),+ phase: !parsed ? "parsing"+ : Reflect.get(window, "__communityApplicationScriptsReleased") ? "hydrating" : "ssr",+ readyState: document.readyState,+ shellChildCount: shell?.childElementCount ?? 0,+ incompleteShellHtml: geometry.surface ? undefined : shell?.outerHTML ?? "",overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,geometry,})}- if (performance.now() < 5_000) requestAnimationFrame(sample)+ if (!Reflect.get(window, "__communitySsrProbeStopped")) requestAnimationFrame(sample)}requestAnimationFrame(sample)}, surface)}-async function firstFrameSamples(page: Page): Promise<FirstFrameSample[]> {+async function ssrLifecycleSamples(page: Page): Promise<SsrLifecycleSample[]> {return page.evaluate(() => (- Reflect.get(window, "__communityFirstFrameSamples") as FirstFrameSample[]+ Reflect.get(window, "__communitySsrLifecycleSamples") as SsrLifecycleSample[]))}@@ -307,43 +331,11 @@ async function desktopPendingFrameSamples(page: Page): Promise<DesktopPendingFra}function expectMobileGeometry(- samples: FirstFrameSample[],+ samples: SsrLifecycleSample[],width: MobileWidth,surface: "list" | "detail",) {- expect(samples.length).toBeGreaterThan(0)- const first = samples[0]!- const geometryDrift: string[] = []- for (const [index, sample] of samples.entries()) {- expect(sample.overflow, `frame ${index} horizontal overflow`).toBe(0)- expect(- Object.keys(sample.geometry).sort(),- `frame ${index} visible modules: ${JSON.stringify(sample)}`,- ).toEqual(- surface === "list"- ? ["rail", "shell", "sidebar", "surface", "userBar"]- : ["main", "shell", "surface"],- )- expect(sample.geometry.shell?.width, `frame ${index} shell width`).toBeCloseTo(width, 0)- expect(sample.geometry.surface?.width, `frame ${index} surface width`).toBeCloseTo(- surface === "list" ? width - 56 : width,- 0,- )- if (surface === "list") {- expect(sample.geometry.sidebar?.width, `frame ${index} sidebar width`).toBeCloseTo(width - 57, 0)- expect(sample.geometry.userBar?.width, `frame ${index} UserBar width`).toBeCloseTo(width, 0)- } else {- expect(sample.geometry.main?.width, `frame ${index} main width`).toBeCloseTo(width, 0)- }- for (const name of Object.keys(first.geometry)) {- for (const coordinate of ["x", "y", "width", "height"] as const) {- if (Math.abs(first.geometry[name]![coordinate] - sample.geometry[name]![coordinate]) > 1) {- geometryDrift.push(`frame ${index} ${name}.${coordinate}`)- }- }- }- }- expect(geometryDrift, "mobile landmark geometry drift").toEqual([])+ expect(ssrGeometryErrors(samples, width, surface), JSON.stringify(samples)).toEqual([])}async function expectMachinesHeadingSpacing(page: Page) {@@ -474,7 +466,7 @@ export async function seedGeometryRoutes(): Promise<Omit<MatrixCase, "width">[]>]}-export async function runAndroidLoadingGeometry(asUser: CommunityAsUser) {+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) {@@ -484,32 +476,61 @@ export async function runAndroidLoadingGeometry(asUser: CommunityAsUser) {] as const) {const { context, page } = await asUser("alice", { userAgent })await page.setViewportSize({ width, height: width === 320 ? 720 : 900 })- await installFirstFrameProbe(page, surface)+ await installSsrLifecycleProbe(page, surface)const session = await holdSession(page)- await page.goto(pathname, { waitUntil: "commit" })- await expect.poll(session.hits).toBeGreaterThan(0)- await expect(page.getByTestId(tid.initialFrame)).toBeVisible()- await page.waitForTimeout(250)-- expectMobileGeometry(await firstFrameSamples(page), width, surface)- const pendingHeading = pathname === "/c/me/machines"- ? await expectMachinesHeadingSpacing(page)- : null-- session.release()- await expect(page.getByTestId(tid.initialFrame)).toHaveCount(0, { timeout: 30_000 })- await expect(- pathname === "/c/me"- ? page.getByRole("button", { name: "Friends", exact: true })- : page.getByTestId(tid.machinePairOpen),- ).toBeVisible({ timeout: 30_000 })- if (pendingHeading) {- const loadedHeading = await expectMachinesHeadingSpacing(page)- expectSameGeometry({ heading: pendingHeading }, { heading: loadedHeading })+ const scripts = await holdApplicationScripts(page)+ let ssrEvidence: unknown+ try {+ await page.goto(pathname, { waitUntil: "domcontentloaded" })+ await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)+ await expect(page.getByTestId(tid.initialFrame)).toBeVisible()+ await page.waitForTimeout(250)+ const ssrSamples = await ssrLifecycleSamples(page)+ ssrEvidence = {+ samples: ssrSamples,+ blockedScripts: [...scripts.blocked],+ receivedScripts: [...scripts.received],+ sessionRequests: session.hits(),+ }+ expect(scripts.received, "application JS must remain blocked during SSR measurement").toEqual([])+ expect(session.hits(), "application session request must not run before JS release").toBe(0)+ expect(ssrSamples.some((sample) => sample.phase === "ssr")).toBe(true)+ expectMobileGeometry(ssrSamples, width, surface)+ const pendingHeading = pathname === "/c/me/machines"+ ? await expectMachinesHeadingSpacing(page)+ : null++ await page.evaluate(() => Reflect.set(window, "__communityApplicationScriptsReleased", true))+ scripts.release()+ await expect.poll(session.hits).toBeGreaterThan(0)+ session.release()+ await expect(page.getByTestId(tid.initialFrame)).toHaveCount(0, { timeout: 30_000 })+ await expect(+ pathname === "/c/me"+ ? page.getByRole("button", { 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({+ ssrEvidence,+ allSamples: await ssrLifecycleSamples(page),+ releasedScriptResponses: scripts.received,+ sessionRequests: session.hits(),+ })),+ contentType: "application/json",+ })+ scripts.release()+ session.release()+ await context.close()}- await page.waitForTimeout(250)- expectMobileGeometry(await firstFrameSamples(page), width, surface)- await context.close()}}}diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ssr-geometry.ts b/src/web/src/test/e2e-ui/_fixtures/community-ssr-geometry.tsnew file mode 100644index 000000000..ac94d70ed--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/community-ssr-geometry.ts@@ -0,0 +1,50 @@+export type SsrGeometry = Record<string, { x: number; y: number; width: number; height: number }>++export type SsrLifecycleSample = {+ timestamp: number+ phase: "parsing" | "ssr" | "hydrating"+ readyState: DocumentReadyState+ shellChildCount: number+ incompleteShellHtml?: string+ overflow: number+ geometry: SsrGeometry+}++export function ssrGeometryErrors(+ samples: SsrLifecycleSample[],+ width: number,+ surface: "list" | "detail",+): string[] {+ const errors: string[] = []+ const widths: Record<string, number> = surface === "list"+ ? { rail: 56, shell: width, sidebar: width - 57, surface: width - 56, userBar: width }+ : { main: width, shell: width, surface: width }+ const expected = Object.keys(widths).sort().join(",")+ let baseline: SsrGeometry | undefined+ if (samples.length === 0) errors.push("no lifecycle samples")+ for (const [index, sample] of samples.entries()) {+ const label = `sample ${index} (${sample.phase})`+ if (sample.overflow !== 0) errors.push(`${label}: horizontal overflow ${sample.overflow}`)+ for (const [name, rect] of Object.entries(sample.geometry)) {+ if (!(name in widths)) errors.push(`${label}: unexpected module ${name}`)+ else if (Math.abs(rect.width - widths[name]) >= 0.5) {+ errors.push(`${label}: ${name} width ${rect.width}, expected ${widths[name]}`)+ }+ }+ if (sample.phase === "parsing") continue+ if (Object.keys(sample.geometry).sort().join(",") !== expected) {+ errors.push(`${label}: incomplete modules ${Object.keys(sample.geometry).join(",")}`)+ continue+ }+ baseline ??= sample.geometry+ for (const [name, rect] of Object.entries(sample.geometry)) {+ for (const coordinate of ["x", "y", "width", "height"] as const) {+ if (Math.abs(baseline[name][coordinate] - rect[coordinate]) > 1) {+ errors.push(`${label}: ${name}.${coordinate} drift`)+ }+ }+ }+ }+ if (!baseline) errors.push("no complete parsed-document sample")+ return errors+}