Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): reduce cached page and anonymous sign-in latency (#1069)
Gustavo Ye15f499545504
diff --git a/src/web/open-next.config.ts b/src/web/open-next.config.tsindex 4c562eb85..ffcee6c81 100644--- a/src/web/open-next.config.ts+++ b/src/web/open-next.config.ts@@ -1,9 +1,10 @@import { defineCloudflareConfig } from "@opennextjs/cloudflare";import r2IncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/r2-incremental-cache";+import { withRegionalCache } from "@opennextjs/cloudflare/overrides/incremental-cache/regional-cache";import doQueue from "@opennextjs/cloudflare/overrides/queue/do-queue";export default defineCloudflareConfig({- incrementalCache: r2IncrementalCache,+ incrementalCache: withRegionalCache(r2IncrementalCache, { mode: "long-lived" }),queue: doQueue,enableCacheInterception: true,});diff --git a/src/web/scripts/open-next-config.test.ts b/src/web/scripts/open-next-config.test.tsindex dff93b7c2..332b7ba53 100644--- a/src/web/scripts/open-next-config.test.ts+++ b/src/web/scripts/open-next-config.test.ts@@ -8,10 +8,11 @@ function resolveOverride(value: unknown): unknown {}describe("Web OpenNext configuration", () => {- it("uses the existing R2 cache and Durable Object revalidation queue", () => {- expect(resolveOverride(config.default.override?.incrementalCache)).toBe(r2IncrementalCache)+ it("wraps the existing R2 store in regional caching and retains the Durable Object queue", () => {+ const cache = resolveOverride(config.default.override?.incrementalCache)+ expect(cache).toMatchObject({ store: r2IncrementalCache, opts: { mode: "long-lived" } })expect(resolveOverride(config.default.override?.queue)).toBe(doQueue)- expect(resolveOverride(config.middleware?.override?.incrementalCache)).toBe(r2IncrementalCache)+ expect(resolveOverride(config.middleware?.override?.incrementalCache)).toBe(cache)expect(resolveOverride(config.middleware?.override?.queue)).toBe(doQueue)})diff --git a/src/web/scripts/regional-cache.test.ts b/src/web/scripts/regional-cache.test.tsnew file mode 100644index 000000000..c490eac92--- /dev/null+++ b/src/web/scripts/regional-cache.test.ts@@ -0,0 +1,57 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import r2 from "@opennextjs/cloudflare/overrides/incremental-cache/r2-incremental-cache";+import { withRegionalCache } from "@opennextjs/cloudflare/overrides/incremental-cache/regional-cache";++const pending: Promise<unknown>[] = [];+const value = { type: "app" as const, html: "<h1>public</h1>", rsc: "rsc-payload", revalidate: false as const };+const entry = { value, lastModified: 1_000 };+let entries: Map<string, Response>;+beforeEach(() => {+ entries = new Map();+ pending.length = 0;+ vi.stubGlobal(Symbol.for("__cloudflare-context__"), { ctx: { waitUntil: (task: Promise<unknown>) => pending.push(task) } });+ vi.stubGlobal("nextVersion", "16.4.1");+ vi.stubEnv("OPEN_NEXT_BUILD_ID", "build-a");+ vi.stubGlobal("caches", { open: async () => ({+ match: async (key: string) => entries.get(key)?.clone(),+ put: async (key: string, response: Response) => { entries.set(key, response.clone()); },+ delete: async (key: string) => entries.delete(key),+ }) });+});+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); });++describe("configured regional incremental cache", () => {+ it("serves a warm page while the backing refresh is still pending, retaining HTML/RSC and tag checks", async () => {+ const get = vi.spyOn(r2, "get").mockResolvedValue(entry);+ const cache = withRegionalCache(r2, { mode: "long-lived" });+ expect(await cache.get("/pricing")).toEqual(entry);+ await Promise.all(pending.splice(0));+ let finish!: (result: typeof entry) => void;+ get.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));+ const warm = await cache.get("/pricing");+ expect(warm).toEqual({ ...entry, shouldBypassTagCache: false });+ expect(pending).toHaveLength(1);+ finish(entry);+ await Promise.all(pending.splice(0));+ });+ it("isolates deployment builds and preserves backing-store writes", async () => {+ const get = vi.spyOn(r2, "get").mockResolvedValue(entry);+ const set = vi.spyOn(r2, "set").mockResolvedValue();+ const cache = withRegionalCache(r2, { mode: "long-lived" });+ await cache.get("/pricing");+ await Promise.all(pending.splice(0));+ vi.stubEnv("OPEN_NEXT_BUILD_ID", "build-b");+ await cache.get("/pricing");+ expect(get).toHaveBeenCalledTimes(2);+ await Promise.all(pending.splice(0));+ expect(entries.size).toBe(2);+ await cache.set("/pricing", value);+ expect(set).toHaveBeenCalledWith("/pricing", value, undefined);+ });+ it("does not invent entries for missing pages", async () => {+ vi.spyOn(r2, "get").mockResolvedValue(null);+ const cache = withRegionalCache(r2, { mode: "long-lived" });+ expect(await cache.get("/missing")).toBeNull();+ expect(entries.size).toBe(0);+ });+});diff --git a/src/web/src/app/(auth)/layout.test.ts b/src/web/src/app/(auth)/layout.test.tsindex ed945beef..d136bdb16 100644--- a/src/web/src/app/(auth)/layout.test.ts+++ b/src/web/src/app/(auth)/layout.test.ts@@ -1,9 +1,38 @@-import { describe, expect, it } from "vitest";-import { metadata } from "./layout";+import { beforeEach, describe, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({ headers: vi.fn(), getSession: vi.fn(), redirect: vi.fn() }));+vi.mock("next/headers", () => ({ headers: mocks.headers }));+vi.mock("@/lib/session", () => ({ getSession: mocks.getSession }));+vi.mock("next/navigation", () => ({ redirect: mocks.redirect }));+import AuthLayout, { metadata } from "./layout";-describe("(auth) layout metadata", () => {+beforeEach(() => {+ vi.clearAllMocks();+ mocks.headers.mockResolvedValue(new Headers());+ mocks.getSession.mockResolvedValue(null);+});+describe("(auth) layout", () => {it("gives sign-in its own noindex metadata", () => {expect(metadata.robots).toEqual({ index: false, follow: true });expect(metadata.alternates).toEqual({ canonical: "/sign-in" });});+ it("renders anonymous children without initializing auth", async () => {+ const result = await AuthLayout({ children: "sign in form" });+ expect(result.props.children).toBe("sign in form");+ expect(mocks.getSession).not.toHaveBeenCalled();+ expect(mocks.redirect).not.toHaveBeenCalled();+ });+ it.each(["Cookie", "Authorization"])("validates %s before redirecting a signed-in visitor", async name => {+ mocks.headers.mockResolvedValue(new Headers({ [name]: "fixture" }));+ mocks.getSession.mockResolvedValue({ user: { id: "viewer" } });+ await AuthLayout({ children: "form" });+ expect(mocks.getSession).toHaveBeenCalledOnce();+ expect(mocks.redirect).toHaveBeenCalledWith("/c/me");+ });+ it("keeps the sign-in form for an invalid cookie", async () => {+ mocks.headers.mockResolvedValue(new Headers({ Cookie: "expired=fixture" }));+ const result = await AuthLayout({ children: "form" });+ expect(result.props.children).toBe("form");+ expect(mocks.getSession).toHaveBeenCalledOnce();+ expect(mocks.redirect).not.toHaveBeenCalled();+ });});diff --git a/src/web/src/app/(auth)/layout.tsx b/src/web/src/app/(auth)/layout.tsxindex 1831e95dd..f1efc7c3f 100644--- a/src/web/src/app/(auth)/layout.tsx+++ b/src/web/src/app/(auth)/layout.tsx@@ -1,6 +1,6 @@import type { Metadata } from "next";import { redirect } from "next/navigation";-import { getSession } from "@/lib/session";+import { headers } from "next/headers";import { BRAND_SLOGAN } from "@/lib/brand-copy";export const metadata: Metadata = {@@ -15,10 +15,12 @@ export default async function AuthLayout({}: {children: React.ReactNode;}) {- const session = await getSession();- // Already signed in → community home. `/workspaces` was the retired legacy- // (v0) surface.- if (session) redirect("/c/me");+ const requestHeaders = await headers();+ if (requestHeaders.has("Cookie") || requestHeaders.has("Authorization")) {+ const { getSession } = await import("@/lib/session");+ const session = await getSession();+ if (session) redirect("/c/me");+ }return <>{children}</>;}diff --git a/src/web/src/middleware.test.ts b/src/web/src/middleware.test.tsindex 5d721f7de..f8ad7f2a6 100644--- a/src/web/src/middleware.test.ts+++ b/src/web/src/middleware.test.ts@@ -31,6 +31,21 @@ describe("middleware", () => {expect(mockGetSession).not.toHaveBeenCalled()})+ it.each(["/sign-in", "/sign-up"])("skips session work for credential-free %s", async path => {+ mockGetSession.mockImplementation(() => { throw new Error("No credentials") })+ const res = await middleware(makeReq(`https://app.com${path}`))+ expect(res.headers.get("x-middleware-next")).toBe("1")+ expect(mockGetSession).not.toHaveBeenCalled()+ })++ it.each(["Cookie", "Authorization"])("validates %s credentials and preserves renewal cookies", async name => {+ mockGetSession.mockResolvedValue({ headers: new Headers({ "Set-Cookie": "session=renewed; HttpOnly" }), response: { user: { id: "u1" } } })+ const res = await middleware(makeReq("https://app.com/sign-up?redirect=%2Fc%2Fme", { [name]: "fixture" }))+ expect(mockGetSession).toHaveBeenCalledOnce()+ expect(res.headers.get("location")).toBe("https://app.com/c/me")+ expect(res.headers.get("Set-Cookie")).toContain("session=renewed")+ })+describe("HTTPS enforcement", () => {it("301-redirects http → https for non-local hosts", async () => {const req = makeReq("http://example.com/c/me", { "x-forwarded-proto": "http" });@@ -101,7 +116,7 @@ describe("middleware", () => {response: { user: { id: "u1" } },});const qs = redirectParam === null ? "" : `?redirect=${encodeURIComponent(redirectParam)}`;- const req = makeReq(`https://app.com/sign-in${qs}`, { "x-forwarded-proto": "https" });+ const req = makeReq(`https://app.com/sign-in${qs}`, { "x-forwarded-proto": "https", Cookie: "session=fixture" });const res = await middleware(req);return new URL(res.headers.get("location")!);}diff --git a/src/web/src/middleware.ts b/src/web/src/middleware.tsindex 3a7cefa1c..144604cc4 100644--- a/src/web/src/middleware.ts+++ b/src/web/src/middleware.ts@@ -13,7 +13,8 @@ export async function middleware(request: NextRequest) {}const { pathname } = request.nextUrl- if (pathname === "/sign-in" || pathname === "/sign-up") {+ if ((pathname === "/sign-in" || pathname === "/sign-up") &&+ (request.headers.has("Cookie") || request.headers.has("Authorization"))) {const [{ getCloudflareContext }, { getAuth, observeAuthSession }] = await Promise.all([import("@opennextjs/cloudflare"), import("@/lib/auth"),])