Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

perf(web): render bundled hero photos before hydration (#1028)

Gustavo Yed87c24d4dafd
diff --git a/src/web/scripts/benchmark-landing.md b/src/web/scripts/benchmark-landing.md
new file mode 100644
index 000000000..76a243269
--- /dev/null
+++ b/src/web/scripts/benchmark-landing.md
@@ -0,0 +1,28 @@
+# Homepage browser benchmark
+
+Use a production build and a dedicated local server. No production requests or new dependencies are needed.
+
+```sh
+pnpm build
+pnpm exec next start --hostname 127.0.0.1 --port 3026
+```
+
+In another shell, from `src/web`, warm the server separately, then measure fresh browser caches:
+
+```sh
+curl -s -o /dev/null http://127.0.0.1:3026/
+BENCH_RUNS=10 BENCH_LATENCY_MS=40 BENCH_DOWNLOAD_MBPS=100 BENCH_BUDGET_MS=300 node scripts/benchmark-landing.mjs
+```
+
+The report and first-run screenshots go to `.alook-qa-scratch/landing-benchmark/` (ignored). Set `BENCH_OUTPUT` to retain separate runs. `BENCH_URL` accepts localhost only. Reports contain build ID, machine, Chromium version, network/CPU settings and every sample.
+
+- `firstScreen`: max(FCP, observed LCP, hero asset/font readiness). Hero readiness includes the fixed photos that animate into view later; it is deliberately stricter than initial paint. It does not wait for every entrance animation to finish or prove all interactions are ready.
+- FCP/LCP are reported separately: earlier asset readiness is not necessarily earlier visible text.
+- Desktop 1440×900 and mobile-sized 390×844 use the same host CPU, DPR 1 and light theme. This is not physical phone testing. `BENCH_CPU_RATE=4` adds simulated CPU slowdown.
+- Each run uses a fresh browser context, followed by a warm-cache visit in that context. Server/module warmup is separate from browser cold cache. Do not describe warmed-server results as process cold starts.
+- GTM, GA and Grafana requests are blocked. Service workers are blocked. First-party HTTP errors and page JavaScript errors fail the run.
+- CDP simulates the configured latency and bandwidth on loopback. It does not reproduce internet DNS, TLS, edge placement or real users. Report the settings with the result.
+
+Repeat with `BENCH_DOWNLOAD_MBPS=10` for the slower-network case. Keep its results separate; passing at 100 Mbps does not imply passing at 10 Mbps. With `BENCH_BUDGET_MS`, any profile/cache p95 at or above the budget exits nonzero after writing the report. Omit the budget for investigation.
+
+`next start` also loads this repository's development Cloudflare adapter from `next.config.ts`. A fresh Node process therefore includes local emulator initialization; that timing is not a production Worker cold-start estimate.
diff --git a/src/web/scripts/benchmark-landing.mjs b/src/web/scripts/benchmark-landing.mjs
new file mode 100644
index 000000000..416712ccd
--- /dev/null
+++ b/src/web/scripts/benchmark-landing.mjs
@@ -0,0 +1,83 @@
+import { chromium } from '@playwright/test';
+import { mkdir, writeFile, readFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+const url = process.env.BENCH_URL ?? 'http://127.0.0.1:3026/';
+if (!['127.0.0.1', 'localhost'].includes(new URL(url).hostname)) throw new Error('Local benchmark only');
+const runs = Number(process.env.BENCH_RUNS ?? 10);
+const latency = Number(process.env.BENCH_LATENCY_MS ?? 0);
+const downloadMbps = Number(process.env.BENCH_DOWNLOAD_MBPS ?? 0);
+const cpuRate = Number(process.env.BENCH_CPU_RATE ?? 1);
+const budget = process.env.BENCH_BUDGET_MS === undefined ? null : Number(process.env.BENCH_BUDGET_MS);
+if (budget !== null && (!Number.isFinite(budget) || budget <= 0)) throw new Error('Invalid benchmark budget');
+const output = process.env.BENCH_OUTPUT ?? '.alook-qa-scratch/landing-benchmark';
+if (!Number.isInteger(runs) || runs < 1 || !Number.isFinite(latency) || latency < 0 || !Number.isFinite(downloadMbps) || downloadMbps < 0 || !Number.isFinite(cpuRate) || cpuRate < 1) throw new Error('Invalid benchmark parameters');
+await mkdir(output, { recursive: true });
+const browser = await chromium.launch({ headless: true });
+const results = [];
+try {
+ for (const [profile, viewport] of Object.entries({ desktop: { width: 1440, height: 900 }, mobile: { width: 390, height: 844 } })) {
+ for (let run = 0; run < runs; run++) {
+ const context = await browser.newContext({ viewport, deviceScaleFactor: 1, colorScheme: 'light', serviceWorkers: 'block' });
+ const page = await context.newPage();
+ const cdp = await context.newCDPSession(page);
+ await cdp.send('Network.enable');
+ await cdp.send('Network.setBlockedURLs', { urls: ['*googletagmanager.com/*', '*google-analytics.com/*', '*grafana.net/*'] });
+ if (latency || downloadMbps) await cdp.send('Network.emulateNetworkConditions', { offline: false, latency, downloadThroughput: downloadMbps ? downloadMbps * 1000000 / 8 : -1, uploadThroughput: downloadMbps ? downloadMbps * 1000000 / 8 : -1 });
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: cpuRate });
+ await page.addInitScript(() => {
+ window.__landingBench = { lcp: 0, fonts: 0, heroReady: 0 };
+ new PerformanceObserver(list => { for (const e of list.getEntries()) window.__landingBench.lcp = e.startTime; }).observe({ type: 'largest-contentful-paint', buffered: true });
+ document.addEventListener('DOMContentLoaded', () => {
+ document.fonts.ready.then(() => { window.__landingBench.fonts = performance.now(); });
+ const check = () => {
+ const hero = document.querySelector('.hero-section');
+ const paper = hero?.querySelector('.tw-paper');
+ const images = hero ? [...hero.querySelectorAll('img')] : [];
+ if (hero && paper && document.fonts.status === 'loaded' && images.every(i => i.complete && i.naturalWidth > 0 && (!i.hasAttribute('data-remote-image-state') || i.dataset.remoteImageState === 'ready'))) {
+ requestAnimationFrame(() => { window.__landingBench.heroReady = performance.now(); });
+ } else requestAnimationFrame(check);
+ };
+ requestAnimationFrame(check);
+ });
+ });
+ for (const cache of ['cold', 'warm']) {
+ const errors = [];
+ const onResponse = r => { if (new URL(r.url()).origin === new URL(url).origin && r.status() >= 400) errors.push(`${r.status()} ${new URL(r.url()).pathname}`); };
+ page.on('response', onResponse);
+ const onError = e => errors.push(e.message);
+ page.on('pageerror', onError);
+ const response = await page.goto(url, { waitUntil: 'load', timeout: 60000 });
+ if (response.status() !== 200) throw new Error(`Homepage status ${response.status()}`);
+ await page.waitForFunction(() => window.__landingBench.heroReady > 0, undefined, { timeout: 30000 });
+ await page.waitForTimeout(1000);
+ const sample = await page.evaluate(() => {
+ const nav = performance.getEntriesByType('navigation')[0];
+ const resources = performance.getEntriesByType('resource');
+ return { ...window.__landingBench, fcp: performance.getEntriesByName('first-contentful-paint')[0]?.startTime, ttfb: nav.responseStart, load: nav.loadEventEnd, resources: resources.map(r => ({ name: new URL(r.name).origin + new URL(r.name).pathname, start: r.startTime, duration: r.duration, bytes: r.transferSize })), title: document.title };
+ });
+ page.off('pageerror', onError);
+ page.off('response', onResponse);
+ if (errors.length) throw new Error(errors.join('\n'));
+ sample.firstScreen = Math.max(sample.fcp ?? 0, sample.lcp, sample.heroReady);
+ results.push({ profile, cache, run, ...sample });
+ if (run === 0) await page.screenshot({ path: path.join(output, `${profile}-${cache}.png`), animations: 'disabled' });
+ console.log(JSON.stringify({ profile, cache, run, fcp: sample.fcp, lcp: sample.lcp, heroReady: sample.heroReady, ttfb: sample.ttfb }));
+ }
+ await context.close();
+ }
+ }
+} finally { await browser.close(); }
+const percentile = (xs, p) => xs.sort((a,b) => a-b)[Math.ceil(xs.length*p)-1];
+const summary = [];
+for (const profile of ['desktop','mobile']) for (const cache of ['cold','warm']) {
+ const samples = results.filter(r => r.profile === profile && r.cache === cache);
+ summary.push({ profile, cache, count: samples.length, ...Object.fromEntries(['fcp','lcp','heroReady','firstScreen','ttfb'].map(key => [key, Object.fromEntries([.5,.75,.95].map(p => [`p${p*100}`,percentile(samples.map(r => r[key]),p)]))])) });
+}
+const passed = budget === null ? null : summary.every(s => s.firstScreen.p95 < budget);
+const report = { budgetMs: budget, passed, url, build: await readFile('.next/BUILD_ID','utf8'), platform: os.platform(), cpu: os.cpus()[0]?.model, chromium: browser.version(), network: { kind: 'loopback simulation; not internet measurement', latencyMs: latency, downloadMbps }, cpuThrottle: cpuRate, deviceScaleFactor: 1, serviceWorkers: 'blocked for both series', externalTelemetry: 'GTM, GA and Grafana blocked by CDP without request routing; browser cache remains enabled', summary, results };
+await writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2));
+console.log(JSON.stringify(summary,null,2));
+
+if (passed === false) process.exitCode = 1;
diff --git a/src/web/src/app/(home)/page.test.ts b/src/web/src/app/(home)/page.test.ts
new file mode 100644
index 000000000..4663719e1
--- /dev/null
+++ b/src/web/src/app/(home)/page.test.ts
@@ -0,0 +1,29 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+const mocks = vi.hoisted(() => ({ headers: vi.fn(), getSession: vi.fn() }))
+vi.mock("next/headers", () => ({ headers: mocks.headers }))
+vi.mock("@/lib/session", () => ({ getSession: mocks.getSession }))
+vi.mock("@/components/home/landing-page", () => ({ LandingPage: () => null }))
+vi.mock("@/lib/observability/regions", () => ({ ObservedStaticContent: () => null }))
+import Page from "./page"
+describe("homepage session personalization", () => {
+ beforeEach(() => vi.clearAllMocks())
+ it("does not initialize authentication for a credential-free visitor", async () => {
+ mocks.headers.mockResolvedValue(new Headers())
+ const page = await Page()
+ expect(page.props.children[1].props.isLoggedIn).toBe(false)
+ expect(mocks.getSession).not.toHaveBeenCalled()
+ })
+ it.each<HeadersInit>([{ cookie: "session=viewer" }, { authorization: "Bearer viewer" }])("validates credentials %j", async headers => {
+ mocks.headers.mockResolvedValue(new Headers(headers))
+ mocks.getSession.mockResolvedValue({ user: { id: "viewer" } })
+ const page = await Page()
+ expect(page.props.children[1].props.isLoggedIn).toBe(true)
+ expect(mocks.getSession).toHaveBeenCalledOnce()
+ })
+ it("keeps unrelated or invalid cookies anonymous", async () => {
+ mocks.headers.mockResolvedValue(new Headers({ cookie: "consent=yes" }))
+ mocks.getSession.mockResolvedValue(null)
+ const page = await Page()
+ expect(page.props.children[1].props.isLoggedIn).toBe(false)
+ })
+})
diff --git a/src/web/src/app/(home)/page.tsx b/src/web/src/app/(home)/page.tsx
index f38714d30..9f4c6bcaf 100644
--- a/src/web/src/app/(home)/page.tsx
+++ b/src/web/src/app/(home)/page.tsx
@@ -5,7 +5,7 @@ import {
LANDING_META_TITLE,
} from "@/components/home/landing-content";
import { LandingPage } from "@/components/home/landing-page";
-import { getSession } from "@/lib/session";
+import { headers } from "next/headers";
import { SITE_OG_IMAGE } from "@/lib/seo/site-metadata";
const title = LANDING_META_TITLE;
@@ -32,6 +32,8 @@ export const metadata: Metadata = {
};
export default async function Page() {
- const session = await getSession();
+ const requestHeaders = await headers();
+ const hasCredentials = requestHeaders.has("cookie") || requestHeaders.has("authorization");
+ const session = hasCredentials ? await (await import("@/lib/session")).getSession() : null;
return <><ObservedStaticContent /><LandingPage isLoggedIn={!!session} /></>;
}
diff --git a/src/web/src/components/home/hero-avatar-swarm.tsx b/src/web/src/components/home/hero-avatar-swarm.tsx
index 21d2db683..429b1b50f 100644
--- a/src/web/src/components/home/hero-avatar-swarm.tsx
+++ b/src/web/src/components/home/hero-avatar-swarm.tsx
@@ -1,4 +1,6 @@
import type { CSSProperties } from "react"
+import Image from "next/image"
+import { Avatar as AvatarFrame } from "@/components/ui/avatar"
import { Avatar } from "@/components/community/avatar"
import { LANDING_HUMAN_AVATARS } from "./landing-human-avatars"
import styles from "./hero-avatar-swarm.module.css"
@@ -61,7 +63,23 @@ export function HeroAvatarSwarm() {
>
<span className={styles.shadow} />
<span className={styles.face}>
- <Avatar label={avatar.name} seed={avatar.seed} src={LANDING_HUMAN_AVATARS[avatar.seed]} size={avatar.size} />
+ {LANDING_HUMAN_AVATARS[avatar.seed] ? (
+ <AvatarFrame className="bg-muted" style={{ width: avatar.size, height: avatar.size, opacity: 1 }} aria-hidden>
+ <span aria-hidden className="absolute inset-0 bg-muted rounded-full" />
+ <Image
+ src={LANDING_HUMAN_AVATARS[avatar.seed]}
+ alt=""
+ width={avatar.size}
+ height={avatar.size}
+ unoptimized
+ loading="eager"
+ data-slot="avatar-image"
+ className="absolute inset-0 size-full object-cover transition-none opacity-100 aspect-square rounded-full"
+ />
+ </AvatarFrame>
+ ) : (
+ <Avatar label={avatar.name} seed={avatar.seed} size={avatar.size} />
+ )}
</span>
</span>
))}
diff --git a/src/web/src/middleware.ts b/src/web/src/middleware.ts
index d5e0309f4..5d33811aa 100644
--- a/src/web/src/middleware.ts
+++ b/src/web/src/middleware.ts
@@ -1,6 +1,4 @@
import { NextRequest, NextResponse } from "next/server"
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { getAuth, observeAuthSession } from "@/lib/auth"
import { safeRedirectPath } from "@/lib/safe-redirect"
import { COMMUNITY_DOCUMENT_ROUTE_HEADER, communityDocumentRoute } from "@/lib/community/document-route"
import { authResponseCookies } from "@/lib/auth-response-cookies"
@@ -32,6 +30,9 @@ export async function middleware(request: NextRequest) {
const needsAuth = !isPublic && (pathname === "/c" || AUTH_REQUIRED_PREFIXES.some((p) => pathname.startsWith(p)))
if (needsAuth) {
+ const [{ getCloudflareContext }, { getAuth, observeAuthSession }] = await Promise.all([
+ import("@opennextjs/cloudflare"), import("@/lib/auth"),
+ ])
const { env } = await getCloudflareContext({ async: true })
const auth = getAuth(env as Env)
const result = await observeAuthSession(auth, () => auth.api.getSession({
@@ -55,6 +56,9 @@ export async function middleware(request: NextRequest) {
}
if (pathname === "/sign-in" || pathname === "/sign-up") {
+ const [{ getCloudflareContext }, { getAuth, observeAuthSession }] = await Promise.all([
+ import("@opennextjs/cloudflare"), import("@/lib/auth"),
+ ])
const { env } = await getCloudflareContext({ async: true })
const auth = getAuth(env as Env)
const result = await observeAuthSession(auth, () => auth.api.getSession({
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.ts
index 0ddc68a1a..108745092 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
@@ -49,7 +49,7 @@ test.describe("threads", () => {
// hover toolbar can close between the hover and the menu click.
await expect(async () => {
await row.hover()
- await page.getByRole("button", { name: "More actions" }).first().click()
+ await page.getByRole("button", { name: "More actions" }).first().click({ timeout: 3_000 })
await page.getByRole("menuitem", { name: "Create Thread" }).click({ timeout: 3_000 })
}).toPass({ timeout: 20_000 })