Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

perf(startup): stream community frame and preserve account lifetime (#879)

Genera69d7f41423d
diff --git a/src/web/src/app/c/QueryProvider.dom.test.ts b/src/web/src/app/c/QueryProvider.dom.test.ts
index 0943da31a..d4dfc411b 100644
--- a/src/web/src/app/c/QueryProvider.dom.test.ts
+++ b/src/web/src/app/c/QueryProvider.dom.test.ts
@@ -72,6 +72,48 @@ describe("QueryProvider profile account lifecycle", () => {
expect(registry.runtime.lifecycle.get().active).toBe(false)
} finally { vi.useRealTimers() }
})
+ it("keeps the account owner alive while a revealed Suspense subtree is hidden", async () => {
+ vi.useFakeTimers()
+ let release!: () => void
+ const pending = new Promise<void>((resolve) => { release = resolve })
+ function Child({ blocked }: { blocked: boolean }) {
+ if (blocked) throw pending
+ return React.createElement("span", null, "resolved account")
+ }
+ const tree = (blocked: boolean) => React.createElement(React.Suspense, {
+ fallback: React.createElement("div", { "data-testid": "session-pending" }, "pending"),
+ }, React.createElement(QueryProvider, { userId: "viewer-suspended" },
+ React.createElement(Child, { blocked })))
+ const renderer = render(tree(false))
+ const registry = getCommunityDbRegistry(queryClient)!
+ const cleanup = vi.spyOn(registry, "cleanup")
+ const key = communityKeys.bots()
+ queryClient.setQueryData(key, { bots: [{ id: "owned-bot" }] })
+ try {
+ await act(async () => vi.advanceTimersByTimeAsync(0))
+ act(() => renderer.rerender(tree(true)))
+ expect(renderer.container.querySelector('[data-testid="session-pending"]')).not.toBeNull()
+ await act(async () => vi.advanceTimersByTimeAsync(0))
+ expect(cleanup).not.toHaveBeenCalled()
+ expect(getCommunityDbRegistry(queryClient)).toBe(registry)
+ expect(registry.runtime.lifecycle.get().active).toBe(true)
+ expect(queryClient.getQueryData(key)).toEqual({ bots: [{ id: "owned-bot" }] })
+ await act(async () => { release(); renderer.rerender(tree(false)); await vi.advanceTimersByTimeAsync(300) })
+ expect(renderer.container.querySelector('[data-testid="session-pending"]')).toBeNull()
+ expect(getCommunityDbRegistry(queryClient)).toBe(registry)
+ expect(queryClient.getQueryData(key)).toEqual({ bots: [{ id: "owned-bot" }] })
+ expect(cleanup).not.toHaveBeenCalled()
+ act(() => renderer.unmount())
+ await act(async () => vi.advanceTimersByTimeAsync(0))
+ expect(cleanup).toHaveBeenCalledOnce()
+ expect(queryClient.getQueryCache().getAll()).toEqual([])
+ } finally {
+ release()
+ act(() => renderer.unmount())
+ await act(async () => vi.advanceTimersByTimeAsync(300))
+ vi.useRealTimers()
+ }
+ })
it("owns the new account before restore while the prior owner remains isolated", async () => {
const previous = await createCommunityQueryOwner("viewer-a")
const observed: string[] = []
diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsx
index 19512959a..411d4b4f4 100644
--- a/src/web/src/app/c/QueryProvider.tsx
+++ b/src/web/src/app/c/QueryProvider.tsx
@@ -59,7 +59,7 @@ function CommunityDbRuntime({
const isRestoring = useIsRestoring()
const disposeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
- useLayoutEffect(() => {
+ useEffect(() => {
if (disposeTimer.current !== null) {
clearTimeout(disposeTimer.current)
disposeTimer.current = null
diff --git a/src/web/src/app/c/community-session-fallback.dom.test.tsx b/src/web/src/app/c/community-session-fallback.dom.test.tsx
new file mode 100644
index 000000000..004d796c8
--- /dev/null
+++ b/src/web/src/app/c/community-session-fallback.dom.test.tsx
@@ -0,0 +1,38 @@
+import { createElement } from "react"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { render, screen } from "@/test/react-dom-harness"
+
+const mocks = vi.hoisted(() => ({ pathname: "/c", pending: vi.fn() }))
+vi.mock("next/navigation", () => ({ usePathname: () => mocks.pathname }))
+vi.mock("@/components/community/shell/community-session-pending-frame", () => ({
+ CommunitySessionPendingFrame: (props: { pathname: string }) => {
+ mocks.pending(props)
+ return createElement("div", { "data-testid": "pending", "data-pathname": props.pathname })
+ },
+}))
+
+import { CommunitySessionFallback } from "./community-session-fallback"
+
+describe("CommunitySessionFallback route adapter", () => {
+ beforeEach(() => {
+ mocks.pending.mockClear()
+ mocks.pathname = "/c"
+ })
+
+ it.each(["/c", "/c/channels/server-a/channel-a", "/c/invite/token", "/c/invite/token/extra"])(
+ "passes only the current pathname %s to the public frame", (pathname) => {
+ mocks.pathname = pathname
+ render(createElement(CommunitySessionFallback))
+ expect(screen.getByTestId("pending")).toHaveAttribute("data-pathname", pathname)
+ expect(mocks.pending).toHaveBeenCalledWith({ pathname })
+ },
+ )
+
+ it("updates the public geometry input when the current route changes", () => {
+ const rendered = render(createElement(CommunitySessionFallback))
+ mocks.pathname = "/c/me/dm-b"
+ rendered.rerender(createElement(CommunitySessionFallback))
+ expect(screen.getByTestId("pending")).toHaveAttribute("data-pathname", "/c/me/dm-b")
+ expect(mocks.pending).toHaveBeenLastCalledWith({ pathname: "/c/me/dm-b" })
+ })
+})
diff --git a/src/web/src/app/c/community-session-fallback.tsx b/src/web/src/app/c/community-session-fallback.tsx
new file mode 100644
index 000000000..7906044e8
--- /dev/null
+++ b/src/web/src/app/c/community-session-fallback.tsx
@@ -0,0 +1,9 @@
+"use client"
+
+import { usePathname } from "next/navigation"
+import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"
+
+export function CommunitySessionFallback() {
+ const pathname = usePathname()
+ return <CommunitySessionPendingFrame pathname={pathname} />
+}
diff --git a/src/web/src/app/c/layout.server.test.ts b/src/web/src/app/c/layout.server.test.ts
new file mode 100644
index 000000000..fc53046f1
--- /dev/null
+++ b/src/web/src/app/c/layout.server.test.ts
@@ -0,0 +1,140 @@
+import { PassThrough } from "node:stream"
+import { createElement, type ReactNode } from "react"
+import { renderToPipeableStream } from "react-dom/server"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type { CurrentUser } from "@/contexts/community/current-user"
+
+const mocks = vi.hoisted(() => ({
+ getSession: vi.fn(),
+ pathname: "/c",
+ client: vi.fn(),
+}))
+
+vi.mock("@/lib/session", () => ({ getSession: mocks.getSession }))
+vi.mock("next/navigation", () => ({ usePathname: () => mocks.pathname }))
+vi.mock("@/components/community/billing/billing-plan.module.css", () => ({
+ default: new Proxy({}, { get: (_target, key) => String(key) }),
+}))
+vi.mock("./community-layout-client", () => ({
+ CommunityLayoutClient: (props: {
+ currentUser: CurrentUser | null
+ children: ReactNode
+ sidebar: ReactNode
+ }) => {
+ mocks.client(props)
+ return createElement("section", { "data-testid": "resolved-session" },
+ props.currentUser?.id ?? "anonymous", props.sidebar, props.children)
+ },
+}))
+
+import CommunityLayout from "./layout"
+
+const children = createElement("main", { "data-testid": "private-child" }, "private content")
+const sidebar = createElement("aside", { "data-testid": "private-sidebar" }, "private sidebar")
+const session = {
+ user: { id: "account-a", name: "Ada", email: "[email protected]", image: "avatar-a" },
+}
+
+function renderLayout() {
+ const output = new PassThrough()
+ const errors: unknown[] = []
+ let html = ""
+ let resolvePublicFrame!: (html: string) => void
+ const publicFrame = new Promise<string>((resolve) => { resolvePublicFrame = resolve })
+ const finished = new Promise<string>((resolve, reject) => {
+ output.on("data", (chunk: Buffer) => {
+ html += chunk.toString()
+ if (html.includes("<!--/$-->")) resolvePublicFrame(html)
+ })
+ output.on("end", () => resolve(html))
+ output.on("error", reject)
+ })
+ const rendering = renderToPipeableStream(createElement("html", null,
+ createElement("body", null, createElement(CommunityLayout, { sidebar }, children))), {
+ onShellReady: () => rendering.pipe(output),
+ onShellError: (error) => output.destroy(error),
+ onError: (error) => { errors.push(error) },
+ })
+ return { publicFrame, finished, errors, abort: rendering.abort }
+}
+
+describe("CommunityLayout server session streaming", () => {
+ beforeEach(() => {
+ mocks.getSession.mockReset()
+ mocks.client.mockClear()
+ mocks.pathname = "/c"
+ })
+
+ it.each([
+ ["/c", "community-root-redirect", "route-resolution"],
+ ["/c/channels/server-a/channel-a", "server-detail", "server-conversation"],
+ ["/c/invite/token", "public-invite", null],
+ ["/c/invite/token/extra", "unknown", "route-resolution"],
+ ])("streams a public frame for %s while the session is held", async (pathname, route, main) => {
+ mocks.pathname = pathname
+ let release!: (value: typeof session) => void
+ mocks.getSession.mockReturnValue(new Promise<typeof session>((resolve) => { release = resolve }))
+ const rendering = renderLayout()
+ try {
+ const first = await rendering.publicFrame
+ expect(first).toContain('data-testid="community-initial-frame"')
+ expect(first).toContain(`data-community-route-kind="${route}"`)
+ if (main) expect(first).toContain(`data-testid="community-pending-main-${main}"`)
+ expect(first).not.toContain("private-child")
+ expect(first).not.toContain("private-sidebar")
+ expect(first).not.toContain("resolved-session")
+ expect(first).not.toContain("account-a")
+ expect(first).not.toContain("[email protected]")
+ expect(first).not.toContain("community-user-bar-name")
+ expect(mocks.client).not.toHaveBeenCalled()
+ expect(mocks.getSession).toHaveBeenCalledTimes(1)
+ release(session)
+ const complete = await rendering.finished
+ expect(complete).toContain("resolved-session")
+ expect(complete).toContain("private-child")
+ expect(complete).toContain("private-sidebar")
+ expect(mocks.client).toHaveBeenCalledTimes(1)
+ expect(mocks.client).toHaveBeenCalledWith({
+ currentUser: { id: "account-a", name: "Ada", email: "[email protected]", avatar: "avatar-a", avatarVersion: 0 },
+ children,
+ sidebar,
+ })
+ expect(rendering.errors).toEqual([])
+ } finally {
+ rendering.abort()
+ }
+ })
+
+ it.each([
+ ["avatar-a", "avatar-a"],
+ ["", "A"],
+ [null, "A"],
+ ])("preserves server user mapping for image %s", async (image, avatar) => {
+ mocks.getSession.mockResolvedValue({ user: { ...session.user, image } })
+ const rendering = renderLayout()
+ await rendering.finished
+ expect(mocks.client).toHaveBeenCalledWith({
+ currentUser: { id: "account-a", name: "Ada", email: "[email protected]", avatar, avatarVersion: 0 },
+ children,
+ sidebar,
+ })
+ expect(rendering.errors).toEqual([])
+ })
+
+ it("passes only a resolved null session to the original anonymous owner", async () => {
+ mocks.getSession.mockResolvedValue(null)
+ const rendering = renderLayout()
+ await rendering.finished
+ expect(mocks.client).toHaveBeenCalledWith({ currentUser: null, children, sidebar })
+ expect(rendering.errors).toEqual([])
+ })
+
+ it("reports a rejected session without invoking an anonymous client branch", async () => {
+ const error = new Error("session unavailable")
+ mocks.getSession.mockRejectedValue(error)
+ const rendering = renderLayout()
+ await rendering.finished
+ expect(rendering.errors).toContain(error)
+ expect(mocks.client).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsx
index 6c5212d63..d416920e3 100644
--- a/src/web/src/app/c/layout.tsx
+++ b/src/web/src/app/c/layout.tsx
@@ -1,9 +1,20 @@
-import type { ReactNode } from "react"
+import { Suspense, type ReactNode } from "react"
import { getSession } from "@/lib/session"
import { avatarInitial } from "@/lib/community/avatar"
import { CommunityLayoutClient } from "./community-layout-client"
+import { CommunitySessionFallback } from "./community-session-fallback"
-export default async function CommunityLayout({ children, sidebar }: { children: ReactNode; sidebar: ReactNode }) {
+type CommunityLayoutProps = { children: ReactNode; sidebar: ReactNode }
+
+export default function CommunityLayout({ children, sidebar }: CommunityLayoutProps) {
+ return (
+ <Suspense fallback={<CommunitySessionFallback />}>
+ <CommunitySessionLayout sidebar={sidebar}>{children}</CommunitySessionLayout>
+ </Suspense>
+ )
+}
+
+async function CommunitySessionLayout({ children, sidebar }: CommunityLayoutProps) {
const session = await getSession()
const currentUser = session
? {